check-workspace-constraints.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 { pathToFileURL } from 'node:url'
  10. import { hasTypertRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
  11. import { collectProjectReferenceFaceViolations } from './project-reference-faces.ts'
  12. const root = resolve(import.meta.dirname, '..')
  13. // vendor/* is single-level; packages/<group>/<pkg> nests one level deeper
  14. // (the group dirs — core/llm/shell/… — are pure containers with no manifest).
  15. const workspaceGlobs = [
  16. { dir: 'vendor', depth: 1 },
  17. { dir: 'packages', depth: 2 },
  18. { dir: 'native', depth: 1 },
  19. { dir: 'native/system/packages', depth: 1 },
  20. { dir: 'apps', depth: 1 },
  21. ] as const
  22. const vendoredPackages = new Set([
  23. '@deepseek-ai/cordis',
  24. '@deepseek-ai/cosmokit',
  25. '@deepseek-ai/schemastery',
  26. '@deepseek-ai/cordis-plugin-loader',
  27. '@deepseek-ai/cordis-plugin-include',
  28. '@deepseek-ai/cordis-plugin-group',
  29. '@deepseek-ai/cordis-plugin-timer',
  30. '@deepseek-ai/cordis-plugin-hmr',
  31. '@deepseek-ai/cordis-plugin-logger-console',
  32. ])
  33. const publicNativePackages = new Set([
  34. '@deepseek-ai/node-addon-system',
  35. '@deepseek-ai/node-addon-system-darwin-arm64',
  36. '@deepseek-ai/node-addon-system-darwin-x64',
  37. '@deepseek-ai/node-addon-system-linux-arm64',
  38. '@deepseek-ai/node-addon-system-linux-x64',
  39. ])
  40. /** Deliberate source payloads whose exact bytes are part of the package's audit surface. */
  41. const publicationSourceAllowlist: Readonly<Record<string, readonly string[]>> = {
  42. '@deepseek-ai/node-addon-system': ['src/main.c', 'src/flock.c'],
  43. }
  44. const repositoryUrl = 'git+https://github.com/deepseek-harness/deepseek-harness.git'
  45. /**
  46. * Source home the published packages point consumers at. It differs from
  47. * {@link repositoryUrl}, which the Landlock packages keep because npm resolves
  48. * their trusted publishing against the repository that runs the workflow.
  49. */
  50. const publishedRepositoryUrl = 'git+https://github.com/deepseek-ai/deepseek-harness.git'
  51. /** Private packages that participate in workspace checks but not releases. */
  52. const experimentalPackageDirectory = /^packages\/experimental\/[^/]+$/
  53. /** npm namespace reserved for private experimental packages. */
  54. const experimentalPackageNamePrefix = '@deepseek-ai/dsh-experimental-'
  55. /** Directories whose packages this repository publishes: one release member each. */
  56. const releaseMemberDirectory = /^(?:packages\/(?!experimental\/)[^/]+\/[^/]+|apps\/(?!desktop(?:-host)?$)[^/]+|vendor\/[^/]+)$/
  57. /** Installable application assembled by electron-builder rather than published to npm. */
  58. const desktopApplicationDirectory = 'apps/desktop'
  59. const localArtifactDirs = new Set(['node_modules'])
  60. const appPackageFiles: Readonly<Record<string, readonly string[]>> = {
  61. '@deepseek-ai/dsh': ['lib/*.js'],
  62. '@deepseek-ai/dsh-desktop-host': [
  63. 'lib/index.js',
  64. 'config/desktop.cordis.patch.yml',
  65. ],
  66. // Sourcemaps stay out by payload policy; the worker-preview surface
  67. // (dist/preview.html and dist/preview/) backs private experimental
  68. // packages and is not published.
  69. '@deepseek-ai/dsh-web-frontend': ['dist', '!dist/**/*.map', '!dist/preview.html', '!dist/preview'],
  70. }
  71. /** The subset of package.json fields this constraint check cares about. */
  72. export interface PackageManifest {
  73. name?: string
  74. version?: string
  75. private?: boolean
  76. type?: string
  77. main?: string
  78. types?: string
  79. bin?: string | Record<string, string>
  80. exports?: Record<
  81. string,
  82. | string
  83. | {
  84. types?: string
  85. default?: string
  86. }
  87. | null
  88. | undefined
  89. >
  90. files?: string[]
  91. publishConfig?: { access?: string }
  92. repository?: { type?: string; url?: string; directory?: string }
  93. peerDependencies?: Record<string, string>
  94. devDependencies?: Record<string, string>
  95. dependencies?: Record<string, string>
  96. optionalDependencies?: Record<string, string>
  97. dsh?: {
  98. bundle?: {
  99. patch?: string
  100. }
  101. }
  102. }
  103. /** One workspace manifest and its repo-relative path. */
  104. export interface WorkspaceManifest {
  105. dir: string
  106. manifest: PackageManifest
  107. }
  108. function readJson(path: string): PackageManifest {
  109. return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
  110. }
  111. const rootManifest = readJson(join(root, 'package.json'))
  112. const repositoryVersion = rootManifest.version
  113. const nativeWorkspaceManifest = readJson(join(root, 'native/system/package.json'))
  114. const nativeVersion = nativeWorkspaceManifest.version
  115. /** Repo-relative dirs holding a package.json, walked to the configured depth. */
  116. function packageDirs(base: string, depth: number): string[] {
  117. if (depth === 1) {
  118. return readdirSync(join(root, base), { withFileTypes: true })
  119. .filter(entry => entry.isDirectory())
  120. .filter(entry => !localArtifactDirs.has(entry.name))
  121. .filter(entry => existsSync(join(root, base, entry.name, 'package.json')))
  122. .map(entry => `${base}/${entry.name}`)
  123. }
  124. return readdirSync(join(root, base), { withFileTypes: true })
  125. .filter(entry => entry.isDirectory())
  126. .filter(entry => !localArtifactDirs.has(entry.name))
  127. .flatMap(group => packageDirs(`${base}/${group.name}`, depth - 1))
  128. }
  129. function workspaceManifests(): WorkspaceManifest[] {
  130. const manifests: WorkspaceManifest[] = [
  131. { dir: '.', manifest: rootManifest },
  132. ]
  133. for (const { dir: base, depth } of workspaceGlobs) {
  134. for (const dir of packageDirs(base, depth)) {
  135. manifests.push({ dir, manifest: readJson(join(root, dir, 'package.json')) })
  136. }
  137. }
  138. return manifests
  139. }
  140. const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
  141. // Statically linked client libraries keep their stylesheets next to the emitted
  142. // JavaScript, which imports them by relative path: the compile shell runs
  143. // them through its own CSS pipeline, so the sheets are published artifacts.
  144. // The glob covers whichever sheets a package emits; sourcemaps stay
  145. // unpublished, as everywhere else in the repository.
  146. '@deepseek-ai/dsh-client-ui-primitives': ['lib/**/*.css'],
  147. '@deepseek-ai/dsh-client-ui-dockkit': ['lib/**/*.css'],
  148. '@deepseek-ai/dsh-client-web': ['lib/**/*.css'],
  149. '@deepseek-ai/dsh-client-ui-theme': ['lib/styles'],
  150. // The CPython side ships as source .py files, published as-is rather than built.
  151. '@deepseek-ai/dsh-experimental-code-runtime-python': ['py/**/*.py'],
  152. // The shipped preset compositions travel inside the roster package.
  153. '@deepseek-ai/dsh-agent-presets': ['presets'],
  154. // The Web Host mounts the default-off settings owner independently of each
  155. // Agent-scoped delegation-tool instance.
  156. '@deepseek-ai/dsh-tool-subagent': ['lib/model-selection-settings.js'],
  157. // The JSONL backend resolves its private verification Worker relative to
  158. // import.meta.url; it is shipped without a public package subpath.
  159. '@deepseek-ai/dsh-session-persistence-jsonl': ['lib/worker.cjs'],
  160. // The argv-prefix runner entry ships beside the lib as its own bundle;
  161. // sandbox-local resolves it through the package's ./runner export. tsdown
  162. // also shares its generated FFI code through a hashed runtime chunk.
  163. '@deepseek-ai/dsh-sandbox-windows-acl': ['lib/runner.js', 'lib/types-*.js'],
  164. '@deepseek-ai/dsh-skill-badge': ['assets'],
  165. // Ordinary native containment ships a path-loaded runner and its shared
  166. // runner chunk beside the existing node-pty permission repair.
  167. '@deepseek-ai/dsh-subprocess-local': [
  168. 'lib/runner.js',
  169. 'lib/runner-*.js',
  170. 'scripts/ensure-spawn-helper.mjs',
  171. ],
  172. // tsdown shares the repository/pack code between the lib entry and the bin
  173. // through a hashed chunk. The committed bin.js is the link target pnpm can
  174. // resolve at install time, before the build produces lib/bin.js.
  175. '@deepseek-ai/dsh-experimental-webworker-packer': ['bin.js', 'lib/repository-*.js'],
  176. }
  177. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  178. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  179. }
  180. export function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  181. const declaredPatch = manifest.dsh?.bundle?.patch
  182. const bundleFiles = declaredPatch === undefined ? [] : [declaredPatch.replace(/^\.\//, '')]
  183. const extras = [
  184. ...bundleFiles,
  185. ...(manifest.name ? packageFileExtras[manifest.name] ?? [] : []),
  186. ]
  187. return [
  188. 'lib/index.js',
  189. // Packages with an invariant export publish its runtime as a separate
  190. // bundle; the package-invariant gate validates the source/export pairing.
  191. ...manifest.exports?.['./invariant'] ? ['lib/invariant.js'] : [],
  192. ...manifest.bin ? ['lib/bin.js'] : [],
  193. // Worker-thread packages ship a CJS worker entry; the browser worker
  194. // bundle is an ES module a page loads with `new Worker(type: 'module')`.
  195. // Keyed on the artifact path, like ./client below.
  196. ...exportDefault(manifest, './worker') === './lib/worker.cjs' ? ['lib/worker.cjs'] : [],
  197. ...exportDefault(manifest, './worker') === './lib/worker.js' ? ['lib/worker.js'] : [],
  198. // UI plugin packages ship their browser bundle beside the node lib
  199. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  200. // Keyed on the artifact path, not the subpath name: a package's ./client is
  201. // a browser-safe source channel, not a bundle.
  202. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  203. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  204. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  205. // A store subpath ships its own bundle (single-entry builds; no shared chunk).
  206. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  207. // A surface bundle's startup row is its own bundle: the Loader imports it
  208. // as a row module, so it cannot ride inside the package entry.
  209. ...exportDefault(manifest, './startup') === './lib/startup.js' ? ['lib/startup.js'] : [],
  210. ...extras,
  211. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  212. // browser-safe source channels rehomed off src so plain Node can import
  213. // them without type stripping) publish the emitted JS alongside the
  214. // declarations.
  215. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  216. 'lib/types/**/*.d.ts',
  217. ...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
  218. ? ['lib/typert.host.js', 'lib/typert.host.d.ts']
  219. : [],
  220. ...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
  221. ? ['lib/typert.client.js', 'lib/typert.client.d.ts']
  222. : [],
  223. ...hasTypertRemoteNavigation(manifest)
  224. ? ['lib/typert.remote-client.js', 'lib/typert.remote-client.d.ts']
  225. : [],
  226. ]
  227. }
  228. /** Whether one conditional export exactly names the generated runtime and declaration pair. */
  229. function hasExportPair(
  230. manifest: PackageManifest,
  231. subpath: string,
  232. types: string,
  233. runtime: string,
  234. ): boolean {
  235. const entry = manifest.exports?.[subpath]
  236. return typeof entry === 'object'
  237. && entry !== null
  238. && entry.types === types
  239. && entry.default === runtime
  240. }
  241. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  242. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  243. const entry = manifest.exports?.[subpath]
  244. if (typeof entry === 'string') return entry
  245. if (typeof entry === 'object' && entry !== null) return entry.default
  246. return undefined
  247. }
  248. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  249. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  250. return Object.keys(manifest.exports ?? {}).some(subpath =>
  251. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  252. }
  253. /** Experimental manifest requirements enforced independently from release metadata. */
  254. export function checkExperimentalManifest({ dir, manifest }: WorkspaceManifest): string[] {
  255. if (!experimentalPackageDirectory.test(dir)) return []
  256. const label = manifest.name ?? dir
  257. const errors: string[] = []
  258. if (manifest.name?.startsWith(experimentalPackageNamePrefix) !== true) {
  259. errors.push(`${label}: experimental package name must start with ${JSON.stringify(experimentalPackageNamePrefix)}`)
  260. }
  261. if (manifest.private !== true) errors.push(`${label}: experimental package must set "private": true`)
  262. if (manifest.publishConfig !== undefined) errors.push(`${label}: experimental package must omit publishConfig`)
  263. return errors
  264. }
  265. /**
  266. * Require a dsh-family manifest to carry the workspace version.
  267. *
  268. * The dsh release sequence publishes packages/ and apps/ members and every
  269. * private dsh package on one shared version, written by `release:dsh` and
  270. * shared with the workspace root. This name test is that boundary: it covers
  271. * the family wherever the manifest lives, so apps/ members cannot drift with
  272. * only the release lane noticing.
  273. * @param manifest - the workspace package manifest.
  274. * @param expected - the version every dsh-family manifest must carry (the root's).
  275. * @returns one violation naming the manifest and the expected version, or
  276. * undefined when the manifest is compliant or not in the family.
  277. */
  278. export function checkDshFamilyVersion(manifest: PackageManifest, expected: string | undefined): string | undefined {
  279. const name = manifest.name
  280. if (name !== '@deepseek-ai/dsh' && name?.startsWith('@deepseek-ai/dsh-') !== true) return undefined
  281. if (manifest.version !== expected) {
  282. return `${name}: package.json version must match root version ${expected ?? '(missing)'}`
  283. }
  284. return undefined
  285. }
  286. /**
  287. * Check one workspace manifest against publication and dsh-package policy.
  288. * @param workspace - package directory and parsed manifest.
  289. * @returns path-qualified policy violations.
  290. */
  291. export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): string[] {
  292. const errors = checkExperimentalManifest({ dir, manifest })
  293. const label = manifest.name ?? dir
  294. const familyVersionError = checkDshFamilyVersion(manifest, repositoryVersion)
  295. if (familyVersionError !== undefined) errors.push(familyVersionError)
  296. const isNativePackageDir = dir.startsWith('native/system/packages/')
  297. const isPublicNativePackage = isNativePackageDir
  298. && manifest.name !== undefined
  299. && publicNativePackages.has(manifest.name)
  300. if (isPublicNativePackage) {
  301. if (manifest.private === true) {
  302. errors.push(`${label}: published Landlock package must not set "private": true`)
  303. }
  304. if (manifest.publishConfig?.access !== 'public') {
  305. errors.push(`${label}: published Landlock package must set publishConfig.access to "public"`)
  306. }
  307. const expectedDirectory = dir
  308. if (manifest.repository?.type !== 'git'
  309. || manifest.repository.url !== repositoryUrl
  310. || manifest.repository.directory !== expectedDirectory) {
  311. errors.push(`${label}: published Landlock package repository must use ${repositoryUrl} with directory ${expectedDirectory} for trusted publishing`)
  312. }
  313. } else if (releaseMemberDirectory.test(dir)) {
  314. // Release members state that they are publishable: npm refuses a private
  315. // package, and the repository field is how a consumer finds the source of
  316. // the package it installed.
  317. //
  318. // Access is per release sequence, not per scope: the vendored framework and
  319. // the Landlock packages publish publicly because outside consumers install
  320. // them, and the dsh family published publicly with its own sequence on
  321. // 2026-08-13. No publish path passes `--access`; each packed manifest declares
  322. // it, and this gate requires every release member to be public.
  323. if (manifest.private === true) {
  324. errors.push(`${label}: release member must not set "private": true`)
  325. }
  326. if (manifest.publishConfig?.access !== 'public') {
  327. errors.push(`${label}: release member must set publishConfig.access to "public"`)
  328. }
  329. if (manifest.repository?.type !== 'git'
  330. || manifest.repository.url !== publishedRepositoryUrl
  331. || manifest.repository.directory !== dir) {
  332. errors.push(`${label}: release member repository must use ${publishedRepositoryUrl} with directory ${dir}`)
  333. }
  334. } else if (!experimentalPackageDirectory.test(dir) && manifest.private !== true) {
  335. errors.push(`${label}: package.json must set "private": true`)
  336. }
  337. if (manifest.name && vendoredPackages.has(manifest.name)) {
  338. return errors
  339. }
  340. if (manifest.name?.startsWith('@deepseek-ai/')) {
  341. const allowedSources = publicationSourceAllowlist[manifest.name] ?? []
  342. for (const file of manifest.files ?? []) {
  343. if (isForbiddenPublicationFile(file) && !allowedSources.includes(file)) {
  344. errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
  345. }
  346. }
  347. }
  348. if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && manifest.name?.startsWith('@deepseek-ai/')) {
  349. const expectedFiles = appPackageFiles[manifest.name]
  350. if (expectedFiles === undefined) {
  351. errors.push(`${label}: app package has no publication files policy`)
  352. } else if (!sameStringList(manifest.files, expectedFiles)) {
  353. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  354. }
  355. }
  356. if (isNativePackageDir) {
  357. if (!isPublicNativePackage) {
  358. errors.push(`${label}: unexpected package in the public Landlock package family`)
  359. }
  360. if (manifest.version !== nativeVersion) {
  361. errors.push(`${label}: package.json version must match native workspace version ${nativeVersion ?? '(missing)'}`)
  362. }
  363. }
  364. if (dir.startsWith('packages/') && manifest.name?.startsWith('@deepseek-ai/dsh-')) {
  365. const peer = manifest.peerDependencies?.['@deepseek-ai/cordis']
  366. const dev = manifest.devDependencies?.['@deepseek-ai/cordis']
  367. if (!peer) errors.push(`${label}: @deepseek-ai/cordis must be a peerDependency`)
  368. if (!dev) errors.push(`${label}: @deepseek-ai/cordis must also be a devDependency`)
  369. if (peer && dev && peer !== dev) {
  370. errors.push(`${label}: @deepseek-ai/cordis peer (${peer}) and dev (${dev}) ranges must match`)
  371. }
  372. if (manifest.type !== 'module') {
  373. errors.push(`${label}: package.json must set "type": "module"`)
  374. }
  375. if (manifest.main !== 'lib/index.js') {
  376. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  377. }
  378. if (manifest.types !== 'lib/types/index.d.ts') {
  379. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  380. }
  381. const rootExport = manifest.exports?.['.']
  382. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  383. if (rootEntry?.types !== './lib/types/index.d.ts') {
  384. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  385. }
  386. if (rootEntry?.default !== './lib/index.js') {
  387. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  388. }
  389. const invariantRaw = manifest.exports?.['./invariant']
  390. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  391. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  392. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  393. }
  394. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  395. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  396. }
  397. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  398. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  399. }
  400. const expectedFiles = expectedDshPackageFiles(manifest)
  401. if (!sameStringList(manifest.files, expectedFiles)) {
  402. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  403. }
  404. }
  405. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  406. }
  407. /**
  408. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  409. * package.json, and packages may be neither flat nor more deeply nested.
  410. */
  411. function checkHierarchyShape(): string[] {
  412. const errors: string[] = []
  413. const packagesRoot = join(root, 'packages')
  414. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  415. if (!group.isDirectory()) continue
  416. const groupRel = join('packages', group.name)
  417. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  418. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  419. continue
  420. }
  421. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  422. if (!pkg.isDirectory()) continue
  423. if (localArtifactDirs.has(pkg.name)) continue
  424. const pkgRel = join(groupRel, pkg.name)
  425. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  426. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  427. }
  428. }
  429. }
  430. return errors
  431. }
  432. function checkRepositoryVersion(): string[] {
  433. // The root carries the dsh release family's version, so a prerelease such as
  434. // 0.0.1-rc.1 is a valid state between `release:dsh` and its publication.
  435. if (repositoryVersion && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(repositoryVersion)) return []
  436. return ['package.json: version must be X.Y.Z with an optional prerelease segment']
  437. }
  438. /** Dependency sections whose ranges reach a published tarball or a local install. */
  439. const dependencySections = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'] as const
  440. /** Dependency sections present in an installed runtime. */
  441. const runtimeDependencySections = ['dependencies', 'optionalDependencies', 'peerDependencies'] as const
  442. /**
  443. * Prevent an official runtime from requiring a package its release omits.
  444. * @param manifests - release, private experimental, and deployment-root manifests.
  445. * @returns One error for each forbidden runtime dependency.
  446. */
  447. export function checkExperimentalDependencyIsolation(manifests: readonly WorkspaceManifest[]): string[] {
  448. const experimentalNames = new Set(manifests
  449. .filter(entry => experimentalPackageDirectory.test(entry.dir))
  450. .map(entry => entry.manifest.name)
  451. .filter(name => name !== undefined))
  452. const errors: string[] = []
  453. for (const { dir, manifest } of manifests) {
  454. if (!releaseMemberDirectory.test(dir) && dir !== 'python/sdk-runtime') continue
  455. for (const section of runtimeDependencySections) {
  456. for (const name of Object.keys(manifest[section] ?? {})) {
  457. if (!experimentalNames.has(name)) continue
  458. errors.push(`${manifest.name ?? dir}: ${section}.${name} must not reference an experimental package`)
  459. }
  460. }
  461. }
  462. return errors
  463. }
  464. /**
  465. * Require the `workspace:` protocol for every reference to a workspace member.
  466. *
  467. * A hand-written range says nothing about the version the workspace actually
  468. * carries, and `pnpm pack` leaves it alone: `^0.0.1` published from version
  469. * `0.0.2` names a version that does not exist. The protocol makes pack
  470. * substitute the member's real version, so no release step rewrites ranges.
  471. * @param manifests - every workspace manifest.
  472. * @returns One error per reference that names a workspace member without the protocol.
  473. */
  474. function checkWorkspaceProtocol(manifests: readonly WorkspaceManifest[]): string[] {
  475. const members = new Set(manifests.map(entry => entry.manifest.name).filter(name => name !== undefined))
  476. const errors: string[] = []
  477. for (const { dir, manifest } of manifests) {
  478. for (const section of dependencySections) {
  479. for (const [name, range] of Object.entries(manifest[section] ?? {})) {
  480. if (!members.has(name) || range.startsWith('workspace:')) continue
  481. errors.push(`${manifest.name ?? dir}: ${section}.${name} must use the workspace: protocol, got ${range}`)
  482. }
  483. }
  484. }
  485. return errors
  486. }
  487. /** Run the repository constraint gate. */
  488. export function main(): void {
  489. const manifests = workspaceManifests()
  490. const dependencyManifests = [
  491. ...manifests,
  492. { dir: 'python/sdk-runtime', manifest: readJson(join(root, 'python/sdk-runtime/package.json')) },
  493. ]
  494. const errors = [
  495. ...checkRepositoryVersion(),
  496. ...manifests.flatMap(checkWorkspaceManifest),
  497. ...checkWorkspaceProtocol(manifests),
  498. ...checkExperimentalDependencyIsolation(dependencyManifests),
  499. ...checkHierarchyShape(),
  500. ...collectProjectReferenceFaceViolations(root),
  501. ]
  502. if (errors.length > 0) {
  503. console.error(errors.join('\n'))
  504. process.exitCode = 1
  505. }
  506. }
  507. if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) main()