check-workspace-constraints.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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', 'config'],
  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 private Python carrier ships only its closed-resolution entry.
  146. '@deepseek-ai/dsh-sdk-python-runtime': ['lib/packaged-bin.js'],
  147. // The argv-prefix runner entry ships beside the lib as its own bundle;
  148. // sandbox-local resolves it through the package's ./runner export. tsdown
  149. // also shares its generated FFI code through a hashed runtime chunk.
  150. '@deepseek-ai/dsh-sandbox-windows-acl': ['lib/runner.js', 'lib/types-*.js'],
  151. // SQLite loads every statement from immutable package resources at runtime.
  152. '@deepseek-ai/dsh-session-persistence-sqlite': ['resources/sql/**/*.sql'],
  153. '@deepseek-ai/dsh-skill-badge': ['assets'],
  154. // tsdown shares the repository/pack code between the lib entry and the bin
  155. // through a hashed chunk. The committed bin.js is the link target pnpm can
  156. // resolve at install time, before the build produces lib/bin.js.
  157. '@deepseek-ai/dsh-experimental-webworker-packer': ['bin.js', 'lib/repository-*.js'],
  158. '@deepseek-ai/dsh-subprocess-local': ['scripts/ensure-spawn-helper.mjs'],
  159. }
  160. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  161. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  162. }
  163. function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  164. const declaredPatch = manifest.dsh?.bundle?.patch
  165. const bundleFiles = declaredPatch === undefined ? [] : [declaredPatch.replace(/^\.\//, '')]
  166. const extras = [
  167. ...bundleFiles,
  168. ...(manifest.name ? packageFileExtras[manifest.name] ?? [] : []),
  169. ]
  170. return [
  171. 'lib/index.js',
  172. // Every package publishes its invariant ownership companion as a separate
  173. // bundle; the package-invariant gate validates the companion itself.
  174. 'lib/invariant.js',
  175. ...manifest.bin ? ['lib/bin.js'] : [],
  176. // Worker-thread packages ship a CJS worker entry; the browser worker
  177. // bundle is an ES module a page loads with `new Worker(type: 'module')`.
  178. // Keyed on the artifact path, like ./client below.
  179. ...exportDefault(manifest, './worker') === './lib/worker.cjs' ? ['lib/worker.cjs'] : [],
  180. ...exportDefault(manifest, './worker') === './lib/worker.js' ? ['lib/worker.js'] : [],
  181. // UI plugin packages ship their browser bundle beside the node lib
  182. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  183. // Keyed on the artifact path, not the subpath name: apiproxy's ./client is
  184. // a browser-safe source channel, not a bundle.
  185. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  186. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  187. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  188. // A store subpath ships its own bundle (single-entry builds; no shared chunk).
  189. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  190. // A surface bundle's startup row is its own bundle: the Loader imports it
  191. // as a row module, so it cannot ride inside the package entry.
  192. ...exportDefault(manifest, './startup') === './lib/startup.js' ? ['lib/startup.js'] : [],
  193. ...extras,
  194. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  195. // browser-safe source channels rehomed off src so plain Node can import
  196. // them without type stripping) publish the emitted JS alongside the
  197. // declarations.
  198. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  199. 'lib/types/**/*.d.ts',
  200. ...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
  201. ? ['lib/typert.host.js', 'lib/typert.host.d.ts']
  202. : [],
  203. ...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
  204. ? ['lib/typert.client.js', 'lib/typert.client.d.ts']
  205. : [],
  206. ...hasTypertRemoteNavigation(manifest)
  207. ? ['lib/typert.remote-client.js', 'lib/typert.remote-client.d.ts']
  208. : [],
  209. ]
  210. }
  211. /** Whether one conditional export exactly names the generated runtime and declaration pair. */
  212. function hasExportPair(
  213. manifest: PackageManifest,
  214. subpath: string,
  215. types: string,
  216. runtime: string,
  217. ): boolean {
  218. const entry = manifest.exports?.[subpath]
  219. return typeof entry === 'object'
  220. && entry !== null
  221. && entry.types === types
  222. && entry.default === runtime
  223. }
  224. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  225. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  226. const entry = manifest.exports?.[subpath]
  227. if (typeof entry === 'string') return entry
  228. if (typeof entry === 'object' && entry !== null) return entry.default
  229. return undefined
  230. }
  231. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  232. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  233. return Object.keys(manifest.exports ?? {}).some(subpath =>
  234. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  235. }
  236. /** Experimental manifest requirements enforced independently from release metadata. */
  237. export function checkExperimentalManifest({ dir, manifest }: WorkspaceManifest): string[] {
  238. if (!experimentalPackageDirectory.test(dir)) return []
  239. const label = manifest.name ?? dir
  240. const errors: string[] = []
  241. if (manifest.name?.startsWith(experimentalPackageNamePrefix) !== true) {
  242. errors.push(`${label}: experimental package name must start with ${JSON.stringify(experimentalPackageNamePrefix)}`)
  243. }
  244. if (manifest.private !== true) errors.push(`${label}: experimental package must set "private": true`)
  245. if (manifest.publishConfig !== undefined) errors.push(`${label}: experimental package must omit publishConfig`)
  246. return errors
  247. }
  248. /**
  249. * Check one workspace manifest against publication and dsh-package policy.
  250. * @param workspace - package directory and parsed manifest.
  251. * @returns path-qualified policy violations.
  252. */
  253. export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): string[] {
  254. const errors = checkExperimentalManifest({ dir, manifest })
  255. const label = manifest.name ?? dir
  256. const isLandlockPackageDir = dir.startsWith('native/landlock-run/packages/')
  257. const isPublicLandlockPackage = isLandlockPackageDir
  258. && manifest.name !== undefined
  259. && publicLandlockPackages.has(manifest.name)
  260. if (isPublicLandlockPackage) {
  261. if (manifest.private === true) {
  262. errors.push(`${label}: published Landlock package must not set "private": true`)
  263. }
  264. if (manifest.publishConfig?.access !== 'public') {
  265. errors.push(`${label}: published Landlock package must set publishConfig.access to "public"`)
  266. }
  267. const expectedDirectory = dir
  268. if (manifest.repository?.type !== 'git'
  269. || manifest.repository.url !== repositoryUrl
  270. || manifest.repository.directory !== expectedDirectory) {
  271. errors.push(`${label}: published Landlock package repository must use ${repositoryUrl} with directory ${expectedDirectory} for trusted publishing`)
  272. }
  273. } else if (privateCarrierDirectories.has(dir)) {
  274. if (manifest.private !== true) {
  275. errors.push(`${label}: private carrier must set "private": true`)
  276. }
  277. if (manifest.publishConfig !== undefined) {
  278. errors.push(`${label}: private carrier must omit publishConfig`)
  279. }
  280. } else if (releaseMemberDirectory.test(dir)) {
  281. // Release members state that they are publishable: npm refuses a private
  282. // package, and the repository field is how a consumer finds the source of
  283. // the package it installed.
  284. //
  285. // Access is per release sequence, not per scope: the vendored framework and
  286. // the Landlock packages publish publicly because outside consumers install
  287. // them, while the dsh family stays restricted until its own sequence goes
  288. // public. A mixed scope is why no publish path passes `--access` — one flag
  289. // cannot serve both, so each packed manifest decides
  290. // ([rationale](../.agents/notes/implemented/process/2026-08-13-public-vendor-and-native-sequences.md)).
  291. if (manifest.private === true) {
  292. errors.push(`${label}: release member must not set "private": true`)
  293. }
  294. if (manifest.publishConfig?.access !== 'public') {
  295. errors.push(`${label}: release member must set publishConfig.access to "public"`)
  296. }
  297. if (manifest.repository?.type !== 'git'
  298. || manifest.repository.url !== publishedRepositoryUrl
  299. || manifest.repository.directory !== dir) {
  300. errors.push(`${label}: release member repository must use ${publishedRepositoryUrl} with directory ${dir}`)
  301. }
  302. } else if (!experimentalPackageDirectory.test(dir) && manifest.private !== true) {
  303. errors.push(`${label}: package.json must set "private": true`)
  304. }
  305. if (manifest.name && vendoredPackages.has(manifest.name)) {
  306. return errors
  307. }
  308. if (manifest.name?.startsWith('@deepseek-ai/')) {
  309. const allowedSources = publicationSourceAllowlist[manifest.name] ?? []
  310. for (const file of manifest.files ?? []) {
  311. if (isForbiddenPublicationFile(file) && !allowedSources.includes(file)) {
  312. errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
  313. }
  314. }
  315. }
  316. if (dir.startsWith('apps/') && manifest.name?.startsWith('@deepseek-ai/')) {
  317. const expectedFiles = appPackageFiles[manifest.name]
  318. if (expectedFiles === undefined) {
  319. errors.push(`${label}: app package has no publication files policy`)
  320. } else if (!sameStringList(manifest.files, expectedFiles)) {
  321. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  322. }
  323. }
  324. if (isLandlockPackageDir) {
  325. if (!isPublicLandlockPackage) {
  326. errors.push(`${label}: unexpected package in the public Landlock package family`)
  327. }
  328. if (manifest.version !== landlockVersion) {
  329. errors.push(`${label}: package.json version must match Landlock workspace version ${landlockVersion ?? '(missing)'}`)
  330. }
  331. }
  332. if (dir.startsWith('packages/') && manifest.name?.startsWith('@deepseek-ai/dsh-')) {
  333. const peer = manifest.peerDependencies?.['@deepseek-ai/cordis']
  334. const dev = manifest.devDependencies?.['@deepseek-ai/cordis']
  335. if (!peer) errors.push(`${label}: @deepseek-ai/cordis must be a peerDependency`)
  336. if (!dev) errors.push(`${label}: @deepseek-ai/cordis must also be a devDependency`)
  337. if (peer && dev && peer !== dev) {
  338. errors.push(`${label}: @deepseek-ai/cordis peer (${peer}) and dev (${dev}) ranges must match`)
  339. }
  340. if (manifest.version !== repositoryVersion) {
  341. errors.push(`${label}: package.json version must match root version ${repositoryVersion ?? '(missing)'}`)
  342. }
  343. if (manifest.type !== 'module') {
  344. errors.push(`${label}: package.json must set "type": "module"`)
  345. }
  346. if (manifest.main !== 'lib/index.js') {
  347. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  348. }
  349. if (manifest.types !== 'lib/types/index.d.ts') {
  350. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  351. }
  352. const rootExport = manifest.exports?.['.']
  353. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  354. if (rootEntry?.types !== './lib/types/index.d.ts') {
  355. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  356. }
  357. if (rootEntry?.default !== './lib/index.js') {
  358. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  359. }
  360. const invariantRaw = manifest.exports?.['./invariant']
  361. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  362. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  363. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  364. }
  365. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  366. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  367. }
  368. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  369. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  370. }
  371. const expectedFiles = expectedDshPackageFiles(manifest)
  372. if (!sameStringList(manifest.files, expectedFiles)) {
  373. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  374. }
  375. }
  376. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  377. }
  378. /**
  379. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  380. * package.json, and packages may be neither flat nor more deeply nested.
  381. */
  382. function checkHierarchyShape(): string[] {
  383. const errors: string[] = []
  384. const packagesRoot = join(root, 'packages')
  385. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  386. if (!group.isDirectory()) continue
  387. const groupRel = join('packages', group.name)
  388. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  389. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  390. continue
  391. }
  392. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  393. if (!pkg.isDirectory()) continue
  394. if (localArtifactDirs.has(pkg.name)) continue
  395. const pkgRel = join(groupRel, pkg.name)
  396. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  397. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  398. }
  399. }
  400. }
  401. return errors
  402. }
  403. function checkRepositoryVersion(): string[] {
  404. // The root carries the dsh release family's version, so a prerelease such as
  405. // 0.0.1-rc.1 is a valid state between `release:dsh` and its publication.
  406. if (repositoryVersion && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(repositoryVersion)) return []
  407. return ['package.json: version must be X.Y.Z with an optional prerelease segment']
  408. }
  409. /** Dependency sections whose ranges reach a published tarball or a local install. */
  410. const dependencySections = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'] as const
  411. /** Dependency sections present in an installed runtime. */
  412. const runtimeDependencySections = ['dependencies', 'optionalDependencies', 'peerDependencies'] as const
  413. /**
  414. * Prevent an official runtime from requiring a package its release omits.
  415. * @param manifests - release, private experimental, and deployment-root manifests.
  416. * @returns One error for each forbidden runtime dependency.
  417. */
  418. export function checkExperimentalDependencyIsolation(manifests: readonly WorkspaceManifest[]): string[] {
  419. const experimentalNames = new Set(manifests
  420. .filter(entry => experimentalPackageDirectory.test(entry.dir))
  421. .map(entry => entry.manifest.name)
  422. .filter(name => name !== undefined))
  423. const errors: string[] = []
  424. for (const { dir, manifest } of manifests) {
  425. if (!releaseMemberDirectory.test(dir) && dir !== 'python/sdk-runtime') continue
  426. for (const section of runtimeDependencySections) {
  427. for (const name of Object.keys(manifest[section] ?? {})) {
  428. if (!experimentalNames.has(name)) continue
  429. errors.push(`${manifest.name ?? dir}: ${section}.${name} must not reference an experimental package`)
  430. }
  431. }
  432. }
  433. return errors
  434. }
  435. /**
  436. * Require the `workspace:` protocol for every reference to a workspace member.
  437. *
  438. * A hand-written range says nothing about the version the workspace actually
  439. * carries, and `pnpm pack` leaves it alone: `^0.0.1` published from version
  440. * `0.0.2` names a version that does not exist. The protocol makes pack
  441. * substitute the member's real version, so no release step rewrites ranges.
  442. * @param manifests - every workspace manifest.
  443. * @returns One error per reference that names a workspace member without the protocol.
  444. */
  445. function checkWorkspaceProtocol(manifests: readonly WorkspaceManifest[]): string[] {
  446. const members = new Set(manifests.map(entry => entry.manifest.name).filter(name => name !== undefined))
  447. const errors: string[] = []
  448. for (const { dir, manifest } of manifests) {
  449. for (const section of dependencySections) {
  450. for (const [name, range] of Object.entries(manifest[section] ?? {})) {
  451. if (!members.has(name) || range.startsWith('workspace:')) continue
  452. errors.push(`${manifest.name ?? dir}: ${section}.${name} must use the workspace: protocol, got ${range}`)
  453. }
  454. }
  455. }
  456. return errors
  457. }
  458. /** Run the repository constraint gate. */
  459. export function main(): void {
  460. const manifests = workspaceManifests()
  461. const dependencyManifests = [
  462. ...manifests,
  463. { dir: 'python/sdk-runtime', manifest: readJson(join(root, 'python/sdk-runtime/package.json')) },
  464. ]
  465. const errors = [
  466. ...checkRepositoryVersion(),
  467. ...manifests.flatMap(checkWorkspaceManifest),
  468. ...checkWorkspaceProtocol(manifests),
  469. ...checkExperimentalDependencyIsolation(dependencyManifests),
  470. ...checkHierarchyShape(),
  471. ...collectProjectReferenceFaceViolations(root),
  472. ]
  473. if (errors.length > 0) {
  474. console.error(errors.join('\n'))
  475. process.exitCode = 1
  476. }
  477. }
  478. if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) main()