@smoothbricks/nx-plugin 0.3.11 → 0.3.13

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 (38) hide show
  1. package/README.md +23 -2
  2. package/dist/bounded-test-policy.d.ts +26 -0
  3. package/dist/bounded-test-policy.d.ts.map +1 -1
  4. package/dist/bounded-test-policy.js +194 -0
  5. package/dist/cargo-workspace.d.ts +67 -0
  6. package/dist/cargo-workspace.d.ts.map +1 -0
  7. package/dist/cargo-workspace.js +215 -0
  8. package/dist/cross-check-policy.d.ts +60 -1
  9. package/dist/cross-check-policy.d.ts.map +1 -1
  10. package/dist/cross-check-policy.js +65 -1
  11. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  12. package/dist/executors/bounded-exec/executor.js +86 -51
  13. package/dist/executors/bounded-exec/schema.d.ts +13 -0
  14. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  15. package/dist/index.d.ts +10 -5
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +455 -95
  18. package/dist/package-target-policy.d.ts +2 -1
  19. package/dist/package-target-policy.d.ts.map +1 -1
  20. package/dist/package-target-policy.js +54 -13
  21. package/dist/workspace-config-policy.js +32 -35
  22. package/nextest.toml +79 -0
  23. package/package.json +2 -1
  24. package/src/bounded-test-policy.test.ts +304 -0
  25. package/src/bounded-test-policy.ts +218 -0
  26. package/src/cargo-workspace.ts +243 -0
  27. package/src/cross-check-policy.test.ts +24 -0
  28. package/src/cross-check-policy.ts +80 -1
  29. package/src/executors/bounded-exec/executor.test.ts +147 -3
  30. package/src/executors/bounded-exec/executor.ts +103 -53
  31. package/src/executors/bounded-exec/schema.json +7 -2
  32. package/src/executors/bounded-exec/schema.ts +13 -0
  33. package/src/index.test.ts +531 -99
  34. package/src/index.ts +527 -104
  35. package/src/package-target-policy.test.ts +50 -0
  36. package/src/package-target-policy.ts +58 -9
  37. package/src/workspace-config-policy.test.ts +15 -30
  38. package/src/workspace-config-policy.ts +32 -39
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { readdir, readFile } from 'node:fs/promises';
3
3
  import { dirname, join, posix } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
 
