verify-client-packages.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. /**
  2. * Verify client package modes, npm dependency sections, and the synchronous
  3. * browser module-request graph.
  4. */
  5. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  6. import { dirname, resolve, sep } from 'node:path'
  7. import { pathToFileURL } from 'node:url'
  8. import ts from 'typescript'
  9. import { TypeScriptProject } from './ts-project.ts'
  10. const GATE = 'verify-client-packages'
  11. const CLIENT_MANIFEST_GLOB = 'packages/client/*/package.json'
  12. const MANIFEST_GLOBS = ['packages/*/*/package.json', 'apps/*/package.json', 'vendor/*/package.json']
  13. const CONFIG_GLOB = 'packages/*/*/tsdown.config.ts'
  14. const PLATFORM_SOURCE = 'packages/client/web/src/platform.ts'
  15. const PARSER_PRELOAD_SOURCE = 'packages/client/modules/src/index.ts'
  16. const STATIC_PRESET_SOURCE = 'packages/client/tsdown.client.ts'
  17. const CORDIS = '@deepseek-ai/cordis'
  18. const DSH_PREFIX = '@deepseek-ai/dsh-'
  19. const CLIENT_WEB = '@deepseek-ai/dsh-client-web'
  20. /** One workspace package's browser-module declaration. */
  21. export interface ClientDeclaration {
  22. readonly name: string
  23. readonly manifest: string
  24. readonly dynamic: boolean
  25. readonly external: readonly string[]
  26. /** Informational package dependencies declared by the row. */
  27. readonly inject: readonly string[]
  28. }
  29. /** One package directly under packages/client. */
  30. export interface ClientPackage extends ClientDeclaration {
  31. readonly staticLinked: boolean
  32. readonly sourceUses: Readonly<Record<string, readonly string[]>>
  33. readonly runtimeSourceUses: Readonly<Record<string, readonly string[]>>
  34. readonly dependencies: Readonly<Record<string, string>>
  35. readonly peerDependencies: Readonly<Record<string, string>>
  36. readonly devDependencies: Readonly<Record<string, string>>
  37. }
  38. /** Complete source-plane input to the client package verifier. */
  39. export interface ClientPackageFacts {
  40. readonly packages: readonly ClientPackage[]
  41. readonly declarations: readonly ClientDeclaration[]
  42. readonly staticLinkedPackages: ReadonlySet<string>
  43. readonly platformModules: readonly string[]
  44. readonly preloadedExternals: readonly string[]
  45. readonly parserPreloadIds: readonly string[]
  46. readonly malformed: readonly string[]
  47. }
  48. /** Result of reading every workspace browser-module declaration. */
  49. export interface ClientDeclarations {
  50. readonly declarations: ClientDeclaration[]
  51. readonly malformed: string[]
  52. }
  53. /**
  54. * Collect bare packages referenced by one production source file.
  55. * @param path - File path used to select TypeScript's parser mode.
  56. * @param source - Source text to inspect.
  57. * @returns Bare package names referenced by imports, declarations, or JSX.
  58. */
  59. export function collectSourcePackageUses(path: string, source: string): Set<string> {
  60. const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
  61. return collectSourceFilePackageUses(sourceFile, false)
  62. }
  63. /**
  64. * Collect bare packages whose values one production source file reaches at runtime.
  65. * @param path - File path used to select TypeScript's parser mode.
  66. * @param source - Source text to inspect.
  67. * @returns Bare package names retained by runtime imports, exports, requires, or JSX.
  68. */
  69. export function collectRuntimeSourcePackageUses(path: string, source: string): Set<string> {
  70. const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
  71. return collectSourceFilePackageUses(sourceFile, true)
  72. }
  73. function importCarriesRuntimeValue(node: ts.ImportDeclaration): boolean {
  74. const clause = node.importClause
  75. if (clause === undefined) return true
  76. if (clause.phaseModifier === ts.SyntaxKind.TypeKeyword) return false
  77. const bindings = clause.namedBindings
  78. return clause.name !== undefined
  79. || bindings === undefined
  80. || ts.isNamespaceImport(bindings)
  81. || bindings.elements.length === 0
  82. || bindings.elements.some(element => !element.isTypeOnly)
  83. }
  84. function exportCarriesRuntimeValue(node: ts.ExportDeclaration): boolean {
  85. if (node.isTypeOnly) return false
  86. const clause = node.exportClause
  87. if (clause === undefined || ts.isNamespaceExport(clause)) return true
  88. return clause.elements.length === 0 || clause.elements.some(element => !element.isTypeOnly)
  89. }
  90. function collectSourceFilePackageUses(sourceFile: ts.SourceFile, runtimeOnly: boolean): Set<string> {
  91. const uses = new Set<string>()
  92. const add = (specifier: ts.Expression | undefined): void => {
  93. if (specifier === undefined || !ts.isStringLiteral(specifier) || !isBareSpecifier(specifier.text)) return
  94. uses.add(packageNameOf(specifier.text))
  95. }
  96. const visit = (node: ts.Node): void => {
  97. if (ts.isImportDeclaration(node)) {
  98. if (!runtimeOnly || importCarriesRuntimeValue(node)) add(node.moduleSpecifier)
  99. } else if (ts.isExportDeclaration(node)) {
  100. if (!runtimeOnly || exportCarriesRuntimeValue(node)) add(node.moduleSpecifier)
  101. } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
  102. if (!runtimeOnly || !node.isTypeOnly) add(node.moduleReference.expression)
  103. } else if (!runtimeOnly && ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
  104. add(node.argument.literal)
  105. } else if (ts.isCallExpression(node)
  106. && (node.expression.kind === ts.SyntaxKind.ImportKeyword
  107. || ts.isIdentifier(node.expression) && node.expression.text === 'require')) {
  108. add(node.arguments[0])
  109. } else if (!runtimeOnly && ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)) {
  110. add(node.name)
  111. } else if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node)) {
  112. uses.add('react')
  113. }
  114. ts.forEachChild(node, visit)
  115. }
  116. visit(sourceFile)
  117. return uses
  118. }
  119. /**
  120. * Read browser-module declarations from workspace manifests.
  121. * @param root - Absolute repository root.
  122. * @returns Declarations and malformed dsh.client fields.
  123. */
  124. export function readClientDeclarations(root: string): ClientDeclarations {
  125. const malformed: string[] = []
  126. const declarations = globSync(MANIFEST_GLOBS, { cwd: root })
  127. .map(normalizePath)
  128. .sort()
  129. .flatMap(path => readDeclaration(root, path, malformed) ?? [])
  130. return { declarations, malformed }
  131. }
  132. /**
  133. * Return every client package policy violation.
  134. * @param facts - Package modes, manifests, source uses, and platform module lists.
  135. * @returns Stable self-contained diagnostics.
  136. */
  137. export function collectClientPackageViolations(facts: ClientPackageFacts): string[] {
  138. return [
  139. ...facts.malformed,
  140. ...collectModeViolations(facts),
  141. ...collectDependencyViolations(facts),
  142. ...collectModuleViolations(facts),
  143. ].sort((left, right) => left.localeCompare(right))
  144. }
  145. interface ManifestDocument {
  146. readonly path: string
  147. readonly manifest: Manifest
  148. changed: boolean
  149. }
  150. type DependencySection = 'dependencies' | 'peerDependencies' | 'devDependencies'
  151. /**
  152. * Repair manifest declarations whose intended result follows uniquely from the policy.
  153. * @param root - Absolute repository root.
  154. * @param facts - Facts used by the verification pass.
  155. * @returns Repository-relative manifests written by the fixer.
  156. */
  157. export function fixClientPackageManifests(root: string, facts: ClientPackageFacts): string[] {
  158. const documents = new Map<string, ManifestDocument>()
  159. const document = (path: string): ManifestDocument => {
  160. const cached = documents.get(path)
  161. if (cached !== undefined) return cached
  162. const loaded: ManifestDocument = {
  163. path,
  164. manifest: JSON.parse(readFileSync(resolve(root, path), 'utf8')) as Manifest,
  165. changed: false,
  166. }
  167. documents.set(path, loaded)
  168. return loaded
  169. }
  170. const baseline = new Set([...facts.platformModules, ...facts.preloadedExternals])
  171. for (const declaration of facts.declarations.filter(entry => entry.dynamic)) {
  172. const target = document(declaration.manifest)
  173. const dsh = isRecord(target.manifest.dsh) ? target.manifest.dsh : undefined
  174. const client = isRecord(dsh?.client) ? dsh.client : undefined
  175. if (client === undefined) continue
  176. target.changed = normalizeClientArray(client, 'inject', () => false) || target.changed
  177. target.changed = normalizeClientArray(
  178. client,
  179. 'external',
  180. value => baseline.has(value) || rowPackageOf(value, new Set([declaration.name])) === declaration.name,
  181. ) || target.changed
  182. }
  183. const staticInputs = new Set([
  184. ...facts.staticLinkedPackages,
  185. ...facts.platformModules.map(packageNameOf),
  186. ])
  187. staticInputs.delete(CORDIS)
  188. const inferredRanges = dependencyRangeCandidates(root)
  189. for (const pkg of facts.packages) {
  190. const target = document(pkg.manifest)
  191. const expected = expectedSections(pkg, staticInputs)
  192. for (const [name, rule] of expected) {
  193. const range = preferredRange(target.manifest, name, rule.kind, inferredRanges)
  194. if (range === undefined) continue
  195. target.changed = rule.kind === 'dependency'
  196. ? ensureDependencyOnly(target.manifest, name, range) || target.changed
  197. : rule.kind === 'dev'
  198. ? ensureDevOnly(target.manifest, name, range) || target.changed
  199. : ensurePeerDev(target.manifest, name, range) || target.changed
  200. }
  201. if (pkg.dynamic) {
  202. const productionNames = new Set([
  203. ...Object.keys(section(target.manifest, 'dependencies')),
  204. ...Object.keys(section(target.manifest, 'peerDependencies')),
  205. ])
  206. for (const name of productionNames) {
  207. if (expected.has(name)) continue
  208. const range = preferredRange(
  209. target.manifest,
  210. name,
  211. staticInputs.has(name) ? 'dev' : 'peer-dev',
  212. inferredRanges,
  213. )
  214. if (range === undefined) continue
  215. if (staticInputs.has(name)) {
  216. target.changed = ensureDevOnly(target.manifest, name, range) || target.changed
  217. } else if (section(target.manifest, 'dependencies')[name] !== undefined && isInternalDsh(name)) {
  218. target.changed = ensurePeerDev(target.manifest, name, range) || target.changed
  219. }
  220. }
  221. }
  222. for (const [name, range] of Object.entries(section(target.manifest, 'peerDependencies'))) {
  223. target.changed = setDependency(target.manifest, 'devDependencies', name, range) || target.changed
  224. }
  225. target.changed = deleteEmptySections(target.manifest) || target.changed
  226. }
  227. const changed = [...documents.values()].filter(target => target.changed).sort((left, right) =>
  228. left.path.localeCompare(right.path))
  229. for (const target of changed) {
  230. writeFileSync(resolve(root, target.path), JSON.stringify(target.manifest, null, 2) + '\n')
  231. }
  232. return changed.map(target => target.path)
  233. }
  234. function normalizeClientArray(
  235. client: Record<string, unknown>,
  236. field: 'external' | 'inject',
  237. remove: (value: string) => boolean,
  238. ): boolean {
  239. const value = client[field]
  240. if (!Array.isArray(value) || value.some(entry => typeof entry !== 'string')) return false
  241. const seen = new Set<string>()
  242. const normalized = value.filter((entry: string) => {
  243. if (entry === '' || seen.has(entry) || remove(entry)) return false
  244. seen.add(entry)
  245. return true
  246. })
  247. if (normalized.length === value.length && normalized.every((entry, index) => entry === value[index])) return false
  248. if (normalized.length === 0) {
  249. if (field === 'external') delete client.external
  250. else delete client.inject
  251. } else {
  252. client[field] = normalized
  253. }
  254. return true
  255. }
  256. function ensureDevOnly(manifest: Manifest, name: string, range: string): boolean {
  257. let changed = deleteDependency(manifest, 'dependencies', name)
  258. changed = deleteDependency(manifest, 'peerDependencies', name) || changed
  259. return setDependency(manifest, 'devDependencies', name, range) || changed
  260. }
  261. function ensureDependencyOnly(manifest: Manifest, name: string, range: string): boolean {
  262. let changed = deleteDependency(manifest, 'peerDependencies', name)
  263. changed = deleteDependency(manifest, 'devDependencies', name) || changed
  264. return setDependency(manifest, 'dependencies', name, range) || changed
  265. }
  266. function ensurePeerDev(manifest: Manifest, name: string, range: string): boolean {
  267. let changed = deleteDependency(manifest, 'dependencies', name)
  268. changed = setDependency(manifest, 'peerDependencies', name, range) || changed
  269. return setDependency(manifest, 'devDependencies', name, range) || changed
  270. }
  271. function setDependency(manifest: Manifest, field: DependencySection, name: string, range: string): boolean {
  272. const dependencies = mutableSection(manifest, field)
  273. if (dependencies[name] === range) return false
  274. dependencies[name] = range
  275. return true
  276. }
  277. function deleteDependency(manifest: Manifest, field: DependencySection, name: string): boolean {
  278. const dependencies = section(manifest, field)
  279. if (dependencies[name] === undefined) return false
  280. manifest[field] = Object.fromEntries(Object.entries(dependencies).filter(([key]) => key !== name))
  281. return true
  282. }
  283. function deleteEmptySections(manifest: Manifest): boolean {
  284. let changed = false
  285. for (const field of ['dependencies', 'peerDependencies', 'devDependencies'] as const) {
  286. if (manifest[field] === undefined || Object.keys(section(manifest, field)).length > 0) continue
  287. if (field === 'dependencies') delete manifest.dependencies
  288. else if (field === 'peerDependencies') delete manifest.peerDependencies
  289. else delete manifest.devDependencies
  290. changed = true
  291. }
  292. return changed
  293. }
  294. function preferredRange(
  295. manifest: Manifest,
  296. name: string,
  297. kind: ExpectedRule['kind'],
  298. inferred: ReadonlyMap<string, ReadonlySet<string>>,
  299. ): string | undefined {
  300. const order: readonly DependencySection[] = kind === 'dependency'
  301. ? ['dependencies', 'devDependencies', 'peerDependencies']
  302. : kind === 'dev'
  303. ? ['devDependencies', 'peerDependencies', 'dependencies']
  304. : ['peerDependencies', 'devDependencies', 'dependencies']
  305. for (const field of order) {
  306. const range = section(manifest, field)[name]
  307. if (range !== undefined) return range
  308. }
  309. if (isInternalDsh(name)) return 'workspace:^'
  310. const candidates = inferred.get(name)
  311. return candidates?.size === 1 ? [...candidates][0] : undefined
  312. }
  313. function dependencyRangeCandidates(root: string): Map<string, Set<string>> {
  314. const candidates = new Map<string, Set<string>>()
  315. const paths = globSync([
  316. 'package.json',
  317. ...MANIFEST_GLOBS,
  318. 'website/package.json',
  319. ], { cwd: root }).map(normalizePath)
  320. for (const path of new Set(paths)) {
  321. const manifest = JSON.parse(readFileSync(resolve(root, path), 'utf8')) as Manifest
  322. for (const field of ['dependencies', 'peerDependencies', 'devDependencies'] as const) {
  323. for (const [name, range] of Object.entries(section(manifest, field))) {
  324. const ranges = candidates.get(name) ?? new Set<string>()
  325. ranges.add(range)
  326. candidates.set(name, ranges)
  327. }
  328. }
  329. }
  330. return candidates
  331. }
  332. function section(manifest: Manifest, field: DependencySection): Record<string, string> {
  333. return manifest[field] ?? {}
  334. }
  335. function mutableSection(manifest: Manifest, field: DependencySection): Record<string, string> {
  336. const value = manifest[field]
  337. if (value !== undefined) return value
  338. const created: Record<string, string> = {}
  339. manifest[field] = created
  340. return created
  341. }
  342. function collectModeViolations(facts: ClientPackageFacts): string[] {
  343. const violations: string[] = []
  344. for (const pkg of facts.packages) {
  345. if (pkg.dynamic && pkg.staticLinked) {
  346. violations.push(
  347. pkg.manifest + ': ' + pkg.name + ' declares dsh.client and uses the staticLinked preset;'
  348. + ' a client package must be dynamic or statically linked, not both',
  349. )
  350. } else if (!pkg.dynamic && !pkg.staticLinked) {
  351. violations.push(
  352. pkg.manifest + ': ' + pkg.name + ' has no supported client package mode;'
  353. + ' declare dsh.client or use the staticLinked preset',
  354. )
  355. }
  356. }
  357. const workspaceNames = new Set(facts.declarations.map(entry => entry.name))
  358. for (const specifier of facts.platformModules) {
  359. const owner = packageNameOf(specifier)
  360. if (!workspaceNames.has(owner) || owner === CORDIS || facts.staticLinkedPackages.has(owner)) continue
  361. violations.push(
  362. PLATFORM_SOURCE + ': seeded workspace module ' + JSON.stringify(specifier)
  363. + ' belongs to ' + owner + ', whose build does not use the staticLinked preset',
  364. )
  365. }
  366. const rows = rowNames(facts.declarations)
  367. for (const specifier of facts.preloadedExternals) {
  368. if (rowPackageOf(specifier, rows) === undefined) {
  369. violations.push(
  370. PLATFORM_SOURCE + ': parser-preloaded external ' + JSON.stringify(specifier)
  371. + ' has no dynamic dsh.client row',
  372. )
  373. }
  374. if (!facts.parserPreloadIds.includes(stripClientSuffix(specifier))) {
  375. violations.push(
  376. PLATFORM_SOURCE + ': parser-preloaded external ' + JSON.stringify(specifier)
  377. + ' has no matching PARSER_PRELOAD_IDS row in ' + PARSER_PRELOAD_SOURCE,
  378. )
  379. }
  380. }
  381. return violations
  382. }
  383. interface ExpectedRule {
  384. readonly kind: 'dependency' | 'dev' | 'peer-dev'
  385. readonly origins: Set<string>
  386. }
  387. function collectDependencyViolations(facts: ClientPackageFacts): string[] {
  388. const violations: string[] = []
  389. const staticInputs = new Set([
  390. ...facts.staticLinkedPackages,
  391. ...facts.platformModules.map(packageNameOf),
  392. ])
  393. staticInputs.delete(CORDIS)
  394. for (const pkg of [...facts.packages].sort((left, right) => left.manifest.localeCompare(right.manifest))) {
  395. const expected = expectedSections(pkg, staticInputs)
  396. for (const [name, rule] of [...expected].sort(([left], [right]) => left.localeCompare(right))) {
  397. const actual = declaredSections(pkg, name)
  398. if (rule.kind === 'dependency') {
  399. if (actual.length === 1 && actual[0] === 'dependencies') continue
  400. violations.push(
  401. pkg.manifest + ': ' + name + ' (' + describeOrigins(rule.origins) + ') is a runtime import'
  402. + ' retained by a statically linked artifact; declare it only in dependencies, found '
  403. + describeSections(actual),
  404. )
  405. continue
  406. }
  407. if (rule.kind === 'dev') {
  408. if (actual.length === 1 && actual[0] === 'devDependencies') continue
  409. violations.push(
  410. pkg.manifest + ': ' + name + ' (' + describeOrigins(rule.origins) + ') is a static client input;'
  411. + ' declare it only in devDependencies, found ' + describeSections(actual),
  412. )
  413. continue
  414. }
  415. const peerRange = pkg.peerDependencies[name]
  416. const devRange = pkg.devDependencies[name]
  417. if (actual.length === 2
  418. && actual.includes('peerDependencies')
  419. && actual.includes('devDependencies')
  420. && peerRange === devRange) continue
  421. violations.push(
  422. pkg.manifest + ': ' + name + ' (' + describeOrigins(rule.origins) + ')'
  423. + ' is a peer-installed DSH relationship; declare it in peerDependencies and devDependencies'
  424. + ' with matching ranges, not dependencies; found ' + describeSections(actual)
  425. + describeRangeMismatch(peerRange, devRange),
  426. )
  427. }
  428. for (const [name, peerRange] of Object.entries(pkg.peerDependencies).sort(([left], [right]) => left.localeCompare(right))) {
  429. if (expected.has(name)) continue
  430. const devRange = pkg.devDependencies[name]
  431. if (devRange === peerRange) continue
  432. violations.push(
  433. pkg.manifest + ': peerDependencies.' + name + ' is ' + peerRange + ', so devDependencies.' + name
  434. + ' must use the same range; found ' + (devRange ?? 'no declaration'),
  435. )
  436. }
  437. if (!pkg.dynamic) continue
  438. for (const section of ['dependencies', 'peerDependencies'] as const) {
  439. for (const name of Object.keys(pkg[section]).sort()) {
  440. if (expected.has(name)) continue
  441. if (staticInputs.has(name)) {
  442. violations.push(
  443. pkg.manifest + ': dynamic package declares static input ' + name + ' in ' + section + ';'
  444. + ' move it to devDependencies or delete the stale declaration',
  445. )
  446. } else if (section === 'dependencies' && isInternalDsh(name)) {
  447. violations.push(
  448. pkg.manifest + ': dynamic package declares ' + name + ' in dependencies;'
  449. + ' dynamic DSH relationships are peer plus dev, and static client inputs are dev-only',
  450. )
  451. }
  452. }
  453. }
  454. }
  455. return violations
  456. }
  457. function expectedSections(pkg: ClientPackage, staticInputs: ReadonlySet<string>): Map<string, ExpectedRule> {
  458. const expected = new Map<string, ExpectedRule>([
  459. [CORDIS, { kind: 'peer-dev', origins: new Set(['client package baseline']) }],
  460. ])
  461. if (!pkg.dynamic) {
  462. if (pkg.name === CLIENT_WEB) return expected
  463. for (const [name, locations] of Object.entries(pkg.runtimeSourceUses)) {
  464. if (name === pkg.name || name === CORDIS || isInternalDsh(name)) continue
  465. expected.set(name, { kind: 'dependency', origins: new Set(locations) })
  466. }
  467. return expected
  468. }
  469. const add = (name: string, origin: string): void => {
  470. if (name === pkg.name) return
  471. const kind = staticInputs.has(name) ? 'dev' : isInternalDsh(name) ? 'peer-dev' : undefined
  472. if (kind === undefined) return
  473. const current = expected.get(name)
  474. if (current !== undefined) current.origins.add(origin)
  475. else expected.set(name, { kind, origins: new Set([origin]) })
  476. }
  477. for (const [name, locations] of Object.entries(pkg.sourceUses)) {
  478. for (const location of locations) add(name, location)
  479. }
  480. for (const name of pkg.inject) add(name, 'dsh.client.inject')
  481. return expected
  482. }
  483. interface ModuleEdge {
  484. readonly from: string
  485. readonly to: string
  486. readonly specifier: string
  487. }
  488. function collectModuleViolations(facts: ClientPackageFacts): string[] {
  489. const violations: string[] = []
  490. const baseline = new Set([...facts.platformModules, ...facts.preloadedExternals])
  491. const rows = rowNames(facts.declarations)
  492. const byName = new Map(facts.declarations.map(entry => [entry.name, entry]))
  493. const edges: ModuleEdge[] = []
  494. for (const pkg of facts.declarations.filter(entry => entry.dynamic)) {
  495. for (const field of ['external', 'inject'] as const) {
  496. const seen = new Set<string>()
  497. for (const value of pkg[field]) {
  498. if (value === '') violations.push(pkg.manifest + ': dsh.client.' + field + ' contains an empty value')
  499. else if (seen.has(value)) {
  500. violations.push(pkg.manifest + ': dsh.client.' + field + ' lists ' + JSON.stringify(value) + ' twice')
  501. }
  502. seen.add(value)
  503. }
  504. }
  505. for (const specifier of new Set(pkg.external)) {
  506. if (specifier === '') continue
  507. if (baseline.has(specifier)) {
  508. violations.push(
  509. pkg.manifest + ': dsh.client.external repeats baseline module ' + JSON.stringify(specifier)
  510. + '; remove the explicit declaration',
  511. )
  512. continue
  513. }
  514. const supplier = rowPackageOf(specifier, rows)
  515. if (supplier === pkg.name) {
  516. violations.push(pkg.manifest + ': dsh.client.external names its own row ' + JSON.stringify(specifier))
  517. } else if (supplier !== undefined) {
  518. edges.push({ from: pkg.name, to: supplier, specifier })
  519. } else {
  520. const owner = stripClientSuffix(specifier)
  521. violations.push(
  522. pkg.manifest + ': dsh.client.external ' + JSON.stringify(specifier) + ' has no supplier;'
  523. + (byName.has(owner)
  524. ? ' workspace package ' + owner
  525. + ' declares no dynamic dsh.client row and the shell does not seed this specifier'
  526. : ' no dynamic row or PLATFORM_MODULES entry answers it'),
  527. )
  528. }
  529. }
  530. }
  531. violations.push(...collectModuleCycles(edges, byName))
  532. return violations
  533. }
  534. function collectModuleCycles(
  535. edges: readonly ModuleEdge[],
  536. byName: ReadonlyMap<string, ClientDeclaration>,
  537. ): string[] {
  538. const outgoing = new Map<string, ModuleEdge[]>()
  539. for (const edge of [...edges].sort((left, right) => left.specifier.localeCompare(right.specifier))) {
  540. outgoing.set(edge.from, [...outgoing.get(edge.from) ?? [], edge])
  541. }
  542. const finished = new Set<string>()
  543. const onPath = new Set<string>()
  544. const path: ModuleEdge[] = []
  545. const reported = new Map<string, string>()
  546. const walk = (name: string): void => {
  547. onPath.add(name)
  548. for (const edge of outgoing.get(name) ?? []) {
  549. if (onPath.has(edge.to)) {
  550. const start = path.findIndex(entry => entry.from === edge.to)
  551. const cycle = start === -1 ? [edge] : [...path.slice(start), edge]
  552. const key = cycleKey(cycle)
  553. if (!reported.has(key)) reported.set(key, formatCycle(cycle, byName))
  554. } else if (!finished.has(edge.to)) {
  555. path.push(edge)
  556. walk(edge.to)
  557. path.pop()
  558. }
  559. }
  560. onPath.delete(name)
  561. finished.add(name)
  562. }
  563. for (const name of [...outgoing.keys()].sort()) {
  564. if (!finished.has(name)) walk(name)
  565. }
  566. return [...reported.values()]
  567. }
  568. function cycleKey(cycle: readonly ModuleEdge[]): string {
  569. const labels = cycle.map(edge => edge.from + ' ' + edge.specifier)
  570. const first = [...labels].sort()[0]
  571. const offset = first === undefined ? 0 : labels.indexOf(first)
  572. return [...labels.slice(offset), ...labels.slice(0, offset)].join(' -> ')
  573. }
  574. function formatCycle(
  575. cycle: readonly ModuleEdge[],
  576. byName: ReadonlyMap<string, ClientDeclaration>,
  577. ): string {
  578. const entry = cycle[0]
  579. const chain = cycle.map(edge => edge.from + ' --(' + edge.specifier + ')-->').join(' ')
  580. const manifest = entry === undefined ? 'packages/client' : byName.get(entry.from)?.manifest ?? entry.from
  581. return manifest + ': synchronous dsh.client.external cycle: ' + chain + ' ' + (entry?.from ?? '')
  582. }
  583. interface Manifest {
  584. name?: unknown
  585. dsh?: unknown
  586. dependencies?: Record<string, string>
  587. peerDependencies?: Record<string, string>
  588. devDependencies?: Record<string, string>
  589. }
  590. function readDeclaration(
  591. root: string,
  592. manifestPath: string,
  593. malformed: string[],
  594. ): ClientDeclaration | undefined {
  595. const manifest = JSON.parse(readFileSync(resolve(root, manifestPath), 'utf8')) as Manifest
  596. if (typeof manifest.name !== 'string') return undefined
  597. const dsh = isRecord(manifest.dsh) ? manifest.dsh : undefined
  598. const rawClient = dsh?.client
  599. if (rawClient === undefined) {
  600. return { name: manifest.name, manifest: manifestPath, dynamic: false, external: [], inject: [] }
  601. }
  602. if (!isRecord(rawClient)) {
  603. malformed.push(manifestPath + ': ' + manifest.name + ' dsh.client must be an object')
  604. return { name: manifest.name, manifest: manifestPath, dynamic: false, external: [], inject: [] }
  605. }
  606. return {
  607. name: manifest.name,
  608. manifest: manifestPath,
  609. dynamic: true,
  610. external: stringArray(rawClient.external, manifest.name, manifestPath, 'external', malformed),
  611. inject: stringArray(rawClient.inject, manifest.name, manifestPath, 'inject', malformed),
  612. }
  613. }
  614. function stringArray(
  615. value: unknown,
  616. packageName: string,
  617. manifestPath: string,
  618. field: string,
  619. malformed: string[],
  620. ): readonly string[] {
  621. if (value === undefined) return []
  622. if (!Array.isArray(value) || value.some(entry => typeof entry !== 'string')) {
  623. malformed.push(manifestPath + ': ' + packageName + ' dsh.client.' + field + ' must be a string array')
  624. return []
  625. }
  626. return value as string[]
  627. }
  628. async function readStaticLinkedRoster(root: string): Promise<Set<string>> {
  629. const presetUrl = pathToFileURL(resolve(import.meta.dirname, '..', STATIC_PRESET_SOURCE)).href
  630. const preset = await import(presetUrl) as { isStaticLinkedConfig?: unknown }
  631. if (typeof preset.isStaticLinkedConfig !== 'function') {
  632. throw new Error(GATE + ': ' + STATIC_PRESET_SOURCE + ' exports no isStaticLinkedConfig')
  633. }
  634. const predicate = preset.isStaticLinkedConfig as (configs: readonly unknown[]) => boolean
  635. const roster = new Set<string>()
  636. for (const configPath of globSync(CONFIG_GLOB, { cwd: root }).map(normalizePath).sort()) {
  637. const loaded = await import(pathToFileURL(resolve(root, configPath)).href) as { default?: unknown }
  638. if (typeof loaded.default !== 'function') continue
  639. const configs = (loaded.default as (input: { env: Record<string, string> }) => unknown)({
  640. env: { DSH_BUILD_FACE: 'client' },
  641. })
  642. if (!Array.isArray(configs) || !predicate(configs)) continue
  643. const manifest = JSON.parse(
  644. readFileSync(resolve(root, configPath.replace(/tsdown\.config\.ts$/, 'package.json')), 'utf8'),
  645. ) as Manifest
  646. if (typeof manifest.name === 'string') roster.add(manifest.name)
  647. }
  648. return roster
  649. }
  650. function unwrapExpression(expression: ts.Expression): ts.Expression {
  651. let current = expression
  652. while (ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isParenthesizedExpression(current)) {
  653. current = current.expression
  654. }
  655. return current
  656. }
  657. function readStringLiteralArray(root: string, sourcePath: string, name: string): string[] {
  658. const path = resolve(root, sourcePath)
  659. const source = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, false, ts.ScriptKind.TS)
  660. const constants = new Map<string, string>()
  661. for (const statement of source.statements) {
  662. if (!ts.isVariableStatement(statement)) continue
  663. for (const declaration of statement.declarationList.declarations) {
  664. if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined) continue
  665. const initializer = unwrapExpression(declaration.initializer)
  666. if (ts.isStringLiteral(initializer)) constants.set(declaration.name.text, initializer.text)
  667. }
  668. }
  669. for (const statement of source.statements) {
  670. if (!ts.isVariableStatement(statement)) continue
  671. for (const declaration of statement.declarationList.declarations) {
  672. if (!ts.isIdentifier(declaration.name) || declaration.name.text !== name) continue
  673. const expression = declaration.initializer === undefined ? undefined : unwrapExpression(declaration.initializer)
  674. if (expression === undefined || !ts.isArrayLiteralExpression(expression)) {
  675. throw new Error(GATE + ': ' + name + ' in ' + sourcePath + ' must be an array literal')
  676. }
  677. return expression.elements.map((element) => {
  678. const value = unwrapExpression(element)
  679. if (ts.isStringLiteral(value)) return value.text
  680. if (ts.isIdentifier(value) && constants.has(value.text)) return constants.get(value.text) as string
  681. throw new Error(GATE + ': ' + name + ' in ' + sourcePath + ' must contain only string constants')
  682. })
  683. }
  684. }
  685. throw new Error(GATE + ': ' + sourcePath + ' declares no ' + name)
  686. }
  687. async function readFacts(root: string): Promise<ClientPackageFacts> {
  688. const { declarations, malformed } = readClientDeclarations(root)
  689. const byManifest = new Map(declarations.map(entry => [entry.manifest, entry]))
  690. const staticLinkedPackages = await readStaticLinkedRoster(root)
  691. const project = new TypeScriptProject(root, 'client')
  692. const packages: ClientPackage[] = []
  693. for (const manifestPath of globSync(CLIENT_MANIFEST_GLOB, { cwd: root }).map(normalizePath).sort()) {
  694. const declaration = byManifest.get(manifestPath)
  695. if (declaration === undefined) throw new Error(GATE + ': no declaration facts for ' + manifestPath)
  696. const manifest = JSON.parse(readFileSync(resolve(root, manifestPath), 'utf8')) as Manifest
  697. if (typeof manifest.name !== 'string') throw new Error(GATE + ': ' + manifestPath + ' has no package name')
  698. const sourceUses = new Map<string, Set<string>>()
  699. const runtimeSourceUses = new Map<string, Set<string>>()
  700. const packageDirectory = dirname(manifestPath)
  701. const sourcePrefix = packageDirectory + '/src/'
  702. for (const sourceFile of project.sourceFiles()) {
  703. if (sourceFile.isDeclarationFile) continue
  704. const file = project.relativePath(sourceFile)
  705. if (!file.startsWith(sourcePrefix)) continue
  706. for (const name of collectSourceFilePackageUses(sourceFile, false)) {
  707. const locations = sourceUses.get(name) ?? new Set<string>()
  708. locations.add(file)
  709. sourceUses.set(name, locations)
  710. }
  711. for (const name of collectSourceFilePackageUses(sourceFile, true)) {
  712. const locations = runtimeSourceUses.get(name) ?? new Set<string>()
  713. locations.add(file)
  714. runtimeSourceUses.set(name, locations)
  715. }
  716. }
  717. packages.push({
  718. ...declaration,
  719. staticLinked: staticLinkedPackages.has(declaration.name),
  720. sourceUses: Object.fromEntries(
  721. [...sourceUses].sort(([left], [right]) => left.localeCompare(right))
  722. .map(([name, locations]) => [name, [...locations].sort()]),
  723. ),
  724. runtimeSourceUses: Object.fromEntries(
  725. [...runtimeSourceUses].sort(([left], [right]) => left.localeCompare(right))
  726. .map(([name, locations]) => [name, [...locations].sort()]),
  727. ),
  728. dependencies: manifest.dependencies ?? {},
  729. peerDependencies: manifest.peerDependencies ?? {},
  730. devDependencies: manifest.devDependencies ?? {},
  731. })
  732. }
  733. return {
  734. packages,
  735. declarations,
  736. staticLinkedPackages,
  737. platformModules: readStringLiteralArray(root, PLATFORM_SOURCE, 'PLATFORM_MODULES'),
  738. preloadedExternals: readStringLiteralArray(root, PLATFORM_SOURCE, 'PRELOADED_CLIENT_EXTERNALS'),
  739. parserPreloadIds: readStringLiteralArray(root, PARSER_PRELOAD_SOURCE, 'PARSER_PRELOAD_IDS'),
  740. malformed,
  741. }
  742. }
  743. function packageNameOf(specifier: string): string {
  744. const segments = specifier.split('/')
  745. return segments.slice(0, specifier.startsWith('@') ? 2 : 1).join('/')
  746. }
  747. function stripClientSuffix(specifier: string): string {
  748. return specifier.endsWith('/client') ? specifier.slice(0, -'/client'.length) : specifier
  749. }
  750. function rowNames(declarations: readonly ClientDeclaration[]): Set<string> {
  751. return new Set(declarations.filter(entry => entry.dynamic).map(entry => entry.name))
  752. }
  753. function rowPackageOf(specifier: string, rows: ReadonlySet<string>): string | undefined {
  754. if (rows.has(specifier)) return specifier
  755. const stripped = stripClientSuffix(specifier)
  756. return rows.has(stripped) ? stripped : undefined
  757. }
  758. function declaredSections(pkg: ClientPackage, name: string): string[] {
  759. return (['dependencies', 'peerDependencies', 'devDependencies'] as const)
  760. .filter(section => pkg[section][name] !== undefined)
  761. }
  762. function describeSections(sections: readonly string[]): string {
  763. return sections.length === 0 ? 'no dependency declaration' : sections.join(' + ')
  764. }
  765. function describeRangeMismatch(peer: string | undefined, dev: string | undefined): string {
  766. if (peer === undefined || dev === undefined || peer === dev) return ''
  767. return ' (peer ' + peer + ', dev ' + dev + ')'
  768. }
  769. function describeOrigins(origins: ReadonlySet<string>): string {
  770. const sorted = [...origins].sort()
  771. const [first, second, ...rest] = sorted
  772. if (first === undefined) return 'production use'
  773. if (second === undefined) return first
  774. return rest.length === 0 ? first + ', ' + second : first + ', ' + second + ', and ' + String(rest.length) + ' more'
  775. }
  776. function isInternalDsh(name: string): boolean {
  777. return name === CORDIS || name.startsWith(DSH_PREFIX)
  778. }
  779. function isBareSpecifier(specifier: string): boolean {
  780. return !specifier.startsWith('.') && !specifier.startsWith('/') && !specifier.startsWith('#')
  781. }
  782. function isRecord(value: unknown): value is Record<string, unknown> {
  783. return typeof value === 'object' && value !== null && !Array.isArray(value)
  784. }
  785. function normalizePath(path: string): string {
  786. return path.split(sep).join('/')
  787. }
  788. async function main(): Promise<void> {
  789. const root = resolve(import.meta.dirname, '..')
  790. let facts = await readFacts(root)
  791. if (process.argv.includes('--fix')) {
  792. const changed = fixClientPackageManifests(root, facts)
  793. console.log(
  794. changed.length === 0
  795. ? GATE + ': no mechanically fixable manifest changes.'
  796. : GATE + ': fixed ' + String(changed.length) + ' manifest(s): ' + changed.join(', '),
  797. )
  798. facts = await readFacts(root)
  799. }
  800. const violations = collectClientPackageViolations(facts)
  801. if (violations.length > 0) {
  802. console.error(GATE + ': ' + String(violations.length) + ' violation(s):')
  803. for (const violation of violations) console.error(' ' + violation)
  804. process.exit(1)
  805. }
  806. const dynamic = facts.packages.filter(pkg => pkg.dynamic).length
  807. const requests = facts.declarations.reduce((total, pkg) => total + pkg.external.length, 0)
  808. console.log(
  809. GATE + ': ' + String(facts.packages.length) + ' client packages (' + String(dynamic) + ' dynamic, '
  810. + String(facts.packages.length - dynamic) + ' statically linked) satisfy dependency and module-request rules; '
  811. + String(requests) + ' explicit external request(s).',
  812. )
  813. }
  814. if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) {
  815. await main()
  816. }