check-workspace-constraints.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. /** Repo-relative dirs holding a package.json, walked to the configured depth. */
  58. function packageDirs(base: string, depth: number): string[] {
  59. if (depth === 1) {
  60. return readdirSync(join(root, base), { withFileTypes: true })
  61. .filter(entry => entry.isDirectory())
  62. .filter(entry => !localArtifactDirs.has(entry.name))
  63. .filter(entry => existsSync(join(root, base, entry.name, 'package.json')))
  64. .map(entry => join(base, entry.name))
  65. }
  66. return readdirSync(join(root, base), { withFileTypes: true })
  67. .filter(entry => entry.isDirectory())
  68. .filter(entry => !localArtifactDirs.has(entry.name))
  69. .flatMap(group => packageDirs(join(base, group.name), depth - 1))
  70. }
  71. function workspaceManifests(): WorkspaceManifest[] {
  72. const manifests: WorkspaceManifest[] = [
  73. { dir: '.', manifest: readJson(join(root, 'package.json')) },
  74. ]
  75. for (const { dir: base, depth } of workspaceGlobs) {
  76. for (const dir of packageDirs(base, depth)) {
  77. manifests.push({ dir, manifest: readJson(join(root, dir, 'package.json')) })
  78. }
  79. }
  80. return manifests
  81. }
  82. const dshPackageFiles = [
  83. 'lib/index.js',
  84. 'lib/types/**/*.d.ts',
  85. 'lib/types/**/*.d.ts.map',
  86. 'src',
  87. ] as const
  88. const dshBinPackageFiles = [
  89. 'lib/index.js',
  90. 'lib/bin.js',
  91. 'lib/types/**/*.d.ts',
  92. 'lib/types/**/*.d.ts.map',
  93. 'src',
  94. ] as const
  95. const dshWorkerPackageFiles = [
  96. 'lib/index.js',
  97. 'lib/worker.js',
  98. 'lib/types/**/*.d.ts',
  99. 'lib/types/**/*.d.ts.map',
  100. 'src',
  101. ] as const
  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. if (manifest.bin) return dshBinPackageFiles
  107. // A declared "./worker" subpath export sanctions the one extra runtime
  108. // bundle a worker-thread entry needs (and NodeNext/publint then validate
  109. // that subpath's targets like any other export).
  110. if (manifest.exports?.['./worker']) return dshWorkerPackageFiles
  111. return dshPackageFiles
  112. }
  113. function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
  114. const errors: string[] = []
  115. const label = manifest.name ?? dir
  116. if (manifest.private !== true) {
  117. errors.push(`${label}: package.json must set "private": true`)
  118. }
  119. if (manifest.name && vendoredPackages.has(manifest.name)) {
  120. return errors
  121. }
  122. if (manifest.name?.startsWith('@deepseek-ai/dsh-') && manifest.name !== '@deepseek-ai/dsh-root') {
  123. const peer = manifest.peerDependencies?.cordis
  124. const dev = manifest.devDependencies?.cordis
  125. if (!peer) errors.push(`${label}: cordis must be a peerDependency`)
  126. if (!dev) errors.push(`${label}: cordis must also be a devDependency`)
  127. if (peer && dev && peer !== dev) {
  128. errors.push(`${label}: cordis peer (${peer}) and dev (${dev}) ranges must match`)
  129. }
  130. if (manifest.version !== '0.0.1') {
  131. errors.push(`${label}: package.json must set "version": "0.0.1"`)
  132. }
  133. if (manifest.type !== 'module') {
  134. errors.push(`${label}: package.json must set "type": "module"`)
  135. }
  136. if (manifest.main !== 'lib/index.js') {
  137. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  138. }
  139. if (manifest.types !== 'lib/types/index.d.ts') {
  140. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  141. }
  142. if (manifest.exports?.['.']?.types !== './lib/types/index.d.ts') {
  143. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  144. }
  145. if (manifest.exports?.['.']?.default !== './lib/index.js') {
  146. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  147. }
  148. const expectedFiles = expectedDshPackageFiles(manifest)
  149. if (!sameStringList(manifest.files, expectedFiles)) {
  150. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  151. }
  152. }
  153. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  154. }
  155. /**
  156. * Enforce the packages/ hierarchy SHAPE: every package lives at exactly
  157. * `packages/<group>/<pkg>`. A group dir is a pure container — it holds packages,
  158. * never sources of its own — so it must NOT carry a package.json, and a package
  159. * must NOT sit directly at the `packages/` root (the old flat layout) nor nest a
  160. * level deeper. The group NAMES are open on purpose: a new group may be added
  161. * without touching this gate, but the depth-2 shape is fixed. This is what keeps
  162. * a stray flat package or an over-nested one from regressing the hierarchy.
  163. */
  164. function checkHierarchyShape(): string[] {
  165. const errors: string[] = []
  166. const packagesRoot = join(root, 'packages')
  167. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  168. if (!group.isDirectory()) continue
  169. const groupRel = join('packages', group.name)
  170. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  171. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  172. continue
  173. }
  174. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  175. if (!pkg.isDirectory()) continue
  176. if (localArtifactDirs.has(pkg.name)) continue
  177. const pkgRel = join(groupRel, pkg.name)
  178. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  179. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  180. }
  181. }
  182. }
  183. return errors
  184. }
  185. const errors = [...workspaceManifests().flatMap(checkWorkspace), ...checkHierarchyShape()]
  186. if (errors.length > 0) {
  187. console.error(errors.join('\n'))
  188. process.exitCode = 1
  189. }