verify-cordis-config.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /**
  2. * Validate Cordis Loader entry metadata and package resolution.
  3. *
  4. * The Loader interpolates a plugin entry's `config` (after declared injections
  5. * activate, against that plugin context) and the entry `disabled` field (at
  6. * every mount decision, against the loader context). Every other entry
  7. * metadata field stays static, so an expression there remains truthy data and
  8. * silently changes composition. Shipped and test-only dsh overlays resolve
  9. * named plugins from the CLI application's owning manifest; package-owned
  10. * Loader fixtures resolve from their package manifest.
  11. */
  12. import { globSync, readFileSync } from 'node:fs'
  13. import { dirname, relative, resolve } from 'node:path'
  14. import { Script } from 'node:vm'
  15. import ts from 'typescript'
  16. import { cordisConfigFiles } from './cordis-config-files.ts'
  17. import { isCordisGroupEntry, isJsExpr, loadCordisYaml } from './cordis-yaml.ts'
  18. export interface PackageManifest {
  19. name?: string
  20. dependencies?: Record<string, string>
  21. devDependencies?: Record<string, string>
  22. optionalDependencies?: Record<string, string>
  23. dsh?: { bundle?: { patch?: string } }
  24. }
  25. export interface PluginReference {
  26. file: string
  27. name: string
  28. }
  29. const root = resolve(import.meta.dirname, '..')
  30. // These overlays are consumed by the built dsh app, so their bare specifiers
  31. // resolve from apps/cli.
  32. const appOverlayFiles = new Set([
  33. ...globSync('apps/cli/config/examples/**/*.yml', { cwd: root }),
  34. ])
  35. const metadataFields = ['id', 'name', 'group', 'inject', 'intercept', 'isolate'] as const
  36. /** The adaptive directory-picker chooser package (mounts a backend row at boot). */
  37. const CHOOSER_PACKAGE = '@deepseek-ai/dsh-host-directory-picker-auto'
  38. /**
  39. * The packages the chooser mounts by runtime string (mirror of its exported
  40. * `BACKEND_PACKAGES` and `SURFACE_PACKAGES`), invisible to yml-row scanning: a
  41. * composition mounting the chooser must resolve every one, or keyless Linux CI
  42. * (which only ever resolves `browse`) hides a dropped `-native` dependency
  43. * until a macOS boot.
  44. */
  45. const CHOOSER_BACKEND_PACKAGES = [
  46. '@deepseek-ai/dsh-host-directory-picker-native',
  47. '@deepseek-ai/dsh-host-directory-picker-browse',
  48. '@deepseek-ai/dsh-client-ui-directory-picker-browse',
  49. '@deepseek-ai/dsh-client-ui-directory-picker-native',
  50. ]
  51. const errors: string[] = []
  52. const pluginReferences: PluginReference[] = []
  53. if (import.meta.main) {
  54. const files = cordisConfigFiles(root)
  55. for (const file of files) {
  56. const document = loadCordisYaml(readFileSync(resolve(root, file), 'utf8'))
  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(...validateAppResolution())
  66. errors.push(...validatePackageTestResolution())
  67. errors.push(...packageTestFixtureDependencyErrors())
  68. errors.push(...validateSourcePlaneResolution())
  69. errors.push(...validatePresetPlaneSeparation())
  70. errors.push(...validateClientHalvesDeclared())
  71. if (errors.length > 0) {
  72. console.error('verify-cordis-config: invalid Loader metadata or plugin package resolution:')
  73. for (const error of errors) console.error(`- ${error}`)
  74. process.exitCode = 1
  75. } else {
  76. console.log(`verify-cordis-config: ${files.length} config files passed.`)
  77. }
  78. }
  79. /**
  80. * A browser plugin must declare the browser half it ships.
  81. *
  82. * The browser roster is discovered by scanning composed packages for a
  83. * `dsh.client` block, and the node half of a surface plugin is an empty
  84. * `apply`. A `packages/client` package that exports `./client` without that
  85. * block therefore composes, activates, and contributes nothing — its bundle is
  86. * never served and no error is raised anywhere. The mismatch is invisible in
  87. * the composition file, so it is checked against the manifests instead. Only
  88. * this group is checked: a Host package's `./client` export is the typed wire
  89. * face its browser consumers import, not a plugin the roster serves.
  90. * @returns one violation per client package whose `./client` export and
  91. * `dsh.client` declaration disagree.
  92. */
  93. function validateClientHalvesDeclared(): string[] {
  94. return globSync('packages/client/*/package.json', { cwd: root }).flatMap((manifestPath) => {
  95. const manifest = readManifest(manifestPath) as PackageManifest & {
  96. exports?: Record<string, unknown>
  97. dsh?: { client?: unknown }
  98. }
  99. const shipsClient = manifest.exports !== undefined && Object.hasOwn(manifest.exports, './client')
  100. const declaresClient = manifest.dsh?.client !== undefined
  101. if (shipsClient === declaresClient) return []
  102. return [shipsClient
  103. ? `${manifestPath}: exports "./client" but declares no dsh.client, so its browser half is never served`
  104. : `${manifestPath}: declares dsh.client but exports no "./client" entry to serve`]
  105. })
  106. }
  107. /**
  108. * No shipped agent preset may repeat a row the host composition still runs.
  109. *
  110. * A preset contributes what ONE session adds to the host's registries. A row
  111. * active on both planes is therefore mounted twice — once per process and once
  112. * per session — and what that costs depends on what the row does: a provider
  113. * behind an `isolate` realm shadows the host's for its own consumers, so a host
  114. * contributor to that service reaches nobody; a row that registers into a host
  115. * singleton registers once per live session, so the second one collides.
  116. *
  117. * Both failure modes have occurred. A preset-local provider once shadowed the
  118. * host route that its consumer needed, and a host-registry contribution once
  119. * registered again for every live session until the second registration threw.
  120. * Neither changes a tool catalog, so no catalog assertion can see them — and the
  121. * shipped presets are near-copies of each other, so a fix applied to three of
  122. * four is the normal failure.
  123. * @returns one diagnostic per preset row that is also active on the host plane.
  124. */
  125. function validatePresetPlaneSeparation(): string[] {
  126. const problems: string[] = []
  127. // The shipped Web surface is two bundle patch layers over an empty root.
  128. const hostFile = 'packages/bundle/base/cordis.patch.yml'
  129. const overlayFile = 'packages/bundle/web-app/cordis.patch.yml'
  130. const hostRows = rowIds(hostFile)
  131. const overlay = loadEntries(overlayFile)
  132. const disabled = new Set<string>()
  133. for (const entry of overlay) {
  134. if (!isRecord(entry)) continue
  135. if (entry.disabled === true && typeof entry.id === 'string') disabled.add(entry.id)
  136. }
  137. // The overlay's own inserts are host-plane too; its disables take them back out.
  138. const active = new Set([...hostRows, ...rowIds(overlayFile)].filter(id => !disabled.has(id)))
  139. for (const file of globSync('packages/preset/agent-presets/presets/*/agent.cordis.yml', { cwd: root })) {
  140. for (const id of rowIds(file)) {
  141. if (!active.has(id)) continue
  142. problems.push(
  143. `${file}: row "${id}" is also active in the host composition; `
  144. + 'a row belongs to exactly one plane',
  145. )
  146. }
  147. }
  148. return problems
  149. }
  150. /** Every entry of one config file, or an empty list when it is not an entry array. */
  151. function loadEntries(file: string): unknown[] {
  152. const document = loadCordisYaml(readFileSync(resolve(root, file), 'utf8'))
  153. return isUnknownArray(document) ? document : []
  154. }
  155. /**
  156. * Row ids declared anywhere in one config file, including inside group `config`
  157. * lists — a preset nests most of its rows in `isolate` groups.
  158. * @param file - repository-relative config path.
  159. * @returns the declared ids.
  160. */
  161. function rowIds(file: string): Set<string> {
  162. const ids = new Set<string>()
  163. const walk = (value: unknown): void => {
  164. if (isUnknownArray(value)) {
  165. for (const item of value) walk(item)
  166. return
  167. }
  168. if (!isRecord(value)) return
  169. if (typeof value.id === 'string' && typeof value.name === 'string') ids.add(value.id)
  170. for (const child of Object.values(value)) walk(child)
  171. }
  172. walk(loadEntries(file))
  173. return ids
  174. }
  175. function validateEntry(value: unknown, file: string, path: string): void {
  176. if (!isRecord(value)) {
  177. errors.push(`${file}${path}: entry must be an object`)
  178. return
  179. }
  180. recordPlugin(value, file)
  181. validateMetadata(value, file, path)
  182. if (isCordisGroupEntry(value)) {
  183. for (let index = 0; index < value.config.length; index++) {
  184. validateEntry(value.config[index], file, `${path}.config[${index}]`)
  185. }
  186. }
  187. if (isUnknownArray(value.insert)) {
  188. for (let index = 0; index < value.insert.length; index++) {
  189. validateEntry(value.insert[index], file, `${path}.insert[${index}]`)
  190. }
  191. }
  192. if (value.name !== '@deepseek-ai/cordis-plugin-include') return
  193. const config = value.config
  194. if (!isRecord(config) || !isUnknownArray(config.patches)) return
  195. for (let index = 0; index < config.patches.length; index++) {
  196. const patch = config.patches[index]
  197. const patchPath = `${path}.config.patches[${index}]`
  198. if (!isRecord(patch)) continue
  199. recordPlugin(patch, file)
  200. validateMetadata(patch, file, patchPath)
  201. if (!isUnknownArray(patch.insert)) continue
  202. for (let insertIndex = 0; insertIndex < patch.insert.length; insertIndex++) {
  203. validateEntry(patch.insert[insertIndex], file, `${patchPath}.insert[${insertIndex}]`)
  204. }
  205. }
  206. }
  207. function recordPlugin(entry: Record<string, unknown>, file: string): void {
  208. if (typeof entry.name === 'string') pluginReferences.push({ file, name: entry.name })
  209. }
  210. function validateAppResolution(): string[] {
  211. const violations: string[] = []
  212. const bundleManifests = bundleManifestPaths()
  213. // App overlays (and any config left under apps/cli/config) resolve from the
  214. // dsh app's own dependency surface — the profile module fallback mirrors it.
  215. const appManifest = readManifest('apps/cli/package.json')
  216. const appDependencies = {
  217. ...appManifest.dependencies,
  218. // The fallback also links every in-box bundle's own dependencies
  219. // (healProfilesModuleFallback). Optional Profile bundles stay outside the
  220. // app installation until that Profile installs them.
  221. ...Object.fromEntries(globSync('packages/bundle/*/package.json', { cwd: root })
  222. .flatMap(file => Object.entries(readManifest(file).dependencies ?? {}))),
  223. }
  224. const shipped = new Set(globSync('*.cordis.yml', { cwd: resolve(root, 'apps/cli/config') })
  225. .map(file => `apps/cli/config/${file}`))
  226. const appReferences = pluginReferences.filter(reference => shipped.has(reference.file) || appOverlayFiles.has(reference.file))
  227. violations.push(...missingPluginDependencies(
  228. appReferences,
  229. appDependencies,
  230. 'apps/cli/package.json dependencies or a bundle manifest',
  231. ))
  232. const appTestReferences = pluginReferences.filter(reference => reference.file.startsWith('apps/cli/tests/'))
  233. violations.push(...missingPluginDependencies(
  234. appTestReferences,
  235. { ...appManifest.dependencies, ...appManifest.devDependencies },
  236. 'apps/cli/package.json dependencies or devDependencies',
  237. ))
  238. // Each bundle's patch rows must resolve from that bundle's own dependencies:
  239. // per-layer resolution anchors on the bundle package directory.
  240. for (const manifestPath of bundleManifests) {
  241. const bundleDir = manifestPath.replace(/\/package\.json$/, '')
  242. const manifest = readManifest(manifestPath)
  243. const patch = manifest.dsh?.bundle?.patch
  244. if (typeof patch !== 'string') continue
  245. const patchFile = relative(root, resolve(root, bundleDir, patch)).replaceAll('\\', '/')
  246. const references = pluginReferences.filter(reference => reference.file === patchFile)
  247. violations.push(...bundlePluginDependencyErrors(manifestPath, manifest, references))
  248. }
  249. return violations
  250. }
  251. /**
  252. * Package-owned Loader fixtures resolve named plugins from their package's
  253. * dependency surface, not from a repository-level test umbrella.
  254. * @returns one violation per configured package absent from the owner manifest.
  255. */
  256. function validatePackageTestResolution(): string[] {
  257. const referencesByManifest = new Map<string, PluginReference[]>()
  258. for (const reference of pluginReferences) {
  259. const manifestPath = packageTestManifestPath(reference.file)
  260. if (manifestPath === undefined) continue
  261. const references = referencesByManifest.get(manifestPath) ?? []
  262. references.push(reference)
  263. referencesByManifest.set(manifestPath, references)
  264. }
  265. return [...referencesByManifest].flatMap(([manifestPath, references]) =>
  266. packageTestPluginDependencyErrors(manifestPath, readManifest(manifestPath), references))
  267. }
  268. /**
  269. * Validate the named plugins one package-owned Loader fixture resolves.
  270. * Self-references use Node package self-resolution; every other package must
  271. * be an ordinary production or test dependency of the owner.
  272. * @param manifestPath Repository-relative owner manifest path.
  273. * @param manifest Parsed owner manifest.
  274. * @param references Named plugin references from owner-local test configs.
  275. * @returns Missing dependency diagnostics.
  276. */
  277. export function packageTestPluginDependencyErrors(
  278. manifestPath: string,
  279. manifest: PackageManifest,
  280. references: readonly PluginReference[],
  281. ): string[] {
  282. return missingPluginDependencies(
  283. references.filter(reference => packageNameFromSpecifier(reference.name) !== manifest.name),
  284. { ...manifest.dependencies, ...manifest.devDependencies },
  285. `${manifestPath} dependencies or devDependencies`,
  286. )
  287. }
  288. /**
  289. * Validate imports made by fixture modules adjacent to package-owned Loader
  290. * configs. These files execute as plain Node/tsx children, so a stale root
  291. * `node_modules` link must not hide an undeclared dependency.
  292. * @param repoRoot Repository root to scan.
  293. * @returns Missing dependency diagnostics.
  294. */
  295. export function packageTestFixtureDependencyErrors(repoRoot: string = root): string[] {
  296. const fixtureDirectories = new Set(cordisConfigFiles(repoRoot)
  297. .filter(file => packageTestManifestPath(file) !== undefined)
  298. .map(file => dirname(file).replaceAll('\\', '/')))
  299. if (fixtureDirectories.size === 0) {
  300. return ['package test fixture dependency scan found no package-owned Loader configs']
  301. }
  302. const referencesByManifest = new Map<string, PluginReference[]>()
  303. let fixtureModuleCount = 0
  304. for (const fixtureDirectory of fixtureDirectories) {
  305. const files = globSync([
  306. `${fixtureDirectory}/**/*.ts`,
  307. `${fixtureDirectory}/**/*.mjs`,
  308. ], { cwd: repoRoot })
  309. fixtureModuleCount += files.length
  310. for (const file of files) {
  311. const manifestPath = packageTestManifestPath(file)
  312. if (manifestPath === undefined) continue
  313. const references = referencesByManifest.get(manifestPath) ?? []
  314. const source = readFileSync(resolve(repoRoot, file), 'utf8')
  315. for (const imported of ts.preProcessFile(source, true, true).importedFiles) {
  316. references.push({ file: file.replaceAll('\\', '/'), name: imported.fileName })
  317. }
  318. referencesByManifest.set(manifestPath, references)
  319. }
  320. }
  321. if (fixtureModuleCount === 0) {
  322. return ['package test fixture dependency scan found no fixture modules beside Loader configs']
  323. }
  324. return [...referencesByManifest].flatMap(([manifestPath, references]) =>
  325. packageTestPluginDependencyErrors(
  326. manifestPath,
  327. readManifest(manifestPath, repoRoot),
  328. references,
  329. ))
  330. }
  331. /** Owner manifest for a package-local test path. */
  332. function packageTestManifestPath(file: string): string | undefined {
  333. const match = /^(packages\/[^/]+\/[^/]+)\/tests(?:\/|$)/.exec(file.replaceAll('\\', '/'))
  334. return match?.[1] === undefined ? undefined : `${match[1]}/package.json`
  335. }
  336. /**
  337. * Discover workspace Bundle packages from their manifest declaration.
  338. * @param repoRoot Repository root to scan.
  339. * @returns Sorted slash-normalized repository-relative package manifest paths.
  340. */
  341. export function bundleManifestPaths(repoRoot: string = root): string[] {
  342. return globSync('packages/*/*/package.json', { cwd: repoRoot })
  343. .filter(path => typeof readManifest(path, repoRoot).dsh?.bundle?.patch === 'string')
  344. .map(path => path.replaceAll('\\', '/'))
  345. .sort()
  346. }
  347. /**
  348. * Validate plugin packages referenced by one Bundle patch.
  349. * @param manifestPath Repository-relative Bundle manifest path.
  350. * @param manifest Parsed Bundle manifest.
  351. * @param references Plugin rows read from the Bundle package directory.
  352. * @returns Missing production dependency diagnostics.
  353. */
  354. export function bundlePluginDependencyErrors(
  355. manifestPath: string,
  356. manifest: PackageManifest,
  357. references: readonly PluginReference[],
  358. ): string[] {
  359. return missingPluginDependencies(
  360. // A Bundle may mount its own package (for example, its provider or runtime row).
  361. references.filter(reference => packageNameFromSpecifier(reference.name) !== manifest.name),
  362. manifest.dependencies ?? {},
  363. `${manifestPath} dependencies`,
  364. )
  365. }
  366. /**
  367. * Every configured specifier of a local workspace package must resolve through
  368. * the tsconfig `paths` facade to a `.ts`/`.tsx` source file. The `dsh` source
  369. * launch (tsx) and vitest resolve in the source plane; without a `paths` match
  370. * they fall back to package `exports`, which reach built `lib/` — present on a
  371. * built dev tree, absent on a clean one — so a missing mapping boots locally
  372. * yet breaks every clean checkout. Anything but a `.ts`/`.tsx` hit (a `.d.ts`
  373. * or `.js` under built `lib/`) is that artifact-plane fallback, not source.
  374. */
  375. function validateSourcePlaneResolution(): string[] {
  376. const violations: string[] = []
  377. const localPackages = localPackageDirectories()
  378. const config = ts.readConfigFile(resolve(root, 'tsconfig.base.json'), path => ts.sys.readFile(path))
  379. if (config.error !== undefined) {
  380. throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))
  381. }
  382. const { options, errors: optionErrors } = ts.convertCompilerOptionsFromJson(
  383. (config.config as { compilerOptions?: unknown }).compilerOptions,
  384. root,
  385. 'tsconfig.base.json',
  386. )
  387. if (optionErrors.length > 0) {
  388. throw new Error(optionErrors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  389. }
  390. // convertCompilerOptionsFromJson leaves `pathsBasePath` unset, so relative
  391. // `paths` targets resolve against the host's current directory; anchor it to
  392. // the repository root to keep the gate cwd-independent.
  393. const host: ts.ModuleResolutionHost = {
  394. fileExists: path => ts.sys.fileExists(path),
  395. readFile: path => ts.sys.readFile(path),
  396. directoryExists: path => ts.sys.directoryExists(path),
  397. getCurrentDirectory: () => root,
  398. }
  399. const sourceExtensions = new Set<string>([ts.Extension.Ts, ts.Extension.Tsx])
  400. const containingFile = resolve(root, 'scripts/verify-cordis-config.ts')
  401. const locationsBySpecifier = new Map<string, Set<string>>()
  402. for (const reference of pluginReferences) {
  403. const packageName = packageNameFromSpecifier(reference.name)
  404. if (packageName === undefined || !localPackages.has(packageName)) continue
  405. const locations = locationsBySpecifier.get(reference.name) ?? new Set<string>()
  406. locations.add(reference.file)
  407. locationsBySpecifier.set(reference.name, locations)
  408. }
  409. for (const [specifier, locations] of locationsBySpecifier) {
  410. const resolved = ts.resolveModuleName(specifier, containingFile, options, host).resolvedModule
  411. if (resolved !== undefined && sourceExtensions.has(resolved.extension)) continue
  412. 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/)`)
  413. }
  414. return violations
  415. }
  416. function missingPluginDependencies(
  417. references: readonly PluginReference[],
  418. dependencies: Readonly<Record<string, string>>,
  419. dependencyOwner: string,
  420. ): string[] {
  421. const requiredPackages = new Map<string, Set<string>>()
  422. const require = (packageName: string, file: string): void => {
  423. const locations = requiredPackages.get(packageName) ?? new Set<string>()
  424. locations.add(file)
  425. requiredPackages.set(packageName, locations)
  426. }
  427. for (const reference of references) {
  428. const packageName = packageNameFromSpecifier(reference.name)
  429. if (packageName === undefined) continue
  430. require(packageName, reference.file)
  431. if (packageName === CHOOSER_PACKAGE) {
  432. for (const backend of CHOOSER_BACKEND_PACKAGES) require(backend, reference.file)
  433. }
  434. }
  435. return [...requiredPackages].flatMap(([packageName, locations]) => packageName in dependencies
  436. ? []
  437. : `${[...locations].join(', ')}: ${packageName} must be declared in ${dependencyOwner}`)
  438. }
  439. function readManifest(path: string, repoRoot: string = root): PackageManifest {
  440. return JSON.parse(readFileSync(resolve(repoRoot, path), 'utf8')) as PackageManifest
  441. }
  442. function localPackageDirectories(): Map<string, string> {
  443. const manifests = globSync(['packages/*/*/package.json', 'vendor/*/package.json'], { cwd: root })
  444. const packages = new Map<string, string>()
  445. for (const manifestPath of manifests) {
  446. const manifest = readManifest(manifestPath)
  447. if (manifest.name !== undefined) packages.set(manifest.name, resolve(root, dirname(manifestPath)))
  448. }
  449. return packages
  450. }
  451. function packageNameFromSpecifier(specifier: string): string | undefined {
  452. if (specifier.startsWith('.') || specifier.startsWith('/') || /^[a-z][a-z+.-]*:/i.test(specifier)) return undefined
  453. const segments = specifier.split('/')
  454. if (specifier.startsWith('@')) {
  455. return segments.length >= 2 ? `${segments[0]}/${segments[1]}` : undefined
  456. }
  457. return segments[0] || undefined
  458. }
  459. function validateMetadata(entry: Record<string, unknown>, file: string, path: string): void {
  460. for (const problem of metadataExpressionErrors(entry, path)) {
  461. errors.push(`${file}${problem}`)
  462. }
  463. }
  464. /**
  465. * Expression-node diagnostics for one entry. `disabled` is the single
  466. * interpolated metadata field: its own `!!js` expression node is allowed and
  467. * must parse, while expressions nested below it stay truthy data; every other
  468. * metadata field must stay fully static.
  469. * @param entry - one loader entry (or patch row).
  470. * @param path - the entry's diagnostic path prefix.
  471. * @returns one diagnostic per offending expression.
  472. */
  473. export function metadataExpressionErrors(entry: Record<string, unknown>, path: string): string[] {
  474. const problems: string[] = []
  475. for (const field of metadataFields) {
  476. if (!(field in entry)) continue
  477. const expressionPaths: string[] = []
  478. collectExpressionPaths(entry[field], `${path}.${field}`, expressionPaths)
  479. for (const expressionPath of expressionPaths) problems.push(`${expressionPath}: !!js is not interpolated here`)
  480. }
  481. const disabled = entry.disabled
  482. if (disabled !== undefined) {
  483. if (isJsExpr(disabled)) {
  484. const detail = disabledExpressionProblem(disabled.__jsExpr)
  485. if (detail !== undefined) problems.push(`${path}.disabled${detail}`)
  486. } else {
  487. // A non-expression value gates on Boolean() at mount; an expression
  488. // nested anywhere below it never evaluates, so it must stay literal.
  489. const expressionPaths: string[] = []
  490. collectExpressionPaths(disabled, `${path}.disabled`, expressionPaths)
  491. for (const expressionPath of expressionPaths) problems.push(`${expressionPath}: !!js is not interpolated here`)
  492. }
  493. }
  494. return problems
  495. }
  496. /**
  497. * Parse-only validation of a `disabled` expression: the Loader evaluates it
  498. * at every mount decision, and a syntax error would fail the boot — rejecting
  499. * it here moves that failure to the earliest resolvable point.
  500. * @param expression - the `!!js` expression text.
  501. * @returns the diagnostic suffix, or `undefined` when the expression parses.
  502. */
  503. function disabledExpressionProblem(expression: string): string | undefined {
  504. try {
  505. // Compilation only — constructing a Script does not execute its source.
  506. new Script(`(${expression})`)
  507. return undefined
  508. } catch (error) {
  509. const detail = error instanceof Error ? error.message : String(error)
  510. return `: disabled expression does not parse: ${detail}`
  511. }
  512. }
  513. function collectExpressionPaths(value: unknown, path: string, output: string[]): void {
  514. if (isJsExpr(value)) {
  515. output.push(path)
  516. return
  517. }
  518. if (isUnknownArray(value)) {
  519. for (let index = 0; index < value.length; index++) collectExpressionPaths(value[index], `${path}[${index}]`, output)
  520. return
  521. }
  522. if (!isRecord(value)) return
  523. for (const [key, child] of Object.entries(value)) collectExpressionPaths(child, `${path}.${key}`, output)
  524. }
  525. function isRecord(value: unknown): value is Record<string, unknown> {
  526. return value !== null && typeof value === 'object'
  527. }
  528. function isUnknownArray(value: unknown): value is unknown[] {
  529. return Array.isArray(value)
  530. }