check-workspace-constraints.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /**
  2. * Workspace package invariant checks for package-manager-independent quality
  3. * gates.
  4. *
  5. * Run: `tsx scripts/check-workspace-constraints.ts`.
  6. */
  7. import { existsSync, readdirSync, readFileSync } from 'node:fs'
  8. import { join, relative, resolve } from 'node:path'
  9. import { hasTypeRTRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
  10. const root = resolve(import.meta.dirname, '..')
  11. // vendor/* is single-level; packages/<group>/<pkg> nests one level deeper
  12. // (the group dirs — core/llm/bash/… — are pure containers with no manifest).
  13. const workspaceGlobs = [
  14. { dir: 'vendor', depth: 1 },
  15. { dir: 'packages', depth: 2 },
  16. { dir: 'apps', depth: 1 },
  17. ] as const
  18. const vendoredPackages = new Set([
  19. 'cordis',
  20. 'cosmokit',
  21. 'schemastery',
  22. '@cordisjs/plugin-loader',
  23. '@cordisjs/plugin-include',
  24. '@cordisjs/plugin-group',
  25. '@cordisjs/plugin-timer',
  26. '@cordisjs/plugin-hmr',
  27. '@cordisjs/plugin-logger-console',
  28. ])
  29. const localArtifactDirs = new Set(['node_modules'])
  30. const appPackageFiles: Readonly<Record<string, readonly string[]>> = {
  31. '@deepseek-ai/dsh': ['lib/*.js', 'config'],
  32. '@deepseek-ai/dsh-frontend': ['dist'],
  33. }
  34. /** The subset of package.json fields this constraint check cares about. */
  35. interface PackageManifest {
  36. name?: string
  37. version?: string
  38. private?: boolean
  39. type?: string
  40. main?: string
  41. types?: string
  42. bin?: string | Record<string, string>
  43. exports?: Record<
  44. string,
  45. | string
  46. | {
  47. types?: string
  48. default?: string
  49. }
  50. | null
  51. | undefined
  52. >
  53. files?: string[]
  54. peerDependencies?: Record<string, string>
  55. devDependencies?: Record<string, string>
  56. }
  57. /** One workspace manifest and its repo-relative path. */
  58. interface WorkspaceManifest {
  59. dir: string
  60. manifest: PackageManifest
  61. }
  62. function readJson(path: string): PackageManifest {
  63. return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
  64. }
  65. const rootManifest = readJson(join(root, 'package.json'))
  66. const repositoryVersion = rootManifest.version
  67. /** Repo-relative dirs holding a package.json, walked to the configured depth. */
  68. function packageDirs(base: string, depth: number): string[] {
  69. if (depth === 1) {
  70. return readdirSync(join(root, base), { withFileTypes: true })
  71. .filter(entry => entry.isDirectory())
  72. .filter(entry => !localArtifactDirs.has(entry.name))
  73. .filter(entry => existsSync(join(root, base, entry.name, 'package.json')))
  74. .map(entry => join(base, entry.name))
  75. }
  76. return readdirSync(join(root, base), { withFileTypes: true })
  77. .filter(entry => entry.isDirectory())
  78. .filter(entry => !localArtifactDirs.has(entry.name))
  79. .flatMap(group => packageDirs(join(base, group.name), depth - 1))
  80. }
  81. function workspaceManifests(): WorkspaceManifest[] {
  82. const manifests: WorkspaceManifest[] = [
  83. { dir: '.', manifest: rootManifest },
  84. ]
  85. for (const { dir: base, depth } of workspaceGlobs) {
  86. for (const dir of packageDirs(base, depth)) {
  87. manifests.push({ dir, manifest: readJson(join(root, dir, 'package.json')) })
  88. }
  89. }
  90. return manifests
  91. }
  92. const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
  93. // Profile bundles publish their dsh.bundle.patch layer beside the lib.
  94. '@deepseek-ai/dsh-base': ['cordis.patch.yml'],
  95. '@deepseek-ai/dsh-web-app': ['cordis.patch.yml'],
  96. '@deepseek-ai/dsh-headless': ['cordis.patch.yml'],
  97. '@deepseek-ai/dsh-client-ui-theme': ['lib/styles'],
  98. '@deepseek-ai/dsh-helper': ['lib/assets'],
  99. '@deepseek-ai/dsh-pty-local': ['scripts/ensure-spawn-helper.mjs'],
  100. '@deepseek-ai/dsh-scripts': [
  101. 'lib/dev/tsdown-config.js',
  102. 'lib/local-plugin-loader-hooks.js',
  103. 'lib/assets',
  104. ],
  105. }
  106. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  107. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  108. }
  109. function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  110. const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
  111. const typeRTRemoteNavigation = hasTypeRTRemoteNavigation(manifest)
  112. return [
  113. 'lib/index.js',
  114. // Every package publishes its invariant ownership companion as a separate
  115. // bundle; the package-invariant gate validates the companion itself.
  116. 'lib/invariant.js',
  117. ...manifest.bin ? ['lib/bin.js'] : [],
  118. ...manifest.exports?.['./worker'] ? ['lib/worker.cjs'] : [],
  119. // UI plugin packages ship their browser bundle beside the node lib
  120. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  121. // Keyed on the artifact path, not the subpath name: apiproxy's ./client is
  122. // a browser-safe source channel, not a bundle.
  123. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  124. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  125. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  126. // web-react's store subpath ships its own bundle (single-entry builds; no shared chunk).
  127. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  128. ...extras,
  129. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  130. // browser-safe source channels rehomed off src so plain Node can import
  131. // them without type stripping) publish the emitted JS alongside the
  132. // declarations.
  133. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  134. 'lib/types/**/*.d.ts',
  135. ...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
  136. ? ['lib/typert.host.js', 'lib/typert.host.d.ts']
  137. : [],
  138. ...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
  139. ? ['lib/typert.client.js', 'lib/typert.client.d.ts']
  140. : [],
  141. ...typeRTRemoteNavigation
  142. ? [
  143. 'lib/typert.remote-client.js',
  144. 'lib/typert.remote-client.d.ts',
  145. 'lib/typert.remote-client.d.ts.map',
  146. 'src',
  147. ]
  148. : [],
  149. ]
  150. }
  151. /** Whether one conditional export exactly names the generated runtime and declaration pair. */
  152. function hasExportPair(
  153. manifest: PackageManifest,
  154. subpath: string,
  155. types: string,
  156. runtime: string,
  157. ): boolean {
  158. const entry = manifest.exports?.[subpath]
  159. return typeof entry === 'object'
  160. && entry !== null
  161. && entry.types === types
  162. && entry.default === runtime
  163. }
  164. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  165. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  166. const entry = manifest.exports?.[subpath]
  167. if (typeof entry === 'string') return entry
  168. if (typeof entry === 'object' && entry !== null) return entry.default
  169. return undefined
  170. }
  171. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  172. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  173. return Object.keys(manifest.exports ?? {}).some(subpath =>
  174. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  175. }
  176. function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
  177. const errors: string[] = []
  178. const label = manifest.name ?? dir
  179. if (manifest.private !== true) {
  180. errors.push(`${label}: package.json must set "private": true`)
  181. }
  182. if (manifest.name && vendoredPackages.has(manifest.name)) {
  183. return errors
  184. }
  185. if (manifest.name?.startsWith('@deepseek-ai/')) {
  186. const publicationPolicy = { typeRTRemoteNavigation: hasTypeRTRemoteNavigation(manifest) }
  187. for (const file of manifest.files ?? []) {
  188. if (isForbiddenPublicationFile(file, publicationPolicy)) {
  189. errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
  190. }
  191. }
  192. }
  193. if (dir.startsWith('apps/') && manifest.name?.startsWith('@deepseek-ai/')) {
  194. const expectedFiles = appPackageFiles[manifest.name]
  195. if (expectedFiles === undefined) {
  196. errors.push(`${label}: app package has no publication files policy`)
  197. } else if (!sameStringList(manifest.files, expectedFiles)) {
  198. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  199. }
  200. }
  201. if (dir.startsWith('packages/') && manifest.name?.startsWith('@deepseek-ai/dsh-')) {
  202. const peer = manifest.peerDependencies?.cordis
  203. const dev = manifest.devDependencies?.cordis
  204. if (!peer) errors.push(`${label}: cordis must be a peerDependency`)
  205. if (!dev) errors.push(`${label}: cordis must also be a devDependency`)
  206. if (peer && dev && peer !== dev) {
  207. errors.push(`${label}: cordis peer (${peer}) and dev (${dev}) ranges must match`)
  208. }
  209. if (manifest.version !== repositoryVersion) {
  210. errors.push(`${label}: package.json version must match root version ${repositoryVersion ?? '(missing)'}`)
  211. }
  212. if (manifest.type !== 'module') {
  213. errors.push(`${label}: package.json must set "type": "module"`)
  214. }
  215. if (manifest.main !== 'lib/index.js') {
  216. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  217. }
  218. if (manifest.types !== 'lib/types/index.d.ts') {
  219. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  220. }
  221. const rootExport = manifest.exports?.['.']
  222. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  223. if (rootEntry?.types !== './lib/types/index.d.ts') {
  224. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  225. }
  226. if (rootEntry?.default !== './lib/index.js') {
  227. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  228. }
  229. const invariantRaw = manifest.exports?.['./invariant']
  230. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  231. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  232. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  233. }
  234. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  235. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  236. }
  237. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  238. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  239. }
  240. const expectedFiles = expectedDshPackageFiles(manifest)
  241. if (!sameStringList(manifest.files, expectedFiles)) {
  242. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  243. }
  244. }
  245. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  246. }
  247. /**
  248. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  249. * package.json, and packages may be neither flat nor more deeply nested.
  250. */
  251. function checkHierarchyShape(): string[] {
  252. const errors: string[] = []
  253. const packagesRoot = join(root, 'packages')
  254. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  255. if (!group.isDirectory()) continue
  256. const groupRel = join('packages', group.name)
  257. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  258. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  259. continue
  260. }
  261. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  262. if (!pkg.isDirectory()) continue
  263. if (localArtifactDirs.has(pkg.name)) continue
  264. const pkgRel = join(groupRel, pkg.name)
  265. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  266. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  267. }
  268. }
  269. }
  270. return errors
  271. }
  272. function checkRepositoryVersion(): string[] {
  273. if (repositoryVersion && /^\d+\.\d+\.\d+$/.test(repositoryVersion)) return []
  274. return ['package.json: version must be stable X.Y.Z']
  275. }
  276. const errors = [
  277. ...checkRepositoryVersion(),
  278. ...workspaceManifests().flatMap(checkWorkspace),
  279. ...checkHierarchyShape(),
  280. ]
  281. if (errors.length > 0) {
  282. console.error(errors.join('\n'))
  283. process.exitCode = 1
  284. }