verify-cordis-config.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /**
  2. * Validate Cordis Loader entry metadata and package resolution.
  3. *
  4. * The Loader interpolates only a plugin entry's `config`; expression objects in
  5. * fields such as `disabled` remain truthy data and silently change composition.
  6. * Example configs and the dsh Web composition resolve named plugins from their
  7. * owning workspace manifests. Local example packages must also be in the root
  8. * TypeScript project graph.
  9. */
  10. import { globSync, readFileSync } from 'node:fs'
  11. import { dirname, relative, resolve } from 'node:path'
  12. import * as yaml from 'js-yaml'
  13. import ts from 'typescript'
  14. import { cordisConfigFiles } from './cordis-config-files.ts'
  15. interface JsExpr {
  16. __jsExpr: string
  17. }
  18. interface PackageManifest {
  19. name?: string
  20. dependencies?: Record<string, string>
  21. }
  22. interface PluginReference {
  23. file: string
  24. name: string
  25. }
  26. const root = resolve(import.meta.dirname, '..')
  27. // These example files are overlays consumed by the built dsh app, so their bare
  28. // specifiers resolve from apps/cli rather than the examples workspace.
  29. const appOverlayFiles = new Set(['examples/web-cordis/cordis.yml'])
  30. const metadataFields = ['id', 'name', 'group', 'disabled', 'inject', 'intercept', 'isolate'] as const
  31. /** The adaptive directory-picker chooser package (mounts a backend row at boot). */
  32. const CHOOSER_PACKAGE = '@deepseek-ai/dsh-host-directory-picker-auto'
  33. /**
  34. * The backends the chooser mounts by runtime string (mirror of its exported
  35. * `BACKEND_PACKAGES`), invisible to yml-row scanning: a composition mounting
  36. * the chooser must resolve both, or keyless Linux CI (which only ever
  37. * resolves `browse`) hides a dropped `-native` dependency until a macOS boot.
  38. */
  39. const CHOOSER_BACKEND_PACKAGES = [
  40. '@deepseek-ai/dsh-host-directory-picker-native',
  41. '@deepseek-ai/dsh-host-directory-picker-browse',
  42. ]
  43. const jsExprType = new yaml.Type('tag:yaml.org,2002:js', {
  44. kind: 'scalar',
  45. resolve: data => typeof data === 'string',
  46. construct: (data: unknown): JsExpr => {
  47. if (typeof data !== 'string') throw new TypeError('!!js requires a scalar string')
  48. return { __jsExpr: data }
  49. },
  50. })
  51. const schema = yaml.JSON_SCHEMA.extend(jsExprType)
  52. const files = cordisConfigFiles(root)
  53. const errors: string[] = []
  54. const pluginReferences: PluginReference[] = []
  55. for (const file of files) {
  56. const document: unknown = yaml.load(readFileSync(resolve(root, file), 'utf8'), { schema })
  57. if (!isUnknownArray(document)) {
  58. errors.push(`${file}: root must be a Loader entry array`)
  59. continue
  60. }
  61. for (let index = 0; index < document.length; index++) {
  62. validateEntry(document[index], file, `[${index}]`)
  63. }
  64. }
  65. errors.push(...validateExampleResolution())
  66. errors.push(...validateAppResolution())
  67. errors.push(...validateSourcePlaneResolution())
  68. if (errors.length > 0) {
  69. console.error('verify-cordis-config: invalid Loader metadata or plugin package resolution:')
  70. for (const error of errors) console.error(`- ${error}`)
  71. process.exitCode = 1
  72. } else {
  73. console.log(`verify-cordis-config: ${files.length} config files passed.`)
  74. }
  75. function validateEntry(value: unknown, file: string, path: string): void {
  76. if (!isRecord(value)) {
  77. errors.push(`${file}${path}: entry must be an object`)
  78. return
  79. }
  80. recordPlugin(value, file)
  81. validateMetadata(value, file, path)
  82. if ((value.group === true || value.name === '@cordisjs/plugin-group') && isUnknownArray(value.config)) {
  83. for (let index = 0; index < value.config.length; index++) {
  84. validateEntry(value.config[index], file, `${path}.config[${index}]`)
  85. }
  86. }
  87. if (isUnknownArray(value.insert)) {
  88. for (let index = 0; index < value.insert.length; index++) {
  89. validateEntry(value.insert[index], file, `${path}.insert[${index}]`)
  90. }
  91. }
  92. if (value.name !== '@cordisjs/plugin-include') return
  93. const config = value.config
  94. if (!isRecord(config) || !isUnknownArray(config.patches)) return
  95. for (let index = 0; index < config.patches.length; index++) {
  96. const patch = config.patches[index]
  97. const patchPath = `${path}.config.patches[${index}]`
  98. if (!isRecord(patch)) continue
  99. recordPlugin(patch, file)
  100. validateMetadata(patch, file, patchPath)
  101. if (!isUnknownArray(patch.insert)) continue
  102. for (let insertIndex = 0; insertIndex < patch.insert.length; insertIndex++) {
  103. validateEntry(patch.insert[insertIndex], file, `${patchPath}.insert[${insertIndex}]`)
  104. }
  105. }
  106. }
  107. function recordPlugin(entry: Record<string, unknown>, file: string): void {
  108. if (typeof entry.name === 'string') pluginReferences.push({ file, name: entry.name })
  109. }
  110. function validateExampleResolution(): string[] {
  111. const violations: string[] = []
  112. const exampleManifest = readManifest('examples/package.json')
  113. const dependencies = exampleManifest.dependencies ?? {}
  114. const localPackages = localPackageDirectories()
  115. const rootReferences = rootProjectReferences()
  116. const exampleReferences = pluginReferences.filter(reference => reference.file.startsWith('examples/') && !appOverlayFiles.has(reference.file))
  117. violations.push(...missingPluginDependencies(exampleReferences, dependencies, 'examples/package.json'))
  118. const requiredPackages = new Set(exampleReferences.map(reference => packageNameFromSpecifier(reference.name)))
  119. const localExamplePackages = new Set([
  120. ...Object.keys(dependencies),
  121. ...[...requiredPackages].filter(packageName => packageName !== undefined),
  122. ])
  123. for (const packageName of localExamplePackages) {
  124. const packageDirectory = localPackages.get(packageName)
  125. if (packageDirectory === undefined || rootReferences.has(packageDirectory)) continue
  126. const repoPath = relative(root, packageDirectory).replaceAll('\\', '/')
  127. violations.push(`tsconfig.json: missing project reference for ${packageName} (${repoPath})`)
  128. }
  129. return violations
  130. }
  131. function validateAppResolution(): string[] {
  132. const dependencies = readManifest('apps/cli/package.json').dependencies ?? {}
  133. const shipped = new Set(globSync('*.cordis.yml', { cwd: resolve(root, 'apps/cli/config') })
  134. .map(file => `apps/cli/config/${file}`))
  135. const references = pluginReferences.filter(reference => shipped.has(reference.file) || appOverlayFiles.has(reference.file))
  136. return missingPluginDependencies(references, dependencies, 'apps/cli/package.json')
  137. }
  138. /**
  139. * Every configured specifier of a local workspace package must resolve through
  140. * the tsconfig `paths` facade to a `.ts`/`.tsx` source file. The `dsh` source
  141. * launch (tsx) and vitest resolve in the source plane; without a `paths` match
  142. * they fall back to package `exports`, which reach built `lib/` — present on a
  143. * built dev tree, absent on a clean one — so a missing mapping boots locally
  144. * yet breaks every clean checkout. Anything but a `.ts`/`.tsx` hit (a `.d.ts`
  145. * or `.js` under built `lib/`) is that artifact-plane fallback, not source.
  146. */
  147. function validateSourcePlaneResolution(): string[] {
  148. const violations: string[] = []
  149. const localPackages = localPackageDirectories()
  150. const config = ts.readConfigFile(resolve(root, 'tsconfig.base.json'), path => ts.sys.readFile(path))
  151. if (config.error !== undefined) {
  152. throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))
  153. }
  154. const { options, errors: optionErrors } = ts.convertCompilerOptionsFromJson(
  155. (config.config as { compilerOptions?: unknown }).compilerOptions,
  156. root,
  157. 'tsconfig.base.json',
  158. )
  159. if (optionErrors.length > 0) {
  160. throw new Error(optionErrors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  161. }
  162. // convertCompilerOptionsFromJson leaves `pathsBasePath` unset, so relative
  163. // `paths` targets resolve against the host's current directory; anchor it to
  164. // the repository root to keep the gate cwd-independent.
  165. const host: ts.ModuleResolutionHost = {
  166. fileExists: path => ts.sys.fileExists(path),
  167. readFile: path => ts.sys.readFile(path),
  168. directoryExists: path => ts.sys.directoryExists(path),
  169. getCurrentDirectory: () => root,
  170. }
  171. const sourceExtensions = new Set<string>([ts.Extension.Ts, ts.Extension.Tsx])
  172. const containingFile = resolve(root, 'scripts/verify-cordis-config.ts')
  173. const locationsBySpecifier = new Map<string, Set<string>>()
  174. for (const reference of pluginReferences) {
  175. const packageName = packageNameFromSpecifier(reference.name)
  176. if (packageName === undefined || !localPackages.has(packageName)) continue
  177. const locations = locationsBySpecifier.get(reference.name) ?? new Set<string>()
  178. locations.add(reference.file)
  179. locationsBySpecifier.set(reference.name, locations)
  180. }
  181. for (const [specifier, locations] of locationsBySpecifier) {
  182. const resolved = ts.resolveModuleName(specifier, containingFile, options, host).resolvedModule
  183. if (resolved !== undefined && sourceExtensions.has(resolved.extension)) continue
  184. violations.push(`${[...locations].join(', ')}: ${specifier} does not resolve to workspace source through tsconfig.base.json paths (add a mapping so the tsx source launch does not depend on built lib/)`)
  185. }
  186. return violations
  187. }
  188. function missingPluginDependencies(
  189. references: readonly PluginReference[],
  190. dependencies: Readonly<Record<string, string>>,
  191. manifestPath: string,
  192. ): string[] {
  193. const requiredPackages = new Map<string, Set<string>>()
  194. const require = (packageName: string, file: string): void => {
  195. const locations = requiredPackages.get(packageName) ?? new Set<string>()
  196. locations.add(file)
  197. requiredPackages.set(packageName, locations)
  198. }
  199. for (const reference of references) {
  200. const packageName = packageNameFromSpecifier(reference.name)
  201. if (packageName === undefined) continue
  202. require(packageName, reference.file)
  203. if (packageName === CHOOSER_PACKAGE) {
  204. for (const backend of CHOOSER_BACKEND_PACKAGES) require(backend, reference.file)
  205. }
  206. }
  207. return [...requiredPackages].flatMap(([packageName, locations]) => packageName in dependencies
  208. ? []
  209. : `${[...locations].join(', ')}: ${packageName} must be declared in ${manifestPath} dependencies`)
  210. }
  211. function readManifest(path: string): PackageManifest {
  212. return JSON.parse(readFileSync(resolve(root, path), 'utf8')) as PackageManifest
  213. }
  214. function localPackageDirectories(): Map<string, string> {
  215. const manifests = globSync(['packages/*/*/package.json', 'vendor/*/package.json'], { cwd: root })
  216. const packages = new Map<string, string>()
  217. for (const manifestPath of manifests) {
  218. const manifest = readManifest(manifestPath)
  219. if (manifest.name !== undefined) packages.set(manifest.name, resolve(root, dirname(manifestPath)))
  220. }
  221. return packages
  222. }
  223. function rootProjectReferences(): Set<string> {
  224. // The root solution references the host and client aggregates (the two
  225. // sides merge cordis Context under the same keys, so one program cannot see
  226. // both — but this BFS only collects reference paths, it never forms a
  227. // program). Seed the solution and follow nested aggregate references to
  228. // collect the covered leaf project set.
  229. const collected = new Set<string>()
  230. const queue = [resolve(root, 'tsconfig.json')]
  231. const seen = new Set<string>()
  232. for (let file = queue.pop(); file !== undefined; file = queue.pop()) {
  233. if (seen.has(file)) continue
  234. seen.add(file)
  235. const config = ts.readConfigFile(file, path => ts.sys.readFile(path))
  236. if (config.error !== undefined) {
  237. throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))
  238. }
  239. const references = (config.config as { references?: Array<{ path?: unknown }> }).references ?? []
  240. for (const reference of references) {
  241. if (typeof reference.path !== 'string') continue
  242. const target = resolve(dirname(file), reference.path)
  243. if (target.endsWith('.json')) queue.push(target)
  244. else collected.add(target)
  245. }
  246. }
  247. return collected
  248. }
  249. function packageNameFromSpecifier(specifier: string): string | undefined {
  250. if (specifier.startsWith('.') || specifier.startsWith('/') || /^[a-z][a-z+.-]*:/i.test(specifier)) return undefined
  251. const segments = specifier.split('/')
  252. if (specifier.startsWith('@')) {
  253. return segments.length >= 2 ? `${segments[0]}/${segments[1]}` : undefined
  254. }
  255. return segments[0] || undefined
  256. }
  257. function validateMetadata(entry: Record<string, unknown>, file: string, path: string): void {
  258. for (const field of metadataFields) {
  259. if (!(field in entry)) continue
  260. const expressionPaths: string[] = []
  261. collectExpressionPaths(entry[field], `${path}.${field}`, expressionPaths)
  262. for (const expressionPath of expressionPaths) errors.push(`${file}${expressionPath}: !!js is not interpolated here`)
  263. }
  264. }
  265. function collectExpressionPaths(value: unknown, path: string, output: string[]): void {
  266. if (isJsExpr(value)) {
  267. output.push(path)
  268. return
  269. }
  270. if (isUnknownArray(value)) {
  271. for (let index = 0; index < value.length; index++) collectExpressionPaths(value[index], `${path}[${index}]`, output)
  272. return
  273. }
  274. if (!isRecord(value)) return
  275. for (const [key, child] of Object.entries(value)) collectExpressionPaths(child, `${path}.${key}`, output)
  276. }
  277. function isJsExpr(value: unknown): value is JsExpr {
  278. return isRecord(value) && typeof value.__jsExpr === 'string'
  279. }
  280. function isRecord(value: unknown): value is Record<string, unknown> {
  281. return value !== null && typeof value === 'object'
  282. }
  283. function isUnknownArray(value: unknown): value is unknown[] {
  284. return Array.isArray(value)
  285. }