5
6
  import {
6
7
  type CreateNodesResultV2,
@@ -11,8 +12,29 @@ import {
11
12
  import { AggregateCreateNodesError } from 'nx/src/project-graph/error-types.js';
12
13
  import { parse as parseToml } from 'smol-toml';
13
14
 
14
- import { CARGO_CROSS_LINT_COMMAND, CARGO_CROSS_LINT_TARGET } from './cross-check-policy.js';
15
- import { BUILD_OUTPUT_DEPENDENCIES, PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
15
+ import { BOUNDED_TEST_KILL_AFTER_MS, BOUNDED_TEST_TIMEOUT_MS } from './bounded-test-policy.js';
16
+ import {
17
+ CARGO_TEST_COMPILE_TARGET,
18
+ CARGO_TEST_EXCEPTIONS_SUFFIX,
19
+ CARGO_TEST_TARGET,
20
+ cargoPackageTestInputs,
21
+ cargoTestPackageTargetName,
22
+ exceptionalTestFilter,
23
+ listCargoWorkspacePackages,
24
+ nextestConfigRelPath,
25
+ } from './cargo-workspace.js';
26
+ import {
27
+ CARGO_CROSS_LINT_COMMAND,
28
+ CARGO_CROSS_LINT_TARGET,
29
+ CARGO_FETCH_COMMAND,
30
+ CARGO_FETCH_TARGET,
31
+ CARGO_FROZEN_PREFIX,
32
+ CARGO_LINT_CLIPPY_COMMAND,
33
+ cargoFrozen,
34
+ } from './cross-check-policy.js';
35
+ import { PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
36
+
37
+ export { CARGO_TEST_COMPILE_TARGET };
16
38
 
17
39
  const BUILD_OUTPUT_TARGET_PATTERN = /-(?:js|web|html|css|android|native|napi|bun|wasm)$/;
18
40
  const TYPESCRIPT_TOOLCHAIN_INPUTS = [
@@ -22,30 +44,56 @@ const TYPESCRIPT_TOOLCHAIN_INPUTS = [
22
44
  '{workspaceRoot}/tsconfig.base.json',
23
45
  ];
24
46
 
25
- // The aggregate `build` pulls in platform-suffixed binary targets for THIS
26
- // machine only: `<tool>-<arch>-<os>` names matching the host (for example
27
- // cli-arm64-macos on Apple Silicon) build locally as part of `nx build`, while
28
- // every foreign platform stays publish-workflow-only. nx.json targetDefaults
29
- // cannot express "current platform" — its dependsOn lists are static — so the
30
- // inference plugin owns this edge.
31
- const HOST_PLATFORM_SUFFIX: string | null = (() => {
32
- const os = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : null;
33
- const arch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : null;
34
- return os !== null && arch !== null ? `-${arch}-${os}` : null;
35
- })();
36
-
37
- export function hostPlatformTargetNames(targetNames: Iterable<string>): string[] {
38
- if (HOST_PLATFORM_SUFFIX === null) return [];
47
+ type NapiArchitecture = 'arm64' | 'x64';
48
+ type NapiTargetFamily = 'linux' | 'macos';
49
+
50
+ interface NapiPlatform {
51
+ architecture: NapiArchitecture;
52
+ targetFamily: NapiTargetFamily;
53
+ }
54
+
55
+ function napiPlatform(platform: NodeJS.Platform, architecture: string): NapiPlatform | null {
56
+ const targetFamily = platform === 'darwin' ? 'macos' : platform === 'linux' ? 'linux' : null;
57
+ const targetArchitecture = architecture === 'arm64' ? 'arm64' : architecture === 'x64' ? 'x64' : null;
58
+ return targetFamily !== null && targetArchitecture !== null
59
+ ? { architecture: targetArchitecture, targetFamily }
60
+ : null;
61
+ }
62
+
63
+ function sameNapiPlatform(left: NapiPlatform, right: NapiPlatform | null): boolean {
64
+ return left.architecture === right?.architecture && left.targetFamily === right.targetFamily;
65
+ }
66
+
67
+ function hostPlatformTargetNames(targetNames: Iterable<string>, hostPlatform: NapiPlatform | null): string[] {
68
+ if (hostPlatform === null) return [];
69
+ const suffix = `-${hostPlatform.architecture}-${hostPlatform.targetFamily}`;
39
70
  return [...new Set(targetNames)]
40
71
  .filter(
41
72
  // Binary targets only. A toolchain prerequisite carries the same platform
42
73
  // suffix but produces no artifact: the cross builds that need it depend
43
74
  // on it directly, so the aggregate stays a list of outputs.
44
- (name) => name.endsWith(HOST_PLATFORM_SUFFIX) && !name.startsWith(NAPI_TOOLCHAIN_TARGET_PREFIX),
75
+ (name) => name.endsWith(suffix) && !name.startsWith(NAPI_TOOLCHAIN_TARGET_PREFIX),
45
76
  )
46
77
  .sort();
47
78
  }
48
79
 
80
+ /**
81
+ * The reserved suffixes name targets that EMIT an artifact, and the `build`
82
+ * aggregate is a list of those. Handing Nx the raw `*-<family>` globs let it
83
+ * match on suffix alone, and one namespace collides by construction: a
84
+ * per-crate cargo test runner is named `cargo-test-<crate>`, so any crate whose
85
+ * name ends in an output family — `*-napi`, `*-wasm`, `*-native`, `*-js` — put
86
+ * its RUNNER in the aggregate. The runners are one serialized chain, so a
87
+ * single such crate made `build` pull an entire cargo test suite. Expanding the
88
+ * families here instead of delegating to Nx's matcher keeps the plugin's own
89
+ * `cargo-test-` namespace out of the aggregate however a crate is named.
90
+ */
91
+ function buildOutputTargetNames(targetNames: Iterable<string>): string[] {
92
+ return [...new Set(targetNames)]
93
+ .filter((name) => BUILD_OUTPUT_TARGET_PATTERN.test(name) && !name.startsWith(`${CARGO_TEST_TARGET}-`))
94
+ .sort();
95
+ }
96
+
49
97
  //#region smoo!n/rust-output-target-inference
50
98
  // Cargo workspace inference: a package.json sitting next to a Cargo.toml that
51
99
  // declares [workspace] gets direct cargo-test/test targets, cargo-lint feeding
@@ -69,11 +117,8 @@ const CARGO_INPUTS = [
69
117
  const CARGO_OUTPUT_INPUTS = [...CARGO_INPUTS, '{projectRoot}/package.json', '{workspaceRoot}/bun.lock'];
70
118
  const NAPI_INPUTS = CARGO_OUTPUT_INPUTS;
71
119
 
72
- interface NapiTargetConvention {
73
- architecture: string;
120
+ interface NapiTargetConvention extends NapiPlatform {
74
121
  outputName: string;
75
- targetFamily: 'linux' | 'macos';
76
- useNapiCross: boolean;
77
122
  }
78
123
 
79
124
  const NAPI_TARGET_CONVENTIONS: Readonly<Record<string, NapiTargetConvention>> = {
@@ -81,28 +126,39 @@ const NAPI_TARGET_CONVENTIONS: Readonly<Record<string, NapiTargetConvention>> =
81
126
  architecture: 'arm64',
82
127
  outputName: 'darwin-arm64',
83
128
  targetFamily: 'macos',
84
- useNapiCross: false,
85
129
  },
86
130
  'x86_64-apple-darwin': {
87
131
  architecture: 'x64',
88
132
  outputName: 'darwin-x64',
89
133
  targetFamily: 'macos',
90
- useNapiCross: false,
91
134
  },
92
135
  'aarch64-unknown-linux-gnu': {
93
136
  architecture: 'arm64',
94
137
  outputName: 'linux-arm64-gnu',
95
138
  targetFamily: 'linux',
96
- useNapiCross: true,
97
139
  },
98
140
  'x86_64-unknown-linux-gnu': {
99
141
  architecture: 'x64',
100
142
  outputName: 'linux-x64-gnu',
101
143
  targetFamily: 'linux',
102
- useNapiCross: true,
103
144
  },
104
145
  };
105
146
 
147
+ const NATIVE_LINUX_COMPILER_ENV = Object.freeze({ CC: 'cc', CXX: 'c++' });
148
+ const CROSS_LINUX_COMPILER_ENV = Object.freeze({ TARGET_CC: 'clang', TARGET_CXX: 'clang++' });
149
+
150
+ function usesNapiCross(target: NapiTargetConvention, hostPlatform: NapiPlatform | null): boolean {
151
+ return target.targetFamily === 'linux' && !sameNapiPlatform(target, hostPlatform);
152
+ }
153
+
154
+ function napiCompilerEnv(
155
+ target: NapiPlatform | null,
156
+ hostPlatform: NapiPlatform | null,
157
+ ): Readonly<Record<string, string>> | undefined {
158
+ if (target?.targetFamily !== 'linux') return undefined;
159
+ return sameNapiPlatform(target, hostPlatform) ? NATIVE_LINUX_COMPILER_ENV : CROSS_LINUX_COMPILER_ENV;
160
+ }
161
+
106
162
  const NAPI_TOOLCHAIN_TARGET_PREFIX = 'napi-toolchain-';
107
163
 
108
164
  /**
@@ -125,7 +181,9 @@ function createCargoWasmTarget(projectRoot: string, config: ResolvedCargoWasmCon
125
181
  outputs: [`{projectRoot}/${config.outputDirectory}`],
126
182
  options: {
127
183
  commands: [
128
- `cargo build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} --manifest-path ${config.manifestPath}`,
184
+ cargoFrozen(
185
+ `build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} --manifest-path ${config.manifestPath}`,
186
+ ),
129
187
  ...config.targets.map(
130
188
  ({ bindgenTarget, outputName }) =>
131
189
  `wasm-bindgen --target ${bindgenTarget} --out-dir ${config.outputDirectory}/${outputName} ${wasmInput}`,
@@ -137,27 +195,145 @@ function createCargoWasmTarget(projectRoot: string, config: ResolvedCargoWasmCon
137
195
  };
138
196
  }
139
197
 
198
+ /**
199
+ * Compilation is excluded from the bounded test window: a cold Cargo
200
+ * workspace can take many minutes to compile while still making progress,
201
+ * which is not a property of the tests. `cargo test --no-run` pays that cost
202
+ * in its own unbounded, cacheable target; the bounded runner then re-invokes
203
+ * cargo against a warm target directory, where only the suites' own runtime
204
+ * counts against the standard bound.
205
+ *
206
+ * Cargo flocks one `target/` per invocation. Nx must not run two cargo
207
+ * writers on that directory at once — that is a mutex, not a deadlock, and
208
+ * the second process sits in "Blocking waiting for file lock" until a
209
+ * timeout. Inference serializes writers that share the default target dir
210
+ * (`napi-debug` after compile, `cargo-test` after `napi-debug`). Clippy uses
211
+ * its own `--target-dir` so lint can overlap tests.
212
+ */
213
+ function createCargoTestCompileTarget(projectRoot: string): TargetConfiguration {
214
+ return {
215
+ executor: 'nx:run-commands',
216
+ cache: true,
217
+ inputs: CARGO_INPUTS,
218
+ options: {
219
+ command: cargoFrozen('test --workspace --no-run'),
220
+ cwd: projectRoot,
221
+ },
222
+ configurations: {
223
+ production: { command: cargoFrozen('test --workspace --release --no-run') },
224
+ },
225
+ };
226
+ }
227
+
140
228
  function createCargoTestTarget(projectRoot: string): TargetConfiguration {
141
229
  return {
142
230
  executor: '@smoothbricks/nx-plugin:bounded-exec',
143
231
  cache: true,
144
232
  inputs: CARGO_INPUTS,
233
+ dependsOn: [CARGO_TEST_COMPILE_TARGET],
145
234
  options: {
146
- command: 'cargo test --workspace',
235
+ command: cargoFrozen('test --workspace'),
147
236
  cwd: projectRoot,
148
- // Cold macOS Cargo workspaces can exceed ten minutes while still making progress.
149
- timeoutMs: 1200000,
150
- killAfterMs: 10000,
237
+ timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
238
+ killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
151
239
  },
152
240
  configurations: {
153
- production: { command: 'cargo test --workspace --release' },
241
+ production: { command: cargoFrozen('test --workspace --release') },
154
242
  },
155
243
  };
156
244
  }
157
245
 
158
- export const createNodesV2: CreateNodesV2 = [
159
- '**/package.json',
160
- async (projectConfigurationFiles, _options, context) => {
246
+ const PLUGIN_NEXTEST_CONFIG = fileURLToPath(new URL('../nextest.toml', import.meta.url));
247
+
248
+ /**
249
+ * One bounded target per crate; a crate that declares `smoothbricks.test.shards`
250
+ * gets one per shard plus one for the tests nextest.toml singles out.
251
+ *
252
+ * `--workspace -E 'package(X)'` rather than `--package X`. A filterset selects
253
+ * what RUNS; `--package` also re-resolves FEATURES for that crate alone, which
254
+ * fingerprints differently from the `cargo test --workspace --no-run` that
255
+ * `cargo-test-compile` already paid for, so cargo rebuilds the divergent half
256
+ * inside the bounded window. Measured on a hosted 3-core macOS runner that
257
+ * rebuild was 57.9s of a 120s budget — the tests were killed with 264 still to
258
+ * run while nothing was wrong with them. The two forms select the same tests;
259
+ * only the filterset reuses the compile target's artifacts.
260
+ *
261
+ * nextest.toml singles some tests out with an override, and each such class
262
+ * breaks a shard in its own way — a `test-group` is scoped to one nextest RUN
263
+ * so the hash would dissolve it, and a raised `slow-timeout` marks a test whose
264
+ * cost is not the suite's. Those are lifted OUT of the hash into one target and
265
+ * the shards run the exact complement, so which tests a shard holds stops
266
+ * depending on how the hash happened to fall.
267
+ *
268
+ * The two filtersets are exact complements, so their union is the crate whatever
269
+ * either one matches; an empty exception set (every real-APFS test is
270
+ * `cfg(target_os = "macos")`, so on Linux there are none) costs coverage
271
+ * nothing, which is why that target may pass having run zero tests. It cannot
272
+ * hide a lost test — only a pin that stopped matching, whose members then fall
273
+ * into the shards.
274
+ *
275
+ * Pieces chain rather than fan out, like the crates do: cargo flocks one
276
+ * `target/`, and chaining keeps even the pinned group from overlapping the
277
+ * shards on a machine-wide resource.
278
+ */
279
+ async function addPerPackageCargoTestTargets(
280
+ targets: Record<string, TargetConfiguration>,
281
+ projectRoot: string,
282
+ workspaceRoot: string,
283
+ absoluteProjectRoot: string,
284
+ ): Promise<string[]> {
285
+ const packages = listCargoWorkspacePackages(absoluteProjectRoot);
286
+ if (packages.length === 0) {
287
+ return [];
288
+ }
289
+ const configFile = nextestConfigRelPath(workspaceRoot, projectRoot, PLUGIN_NEXTEST_CONFIG);
290
+ const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
291
+ const packageTargetNames: string[] = [];
292
+ let previous = CARGO_TEST_COMPILE_TARGET;
293
+ for (const pkg of packages) {
294
+ const inputs = await cargoPackageTestInputs(absoluteProjectRoot, pkg.dir);
295
+ const sharded = pkg.testShards > 1;
296
+ const pin = sharded && exceptional !== null ? exceptional : null;
297
+ const addTarget = (piece: string | undefined, selector: string, extra: string) => {
298
+ const targetName = cargoTestPackageTargetName(pkg.name, piece);
299
+ packageTargetNames.push(targetName);
300
+ targets[targetName] = {
301
+ executor: '@smoothbricks/nx-plugin:bounded-exec',
302
+ cache: true,
303
+ inputs,
304
+ dependsOn: [previous],
305
+ options: {
306
+ command: cargoFrozen(
307
+ `nextest run --workspace -E '${selector}'${extra} --user-config-file none --config-file ${configFile}`,
308
+ ),
309
+ cwd: projectRoot,
310
+ timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
311
+ killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
312
+ },
313
+ };
314
+ previous = targetName;
315
+ };
316
+ const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
317
+ for (let index = 1; index <= pkg.testShards; index += 1) {
318
+ // nextest hashes the test name, so a shard holds the same tests whatever
319
+ // else the filterset selects and whatever tests are added later.
320
+ addTarget(
321
+ sharded ? `shard${index}` : undefined,
322
+ shardable,
323
+ sharded ? ` --partition hash:${index}/${pkg.testShards}` : '',
324
+ );
325
+ }
326
+ if (pin !== null) {
327
+ addTarget(CARGO_TEST_EXCEPTIONS_SUFFIX, `package(${pkg.name}) and (${pin})`, ' --no-tests=pass');
328
+ }
329
+ }
330
+ return packageTargetNames;
331
+ }
332
+
333
+ type CreateNodesHandler = CreateNodesV2[1];
334
+
335
+ function createNodesHandler(hostPlatform: NapiPlatform | null): CreateNodesHandler {
336
+ return async (projectConfigurationFiles, _options, context) => {
161
337
  const results: CreateNodesResultV2 = [];
162
338
  const errors: Array<[file: string | null, error: Error]> = [];
163
339
 
@@ -170,7 +346,10 @@ export const createNodesV2: CreateNodesV2 = [
170
346
  results.push([packageJsonPath, {}]);
171
347
  return;
172
348
  }
173
- results.push([packageJsonPath, await createProjectTargets(packageJsonPath, context.workspaceRoot)]);
349
+ results.push([
350
+ packageJsonPath,
351
+ await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform),
352
+ ]);
174
353
  } catch (error) {
175
354
  errors.push([packageJsonPath, error instanceof Error ? error : new Error(String(error))]);
176
355
  }
@@ -182,7 +361,16 @@ export const createNodesV2: CreateNodesV2 = [
182
361
  }
183
362
 
184
363
  return results;
185
- },
364
+ };
365
+ }
366
+
367
+ export function createNodesV2ForPlatform(platform: NodeJS.Platform, architecture: string): CreateNodesV2 {
368
+ return ['**/package.json', createNodesHandler(napiPlatform(platform, architecture))];
369
+ }
370
+
371
+ export const createNodesV2: CreateNodesV2 = [
372
+ '**/package.json',
373
+ (...args) => createNodesHandler(napiPlatform(process.platform, process.arch))(...args),
186
374
  ];
187
375
 
188
376
  function isManagedPackageJsonSource(packageJsonPath: string): boolean {
@@ -202,7 +390,7 @@ interface PackageJson {
202
390
  };
203
391
  }
204
392
 
205
- async function createProjectTargets(packageJsonPath: string, workspaceRoot: string) {
393
+ async function createProjectTargets(packageJsonPath: string, workspaceRoot: string, hostPlatform: NapiPlatform | null) {
206
394
  const projectRoot = dirname(packageJsonPath);
207
395
  const absoluteProjectRoot = join(workspaceRoot, projectRoot);
208
396
  const packageJson = await readPackageJson(join(workspaceRoot, packageJsonPath));
@@ -297,8 +485,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
297
485
  }
298
486
 
299
487
  if (napiConfig) {
300
- const napiTargets = createNapiTargets(projectRoot, napiConfig);
301
- Object.assign(targets, napiTargets.targets);
488
+ Object.assign(targets, createNapiTargets(projectRoot, napiConfig, hostPlatform));
302
489
  if (
303
490
  !('napi-test' in (packageJson.nx?.targets ?? {})) &&
304
491
  existsSync(join(absoluteProjectRoot, 'src/native.test.ts'))
@@ -306,30 +493,78 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
306
493
  targets['napi-test'] = createNapiTestTarget(
307
494
  projectRoot,
308
495
  existsSync(join(absoluteProjectRoot, 'bunfig.napi-test.toml')),
309
- napiTargets.hostProvider,
310
496
  );
311
497
  }
312
498
  }
313
499
 
314
500
  // Member crates get their targets from the workspace-root package.json,
315
501
  // never per-crate — one Nx project per Cargo workspace.
502
+ //
503
+ // Every cargo tool target below is inferred unconditionally, INCLUDING when
504
+ // the package already declares that key in `nx.targets`. Nx merges a
505
+ // package-local declaration over an inference plugin's target one layer
506
+ // later — the precedence order is specified plugins → target defaults →
507
+ // default plugins, and the package.json reader is a default plugin — so a
508
+ // declaration only has to name the fields it changes:
509
+ //
510
+ // - `executor`, `cache`, `inputs`, `outputs`, `dependsOn`: the declared
511
+ // value REPLACES the inferred one, and every field the declaration omits
512
+ // is inherited from here.
513
+ // - `options` and `configurations`: merged key by key with declared keys
514
+ // winning, unless the declaration names a different executor — then its
515
+ // options mean something else and replace them wholesale.
516
+ // - `"dependsOn": ["...", "extra"]` expands the inferred list at the
517
+ // token's position. That is how a package ADDS an edge.
518
+ //
519
+ // Skipping inference for a declared key — what this used to do — is what made
520
+ // a one-line addition catastrophic: `nx.targets['cargo-test'] = { dependsOn:
521
+ // [...] }` left nothing to merge onto, and Nx normalizes a bare `dependsOn`
522
+ // to `executor: nx:noop` with empty options. That is the worst kind of green:
523
+ // `cargo-test` reaches its dependencies and runs no test binary.
524
+ // `checkWorkspaceCargoTestReachabilityPolicy` fails that shape, but the fix is
525
+ // to leave a base for the declaration to land on.
526
+ //
527
+ // The overlay is deliberately NOT re-implemented here. Applying it in this
528
+ // plugin as well would expand a `"..."` spread twice — once against the
529
+ // inferred list here, once when Nx merges the same declaration over this
530
+ // result — duplicating the very edges the spread exists to add.
531
+ //
532
+ // `dependsOn` REPLACES rather than unions. These lists are not a bag of
533
+ // independent wishes; they are the serialization chain that keeps two cargo
534
+ // writers off one flocked `target/` (see CARGO_TEST_COMPILE_TARGET), and their
535
+ // ORDER carries the invariant. A package that must re-route the chain — build
536
+ // its artifact ahead of the test run, or drop `cargo-test-compile` because it
537
+ // compiles differently — can only say so by replacing the list; a union would
538
+ // make every inferred edge unremovable and a corrected order unrepresentable.
539
+ // Additive intent already has a spelling (`"..."` above), so a plugin-local
540
+ // additive key would be a second convention beside a working one.
541
+ //
542
+ // The output families (`cargo-wasm`, `napi-*`) and the `test` aggregate stay
543
+ // all-or-nothing, because for those the package decides whether the target
544
+ // EXISTS — a packaging decision for output families, the bounded-test policy's
545
+ // rewrite for `test` — so there is no inferred base to partially override.
316
546
  if (isCargoWorkspace) {
317
- const declared = declaredTargets;
318
- if (!('cargo-test' in declared)) {
319
- targets['cargo-test'] = createCargoTestTarget(projectRoot);
320
- }
321
- if (!('cargo-lint' in declared)) {
322
- targets['cargo-lint'] = {
323
- executor: 'nx:run-commands',
324
- cache: true,
325
- inputs: CARGO_INPUTS,
326
- options: {
327
- commands: ['cargo fmt --all --check', 'cargo clippy --workspace --all-targets -- -D warnings'],
328
- cwd: projectRoot,
329
- parallel: false,
330
- },
331
- };
332
- }
547
+ targets[CARGO_TEST_COMPILE_TARGET] = createCargoTestCompileTarget(projectRoot);
548
+ const packageTargetNames = await addPerPackageCargoTestTargets(
549
+ targets,
550
+ projectRoot,
551
+ workspaceRoot,
552
+ absoluteProjectRoot,
553
+ );
554
+ targets[CARGO_TEST_TARGET] =
555
+ packageTargetNames.length > 0
556
+ ? { executor: 'nx:noop', cache: true, dependsOn: packageTargetNames }
557
+ : createCargoTestTarget(projectRoot);
558
+ targets['cargo-lint'] = {
559
+ executor: 'nx:run-commands',
560
+ cache: true,
561
+ inputs: CARGO_INPUTS,
562
+ options: {
563
+ commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
564
+ cwd: projectRoot,
565
+ parallel: false,
566
+ },
567
+ };
333
568
  validationTargets.push('cargo-lint');
334
569
  // The Linux arm of `cargo-lint`, as its own target. Rationale for the name,
335
570
  // the command and the absent cross test leg lives in ./cross-check-policy.ts.
@@ -349,53 +584,213 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
349
584
  // see, so it would silently skip projects — today's bug in a new costume. An
350
585
  // opt-in flag has the same failure mode by construction. Every Rust project is
351
586
  // in scope because CI compiles every Rust project on Linux; a project that
352
- // genuinely cannot cross-compile overrides the target by declaring it, which is
353
- // a visible edit to its package.json rather than a silent absence.
587
+ // genuinely cannot cross-compile overrides the target by declaring it with
588
+ // `executor: nx:noop`, which is a visible edit to its package.json rather
589
+ // than a silent absence.
354
590
  //
355
591
  // Deliberately NOT pushed to validationTargets: joining the lint aggregate
356
592
  // would make `bun run lint` — and CI's own Linux lint, already native — demand
357
593
  // the 0.4 GiB cross toolchain that the devenv profile exists to keep opt-in.
358
- if (!(CARGO_CROSS_LINT_TARGET in declared)) {
359
- targets[CARGO_CROSS_LINT_TARGET] = {
360
- executor: 'nx:run-commands',
594
+ targets[CARGO_CROSS_LINT_TARGET] = {
595
+ executor: 'nx:run-commands',
596
+ cache: true,
597
+ inputs: CARGO_INPUTS,
598
+ options: {
599
+ command: CARGO_CROSS_LINT_COMMAND,
600
+ cwd: projectRoot,
601
+ },
602
+ };
603
+ if (!targets.test && !('test' in declaredTargets) && typeof packageJson.scripts?.test !== 'string') {
604
+ targets.test = {
605
+ executor: 'nx:noop',
361
606
  cache: true,
362
- inputs: CARGO_INPUTS,
363
- options: {
364
- command: CARGO_CROSS_LINT_COMMAND,
365
- cwd: projectRoot,
366
- },
607
+ dependsOn: [CARGO_TEST_TARGET],
367
608
  };
368
609
  }
369
- if (!targets.test && !('test' in declared) && typeof packageJson.scripts?.test !== 'string') {
370
- // Execute Cargo directly: workspace targetDefaults may replace test.dependsOn.
371
- targets.test = createCargoTestTarget(projectRoot);
610
+ // Mutation runs are minutes-to-hours: never cached, never part of build/lint.
611
+ // CI runs these per-PR via `cargo mutants --in-diff` (see mutants.toml docs).
612
+ targets.mutation = {
613
+ executor: 'nx:run-commands',
614
+ cache: false,
615
+ options: { command: cargoFrozen('mutants --workspace'), cwd: projectRoot },
616
+ };
617
+ targets.bench = {
618
+ executor: 'nx:run-commands',
619
+ cache: false,
620
+ options: { command: cargoFrozen('bench --workspace'), cwd: projectRoot },
621
+ };
622
+ // Target-dir GC. Cargo never removes superseded artifacts, so a busy
623
+ // workspace grows tens of GB of stale variants no fingerprint references;
624
+ // sweeping by age prunes exactly that junk while the warm current
625
+ // surface — the gated asset — survives untouched. Never cached: the
626
+ // verdict is about this machine's disk, not the commit.
627
+ targets['cargo-sweep'] = {
628
+ executor: 'nx:run-commands',
629
+ cache: false,
630
+ options: { command: 'cargo sweep --time 7', cwd: projectRoot },
631
+ };
632
+ }
633
+
634
+ // Every `cargoFrozen` command needs a registry cache holding the whole locked
635
+ // graph, and offline cargo checks that at RESOLUTION — so a dev-dependency no
636
+ // build ever downloaded takes down `cargo --frozen build` just as surely as
637
+ // `cargo --frozen test`. On an ephemeral runner the only thing that had been
638
+ // populating that cache was a preceding NON-frozen `napi build`, which
639
+ // downloads normal dependencies and never dev-dependencies; a workspace no
640
+ // platform target reaches got nothing at all. `cargo-fetch` states the
641
+ // precondition instead of inheriting it from another target's side effects.
642
+ //
643
+ // Derived from the command text rather than a curated list of target names:
644
+ // the fact that makes a target need this is that it runs frozen cargo, so a
645
+ // frozen target added later is covered without anyone remembering to. The edge
646
+ // goes on EVERY frozen target, not just the head of the serialization chain,
647
+ // so re-routing that chain cannot strip a surviving target's precondition.
648
+ //
649
+ // A package that REPLACES one of these `dependsOn` lists drops the edge with
650
+ // it (see the merge rules above) and gets its cold-cache failure back; `"..."`
651
+ // keeps it.
652
+ const frozenCargoManifests = new Set<string>();
653
+ if (isCargoWorkspace) {
654
+ frozenCargoManifests.add('Cargo.toml');
655
+ }
656
+ if (inferCargoWasm && cargoWasmConfig) {
657
+ // A wasm-bindgen crate can sit in a nested Cargo workspace the project root
658
+ // is not a member of, so its graph is a second fetch, not the same one.
659
+ frozenCargoManifests.add(cargoWasmConfig.manifestPath);
660
+ }
661
+ if (frozenCargoManifests.size > 0) {
662
+ targets[CARGO_FETCH_TARGET] = {
663
+ executor: 'nx:run-commands',
664
+ // The download lands in CARGO_HOME, outside the workspace: a cache hit
665
+ // would skip work a cold registry still needs — same reason
666
+ // napi-toolchain-* is uncached. Nothing here is a workspace output, so
667
+ // there is nothing for Nx to restore in its place.
668
+ cache: false,
669
+ options: {
670
+ commands: [...frozenCargoManifests]
671
+ .sort()
672
+ .map((manifestPath) =>
673
+ manifestPath === 'Cargo.toml'
674
+ ? CARGO_FETCH_COMMAND
675
+ : `${CARGO_FETCH_COMMAND} --manifest-path ${manifestPath}`,
676
+ ),
677
+ cwd: projectRoot,
678
+ // Two fetches into one CARGO_HOME contend on its package-cache flock;
679
+ // serializing here spends the wait in Nx instead of inside cargo.
680
+ parallel: false,
681
+ },
682
+ };
683
+ for (const [name, target] of Object.entries(targets)) {
684
+ if (name === CARGO_FETCH_TARGET) {
685
+ continue;
686
+ }
687
+ const command: unknown = target.options?.command;
688
+ const commands: unknown = target.options?.commands;
689
+ const text = [
690
+ typeof command === 'string' ? command : '',
691
+ ...(Array.isArray(commands) ? commands.filter((entry) => typeof entry === 'string') : []),
692
+ ].join('\n');
693
+ if (!text.includes(CARGO_FROZEN_PREFIX)) {
694
+ continue;
695
+ }
696
+ const dependsOn = target.dependsOn ?? [];
697
+ if (!dependsOn.includes(CARGO_FETCH_TARGET)) {
698
+ target.dependsOn = [CARGO_FETCH_TARGET, ...dependsOn];
699
+ }
700
+ }
701
+ }
702
+
703
+ // Cargo flocks the package's default `target/`. Writers that share it must
704
+ // not be Nx siblings. Clippy is not in this set: it has its own --target-dir.
705
+ const napiDebug = targets['napi-debug'];
706
+ if (napiDebug && targets[CARGO_TEST_COMPILE_TARGET]) {
707
+ const dependsOn = napiDebug.dependsOn ?? [];
708
+ if (!dependsOn.includes(CARGO_TEST_COMPILE_TARGET)) {
709
+ napiDebug.dependsOn = [...dependsOn, CARGO_TEST_COMPILE_TARGET];
372
710
  }
373
- if (!('mutation' in declared)) {
374
- // Mutation runs are minutes-to-hours: never cached, never part of build/lint.
375
- // CI runs these per-PR via `cargo mutants --in-diff` (see mutants.toml docs).
376
- targets.mutation = {
377
- executor: 'nx:run-commands',
378
- cache: false,
379
- options: { command: 'cargo mutants --workspace', cwd: projectRoot },
380
- };
711
+ }
712
+ if (napiDebug) {
713
+ for (const [name, target] of Object.entries(targets)) {
714
+ if (!name.startsWith('cargo-test-') || name === CARGO_TEST_COMPILE_TARGET) {
715
+ continue;
716
+ }
717
+ const dependsOn = target.dependsOn ?? [];
718
+ if (dependsOn.includes(CARGO_TEST_COMPILE_TARGET) && !dependsOn.includes('napi-debug')) {
719
+ target.dependsOn = dependsOn.map((dep) => (dep === CARGO_TEST_COMPILE_TARGET ? 'napi-debug' : dep));
720
+ }
381
721
  }
382
- if (!('bench' in declared)) {
383
- targets.bench = {
384
- executor: 'nx:run-commands',
385
- cache: false,
386
- options: { command: 'cargo bench --workspace', cwd: projectRoot },
387
- };
722
+ const cargoTest = targets[CARGO_TEST_TARGET];
723
+ if (
724
+ cargoTest?.options &&
725
+ typeof cargoTest.options.command === 'string' &&
726
+ cargoTest.options.command.startsWith('cargo ')
727
+ ) {
728
+ const dependsOn = cargoTest.dependsOn ?? [];
729
+ if (!dependsOn.includes('napi-debug')) {
730
+ cargoTest.dependsOn = [...dependsOn, 'napi-debug'];
731
+ }
388
732
  }
389
733
  }
390
734
 
735
+ // `build` lists cargo-test-compile beside the host's platform binaries, and
736
+ // every one of those is a `napi build` — another cargo writer on the package's
737
+ // default `target/`, which cargo flocks.
738
+ //
739
+ // Only `cargo-napi` gets the ordering edge. A platform-suffixed target may NOT
740
+ // have one: `validatePlatformTargetDependencies` (package-target-policy.ts:674)
741
+ // walks each platform target's dependency closure and refuses any member of a
742
+ // different family, because the publish flow builds and collects one platform
743
+ // at a time — a `*-macos` collect that reached a familyless sibling would drag
744
+ // in work the macOS runner has no business doing. `cargo-napi` carries no
745
+ // platform suffix, so it is not scanned and the edge is legal there.
746
+ //
747
+ // The platform binaries therefore stay Nx siblings of cargo-test-compile and
748
+ // serialize on cargo's flock instead of on a graph edge. That is the same
749
+ // arrangement `cli-<arch>-<os>` and `napi-<arch>-<os>` already have with each
750
+ // other — both `napi build --release` on one target dir — so this adds a third
751
+ // participant to an existing wait, not a new hazard. The flock makes them wait;
752
+ // it does not corrupt anything, and these are unbounded `nx:run-commands`
753
+ // targets, so the wait is not charged against a test budget.
754
+ const cargoWriterNames = hostPlatformTargetNames(
755
+ [...Object.keys(declaredTargets), ...Object.keys(targets)],
756
+ hostPlatform,
757
+ );
758
+ const cargoNapi = targets['cargo-napi'];
759
+ if (cargoNapi && targets[CARGO_TEST_COMPILE_TARGET]) {
760
+ const dependsOn = cargoNapi.dependsOn ?? [];
761
+ if (!dependsOn.includes(CARGO_TEST_COMPILE_TARGET)) {
762
+ cargoNapi.dependsOn = [...dependsOn, CARGO_TEST_COMPILE_TARGET];
763
+ }
764
+ }
765
+
766
+ // No `outputs`, deliberately: this aggregate runs no command, so every file
767
+ // under dist belongs to the concrete target that emitted it. Claiming
768
+ // `{projectRoot}/dist` here would cache the children's bytes a second time
769
+ // under the aggregate's hash, and would make `smoo github-ci nx-run-many
770
+ // --collect-outputs` attribute to `build` whatever sits under dist — including
771
+ // platform-target artifacts the collect excludes on purpose and stale
772
+ // artifacts of targets that never ran. Two collected trees then claim one
773
+ // binary and `apply-outputs` rejects the overlap. `lint` and `test` are
774
+ // aggregates on the same terms. Same reason nx.json must not put `outputs` in
775
+ // targetDefaults.build (see validateBuildTargetDefault).
391
776
  if (hasOrdinaryBuildOutputTarget) {
392
777
  targets.build = {
393
778
  executor: 'nx:noop',
394
779
  cache: true,
780
+ // `cargo-napi` is both an output family and a serialized cargo writer, so
781
+ // the two sources overlap; the Set keeps one edge per target while holding
782
+ // the order the families are listed in.
395
783
  dependsOn: [
396
- '^build',
397
- ...BUILD_OUTPUT_DEPENDENCIES,
398
- ...hostPlatformTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
784
+ ...new Set([
785
+ '^build',
786
+ // Compiling the test executables is build work: it is unbounded and
787
+ // cacheable, while every RUNNER is a bounded-exec target reached only
788
+ // through the `test` aggregate. That split is what keeps a cold cargo
789
+ // workspace's compile time out of the bounded test window.
790
+ ...(targets[CARGO_TEST_COMPILE_TARGET] ? [CARGO_TEST_COMPILE_TARGET] : []),
791
+ ...buildOutputTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
792
+ ...cargoWriterNames,
793
+ ]),
399
794
  ],
400
795
  };
401
796
  }
@@ -610,22 +1005,44 @@ function resolveNapiConfig(
610
1005
  function createNapiTargets(
611
1006
  projectRoot: string,
612
1007
  config: ResolvedNapiConfig,
613
- ): { targets: Record<string, TargetConfiguration>; hostProvider: string } {
1008
+ hostPlatform: NapiPlatform | null,
1009
+ ): Record<string, TargetConfiguration> {
614
1010
  const commonCommand = `--manifest-path ${config.manifestPath} --package ${config.cargoPackage}`;
615
- const hostPlatformTargetName = HOST_PLATFORM_SUFFIX === null ? null : `napi${HOST_PLATFORM_SUFFIX}`;
1011
+ const hostPlatformTargetName =
1012
+ hostPlatform === null ? null : `napi-${hostPlatform.architecture}-${hostPlatform.targetFamily}`;
616
1013
  let nativeHostTargetName: string | null = null;
617
1014
  if (hostPlatformTargetName !== null) {
618
1015
  for (const triple of config.targets) {
619
1016
  const convention = NAPI_TARGET_CONVENTIONS[triple];
620
1017
  const targetName = convention ? `napi-${convention.architecture}-${convention.targetFamily}` : null;
621
- if (targetName === hostPlatformTargetName && !convention?.useNapiCross) {
1018
+ if (targetName === hostPlatformTargetName && convention && !usesNapiCross(convention, hostPlatform)) {
622
1019
  nativeHostTargetName = targetName;
623
1020
  break;
624
1021
  }
625
1022
  }
626
1023
  }
627
- const hostProvider = nativeHostTargetName ?? 'cargo-napi';
628
1024
  const targets: Record<string, TargetConfiguration> = {};
1025
+ const hostCompilerEnv = napiCompilerEnv(hostPlatform, hostPlatform);
1026
+
1027
+ // The addon the test suite loads. A dev-profile build shares target/debug
1028
+ // with cargo-test's dependency graph, so after the tests compile this is
1029
+ // nearly free — where the release platform build it replaces cost minutes
1030
+ // and sat alone on the test critical path. The output lives OUTSIDE dist/
1031
+ // because packages publish `files: ["dist"]` wholesale: a debug addon under
1032
+ // dist/ would ship. native.ts resolves this directory only when the
1033
+ // napi-test target sets NAPI_DEBUG_ADDON=1, so production loads never see it.
1034
+ targets['napi-debug'] = {
1035
+ executor: 'nx:run-commands',
1036
+ cache: true,
1037
+ dependsOn: ['^build'],
1038
+ inputs: NAPI_INPUTS,
1039
+ outputs: ['{projectRoot}/.cache/native-debug'],
1040
+ options: {
1041
+ cwd: projectRoot,
1042
+ command: `napi build --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir .cache/native-debug`,
1043
+ ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
1044
+ },
1045
+ };
629
1046
 
630
1047
  if (nativeHostTargetName === null) {
631
1048
  // The platform target for this host triple is the same compilation, so a
@@ -641,13 +1058,14 @@ function createNapiTargets(
641
1058
  options: {
642
1059
  cwd: projectRoot,
643
1060
  command: `napi build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir dist/native/host`,
1061
+ ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
644
1062
  },
645
1063
  };
646
1064
  }
647
1065
 
648
1066
  for (const triple of config.targets) {
649
1067
  const convention = NAPI_TARGET_CONVENTIONS[triple];
650
- if (!convention?.useNapiCross) {
1068
+ if (!convention || !usesNapiCross(convention, hostPlatform)) {
651
1069
  continue;
652
1070
  }
653
1071
  // One toolchain target per triple, shared by every cross build that needs
@@ -672,36 +1090,38 @@ function createNapiTargets(
672
1090
  }
673
1091
  const targetName = `napi-${convention.architecture}-${convention.targetFamily}`;
674
1092
  const outputDirectory = `dist/native/${convention.outputName}`;
675
- const crossFlag = convention.useNapiCross ? ' --use-napi-cross' : '';
1093
+ const useNapiCross = usesNapiCross(convention, hostPlatform);
1094
+ const crossFlag = useNapiCross ? ' --use-napi-cross' : '';
1095
+ const compilerEnv = napiCompilerEnv(convention, hostPlatform);
676
1096
  targets[targetName] = {
677
1097
  executor: 'nx:run-commands',
678
1098
  cache: true,
679
- ...(convention.useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
1099
+ ...(useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
680
1100
  inputs: NAPI_INPUTS,
681
1101
  outputs: [`{projectRoot}/${outputDirectory}`],
682
1102
  options: {
683
1103
  cwd: projectRoot,
684
1104
  command: `napi build --release --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputDirectory}`,
685
- // @napi-rs recognizes Clang and supplies its downloaded GNU sysroot
686
- // and toolchain flags. This keeps sccache enabled while avoiding the
687
- // old bundled GCC, which rejects sccache's diagnostics-color flag.
688
- ...(convention.useNapiCross ? { env: { TARGET_CC: 'clang', TARGET_CXX: 'clang++' } } : {}),
1105
+ // Genuine Linux cross-compiles use Clang plus napi-rs's downloaded
1106
+ // GNU sysroot. A native Linux target uses Nix's cc wrapper so C build
1107
+ // scripts resolve the host libc headers instead.
1108
+ ...(compilerEnv ? { env: compilerEnv } : {}),
689
1109
  },
690
1110
  };
691
1111
  }
692
- return { targets, hostProvider };
1112
+ return targets;
693
1113
  }
694
1114
 
695
- function createNapiTestTarget(
696
- projectRoot: string,
697
- hasDedicatedBunfig: boolean,
698
- hostProvider: string,
699
- ): TargetConfiguration {
1115
+ function createNapiTestTarget(projectRoot: string, hasDedicatedBunfig: boolean): TargetConfiguration {
700
1116
  const configFlag = hasDedicatedBunfig ? ' --config=../bunfig.napi-test.toml' : ' --config=../bunfig.toml';
701
1117
  return {
702
1118
  executor: '@smoothbricks/nx-plugin:bounded-exec',
703
1119
  cache: true,
704
- dependsOn: ['cargo-test', hostProvider, 'tsc-js', '^build', 'build'],
1120
+ // Deliberately NOT `build`: the aggregate drags the host-platform release
1121
+ // binaries onto the test critical path, and the tests assert behavior, not
1122
+ // optimization level. tsc-js supplies dist/ts for the suite's own imports;
1123
+ // napi-debug supplies the addon.
1124
+ dependsOn: ['cargo-test', 'napi-debug', 'tsc-js', '^build'],
705
1125
  options: {
706
1126
  // cwd is src/, not the package root: `bun test <arg>` treats the arg as a
707
1127
  // FILTER and scans the whole cwd tree for test files, and a Rust
@@ -710,6 +1130,9 @@ function createNapiTestTarget(
710
1130
  // config is passed explicitly.
711
1131
  command: `bun test${configFlag} --timeout=30000 native.test.ts`,
712
1132
  cwd: `${projectRoot}/src`,
1133
+ // Routes the package's native loader to the napi-debug artifact under
1134
+ // .cache/native-debug instead of the packaged dist/native tree.
1135
+ env: { NAPI_DEBUG_ADDON: '1' },
713
1136
  timeoutMs: 120000,
714
1137
  killAfterMs: 10000,
715
1138
  },