check-workspace-constraints.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 { 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. '@deepseek-ai/dsh-client-ui-theme': ['lib/styles'],
  94. '@deepseek-ai/dsh-helper': ['lib/assets'],
  95. '@deepseek-ai/dsh-pty-local': ['scripts/ensure-spawn-helper.mjs'],
  96. '@deepseek-ai/dsh-scripts': [
  97. 'lib/dev/tsdown-config.js',
  98. 'lib/local-plugin-loader-hooks.js',
  99. 'lib/assets',
  100. ],
  101. }
  102. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  103. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  104. }
  105. function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  106. const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
  107. return [
  108. 'lib/index.js',
  109. // Every package publishes its invariant ownership companion as a separate
  110. // bundle; the package-invariant gate validates the companion itself.
  111. 'lib/invariant.js',
  112. ...manifest.bin ? ['lib/bin.js'] : [],
  113. ...manifest.exports?.['./worker'] ? ['lib/worker.cjs'] : [],
  114. // UI plugin packages ship their browser bundle beside the node lib
  115. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  116. // Keyed on the artifact path, not the subpath name: apiproxy's ./client is
  117. // a browser-safe source channel, not a bundle.
  118. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  119. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  120. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  121. // web-react's store subpath ships its own bundle (single-entry builds; no shared chunk).
  122. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  123. ...extras,
  124. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  125. // browser-safe source channels rehomed off src so plain Node can import
  126. // them without type stripping) publish the emitted JS alongside the
  127. // declarations.
  128. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  129. 'lib/types/**/*.d.ts',
  130. ]
  131. }
  132. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  133. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  134. const entry = manifest.exports?.[subpath]
  135. if (typeof entry === 'string') return entry
  136. if (typeof entry === 'object' && entry !== null) return entry.default
  137. return undefined
  138. }
  139. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  140. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  141. return Object.keys(manifest.exports ?? {}).some(subpath =>
  142. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  143. }
  144. function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
  145. const errors: string[] = []
  146. const label = manifest.name ?? dir
  147. if (manifest.private !== true) {
  148. errors.push(`${label}: package.json must set "private": true`)
  149. }
  150. if (manifest.name && vendoredPackages.has(manifest.name)) {
  151. return errors
  152. }
  153. if (manifest.name?.startsWith('@deepseek-ai/')) {
  154. for (const file of manifest.files ?? []) {
  155. if (isForbiddenPublicationFile(file)) {
  156. errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
  157. }
  158. }
  159. }
  160. if (dir.startsWith('apps/') && manifest.name?.startsWith('@deepseek-ai/')) {
  161. const expectedFiles = appPackageFiles[manifest.name]
  162. if (expectedFiles === undefined) {
  163. errors.push(`${label}: app package has no publication files policy`)
  164. } else if (!sameStringList(manifest.files, expectedFiles)) {
  165. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  166. }
  167. }
  168. if (dir.startsWith('packages/') && manifest.name?.startsWith('@deepseek-ai/dsh-')) {
  169. const peer = manifest.peerDependencies?.cordis
  170. const dev = manifest.devDependencies?.cordis
  171. if (!peer) errors.push(`${label}: cordis must be a peerDependency`)
  172. if (!dev) errors.push(`${label}: cordis must also be a devDependency`)
  173. if (peer && dev && peer !== dev) {
  174. errors.push(`${label}: cordis peer (${peer}) and dev (${dev}) ranges must match`)
  175. }
  176. if (manifest.version !== repositoryVersion) {
  177. errors.push(`${label}: package.json version must match root version ${repositoryVersion ?? '(missing)'}`)
  178. }
  179. if (manifest.type !== 'module') {
  180. errors.push(`${label}: package.json must set "type": "module"`)
  181. }
  182. if (manifest.main !== 'lib/index.js') {
  183. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  184. }
  185. if (manifest.types !== 'lib/types/index.d.ts') {
  186. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  187. }
  188. const rootExport = manifest.exports?.['.']
  189. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  190. if (rootEntry?.types !== './lib/types/index.d.ts') {
  191. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  192. }
  193. if (rootEntry?.default !== './lib/index.js') {
  194. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  195. }
  196. const invariantRaw = manifest.exports?.['./invariant']
  197. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  198. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  199. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  200. }
  201. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  202. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  203. }
  204. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  205. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  206. }
  207. const expectedFiles = expectedDshPackageFiles(manifest)
  208. if (!sameStringList(manifest.files, expectedFiles)) {
  209. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  210. }
  211. }
  212. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  213. }
  214. /**
  215. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  216. * package.json, and packages may be neither flat nor more deeply nested.
  217. */
  218. function checkHierarchyShape(): string[] {
  219. const errors: string[] = []
  220. const packagesRoot = join(root, 'packages')
  221. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  222. if (!group.isDirectory()) continue
  223. const groupRel = join('packages', group.name)
  224. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  225. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  226. continue
  227. }
  228. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  229. if (!pkg.isDirectory()) continue
  230. if (localArtifactDirs.has(pkg.name)) continue
  231. const pkgRel = join(groupRel, pkg.name)
  232. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  233. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  234. }
  235. }
  236. }
  237. return errors
  238. }
  239. function checkRepositoryVersion(): string[] {
  240. if (repositoryVersion && /^\d+\.\d+\.\d+$/.test(repositoryVersion)) return []
  241. return ['package.json: version must be stable X.Y.Z']
  242. }
  243. const errors = [
  244. ...checkRepositoryVersion(),
  245. ...workspaceManifests().flatMap(checkWorkspace),
  246. ...checkHierarchyShape(),
  247. ]
  248. if (errors.length > 0) {
  249. console.error(errors.join('\n'))
  250. process.exitCode = 1
  251. }