verify-application-entrypoints.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /**
  2. * Enforce dsh profiles as the only supported Node application launcher.
  3. * Vendor CLIs, build tools, and test tools are explicit classifications
  4. * rather than implicit holes.
  5. */
  6. import { existsSync, globSync, readFileSync } from 'node:fs'
  7. import { resolve, sep } from 'node:path'
  8. import { pathToFileURL } from 'node:url'
  9. type ManifestBin = string | Record<string, string>
  10. interface PackageManifest {
  11. readonly bin?: unknown
  12. }
  13. interface RootManifest {
  14. readonly scripts?: Record<string, unknown>
  15. }
  16. interface DemoPolicy {
  17. readonly kind: 'dsh-direct' | 'dsh-wrapper'
  18. readonly wrapper?: string
  19. }
  20. /** Public product launcher plus the private build-only WebWorker packer. */
  21. const MANIFEST_BIN_ALLOWLIST = new Map<string, ManifestBin>([
  22. ['apps/cli/package.json', { dsh: 'lib/bin.js' }],
  23. ['packages/experimental/webworker-packer/package.json', { 'dsh-pack-vfs-image': './bin.js' }],
  24. ])
  25. /** Every JavaScript executable in an application or packaging workspace has one explicit role. */
  26. const EXECUTABLE_SOURCE_ALLOWLIST = new Map<string, string>([
  27. ['apps/cli/src/bin.ts', 'supported dsh application launcher'],
  28. ['packages/context/time-context/tests/fixtures/driver.ts', 'test-only subprocess driver'],
  29. ['packages/experimental/webworker-packer/bin.js', 'private build-only wrapper'],
  30. ['packages/experimental/webworker-packer/src/bin.ts', 'private build-only implementation'],
  31. ['packages/sdk/client/tests/fake-runtime.ts', 'test-only SDK runtime peer'],
  32. ['packages/session/session-telemetry-otel/tests/fixtures/driver.ts', 'test-only subprocess driver'],
  33. ['packages/shell/tool-pwsh/tests/fixtures/loader/driver.ts', 'test-only subprocess driver'],
  34. ['packages/subagent/subagent-acp/tests/fixtures/loader/driver.ts', 'test-only subprocess driver'],
  35. ['packages/subagent/subagent-claude-code/tests/fixtures/loader/driver.ts', 'test-only subprocess driver'],
  36. ['packages/subagent/subagent-codex/tests/fixtures/loader/driver.ts', 'test-only subprocess driver'],
  37. ['packages/subagent/subagent-dsh-sdk/tests/fixtures/loader/driver.ts', 'test-only subprocess driver'],
  38. ['packages/test-support/loader-smoke/tests/fixtures/headless-driver.ts', 'test-only subprocess driver'],
  39. ['packages/test-support/llm-mock-server/src/bin.ts', 'test-only model server'],
  40. ['python/sdk-runtime/runtime-bootstrap.mjs', 'private packaging-only runtime dispatcher'],
  41. ])
  42. /** Root demos are application wrappers and therefore must visibly select dsh. */
  43. const ROOT_DEMO_POLICIES = new Map<string, DemoPolicy>([
  44. ['demo:ptc', { kind: 'dsh-wrapper', wrapper: 'scripts/demo-ptc.mjs' }],
  45. ['demo:inspector', { kind: 'dsh-direct' }],
  46. ])
  47. const SOURCE_PATTERNS = [
  48. '*.ts',
  49. '*.js',
  50. '*.mjs',
  51. '*.cjs',
  52. 'apps/**/*.ts',
  53. 'apps/**/*.js',
  54. 'apps/**/*.mjs',
  55. 'apps/**/*.cjs',
  56. 'packages/**/*.ts',
  57. 'packages/**/*.js',
  58. 'packages/**/*.mjs',
  59. 'packages/**/*.cjs',
  60. 'python/sdk-runtime/*.mjs',
  61. ]
  62. const SOURCE_EXCLUDES = [
  63. '**/node_modules/**',
  64. '**/lib/**',
  65. '**/dist/**',
  66. '**/coverage/**',
  67. ]
  68. /** Convert a host path from glob output to the repository's slash form. */
  69. function repositoryPath(path: string): string {
  70. return path.split(sep).join('/')
  71. }
  72. /** Stable comparison for string and object npm `bin` declarations. */
  73. function normalizedBin(value: unknown): string | undefined {
  74. if (typeof value === 'string') return JSON.stringify(value)
  75. if (!isRecord(value)) return undefined
  76. const entries = Object.entries(value)
  77. if (!entries.every(([, target]) => typeof target === 'string')) return undefined
  78. return JSON.stringify(Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right))))
  79. }
  80. function manifestBinViolations(root: string): string[] {
  81. const failures: string[] = []
  82. const manifests = globSync(['apps/*/package.json', 'packages/*/*/package.json'], { cwd: root }).sort()
  83. for (const rawPath of manifests) {
  84. const path = repositoryPath(rawPath)
  85. const manifest = JSON.parse(readFileSync(resolve(root, path), 'utf8')) as PackageManifest
  86. if (manifest.bin === undefined) continue
  87. const expected = MANIFEST_BIN_ALLOWLIST.get(path)
  88. if (expected === undefined) {
  89. failures.push(`${path}: package bin bypasses the dsh launcher; applications use apps/cli profiles`)
  90. continue
  91. }
  92. if (normalizedBin(manifest.bin) !== normalizedBin(expected)) {
  93. failures.push(`${path}: classified bin must remain ${JSON.stringify(expected)}, got ${JSON.stringify(manifest.bin)}`)
  94. }
  95. }
  96. return failures
  97. }
  98. function executableSourceViolations(root: string): string[] {
  99. const failures: string[] = []
  100. for (const rawPath of globSync(SOURCE_PATTERNS, { cwd: root, exclude: SOURCE_EXCLUDES }).sort()) {
  101. const path = repositoryPath(rawPath)
  102. const source = readFileSync(resolve(root, path), 'utf8')
  103. if (!source.startsWith('#!')) continue
  104. if (!EXECUTABLE_SOURCE_ALLOWLIST.has(path)) {
  105. failures.push(`${path}: executable source has no application/build/test classification`)
  106. }
  107. }
  108. return failures
  109. }
  110. function referencesDshCli(source: string): boolean {
  111. return source.includes('apps/cli/src/bin.ts')
  112. }
  113. function referencesPackageEntry(source: string): boolean {
  114. return /packages\/[^/\s'"`]+\/[^/\s'"`]+\/(?:src|lib)\/[^\s'"`]+/.test(source)
  115. }
  116. function rootDemoViolations(root: string): string[] {
  117. const manifestPath = resolve(root, 'package.json')
  118. if (!existsSync(manifestPath)) return []
  119. const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as RootManifest
  120. const failures: string[] = []
  121. for (const [name, commandValue] of Object.entries(manifest.scripts ?? {}).sort(([left], [right]) => left.localeCompare(right))) {
  122. if (!name.startsWith('demo:')) continue
  123. const command = typeof commandValue === 'string' ? commandValue : ''
  124. const policy = ROOT_DEMO_POLICIES.get(name)
  125. if (policy === undefined) {
  126. failures.push(`package.json scripts.${name}: demo launcher has no explicit dsh or in-process classification`)
  127. continue
  128. }
  129. if (policy.kind === 'dsh-direct') {
  130. if (!referencesDshCli(command)) failures.push(`package.json scripts.${name}: application demo must launch apps/cli/src/bin.ts`)
  131. if (referencesPackageEntry(command)) failures.push(`package.json scripts.${name}: application demo must not launch a package entry directly`)
  132. continue
  133. }
  134. const wrapper = policy.wrapper
  135. if (wrapper === undefined || !command.includes(wrapper)) {
  136. failures.push(`package.json scripts.${name}: classified wrapper must be ${String(wrapper)}`)
  137. continue
  138. }
  139. const wrapperPath = resolve(root, wrapper)
  140. if (!existsSync(wrapperPath)) {
  141. failures.push(`${wrapper}: classified demo wrapper is missing`)
  142. continue
  143. }
  144. const source = readFileSync(wrapperPath, 'utf8')
  145. if (!referencesDshCli(source)) failures.push(`${wrapper}: application demo wrapper must launch apps/cli/src/bin.ts`)
  146. if (referencesPackageEntry(source)) failures.push(`${wrapper}: application demo wrapper must not launch a package entry directly`)
  147. }
  148. return failures
  149. }
  150. /**
  151. * Find unsupported application entrypoints below a repository root.
  152. * @param root - repository or test-fixture root.
  153. * @returns deterministic path-qualified violations.
  154. */
  155. export function applicationEntrypointViolations(root: string): string[] {
  156. return [
  157. ...manifestBinViolations(root),
  158. ...executableSourceViolations(root),
  159. ...rootDemoViolations(root),
  160. ]
  161. }
  162. function isRecord(value: unknown): value is Record<string, unknown> {
  163. return typeof value === 'object' && value !== null && !Array.isArray(value)
  164. }
  165. if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  166. const root = resolve(import.meta.dirname, '..')
  167. const failures = applicationEntrypointViolations(root)
  168. if (failures.length > 0) {
  169. console.error('verify-application-entrypoints: unsupported launcher(s):')
  170. for (const failure of failures) console.error(` ${failure}`)
  171. process.exitCode = 1
  172. } else {
  173. console.log('verify-application-entrypoints: dsh is the only supported Node application launcher.')
  174. }
  175. }