@smoothbricks/nx-plugin 0.7.17 → 0.7.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +204 -64
  2. package/dist/.build-inputs.json +24 -21
  3. package/dist/bun-lock-scope.d.ts +128 -20
  4. package/dist/bun-lock-scope.d.ts.map +1 -1
  5. package/dist/bun-lock-scope.js +267 -44
  6. package/dist/cargo-closure-input.d.ts +8 -6
  7. package/dist/cargo-closure-input.d.ts.map +1 -1
  8. package/dist/cargo-closure-input.js +14 -11
  9. package/dist/cargo-source-hash.d.ts +23 -4
  10. package/dist/cargo-source-hash.d.ts.map +1 -1
  11. package/dist/cargo-source-hash.js +80 -14
  12. package/dist/cargo-workspace.d.ts +20 -2
  13. package/dist/cargo-workspace.d.ts.map +1 -1
  14. package/dist/cargo-workspace.js +42 -22
  15. package/dist/ensure-built-receipt.d.ts +3 -2
  16. package/dist/ensure-built-receipt.d.ts.map +1 -1
  17. package/dist/ensure-built-receipt.js +3 -2
  18. package/dist/eslint-config-closure.d.ts +8 -3
  19. package/dist/eslint-config-closure.d.ts.map +1 -1
  20. package/dist/eslint-config-closure.js +24 -5
  21. package/dist/executors/bounded-exec/bounds.d.ts +12 -1
  22. package/dist/executors/bounded-exec/bounds.d.ts.map +1 -1
  23. package/dist/executors/bounded-exec/bounds.js +8 -4
  24. package/dist/executors/bounded-exec/cpu-rise.d.ts +73 -0
  25. package/dist/executors/bounded-exec/cpu-rise.d.ts.map +1 -0
  26. package/dist/executors/bounded-exec/cpu-rise.js +111 -0
  27. package/dist/executors/bounded-exec/executor.d.ts +1 -1
  28. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  29. package/dist/executors/bounded-exec/executor.js +54 -22
  30. package/dist/executors/bounded-exec/hang-diagnostics.d.ts +8 -0
  31. package/dist/executors/bounded-exec/hang-diagnostics.d.ts.map +1 -1
  32. package/dist/executors/bounded-exec/hang-diagnostics.js +66 -6
  33. package/dist/executors/bounded-exec/mbx-pool.d.ts +16 -2
  34. package/dist/executors/bounded-exec/mbx-pool.d.ts.map +1 -1
  35. package/dist/executors/bounded-exec/mbx-pool.js +18 -2
  36. package/dist/executors/bounded-exec/mbx-reservations.d.ts +5 -2
  37. package/dist/executors/bounded-exec/mbx-reservations.d.ts.map +1 -1
  38. package/dist/executors/bounded-exec/mbx-reservations.js +5 -3
  39. package/dist/executors/bounded-exec/progress-channel.d.ts +38 -0
  40. package/dist/executors/bounded-exec/progress-channel.d.ts.map +1 -0
  41. package/dist/executors/bounded-exec/progress-channel.js +113 -0
  42. package/dist/executors/bounded-exec/progress.d.ts +2 -1
  43. package/dist/executors/bounded-exec/progress.d.ts.map +1 -1
  44. package/dist/executors/bounded-exec/ram-temp.d.ts +24 -1
  45. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
  46. package/dist/executors/bounded-exec/ram-temp.js +123 -16
  47. package/dist/executors/bounded-exec/schema.d.ts +5 -0
  48. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  49. package/dist/executors/bounded-exec/schema.js +17 -1
  50. package/dist/executors/bounded-exec/verdict.d.ts +13 -6
  51. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -1
  52. package/dist/executors/bounded-exec/verdict.js +34 -9
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +199 -89
  55. package/dist/managed-files/generator.d.ts +5 -1
  56. package/dist/managed-files/generator.d.ts.map +1 -1
  57. package/dist/managed-files/generator.js +22 -7
  58. package/dist/managed-files/render-memo.d.ts +13 -0
  59. package/dist/managed-files/render-memo.d.ts.map +1 -0
  60. package/dist/managed-files/render-memo.js +94 -0
  61. package/dist/test-program.d.ts +11 -6
  62. package/dist/test-program.d.ts.map +1 -1
  63. package/dist/test-program.js +39 -35
  64. package/dist/tool-bins.d.ts +12 -0
  65. package/dist/tool-bins.d.ts.map +1 -1
  66. package/dist/tool-bins.js +31 -6
  67. package/dist/typecheck-test-policy.d.ts +10 -1
  68. package/dist/typecheck-test-policy.d.ts.map +1 -1
  69. package/dist/typecheck-test-policy.js +40 -24
  70. package/dist/workspace-index.d.ts +14 -1
  71. package/dist/workspace-index.d.ts.map +1 -1
  72. package/dist/workspace-index.js +36 -4
  73. package/managed/raw/patches/nx@24.0.3.patch +703 -119
  74. package/managed/raw/tooling/direnv/developer-links.ts +17 -3
  75. package/managed/templates/github/actions/save-nix-devenv/action.yml +19 -1
  76. package/managed/templates/github/actions/setup-devenv/action.yml +2 -0
  77. package/package.json +3 -2
  78. package/src/bun-lock-scope.ts +293 -40
  79. package/src/cargo-closure-input.ts +19 -11
  80. package/src/cargo-source-hash.ts +103 -13
  81. package/src/cargo-workspace.ts +59 -20
  82. package/src/ensure-built-receipt.ts +3 -2
  83. package/src/eslint-config-closure.ts +27 -6
  84. package/src/executors/bounded-exec/bounds.ts +13 -4
  85. package/src/executors/bounded-exec/cpu-rise.ts +156 -0
  86. package/src/executors/bounded-exec/executor.ts +65 -21
  87. package/src/executors/bounded-exec/hang-diagnostics.ts +88 -6
  88. package/src/executors/bounded-exec/mbx-pool.ts +24 -3
  89. package/src/executors/bounded-exec/mbx-reservations.ts +7 -5
  90. package/src/executors/bounded-exec/progress-channel.ts +129 -0
  91. package/src/executors/bounded-exec/progress.ts +2 -1
  92. package/src/executors/bounded-exec/ram-temp.ts +137 -17
  93. package/src/executors/bounded-exec/schema.ts +19 -0
  94. package/src/executors/bounded-exec/verdict.ts +44 -16
  95. package/src/index.ts +255 -98
  96. package/src/managed-files/generator.ts +21 -6
  97. package/src/managed-files/render-memo.ts +135 -0
  98. package/src/test-program.ts +36 -41
  99. package/src/tool-bins.ts +35 -6
  100. package/src/typecheck-test-policy.ts +49 -24
  101. package/src/workspace-index.ts +40 -5
  102. package/test-timings.json +6 -0
