check-workspace-constraints.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. const root = resolve(import.meta.dirname, '..')
  10. // vendor/* is single-level; packages/<group>/<pkg> nests one level deeper
  11. // (the group dirs — core/llm/bash/… — are pure containers with no manifest).
  12. const workspaceGlobs = [
  13. { dir: 'vendor', depth: 1 },
  14. { dir: 'packages', depth: 2 },
  15. ] as const
  16. const vendoredPackages = new Set([
  17. 'cordis',
  18. 'cosmokit',
  19. 'schemastery',
  20. '@cordisjs/plugin-loader',
  21. '@cordisjs/plugin-include',
  22. '@cordisjs/plugin-group',
  23. '@cordisjs/plugin-timer',
  24. '@cordisjs/plugin-hmr',
  25. '@cordisjs/plugin-logger-console',
  26. ])
  27. const localArtifactDirs = new Set(['node_modules'])
  28. /** The subset of package.json fields this constraint check cares about. */
  29. interface PackageManifest {
  30. name?: string
  31. version?: string
  32. private?: boolean
  33. type?: string
  34. main?: string
  35. types?: string
  36. bin?: string | Record<string, string>
  37. exports?: Record<
  38. string,
  39. | {
  40. types?: string
  41. default?: string
  42. }
  43. | undefined
  44. >
  45. files?: string[]
  46. peerDependencies?: Record<string, string>
  47. devDependencies?: Record<string, string>
  48. }
  49. /** One workspace manifest and its repo-relative path. */
  50. interface WorkspaceManifest {
  51. dir: string
  52. manifest: PackageManifest
  53. }
  54. function readJson(path: string): PackageManifest {
  55. return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
  56. }
  57. const rootManifest = readJson(join(root, 'package.json'))
  58. const repositoryVersion = rootManifest.version
  59. /** Repo-relative dirs holding a package.json, walked to the configured depth. */
  60. function packageDirs(base: string, depth: number): string[] {
  61. if (depth === 1) {
  62. return readdirSync(join(root, base), { withFileTypes: true })
  63. .filter(entry => entry.isDirectory())
  64. .filter(entry => !localArtifactDirs.has(entry.name))
  65. .filter(entry => existsSync(join(root, base, entry.name, 'package.json')))
  66. .map(entry => join(base, entry.name))
  67. }
  68. return readdirSync(join(root, base), { withFileTypes: true })
  69. .filter(entry => entry.isDirectory())
  70. .filter(entry => !localArtifactDirs.has(entry.name))
  71. .flatMap(group => packageDirs(join(base, group.name), depth - 1))
  72. }
  73. function workspaceManifests(): WorkspaceManifest[] {
  74. const manifests: WorkspaceManifest[] = [
  75. { dir: '.', manifest: rootManifest },
  76. ]
  77. for (const { dir: base, depth } of workspaceGlobs) {
  78. for (const dir of packageDirs(base, depth)) {
  79. manifests.push({ dir, manifest: readJson(join(root, dir, 'package.json')) })
  80. }
  81. }
  82. return manifests
  83. }
  84. const dshPackageFiles = [
  85. 'lib/index.js',
  86. 'lib/types/**/*.d.ts',
  87. 'lib/types/**/*.d.ts.map',
  88. 'src',
  89. ] as const
  90. const dshBinPackageFiles = [
  91. 'lib/index.js',
  92. 'lib/bin.js',
  93. 'lib/types/**/*.d.ts',
  94. 'lib/types/**/*.d.ts.map',
  95. 'src',
  96. ] as const
  97. const dshWorkerPackageFiles = [
  98. 'lib/index.js',
  99. 'lib/worker.cjs',
  100. 'lib/types/**/*.d.ts',
  101. 'lib/types/**/*.d.ts.map',
  102. 'src',
  103. ] as const
  104. const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
  105. '@deepseek-ai/dsh-helper': ['lib/assets'],
  106. '@deepseek-ai/dsh-scripts': [
  107. 'lib/dev/tsdown-config.js',
  108. 'lib/local-plugin-loader-hooks.js',
  109. 'lib/assets',
  110. ],
  111. }
  112. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  113. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  114. }
  115. function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  116. const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
  117. if (extras.length > 0) {
  118. return [
  119. 'lib/index.js',
  120. ...manifest.bin ? ['lib/bin.js'] : [],
  121. ...extras,
  122. 'lib/types/**/*.d.ts',
  123. 'lib/types/**/*.d.ts.map',
  124. 'src',
  125. ]
  126. }
  127. if (manifest.bin) return dshBinPackageFiles
  128. // A declared "./worker" subpath export sanctions the one extra runtime
  129. // bundle a worker-thread entry needs (and NodeNext/publint then validate
  130. // that subpath's targets like any other export).
  131. if (manifest.exports?.['./worker']) return dshWorkerPackageFiles
  132. return dshPackageFiles
  133. }
  134. function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
  135. const errors: string[] = []
  136. const label = manifest.name ?? dir
  137. if (manifest.private !== true) {
  138. errors.push(`${label}: package.json must set "private": true`)
  139. }
  140. if (manifest.name && vendoredPackages.has(manifest.name)) {
  141. return errors
  142. }
  143. if (manifest.name?.startsWith('@deepseek-ai/dsh-') && manifest.name !== '@deepseek-ai/dsh-root') {
  144. const peer = manifest.peerDependencies?.cordis
  145. const dev = manifest.devDependencies?.cordis
  146. if (!peer) errors.push(`${label}: cordis must be a peerDependency`)
  147. if (!dev) errors.push(`${label}: cordis must also be a devDependency`)
  148. if (peer && dev && peer !== dev) {
  149. errors.push(`${label}: cordis peer (${peer}) and dev (${dev}) ranges must match`)
  150. }
  151. if (manifest.version !== repositoryVersion) {
  152. errors.push(`${label}: package.json version must match root version ${repositoryVersion ?? '(missing)'}`)
  153. }
  154. if (manifest.type !== 'module') {
  155. errors.push(`${label}: package.json must set "type": "module"`)
  156. }
  157. if (manifest.main !== 'lib/index.js') {
  158. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  159. }
  160. if (manifest.types !== 'lib/types/index.d.ts') {
  161. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  162. }
  163. if (manifest.exports?.['.']?.types !== './lib/types/index.d.ts') {
  164. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  165. }
  166. if (manifest.exports?.['.']?.default !== './lib/index.js') {
  167. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  168. }
  169. const expectedFiles = expectedDshPackageFiles(manifest)
  170. if (!sameStringList(manifest.files, expectedFiles)) {
  171. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  172. }
  173. }
  174. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  175. }
  176. /**
  177. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  178. * package.json, and packages may be neither flat nor more deeply nested.
  179. */
  180. function checkHierarchyShape(): string[] {
  181. const errors: string[] = []
  182. const packagesRoot = join(root, 'packages')
  183. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  184. if (!group.isDirectory()) continue
  185. const groupRel = join('packages', group.name)
  186. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  187. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  188. continue
  189. }
  190. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  191. if (!pkg.isDirectory()) continue
  192. if (localArtifactDirs.has(pkg.name)) continue
  193. const pkgRel = join(groupRel, pkg.name)
  194. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  195. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  196. }
  197. }
  198. }
  199. return errors
  200. }
  201. function checkRepositoryVersion(): string[] {
  202. if (repositoryVersion && /^\d+\.\d+\.\d+$/.test(repositoryVersion)) return []
  203. return ['package.json: version must be stable X.Y.Z']
  204. }
  205. const errors = [
  206. ...checkRepositoryVersion(),
  207. ...workspaceManifests().flatMap(checkWorkspace),
  208. ...checkHierarchyShape(),
  209. ]
  210. if (errors.length > 0) {
  211. console.error(errors.join('\n'))
  212. process.exitCode = 1
  213. }