check-workspace-constraints.ts 23 KB

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