@@ -14,6 +14,11 @@
14
14
  * Recorded declarations follow their current target after a successful install.
15
15
  * A plain `bun install` still relinks an undeclared link: only a wrapper around
16
16
  * bun itself could intercept that. A declared one (below) comes back on its own.
17
+ * A consumer's Nx key never hashes an undeclared link as the installed version:
18
+ * a key that omits a linked package's live files is sound only while every
19
+ * link is a tracked `smoo.developerLinks` declaration, whose edit recomputes
20
+ * the graph, so a consumer's Nx plugin refuses an undeclared link by name,
21
+ * applying the definition below through `developerLinksIn`.
17
22
  *
18
23
  * A developer link is a symlink directly inside a node_modules tree bun
19
24
  * installs (the root's or a workspace member's, scoped names included) whose
@@ -146,14 +151,14 @@ import {
146
151
  snapshotBinding,
147
152
  } from './linked-snapshots.ts';
148
153
 
149
- interface DeveloperLink {
154
+ export interface DeveloperLink {
150
155
  /** Where the link is, relative to the project root. */
151
156
  readonly path: string;
152
157
  /** The link's own text, restored byte for byte. */
153
158
  readonly target: string;
154
159
  }
155
160
 
156
- interface DeveloperLinks {
161
+ export interface DeveloperLinks {
157
162
  /** Links kept across an install: every link whose target is not known to be gone, unreadable ones included. */
158
163
  readonly live: readonly DeveloperLink[];
159
164
  /** Links whose target no longer exists. */
@@ -378,10 +383,19 @@ function describeDeveloperLinks(root: string, { live, unreadable }: Omit<Develop
378
383
  }
379
384
 
380
385
  function findDeveloperLinks(root: string): DeveloperLinks {
386
+ return developerLinksIn(root, nodeModulesTrees(root));
387
+ }
388
+
389
+ /**
390
+ * The developer links directly inside `trees` (node_modules directories relative to `root`), classified as
391
+ * `findDeveloperLinks` classifies them. The caller names the trees, so a process that is not Bun (an Nx plugin
392
+ * worker under Node, which takes them from its project graph) applies the same definition without reading bun.lock.
393
+ */
394
+ export function developerLinksIn(root: string, trees: readonly string[]): DeveloperLinks {
381
395
  const live: DeveloperLink[] = [];
382
396
  const dangling: DeveloperLink[] = [];
383
397
  const unreadable: (DeveloperLink & { readonly code: string })[] = [];
384
- for (const tree of nodeModulesTrees(root)) {
398
+ for (const tree of trees) {
385
399
  for (const entry of packageLinks(root, tree)) {
386
400
  const link: DeveloperLink = { path: entry, target: readlinkSync(path.join(root, entry)) };
387
401
  const target = resolvedTarget(root, link);
@@ -3,7 +3,7 @@ description: >
3
3
  Save what must outlive the job, after it ends and whatever its result: the devenv/direnv eval-cache segment, on every
4
4
  ephemeral runner where setup missed and build-shell produced nix-eval-cache.db, and the ttsc plugin binaries the job
5
5
  used, when setup's restore was not an exact hit. The Nix store cache saves itself in setup-devenv's post phase
6
- (ephemeral runners only).
6
+ (ephemeral runners only). Release this job's host cache mounts before the runner removes its checkout.
7
7
 
8
8
  inputs:
9
9
  devenv-cache-hit:
@@ -40,3 +40,21 @@ runs:
40
40
  uses: ./.github/actions/cache-ttsc-plugins
41
41
  with:
42
42
  mode: save
43
+
44
+ # Release children before their workspace bind. Lazy detach lets the runner remove its checkout even while a
45
+ # job-local daemon still holds an open path; it does not delete the shared cache backing either mount.
46
+ - name: Release job-owned host cache mounts
47
+ if: always()
48
+ shell: bash
49
+ run: |
50
+ status=0
51
+ for mount_path in "${CI_CARGO_TARGET_MOUNT:-}" "${CI_DEVENV_WORKSPACE_MOUNT:-}"; do
52
+ if [[ -z "$mount_path" ]]; then
53
+ continue
54
+ fi
55
+ echo "detaching this job's cache mount at $mount_path"
56
+ if ! sudo umount --lazy -- "$mount_path"; then
57
+ status=1
58
+ fi
59
+ done
60
+ exit "$status"
@@ -241,6 +241,7 @@ runs:
241
241
  done
242
242
  if mkdir -p "$stable" && sudo mount --bind "$GITHUB_WORKSPACE" "$stable"; then
243
243
  echo "DEVENV_WORKDIR=$stable" >> "$GITHUB_ENV"
244
+ echo "CI_DEVENV_WORKSPACE_MOUNT=$stable" >> "$GITHUB_ENV"
244
245
  echo "devenv state: $root (workspace bind-mounted at $stable)"
245
246
  else
246
247
  echo "DEVENV_WORKDIR=$GITHUB_WORKSPACE" >> "$GITHUB_ENV"
@@ -277,6 +278,7 @@ runs:
277
278
  target="$DEVENV_WORKDIR/target"
278
279
  if mkdir -p "$root" "$target" && sudo mount --bind "$root" "$target"; then
279
280
  echo "CARGO_UNSTABLE_CHECKSUM_FRESHNESS=true" >> "$GITHUB_ENV"
281
+ echo "CI_CARGO_TARGET_MOUNT=$target" >> "$GITHUB_ENV"
280
282
  echo "cargo target: $root (bound at $target)"
281
283
  else
282
284
  echo "::warning::cargo target bind refused; this job builds $target from cold"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smoothbricks/nx-plugin",
3
- "version": "0.7.17",
3
+ "version": "0.7.18",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "main": "./loader.js",
@@ -661,7 +661,7 @@
661
661
  "@nx/js": "24.0.3",
662
662
  "@smoothbricks/build-inputs": "0.0.3",
663
663
  "@smoothbricks/cargo-retain": "0.0.2",
664
- "@smoothbricks/cowshed": "0.5.1",
664
+ "@smoothbricks/cowshed": "0.5.2",
665
665
  "@smoothbricks/nextest-extract": "0.0.2",
666
666
  "jsonc-parser": "^3.3.1",
667
667
  "minimatch": "10.2.5",
@@ -676,6 +676,7 @@
676
676
  "devDependencies": {
677
677
  "@smoothbricks/lmao": "0.6.2",
678
678
  "@smoothbricks/validation": "0.1.14",
679
+ "@typescript/native": "npm:typescript@^7.0.2",
679
680
  "fast-check": "^4.4.0"
680
681
  }
681
682
  }
@@ -4,6 +4,7 @@ import { join, posix } from 'node:path';
4
4
  import {
5
5
  type CreateDependenciesContext,
6
6
  DependencyType,
7
+ type ProjectGraph,
7
8
  type ProjectGraphExternalNode,
8
9
  type ProjectGraphProjectNode,
9
10
  type RawProjectGraphDependency,
@@ -17,17 +18,25 @@ import { TargetProjectLocator } from 'nx/src/plugins/js/project-graph/build-depe
17
18
  *
18
19
  * A lock-scope node is the part of bun.lock one manifest reaches: what the
19
20
  * package can load. Its edges go to the npm nodes the manifest's dependencies
20
- * resolve to; a member's also go to the node of each workspace member it
21
- * depends on and to the root's, since a member's `node_modules` lookup ends in
22
- * the root's. The root's node has no member edges: every member reaches it, so
23
- * one would key every member on the packages of whichever members the root
24
- * manifest lists, which a member loads only through its own declaration (or an
25
- * import Nx turns into a project edge, which a `^` input follows). Nx's
26
- * lockfile parser links each npm node to the packages it depends on, so a
27
- * target naming a node in its `externalDependencies` is keyed on every package
28
- * of that closure by the hash bun.lock records for it, and on nothing else in
29
- * the lockfile. That replaces bun.lock as a file input: a lockfile edit re-keys
30
- * the tasks that can load what changed.
21
+ * resolve to and to the node of each workspace member it depends on, the
22
+ * root's manifest included. Nx's lockfile parser links each versioned npm node
23
+ * to the packages it depends on, and the plugin links each unversioned alias
24
+ * to its versioned node ({@link bunVersionAliasDependencies}), so a target naming a node in its
25
+ * `externalDependencies` is keyed on every package of that closure by the hash
26
+ * bun.lock records for it, and on nothing else in the lockfile. That replaces
27
+ * bun.lock as a file input: a lockfile edit re-keys the tasks that can load
28
+ * what changed.
29
+ *
30
+ * A member's node has no edge to the root's. Bun's isolated linker links into
31
+ * a directory's `node_modules` exactly the packages its manifest declares, but
32
+ * Node's lookup from a member continues into the root's `node_modules`, so a
33
+ * member can load any package the root declares. Two rules keep the member's
34
+ * own closure the whole of what it loads: a source import of a package outside
35
+ * that closure refuses the graph ({@link undeclaredImports}), and a tool a
36
+ * target runs names each package it loads by name from a directory by the
37
+ * scope that declares it ({@link bunLoadInput}). The root's own tooling (Nx
38
+ * plugins and generators, release and mutation tooling) then keys only the
39
+ * tasks that load it.
31
40
  *
32
41
  * The nodes carry no content of their own; Nx hashes a node's version and the
33
42
  * nodes it reaches.
@@ -39,9 +48,16 @@ export function bunLockNodeName(projectRoot: string): string {
39
48
  return `${BUN_LOCK_NODE_PREFIX}${posix.normalize(projectRoot === '' ? '.' : projectRoot)}`;
40
49
  }
41
50
 
42
- /** The node of the workspace root manifest, which every member's node reaches. */
51
+ /** The node of the workspace root manifest. */
43
52
  export const BUN_ROOT_LOCK_NODE = bunLockNodeName('.');
44
53
 
54
+ /**
55
+ * The named input every `package.json` project defines as its own lock-scope
56
+ * input. `externalDependencies` takes no `{projectRoot}` token, so a
57
+ * workspace-wide named input or target default names this to key each
58
+ * project's targets on its own manifest's closure.
59
+ */
60
+ export const BUN_LOCK_SCOPE_NAMED_INPUT = 'bunLockScope';
45
61
  /** The input that keys a target on the bun.lock entries its project's manifest reaches. */
46
62
  export function bunLockInput(projectRoot: string): { externalDependencies: string[] } {
47
63
  return { externalDependencies: [bunLockNodeName(projectRoot)] };
@@ -53,17 +69,57 @@ export function bunLockNode(projectRoot: string): ProjectGraphExternalNode {
53
69
  return { type: 'bun', name, data: { packageName: name, version: '0.0.0' } };
54
70
  }
55
71
 
72
+ /**
73
+ * Every bun runtime-scope node's name starts with this; the rest is a project
74
+ * root. It is the part of bun.lock a dependent loads through that package: the
75
+ * closure of its `dependencies`, `optionalDependencies` and
76
+ * `peerDependencies`. A package's devDependencies are installed for its own
77
+ * targets only, so a dependent's lock-scope node reaches the runtime node of
78
+ * each member it declares, never that member's own node.
79
+ */
80
+ export const BUN_LOCK_RUNTIME_NODE_PREFIX = 'bun-lock-runtime:';
81
+
82
+ /** The runtime-scope node of the project at `projectRoot`. */
83
+ export function bunLockRuntimeNodeName(projectRoot: string): string {
84
+ return `${BUN_LOCK_RUNTIME_NODE_PREFIX}${posix.normalize(projectRoot === '' ? '.' : projectRoot)}`;
85
+ }
86
+
87
+ /** The runtime-scope node itself, published by its project beside its lock-scope node. */
88
+ export function bunLockRuntimeNode(projectRoot: string): ProjectGraphExternalNode {
89
+ const name = bunLockRuntimeNodeName(projectRoot);
90
+ return { type: 'bun', name, data: { packageName: name, version: '0.0.0' } };
91
+ }
92
+
56
93
  /** The manifest sections Nx reads a project's package dependencies from, in the order it lets them override. */
57
94
  const DEPENDENCY_SECTIONS = ['optionalDependencies', 'peerDependencies', 'devDependencies', 'dependencies'] as const;
95
+ /** The sections a dependent loads through a package: all but its devDependencies. */
96
+ const RUNTIME_SECTIONS = ['optionalDependencies', 'peerDependencies', 'dependencies'] as const;
97
+
98
+ /** Each package a manifest declares in `sections`, with the specifier of the section Nx lets win. */
99
+ function declaredSpecifiers(
100
+ manifest: Readonly<Record<string, unknown>>,
101
+ sections: readonly string[] = DEPENDENCY_SECTIONS,
102
+ ): Map<string, string> {
103
+ const specifiers = new Map<string, string>();
104
+ for (const section of sections) {
105
+ const declared = manifest[section];
106
+ if (typeof declared !== 'object' || declared === null) continue;
107
+ for (const [name, specifier] of Object.entries(declared)) {
108
+ if (typeof specifier === 'string') specifiers.set(name, specifier);
109
+ }
110
+ }
111
+ return specifiers;
112
+ }
58
113
 
59
114
  /**
60
- * The edges of every published bun lock-scope node. A manifest's dependencies
61
- * are resolved exactly as Nx resolves a project's own package edges
62
- * (`buildExplicitPackageJsonDependencies`, one `TargetProjectLocator` over
63
- * the same projects and lockfile nodes): an installed package becomes an edge
64
- * to its npm node, a workspace member (outside the root manifest) an edge to
65
- * that member's node, and a package that resolves to no node is skipped
66
- * exactly as Nx skips it.
115
+ * The edges of every published bun lock-scope and runtime-scope node. A
116
+ * manifest's dependencies are resolved exactly as Nx resolves a project's own
117
+ * package edges (`buildExplicitPackageJsonDependencies`, one
118
+ * `TargetProjectLocator` over the same projects and lockfile nodes): an
119
+ * installed package becomes an edge to its npm node, a workspace member an
120
+ * edge to that member's runtime node, and a package that resolves to no node
121
+ * is skipped exactly as Nx skips it. The lock-scope node takes every section,
122
+ * the runtime node all but devDependencies.
67
123
  */
68
124
  export function bunLockDependencies(context: CreateDependenciesContext): RawProjectGraphDependency[] {
69
125
  const externalNodes = context.externalNodes ?? {};
@@ -72,37 +128,234 @@ export function bunLockDependencies(context: CreateDependenciesContext): RawProj
72
128
  nodes[name] = { name, type: data.projectType === 'application' ? 'app' : 'lib', data };
73
129
  }
74
130
  const locator = new TargetProjectLocator(nodes, externalNodes);
75
- const nodeOfMember = (member: string): string | null => {
76
- const root = context.projects[member]?.root;
77
- return root === undefined ? null : bunLockNodeName(root);
78
- };
79
131
  const dependencies: RawProjectGraphDependency[] = [];
80
132
  for (const project of Object.values(context.projects).sort((left, right) =>
81
133
  left.root < right.root ? -1 : left.root > right.root ? 1 : 0,
82
134
  )) {
83
- const source = bunLockNodeName(project.root);
84
- if (externalNodes[source] === undefined) continue;
85
135
  const manifestPath = posix.join(project.root, 'package.json');
86
136
  if (!existsSync(join(context.workspaceRoot, manifestPath))) continue;
87
137
  const manifest = readJsonFile<Record<string, unknown>>(join(context.workspaceRoot, manifestPath));
88
- const specifiers = new Map<string, string>();
89
- for (const section of DEPENDENCY_SECTIONS) {
90
- const declared = manifest[section];
91
- if (typeof declared !== 'object' || declared === null) continue;
92
- for (const [name, specifier] of Object.entries(declared)) {
93
- if (typeof specifier === 'string') specifiers.set(name, specifier);
138
+ for (const [source, sections] of [
139
+ [bunLockNodeName(project.root), DEPENDENCY_SECTIONS],
140
+ [bunLockRuntimeNodeName(project.root), RUNTIME_SECTIONS],
141
+ ] as const) {
142
+ if (externalNodes[source] === undefined) continue;
143
+ const targets = new Set<string>();
144
+ for (const [name, specifier] of declaredSpecifiers(manifest, sections)) {
145
+ const member = locator.findDependencyInWorkspaceProjects(manifestPath, name, specifier);
146
+ const memberRoot = member === null ? undefined : context.projects[member]?.root;
147
+ const target =
148
+ member === null
149
+ ? locator.findNpmProjectFromImport(name, manifestPath)
150
+ : memberRoot === undefined
151
+ ? null
152
+ : bunLockRuntimeNodeName(memberRoot);
153
+ if (target !== null && target !== source && externalNodes[target] !== undefined) targets.add(target);
154
+ }
155
+ for (const target of [...targets].sort()) {
156
+ dependencies.push({ source, target, type: DependencyType.static });
94
157
  }
95
158
  }
96
- const targets = new Set<string>(source === BUN_ROOT_LOCK_NODE ? [] : [BUN_ROOT_LOCK_NODE]);
97
- for (const [name, specifier] of specifiers) {
98
- const member = locator.findDependencyInWorkspaceProjects(manifestPath, name, specifier);
99
- if (member !== null && source === BUN_ROOT_LOCK_NODE) continue;
100
- const target = member === null ? locator.findNpmProjectFromImport(name, manifestPath) : nodeOfMember(member);
101
- if (target !== null && target !== source && externalNodes[target] !== undefined) targets.add(target);
159
+ }
160
+ return dependencies;
161
+ }
162
+
163
+ /** A package a module loads by name, and the workspace-relative directory of that module. */
164
+ export interface PackageLoad {
165
+ readonly directory: string;
166
+ readonly name: string;
167
+ }
168
+
169
+ /** The package a bare specifier names: its scope and name, without the subpath. */
170
+ export function specifierPackage(specifier: string): string {
171
+ const parts = specifier.split('/');
172
+ return (specifier.startsWith('@') ? parts.slice(0, 2) : parts.slice(0, 1)).join('/');
173
+ }
174
+
175
+ /** One manifest at or above a directory: its project root and the packages it declares. */
176
+ export interface ManifestDeclarations {
177
+ readonly root: string;
178
+ readonly declared: ReadonlySet<string>;
179
+ }
180
+
181
+ /** The manifests at and above the workspace-relative `directory`, nearest first, ending with the root's. */
182
+ export function manifestsAbove(workspaceRoot: string, directory: string): ManifestDeclarations[] {
183
+ const manifests: ManifestDeclarations[] = [];
184
+ for (let current = posix.normalize(directory === '' ? '.' : directory); ; current = posix.dirname(current)) {
185
+ const path = join(workspaceRoot, current, 'package.json');
186
+ if (existsSync(path)) {
187
+ manifests.push({ root: current, declared: new Set(declaredSpecifiers(readJsonFile(path)).keys()) });
188
+ }
189
+ if (current === '.') return manifests;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * The `externalDependencies` entry that keys package `name` as a process loads
195
+ * it by name from a directory, given the manifests at and above it, nearest
196
+ * first; `null` when none declares it, so nothing on that path loads it. Node's
197
+ * lookup walks the directory's ancestors' `node_modules`, and bun's isolated
198
+ * linker links into each exactly what its manifest declares, so the nearest
199
+ * declaring manifest decides what loads. A member's declaration is keyed by its
200
+ * lock-scope node. The root's is named by itself, and Nx keys that package's
201
+ * node and what it reaches: the root's node would key the whole of the root's
202
+ * tooling.
203
+ */
204
+ export function bunLoadScope(manifests: readonly ManifestDeclarations[], name: string): string | null {
205
+ const declaring = manifests.find((manifest) => manifest.declared.has(name));
206
+ if (declaring === undefined) return null;
207
+ return declaring.root === '.' ? name : bunLockNodeName(declaring.root);
208
+ }
209
+
210
+ /** The lock scope of each package load, from the manifests above its directory; sorted, each once. */
211
+ export function bunLoadScopes(workspaceRoot: string, loads: readonly PackageLoad[]): string[] {
212
+ const manifests = new Map<string, ManifestDeclarations[]>();
213
+ const scopes = new Set<string>();
214
+ for (const { directory, name } of loads) {
215
+ let above = manifests.get(directory);
216
+ if (above === undefined) {
217
+ above = manifestsAbove(workspaceRoot, directory);
218
+ manifests.set(directory, above);
219
+ }
220
+ const scope = bunLoadScope(above, name);
221
+ if (scope !== null) scopes.add(scope);
222
+ }
223
+ return [...scopes].sort();
224
+ }
225
+
226
+ /** A target's one `externalDependencies` input: its project's lock-scope node first, then each other scope once, sorted. */
227
+ export function bunScopeInput(
228
+ projectRoot: string,
229
+ ...scopes: readonly (readonly string[])[]
230
+ ): { externalDependencies: string[] } {
231
+ const own = bunLockNodeName(projectRoot);
232
+ return { externalDependencies: [own, ...[...new Set(scopes.flat())].filter((scope) => scope !== own).sort()] };
233
+ }
234
+
235
+ /** The input keying every package of `names` a process loads by name from the directory `manifests` stand above. */
236
+ export function bunLoadInput(
237
+ manifests: readonly ManifestDeclarations[],
238
+ names: Iterable<string>,
239
+ ): { externalDependencies: string[] } {
240
+ const scopes = new Set<string>();
241
+ for (const name of names) {
242
+ const scope = bunLoadScope(manifests, name);
243
+ if (scope !== null) scopes.add(scope);
244
+ }
245
+ return { externalDependencies: [...scopes].sort() };
246
+ }
247
+
248
+ /**
249
+ * The packages a TypeScript compile in a directory loads by name beyond its
250
+ * sources' imports: every `@types` package a manifest at or above it declares
251
+ * (TypeScript includes each ancestor's `node_modules/@types` unless the config
252
+ * lists `types`, a narrower set), and the `tslib` an `importHelpers` compile
253
+ * resolves.
254
+ */
255
+ export function typescriptLoads(manifests: readonly ManifestDeclarations[]): string[] {
256
+ const names = new Set(['tslib']);
257
+ for (const manifest of manifests) {
258
+ for (const name of manifest.declared) {
259
+ if (name.startsWith('@types/')) names.add(name);
260
+ }
261
+ }
262
+ return [...names].sort();
263
+ }
264
+
265
+ /** A project source import of a package its own lock-scope node does not reach. */
266
+ export interface UndeclaredImport {
267
+ readonly project: string;
268
+ readonly root: string;
269
+ readonly packageName: string;
270
+ }
271
+
272
+ /**
273
+ * The npm packages each workspace member's sources import (Nx's own `static`
274
+ * and `dynamic` edges) that its lock-scope node does not reach. Node loads such
275
+ * a package through an ancestor's `node_modules`, the root's, and the
276
+ * project's targets, keyed on the member's own closure, would miss it. The
277
+ * root's project is exempt: its node reaches everything its manifest declares.
278
+ * So is a `@types` package: TypeScript loads it by ancestry, not Node, and
279
+ * every TypeScript target keys the `@types` the manifests above it declare
280
+ * ({@link typescriptLoads}). A package is compared by name and version, never
281
+ * by node name: Nx publishes a hoisted package as both `npm:<name>` and
282
+ * `npm:<name>@<version>`, and its locator resolves a declaration and an
283
+ * import to either ({@link bunVersionAliasDependencies}).
284
+ */
285
+ export function undeclaredImports(graph: ProjectGraph): UndeclaredImport[] {
286
+ const externalNodes = graph.externalNodes ?? {};
287
+ const identity = (name: string): string | null => {
288
+ const node = externalNodes[name];
289
+ return node?.type === 'npm' ? `${node.data.packageName}@${node.data.version}` : null;
290
+ };
291
+ const namesOf = new Map<string, string[]>();
292
+ for (const name of Object.keys(externalNodes)) {
293
+ const key = identity(name);
294
+ if (key !== null) namesOf.set(key, [...(namesOf.get(key) ?? []), name]);
295
+ }
296
+ const findings: UndeclaredImport[] = [];
297
+ for (const [project, node] of Object.entries(graph.nodes).sort(([left], [right]) => (left < right ? -1 : 1))) {
298
+ const scope = bunLockNodeName(node.data.root);
299
+ if (scope === BUN_ROOT_LOCK_NODE || externalNodes[scope] === undefined) continue;
300
+ const reached = new Set<string>();
301
+ for (let pending = [scope]; pending.length > 0; ) {
302
+ const next: string[] = [];
303
+ for (const name of pending) {
304
+ if (reached.has(name)) continue;
305
+ reached.add(name);
306
+ for (const edge of graph.dependencies[name] ?? []) next.push(edge.target);
307
+ const key = identity(name);
308
+ if (key !== null) next.push(...(namesOf.get(key) ?? []));
309
+ }
310
+ pending = next;
102
311
  }
103
- for (const target of [...targets].sort()) {
104
- dependencies.push({ source, target, type: DependencyType.static });
312
+ const missing = new Set<string>();
313
+ for (const edge of graph.dependencies[project] ?? []) {
314
+ if (edge.type === DependencyType.implicit) continue;
315
+ const external = externalNodes[edge.target];
316
+ if (external === undefined || external.type !== 'npm' || reached.has(edge.target)) continue;
317
+ if (external.data.packageName.startsWith('@types/')) continue;
318
+ missing.add(external.data.packageName);
105
319
  }
320
+ for (const packageName of [...missing].sort()) findings.push({ project, root: node.data.root, packageName });
106
321
  }
107
- return dependencies;
322
+ return findings;
323
+ }
324
+
325
+ /**
326
+ * An edge from each unversioned npm node to the versioned node of the same
327
+ * package and version. Nx's bun lockfile parser publishes a hoisted package as
328
+ * both `npm:<name>` and `npm:<name>@<version>`, with one integrity, and links
329
+ * only the versioned node to the package's dependencies. A key on the
330
+ * unversioned node (an `externalDependencies` entry naming a package, or a
331
+ * lock-scope edge the locator resolved to it) then held the package's own
332
+ * integrity and none of its closure; through this edge it holds both.
333
+ */
334
+ export function bunVersionAliasDependencies(
335
+ externalNodes: Readonly<Record<string, ProjectGraphExternalNode>>,
336
+ ): RawProjectGraphDependency[] {
337
+ const dependencies: RawProjectGraphDependency[] = [];
338
+ for (const [name, node] of Object.entries(externalNodes)) {
339
+ if (node.type !== 'npm') continue;
340
+ const target = `npm:${node.data.packageName}@${node.data.version}`;
341
+ const versioned = externalNodes[target];
342
+ if (target === name || versioned?.type !== 'npm' || versioned.data.version !== node.data.version) continue;
343
+ dependencies.push({ source: name, target, type: DependencyType.static });
344
+ }
345
+ return dependencies.sort((left, right) => (left.source < right.source ? -1 : left.source > right.source ? 1 : 0));
346
+ }
347
+ export class UndeclaredImportError extends Error {
348
+ constructor(readonly findings: readonly UndeclaredImport[]) {
349
+ super(
350
+ 'Workspace members import packages their package.json does not declare. Node loads each through the root' +
351
+ "'s node_modules, and no lock-scope node of the member keys it; declare each in the member's package.json:\n" +
352
+ findings.map(({ project, root, packageName }) => ` ${project} (${root}): ${packageName}`).join('\n'),
353
+ );
354
+ this.name = 'UndeclaredImportError';
355
+ }
356
+ }
357
+
358
+ export function refuseUndeclaredImports(graph: ProjectGraph): void {
359
+ const findings = undeclaredImports(graph);
360
+ if (findings.length > 0) throw new UndeclaredImportError(findings);
108
361
  }
@@ -7,14 +7,17 @@ import type { ProjectGraphExternalNode, TargetConfiguration } from 'nx/src/devki
7
7
 
8
8
  import {
9
9
  type CargoResolve,
10
+ type CargoSourceIndex,
10
11
  type CompiledCargoInput,
12
+ cargoSourceIndex,
11
13
  compiledInFiles,
12
14
  dependencyClosure,
13
15
  HASH_SKIPPED_DIRECTORIES,
14
16
  readCargoResolve,
17
+ retainIncludeScans,
15
18
  } from './cargo-source-hash.js';
16
19
  import { runtimeInput, shellWord } from './runtime-input.js';
17
- import { globIndexedFiles } from './workspace-index.js';
20
+ import { globIndexedFiles, indexedFileData } from './workspace-index.js';
18
21
 
19
22
  /**
20
23
  * The named input the plugin infers for every project with crates of a Cargo
@@ -88,16 +91,21 @@ export interface CargoClosureSource {
88
91
  readonly cargo: CargoResolve;
89
92
  /** Every `Cargo.toml` in Nx's file index, relative to the workspace root. */
90
93
  readonly indexed: ReadonlySet<string>;
94
+ /** The Rust sources and packages of Nx's file index the compiled-in scan reads. */
95
+ readonly sources: CargoSourceIndex;
91
96
  readonly compiledFilesCache: Map<string, CompiledCargoInput[]>;
92
97
  }
93
98
 
94
99
  /**
95
- * Every `Cargo.toml` Nx's workspace file index holds: .gitignore and .nxignore
96
- * applied, `node_modules` never entered. A package whose manifest is missing
97
- * here has no files a fileset input can hash.
100
+ * The Cargo manifests and Rust sources of Nx's workspace file index, with Nx's content hash of each source:
101
+ * .gitignore and .nxignore applied, `node_modules` never entered. A package whose manifest is missing here has no
102
+ * files a fileset input can hash. Scans of source texts no longer indexed are forgotten here.
98
103
  */
99
- export async function indexedCargoManifests(workspaceRoot: string): Promise<ReadonlySet<string>> {
100
- return new Set(await globIndexedFiles(workspaceRoot, ['**/Cargo.toml']));
104
+ export async function indexedCargoSources(workspaceRoot: string): Promise<CargoSourceIndex> {
105
+ const [root, files] = await Promise.all([realpath(workspaceRoot), indexedFileData(workspaceRoot)]);
106
+ const index = cargoSourceIndex(root, files);
107
+ retainIncludeScans(index);
108
+ return index;
101
109
  }
102
110
 
103
111
  /**
@@ -108,12 +116,12 @@ export async function indexedCargoManifests(workspaceRoot: string): Promise<Read
108
116
  export async function resolveCargoClosureSource(
109
117
  manifest: string,
110
118
  workspaceRoot: string,
111
- indexed: Promise<ReadonlySet<string>>,
119
+ indexed: Promise<CargoSourceIndex>,
112
120
  compiledFilesCache: Map<string, CompiledCargoInput[]>,
113
121
  ): Promise<CargoClosureSource> {
114
- const [root, index] = await Promise.all([realpath(workspaceRoot), indexed]);
115
- const cargo = await readCargoResolve(join(root, manifest), root, index);
116
- return { manifest, workspaceRoot, root, cargo, indexed: index, compiledFilesCache };
122
+ const [root, sources] = await Promise.all([realpath(workspaceRoot), indexed]);
123
+ const cargo = await readCargoResolve(join(root, manifest), root, sources.manifests);
124
+ return { manifest, workspaceRoot, root, cargo, indexed: sources.manifests, sources, compiledFilesCache };
117
125
  }
118
126
 
119
127
  /**
@@ -188,7 +196,7 @@ async function workspaceClosureInputs(projectRoot: string, source: CargoClosureS
188
196
  if (!indexed.has(posix.join(directory, 'Cargo.toml'))) {
189
197
  throw new Error(`the Cargo package ${directory} is not in Nx's file index (an ignored directory)`);
190
198
  }
191
- for (const compiled of compiledInFiles(pkg.directory, source.compiledFilesCache)) {
199
+ for (const compiled of compiledInFiles(pkg.directory, source.sources, source.compiledFilesCache)) {
192
200
  const file = indexablePath(root, compiled.file);
193
201
  if (file === null) throw new Error(`${directory} compiles ${compiled.file}, which Nx's file index cannot hold`);
194
202
  // The scan starts inside this package's indexable directory, so its sources can always be named.