@smoothbricks/nx-plugin 0.4.1 → 0.4.3

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.
package/dist/index.js CHANGED
@@ -17,6 +17,46 @@ const TYPESCRIPT_TOOLCHAIN_INPUTS = [
17
17
  '{workspaceRoot}/patches/**/*',
18
18
  '{workspaceRoot}/tsconfig.base.json',
19
19
  ];
20
+ const BIOME_CONFIG_FILES = ['biome.json', 'biome.jsonc'];
21
+ const ESLINT_CONFIG_FILES = [
22
+ 'eslint.config.js',
23
+ 'eslint.config.mjs',
24
+ 'eslint.config.cjs',
25
+ 'eslint.config.ts',
26
+ 'eslint.config.mts',
27
+ 'eslint.config.cts',
28
+ ];
29
+ async function javaScriptSourceFiles(directory) {
30
+ if (!existsSync(directory))
31
+ return [];
32
+ const files = [];
33
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
34
+ if (entry.isDirectory()) {
35
+ if (entry.name !== 'node_modules' && entry.name !== 'target' && entry.name !== 'dist') {
36
+ files.push(...(await javaScriptSourceFiles(join(directory, entry.name))));
37
+ }
38
+ }
39
+ else if (entry.isFile() && /\.[cm]?[jt]sx?$/.test(entry.name)) {
40
+ files.push(join(directory, entry.name));
41
+ }
42
+ }
43
+ return files.sort();
44
+ }
45
+ async function projectLintCommands(projectRoot, workspaceRoot) {
46
+ const commands = [];
47
+ const absoluteProjectRoot = join(workspaceRoot, projectRoot);
48
+ const quote = (path) => `'${path.replaceAll("'", "'\"'\"'")}'`;
49
+ if (BIOME_CONFIG_FILES.some((name) => existsSync(join(workspaceRoot, name)))) {
50
+ commands.push(`biome check --files-ignore-unknown=true ${quote(projectRoot)}`);
51
+ }
52
+ if (ESLINT_CONFIG_FILES.some((name) => existsSync(join(workspaceRoot, name)))) {
53
+ const sourceFiles = await javaScriptSourceFiles(join(absoluteProjectRoot, 'src'));
54
+ if (sourceFiles.length > 0) {
55
+ commands.push(`eslint ${sourceFiles.map((file) => quote(relative(workspaceRoot, file))).join(' ')}`);
56
+ }
57
+ }
58
+ return commands;
59
+ }
20
60
  function napiPlatform(platform, architecture) {
21
61
  const targetFamily = platform === 'darwin' ? 'macos' : platform === 'linux' ? 'linux' : null;
22
62
  const targetArchitecture = architecture === 'arm64' ? 'arm64' : architecture === 'x64' ? 'x64' : null;
@@ -52,7 +92,9 @@ function hostPlatformTargetNames(targetNames, hostPlatform) {
52
92
  */
53
93
  function buildOutputTargetNames(targetNames) {
54
94
  return [...new Set(targetNames)]
55
- .filter((name) => BUILD_OUTPUT_TARGET_PATTERN.test(name) && !name.startsWith(`${CARGO_TEST_TARGET}-`))
95
+ .filter((name) => BUILD_OUTPUT_TARGET_PATTERN.test(name) &&
96
+ !name.startsWith(`${CARGO_TEST_TARGET}-`) &&
97
+ !name.startsWith('cargo-lint-'))
56
98
  .sort();
57
99
  }
58
100
  //#region smoo!n/rust-output-target-inference
@@ -86,6 +128,13 @@ const REPO_ROOT_CARGO_OUTPUT_INPUTS = [
86
128
  '{projectRoot}/package.json',
87
129
  '{workspaceRoot}/bun.lock',
88
130
  ];
131
+ const CARGO_ENVIRONMENT_INPUT = {
132
+ runtime: `bun -e 'const fs = require("node:fs"); const path = require("node:path"); const home = process.env.CARGO_HOME || path.join(require("node:os").homedir(), ".cargo"); console.log(JSON.stringify({env: Object.entries(process.env).filter(([name]) => /^(?:CARGO_|RUST|NEXTEST_|CLIPPY_|CC(?:_|$)|CXX(?:_|$)|AR(?:_|$)|CFLAGS|CXXFLAGS|CPPFLAGS|LDFLAGS|PKG_CONFIG|TARGET_|HOST_)/.test(name)).sort(([a], [b]) => a.localeCompare(b)), config: ["config", "config.toml"].map(name => { const file = path.join(home, name); return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; })}));'`,
133
+ };
134
+ function cargoRuntimeInput(projectRoot, command) {
135
+ const quotedRoot = `'${projectRoot.replaceAll("'", "'\"'\"'")}'`;
136
+ return { runtime: `cd ${quotedRoot} && ${command}` };
137
+ }
89
138
  const NAPI_INPUTS = CARGO_OUTPUT_INPUTS;
90
139
  const NAPI_TARGET_CONVENTIONS = {
91
140
  'aarch64-apple-darwin': {
@@ -155,9 +204,9 @@ function createCargoWasmTarget(projectRoot, config, repoRooted) {
155
204
  * Compilation is excluded from the bounded test window: a cold Cargo
156
205
  * workspace can take many minutes to compile while still making progress,
157
206
  * which is not a property of the tests. `cargo test --no-run` pays that cost
158
- * in its own unbounded, cacheable target; the bounded runner then re-invokes
159
- * cargo against a warm target directory, where only the suites' own runtime
160
- * counts against the standard bound.
207
+ * in its own unbounded target. Cargo reuses incremental compilation locally;
208
+ * Nx cannot cache this warming action without restoring shared mutable state.
209
+ * The bounded runner then uses the warm directory for the suites' own runtime.
161
210
  *
162
211
  * Cargo flocks one `target/` per invocation. Nx must not run two cargo
163
212
  * writers on that directory at once — that is a mutex, not a deadlock, and
@@ -169,8 +218,9 @@ function createCargoWasmTarget(projectRoot, config, repoRooted) {
169
218
  function createCargoTestCompileTarget(projectRoot) {
170
219
  return {
171
220
  executor: 'nx:run-commands',
172
- cache: true,
221
+ cache: false,
173
222
  inputs: CARGO_INPUTS,
223
+ outputs: [],
174
224
  options: {
175
225
  command: cargoFrozen('test --workspace --no-run'),
176
226
  cwd: projectRoot,
@@ -198,89 +248,17 @@ function createCargoTestTarget(projectRoot) {
198
248
  };
199
249
  }
200
250
  const PLUGIN_NEXTEST_CONFIG = fileURLToPath(new URL('../nextest.toml', import.meta.url));
201
- /**
202
- * One bounded target per crate; a crate that declares `smoothbricks.test.shards`
203
- * gets one per shard plus one for the tests nextest.toml singles out.
204
- *
205
- * `--workspace -E 'package(X)'` rather than `--package X`. A filterset selects
206
- * what RUNS; `--package` also re-resolves FEATURES for that crate alone, which
207
- * fingerprints differently from the `cargo test --workspace --no-run` that
208
- * `cargo-test-compile` already paid for, so cargo rebuilds the divergent half
209
- * inside the bounded window. Measured on a hosted 3-core macOS runner that
210
- * rebuild was 57.9s of a 120s budget — the tests were killed with 264 still to
211
- * run while nothing was wrong with them. The two forms select the same tests;
212
- * only the filterset reuses the compile target's artifacts.
213
- *
214
- * nextest.toml singles some tests out with an override, and each such class
215
- * breaks a shard in its own way — a `test-group` is scoped to one nextest RUN
216
- * so the hash would dissolve it, and a raised `slow-timeout` marks a test whose
217
- * cost is not the suite's. Those are lifted OUT of the hash into one target and
218
- * the shards run the exact complement, so which tests a shard holds stops
219
- * depending on how the hash happened to fall.
220
- *
221
- * The two filtersets are exact complements, so their union is the crate whatever
222
- * either one matches. Every piece uses `--no-tests=pass`: a valid workspace
223
- * member may expose no nextest tests, a small suite can leave a declared hash
224
- * shard empty, and platform-specific exceptions may not exist on this host.
225
- * Manifest discovery proves the package exists and generates the selector from
226
- * its Cargo name, so accepting an empty run cannot hide a misspelled package.
227
- *
228
- * The trade is explicit: a generated target cannot distinguish an intentionally
229
- * test-less crate from one whose entire suite stopped matching, so both pass.
230
- * Detecting that regression requires a separate coverage policy rather than
231
- * making valid empty crates and shards fail execution.
232
- *
233
- * Pieces chain rather than fan out, like the crates do: cargo flocks one
234
- * `target/`, and chaining keeps even the pinned group from overlapping the
235
- * shards on a machine-wide resource.
236
- */
237
- async function addPerPackageCargoTestTargets(targets, projectRoot, workspaceRoot, absoluteProjectRoot) {
238
- const packages = listCargoWorkspacePackages(absoluteProjectRoot);
239
- if (packages.length === 0) {
240
- return [];
241
- }
242
- const configFile = nextestConfigRelPath(workspaceRoot, projectRoot, PLUGIN_NEXTEST_CONFIG);
243
- const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
244
- const packageTargetNames = [];
245
- let previous = CARGO_TEST_COMPILE_TARGET;
246
- for (const pkg of packages) {
247
- const inputs = await cargoPackageTestInputs(absoluteProjectRoot, pkg.dir);
248
- const sharded = pkg.testShards > 1;
249
- const pin = sharded && exceptional !== null ? exceptional : null;
250
- const addTarget = (piece, selector, extra) => {
251
- const targetName = cargoTestPackageTargetName(pkg.name, piece);
252
- packageTargetNames.push(targetName);
253
- targets[targetName] = {
254
- executor: '@smoothbricks/nx-plugin:bounded-exec',
255
- cache: true,
256
- inputs,
257
- dependsOn: [previous],
258
- options: {
259
- command: cargoFrozen(`nextest run --workspace -E '${selector}'${extra} --no-tests=pass --user-config-file none --config-file ${configFile}`),
260
- cwd: projectRoot,
261
- timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
262
- killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
263
- },
264
- };
265
- previous = targetName;
266
- };
267
- const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
268
- for (let index = 1; index <= pkg.testShards; index += 1) {
269
- // nextest hashes the test name, so a shard holds the same tests whatever
270
- // else the filterset selects and whatever tests are added later.
271
- addTarget(sharded ? `shard${index}` : undefined, shardable, sharded ? ` --partition hash:${index}/${pkg.testShards}` : '');
272
- }
273
- if (pin !== null) {
274
- addTarget(CARGO_TEST_EXCEPTIONS_SUFFIX, `package(${pkg.name}) and (${pin})`, '');
275
- }
276
- }
277
- return packageTargetNames;
278
- }
279
251
  function createNodesHandler(hostPlatform) {
280
252
  return async (projectConfigurationFiles, _options, context) => {
281
253
  const results = [];
282
254
  const errors = [];
283
- const repoRootCargoWorkspace = await resolveRepoRootCargoWorkspace(projectConfigurationFiles, context.workspaceRoot);
255
+ let cargoWorkspaces;
256
+ try {
257
+ cargoWorkspaces = await resolveCargoWorkspaces(projectConfigurationFiles, context.workspaceRoot);
258
+ }
259
+ catch (error) {
260
+ throw new AggregateCreateNodesError([[null, error instanceof Error ? error : new Error(String(error))]], results);
261
+ }
284
262
  await Promise.all(projectConfigurationFiles.map(async (packageJsonPath) => {
285
263
  try {
286
264
  if (isManagedPackageJsonSource(packageJsonPath) || isBuildOutputPackageJson(packageJsonPath)) {
@@ -295,7 +273,7 @@ function createNodesHandler(hostPlatform) {
295
273
  }
296
274
  results.push([
297
275
  packageJsonPath,
298
- await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform, repoRootCargoWorkspace),
276
+ await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform, cargoWorkspaces),
299
277
  ]);
300
278
  }
301
279
  catch (error) {
@@ -348,7 +326,7 @@ function packageBinOutputs(packageJson, packageJsonPath) {
348
326
  }
349
327
  return [...outputs];
350
328
  }
351
- async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform, repoRootCargoWorkspace) {
329
+ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform, cargoWorkspaces) {
352
330
  const projectRoot = dirname(packageJsonPath);
353
331
  const absoluteProjectRoot = join(workspaceRoot, projectRoot);
354
332
  const packageJson = await readPackageJson(join(workspaceRoot, packageJsonPath));
@@ -362,11 +340,13 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
362
340
  const hasLibTsconfig = existsSync(libTsconfigPath);
363
341
  const cargoTomlPath = join(absoluteProjectRoot, 'Cargo.toml');
364
342
  const isCargoWorkspace = existsSync(cargoTomlPath) && CARGO_WORKSPACE_PATTERN.test(await readFile(cargoTomlPath, 'utf-8'));
365
- const repoRootPackagePlans = repoRootCargoWorkspace?.packages.filter((plan) => plan.package.projectRoot === projectRoot) ?? [];
366
- const isRepoRootWorkspaceRoot = repoRootCargoWorkspace !== null && projectRoot === '.';
367
- const isRepoRootCargoProject = isRepoRootWorkspaceRoot || repoRootPackagePlans.length > 0;
368
- const repoRootPackages = repoRootPackagePlans.map((plan) => plan.package);
369
- const isRepoRootedCargoProject = isRepoRootCargoProject && (!isCargoWorkspace || isRepoRootWorkspaceRoot);
343
+ const cargoWorkspace = cargoWorkspaces.find((workspace) => workspace.projectRoot === projectRoot) ??
344
+ cargoWorkspaces.find((workspace) => workspace.packages.some((plan) => plan.package.projectRoot === projectRoot));
345
+ const cargoPackagePlans = cargoWorkspace?.packages.filter((plan) => plan.package.projectRoot === projectRoot) ?? [];
346
+ const isCargoWorkspaceRoot = cargoWorkspace?.projectRoot === projectRoot;
347
+ const isCargoProject = cargoWorkspace !== undefined;
348
+ const repoRootPackages = cargoWorkspace?.projectRoot === '.' ? cargoPackagePlans.map((plan) => plan.package) : [];
349
+ const isRepoRootedCargoProject = cargoWorkspace?.projectRoot === '.';
370
350
  const napiConfig = resolveNapiConfig(packageJson, packageJsonPath, absoluteProjectRoot, isCargoWorkspace, repoRootPackages);
371
351
  const declaredTargets = packageJson.nx?.targets ?? {};
372
352
  const cargoWasmConfig = await resolveCargoWasmConfig(absoluteProjectRoot, packageJsonPath, workspaceRoot, repoRootPackages);
@@ -455,8 +435,8 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
455
435
  targets['napi-test'] = createNapiTestTarget(projectRoot, existsSync(join(absoluteProjectRoot, 'bunfig.napi-test.toml')));
456
436
  }
457
437
  }
458
- // Member crates get their targets from the workspace-root package.json,
459
- // never per-crate — one Nx project per Cargo workspace.
438
+ // Cargo members belong to the deepest containing Nx project. Workspace-wide
439
+ // prerequisites belong once to the project beside the workspace manifest.
460
440
  //
461
441
  // Every cargo tool target below is inferred unconditionally, INCLUDING when
462
442
  // the package already declares that key in `nx.targets`. Nx merges a
@@ -497,38 +477,46 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
497
477
  // Additive intent already has a spelling (`"..."` above), so a plugin-local
498
478
  // additive key would be a second convention beside a working one.
499
479
  //
500
- // The output families (`cargo-wasm`, `napi-*`) and the `test` aggregate stay
501
- // all-or-nothing, because for those the package decides whether the target
502
- // EXISTS — a packaging decision for output families, the bounded-test policy's
503
- // rewrite for `test` — so there is no inferred base to partially override.
504
- const ownsCargoWorkspaceTargets = isCargoWorkspace || isRepoRootWorkspaceRoot;
505
- if (ownsCargoWorkspaceTargets) {
506
- const cargoWorkspaceRoot = isRepoRootWorkspaceRoot ? '.' : projectRoot;
480
+ // The output families (`cargo-wasm`, `napi-*`) stay all-or-nothing: the
481
+ // package decides whether that target EXISTS. The `test` aggregate is inferred
482
+ // for cargo workspaces that do not declare it. A declared `test` gets only a
483
+ // dependsOn base of `^build`/`build` so TypeScript packages that omit dependsOn
484
+ // keep those edges now that targetDefaults.test.dependsOn is forbidden — it
485
+ // replaced inferred cargo-test rather than merging.
486
+ const ownsCargoWorkspaceTargets = isCargoWorkspaceRoot;
487
+ if (ownsCargoWorkspaceTargets && cargoWorkspace) {
488
+ const cargoWorkspaceRoot = cargoWorkspace.projectRoot;
507
489
  targets[CARGO_TEST_COMPILE_TARGET] = createCargoTestCompileTarget(cargoWorkspaceRoot);
508
- const packageTargetNames = isRepoRootWorkspaceRoot
509
- ? await addRepoRootCargoTestTargets(targets, projectName, projectRoot, workspaceRoot, repoRootCargoWorkspace)
510
- : await addPerPackageCargoTestTargets(targets, projectRoot, workspaceRoot, absoluteProjectRoot);
511
- const aggregateDependencies = isRepoRootWorkspaceRoot
512
- ? repoRootCargoWorkspace.packages.flatMap((plan) => plan.pieces.map((piece) => cargoTargetDependency(projectName, {
513
- projectName: plan.package.projectName,
514
- targetName: piece.targetName,
515
- })))
516
- : packageTargetNames;
490
+ const workspaceInputs = [
491
+ ...new Set((await Promise.all(cargoWorkspace.packages.map((plan) => cargoPackageTestInputs({
492
+ workspaceRoot,
493
+ absoluteProjectRoot: join(workspaceRoot, cargoWorkspaceRoot),
494
+ memberDir: plan.package.dir,
495
+ })))).flat()),
496
+ ];
497
+ targets[CARGO_TEST_COMPILE_TARGET].inputs = workspaceInputs.length > 0 ? workspaceInputs : CARGO_INPUTS;
498
+ const aggregateDependencies = cargoWorkspace.packages.flatMap((plan) => plan.pieces.map((piece) => cargoTargetDependency(projectName, {
499
+ projectName: plan.package.projectName,
500
+ targetName: piece.targetName,
501
+ })));
517
502
  targets[CARGO_TEST_TARGET] =
518
503
  aggregateDependencies.length > 0
519
- ? { executor: 'nx:noop', cache: true, dependsOn: aggregateDependencies }
504
+ ? { executor: 'nx:noop', cache: true, outputs: [], dependsOn: aggregateDependencies }
520
505
  : createCargoTestTarget(cargoWorkspaceRoot);
521
- targets['cargo-lint'] = {
522
- executor: 'nx:run-commands',
523
- cache: true,
524
- inputs: CARGO_INPUTS,
525
- options: {
526
- commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
527
- cwd: cargoWorkspaceRoot,
528
- parallel: false,
529
- },
530
- };
531
- validationTargets.push('cargo-lint');
506
+ if (cargoWorkspace.packages.length === 0) {
507
+ targets['cargo-lint'] = {
508
+ executor: 'nx:run-commands',
509
+ cache: true,
510
+ inputs: CARGO_INPUTS,
511
+ outputs: [],
512
+ options: {
513
+ commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
514
+ cwd: cargoWorkspaceRoot,
515
+ parallel: false,
516
+ },
517
+ };
518
+ validationTargets.push('cargo-lint');
519
+ }
532
520
  // The Linux arm of `cargo-lint`, as its own target. Rationale for the name,
533
521
  // the command and the absent cross test leg lives in ./cross-check-policy.ts.
534
522
  //
@@ -559,7 +547,8 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
559
547
  targets[CARGO_CROSS_LINT_TARGET] = {
560
548
  executor: 'nx:run-commands',
561
549
  cache: true,
562
- inputs: CARGO_INPUTS,
550
+ inputs: workspaceInputs.length > 0 ? workspaceInputs : CARGO_INPUTS,
551
+ outputs: [],
563
552
  options: {
564
553
  command: CARGO_CROSS_LINT_COMMAND,
565
554
  cwd: cargoWorkspaceRoot,
@@ -595,13 +584,53 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
595
584
  options: { command: 'cargo sweep --time 7', cwd: cargoWorkspaceRoot },
596
585
  };
597
586
  }
598
- if (!isCargoWorkspace && !isRepoRootWorkspaceRoot && repoRootPackagePlans.length > 0 && repoRootCargoWorkspace) {
599
- const packageTargetNames = await addRepoRootCargoTestTargets(targets, projectName, projectRoot, workspaceRoot, repoRootCargoWorkspace);
600
- targets[CARGO_TEST_TARGET] = {
601
- executor: 'nx:noop',
602
- cache: true,
603
- dependsOn: packageTargetNames,
604
- };
587
+ if (cargoWorkspace) {
588
+ const packageTargetNames = await addCargoTestTargets(targets, projectName, projectRoot, workspaceRoot, cargoWorkspace);
589
+ if (!isCargoWorkspaceRoot) {
590
+ targets[CARGO_TEST_TARGET] = {
591
+ executor: 'nx:noop',
592
+ cache: true,
593
+ outputs: [],
594
+ dependsOn: packageTargetNames,
595
+ };
596
+ }
597
+ for (const plan of cargoPackagePlans) {
598
+ const name = plan.package.name;
599
+ targets[`cargo-lint-${name}`] = {
600
+ executor: 'nx:run-commands',
601
+ cache: true,
602
+ inputs: await cargoPackageTestInputs({
603
+ workspaceRoot,
604
+ absoluteProjectRoot: join(workspaceRoot, cargoWorkspace.projectRoot),
605
+ memberDir: plan.package.dir,
606
+ inputRoot: projectRoot === cargoWorkspace.projectRoot
607
+ ? '{projectRoot}'
608
+ : posix.join('{workspaceRoot}', cargoWorkspace.projectRoot),
609
+ }),
610
+ outputs: [],
611
+ options: {
612
+ commands: [
613
+ `cargo fmt -p ${name} --check`,
614
+ cargoFrozen(`clippy -p ${name} --all-targets --target-dir target/cargo-lint-${name} -- -D warnings`),
615
+ ],
616
+ cwd: cargoWorkspace.projectRoot,
617
+ parallel: false,
618
+ },
619
+ };
620
+ }
621
+ const lintPlans = isCargoWorkspaceRoot ? cargoWorkspace.packages : cargoPackagePlans;
622
+ if (lintPlans.length > 0) {
623
+ targets['cargo-lint'] = {
624
+ executor: 'nx:noop',
625
+ cache: true,
626
+ outputs: [],
627
+ dependsOn: lintPlans.map((plan) => cargoTargetDependency(projectName, {
628
+ projectName: plan.package.projectName,
629
+ targetName: `cargo-lint-${plan.package.name}`,
630
+ })),
631
+ };
632
+ validationTargets.push('cargo-lint');
633
+ }
605
634
  if (!targets.test && !('test' in declaredTargets) && typeof packageJson.scripts?.test !== 'string') {
606
635
  targets.test = {
607
636
  executor: 'nx:noop',
@@ -609,6 +638,18 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
609
638
  dependsOn: [CARGO_TEST_TARGET],
610
639
  };
611
640
  }
641
+ for (const name of [CARGO_TEST_TARGET, 'test']) {
642
+ const target = targets[name];
643
+ if (target?.executor === 'nx:noop') {
644
+ target.outputs = [];
645
+ target.configurations = { production: {} };
646
+ }
647
+ }
648
+ }
649
+ if ('test' in declaredTargets && targets.test === undefined) {
650
+ targets.test = {
651
+ dependsOn: ['^build', 'build'],
652
+ };
612
653
  }
613
654
  // Every `cargoFrozen` command needs a registry cache holding the whole locked
614
655
  // graph, and offline cargo checks that at RESOLUTION — so a dev-dependency no
@@ -651,7 +692,7 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
651
692
  .map((manifestPath) => manifestPath === 'Cargo.toml'
652
693
  ? CARGO_FETCH_COMMAND
653
694
  : `${CARGO_FETCH_COMMAND} --manifest-path ${manifestPath}`),
654
- cwd: isRepoRootWorkspaceRoot ? '.' : projectRoot,
695
+ cwd: projectRoot,
655
696
  // Two fetches into one CARGO_HOME contend on its package-cache flock;
656
697
  // serializing here spends the wait in Nx instead of inside cargo.
657
698
  parallel: false,
@@ -672,9 +713,9 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
672
713
  }
673
714
  }
674
715
  }
675
- else if (isRepoRootedCargoProject && repoRootCargoWorkspace) {
716
+ else if (cargoWorkspace) {
676
717
  const rootFetch = cargoTargetDependency(projectName, {
677
- projectName: repoRootCargoWorkspace.rootProjectName,
718
+ projectName: cargoWorkspace.rootProjectName,
678
719
  targetName: CARGO_FETCH_TARGET,
679
720
  });
680
721
  for (const target of Object.values(targets)) {
@@ -689,14 +730,40 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
689
730
  }
690
731
  }
691
732
  }
733
+ // Cache verdicts and dedicated artifacts, never Cargo's shared mutable build
734
+ // directories. Resolve tool versions from the command's actual directory.
735
+ for (const [name, target] of Object.entries(targets)) {
736
+ const command = target.options?.command;
737
+ const commands = target.options?.commands;
738
+ const text = [
739
+ typeof command === 'string' ? command : '',
740
+ ...(Array.isArray(commands) ? commands.filter((entry) => typeof entry === 'string') : []),
741
+ ].join('\n');
742
+ if (!text.includes(CARGO_FROZEN_PREFIX))
743
+ continue;
744
+ target.outputs ??= [];
745
+ if (!target.cache)
746
+ continue;
747
+ const cwd = target.options?.cwd;
748
+ const versions = name.startsWith('cargo-lint')
749
+ ? ` && cargo clippy -V${name === CARGO_CROSS_LINT_TARGET ? '' : ' && cargo fmt --version'}`
750
+ : text.includes('nextest run')
751
+ ? ' && cargo nextest --version'
752
+ : '';
753
+ target.inputs = [
754
+ ...(target.inputs ?? CARGO_INPUTS),
755
+ cargoRuntimeInput(typeof cwd === 'string' ? cwd : projectRoot, CARGO_ENVIRONMENT_INPUT.runtime),
756
+ cargoRuntimeInput(typeof cwd === 'string' ? cwd : projectRoot, `rustc -vV && cargo -V${versions}`),
757
+ ];
758
+ }
692
759
  // Cargo flocks the workspace's default target/. Keep every writer out of the
693
760
  // bounded test window by placing N-API debug builds on the same serialized
694
761
  // chain as the root compile and per-crate runners.
695
762
  const cargoTestCompileDependency = targets[CARGO_TEST_COMPILE_TARGET]
696
763
  ? CARGO_TEST_COMPILE_TARGET
697
- : isRepoRootCargoProject && repoRootCargoWorkspace
764
+ : isCargoProject && cargoWorkspace
698
765
  ? cargoTargetDependency(projectName, {
699
- projectName: repoRootCargoWorkspace.rootProjectName,
766
+ projectName: cargoWorkspace.rootProjectName,
700
767
  targetName: CARGO_TEST_COMPILE_TARGET,
701
768
  })
702
769
  : null;
@@ -707,8 +774,8 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
707
774
  napiDebug.dependsOn = [...dependsOn, cargoTestCompileDependency];
708
775
  }
709
776
  }
710
- if (napiDebug && isRepoRootedCargoProject) {
711
- const firstCargoTest = repoRootPackagePlans.flatMap((plan) => plan.pieces)[0];
777
+ if (napiDebug && cargoWorkspace) {
778
+ const firstCargoTest = cargoPackagePlans.flatMap((plan) => plan.pieces)[0];
712
779
  const firstTarget = firstCargoTest ? targets[firstCargoTest.targetName] : undefined;
713
780
  if (firstCargoTest && firstTarget) {
714
781
  const previous = cargoTargetDependency(projectName, firstCargoTest.previous);
@@ -786,10 +853,8 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
786
853
  dependsOn: [
787
854
  ...new Set([
788
855
  '^build',
789
- // Compiling the test executables is build work: it is unbounded and
790
- // cacheable, while every RUNNER is a bounded-exec target reached only
791
- // through the `test` aggregate. That split is what keeps a cold cargo
792
- // workspace's compile time out of the bounded test window.
856
+ // Compiling the test executables is unbounded preparation. Cargo
857
+ // reuses its incremental state; Nx never restores that shared state.
793
858
  ...(cargoTestCompileDependency ? [cargoTestCompileDependency] : []),
794
859
  ...buildOutputTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
795
860
  ...cargoWriterNames,
@@ -814,10 +879,27 @@ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform
814
879
  targets['typecheck-tests'].dependsOn = ['build'];
815
880
  }
816
881
  }
817
- if (validationTargets.length > 0) {
882
+ const lintCommands = await projectLintCommands(projectRoot, workspaceRoot);
883
+ if (validationTargets.length > 0 || lintCommands.length > 0) {
818
884
  targets.lint = {
885
+ executor: lintCommands.length > 0 ? 'nx:run-commands' : 'nx:noop',
819
886
  cache: true,
820
887
  dependsOn: validationTargets,
888
+ outputs: [],
889
+ inputs: [
890
+ 'default',
891
+ ...TYPESCRIPT_TOOLCHAIN_INPUTS,
892
+ ...[...BIOME_CONFIG_FILES, ...ESLINT_CONFIG_FILES].flatMap((name) => [
893
+ `{workspaceRoot}/${name}`,
894
+ `{projectRoot}/${name}`,
895
+ ]),
896
+ '{workspaceRoot}/tooling/checks/**/*',
897
+ ],
898
+ ...(lintCommands.length > 0
899
+ ? {
900
+ options: { commands: lintCommands, cwd: '.', parallel: false },
901
+ }
902
+ : {}),
821
903
  };
822
904
  }
823
905
  return {
@@ -1176,11 +1258,7 @@ function cargoTargetDependency(currentProjectName, target) {
1176
1258
  ? target.targetName
1177
1259
  : { projects: [target.projectName], target: target.targetName };
1178
1260
  }
1179
- async function resolveRepoRootCargoWorkspace(packageJsonPaths, workspaceRoot) {
1180
- const cargoTomlPath = join(workspaceRoot, 'Cargo.toml');
1181
- if (!existsSync(cargoTomlPath) || !CARGO_WORKSPACE_PATTERN.test(await readFile(cargoTomlPath, 'utf-8'))) {
1182
- return null;
1183
- }
1261
+ async function resolveCargoWorkspaces(packageJsonPaths, workspaceRoot) {
1184
1262
  const projects = [];
1185
1263
  for (const packageJsonPath of packageJsonPaths) {
1186
1264
  if (isManagedPackageJsonSource(packageJsonPath) || isBuildOutputPackageJson(packageJsonPath)) {
@@ -1197,46 +1275,90 @@ async function resolveRepoRootCargoWorkspace(packageJsonPaths, workspaceRoot) {
1197
1275
  // createProjectTargets records the path-specific parse failure below.
1198
1276
  }
1199
1277
  }
1200
- const rootProject = projects.find((project) => project.root === '.');
1201
- if (!rootProject) {
1202
- return null;
1203
- }
1204
- const attributed = attributeCargoWorkspacePackages(listCargoWorkspacePackages(workspaceRoot), projects);
1205
- const packages = [];
1206
- let previous = {
1207
- projectName: rootProject.name,
1208
- targetName: CARGO_TEST_COMPILE_TARGET,
1209
- };
1210
- const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
1211
- for (const pkg of attributed) {
1212
- const pieces = [];
1213
- const sharded = pkg.testShards > 1;
1214
- const pin = sharded && exceptional !== null ? exceptional : null;
1215
- const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
1216
- for (let index = 1; index <= pkg.testShards; index += 1) {
1217
- const targetName = cargoTestPackageTargetName(pkg.name, sharded ? `shard${index}` : undefined);
1218
- pieces.push({
1219
- extra: sharded ? ` --partition hash:${index}/${pkg.testShards}` : '',
1220
- previous,
1221
- selector: shardable,
1222
- targetName,
1223
- });
1224
- previous = { projectName: pkg.projectName, targetName };
1278
+ const workspaces = [];
1279
+ for (const rootProject of projects) {
1280
+ const absoluteRoot = join(workspaceRoot, rootProject.root);
1281
+ const manifest = join(absoluteRoot, 'Cargo.toml');
1282
+ if (!existsSync(manifest) || !CARGO_WORKSPACE_PATTERN.test(await readFile(manifest, 'utf-8'))) {
1283
+ continue;
1225
1284
  }
1226
- if (pin !== null) {
1227
- const targetName = cargoTestPackageTargetName(pkg.name, CARGO_TEST_EXCEPTIONS_SUFFIX);
1228
- pieces.push({
1229
- extra: '',
1230
- previous,
1231
- selector: `package(${pkg.name}) and (${pin})`,
1232
- targetName,
1233
- });
1234
- previous = { projectName: pkg.projectName, targetName };
1285
+ const attributed = attributeCargoWorkspacePackages(listCargoWorkspacePackages(absoluteRoot).map((pkg) => ({
1286
+ ...pkg,
1287
+ dir: posix.join(rootProject.root, pkg.dir),
1288
+ })), projects).map((pkg) => ({ ...pkg, dir: posix.relative(rootProject.root, pkg.dir) || '.' }));
1289
+ const packages = [];
1290
+ let previous = {
1291
+ projectName: rootProject.name,
1292
+ targetName: CARGO_TEST_COMPILE_TARGET,
1293
+ };
1294
+ const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
1295
+ for (const pkg of attributed) {
1296
+ const pieces = [];
1297
+ const sharded = pkg.testShards > 1;
1298
+ const pin = sharded && exceptional !== null ? exceptional : null;
1299
+ const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
1300
+ for (let index = 1; index <= pkg.testShards; index += 1) {
1301
+ const targetName = cargoTestPackageTargetName(pkg.name, sharded ? `shard${index}` : undefined);
1302
+ pieces.push({
1303
+ extra: sharded ? ` --partition hash:${index}/${pkg.testShards}` : '',
1304
+ previous,
1305
+ selector: shardable,
1306
+ targetName,
1307
+ });
1308
+ previous = { projectName: pkg.projectName, targetName };
1309
+ }
1310
+ if (pin !== null) {
1311
+ const targetName = cargoTestPackageTargetName(pkg.name, CARGO_TEST_EXCEPTIONS_SUFFIX);
1312
+ pieces.push({
1313
+ extra: '',
1314
+ previous,
1315
+ selector: `package(${pkg.name}) and (${pin})`,
1316
+ targetName,
1317
+ });
1318
+ previous = { projectName: pkg.projectName, targetName };
1319
+ }
1320
+ packages.push({ package: pkg, pieces });
1235
1321
  }
1236
- packages.push({ package: pkg, pieces });
1322
+ workspaces.push({ packages, rootProjectName: rootProject.name, projectRoot: rootProject.root });
1237
1323
  }
1238
- return { packages, rootProjectName: rootProject.name };
1324
+ return workspaces;
1239
1325
  }
1326
+ /**
1327
+ * One bounded target per crate; a crate that declares `smoothbricks.test.shards`
1328
+ * gets one per shard plus one for the tests nextest.toml singles out.
1329
+ *
1330
+ * `--workspace -E 'package(X)'` rather than `--package X`. A filterset selects
1331
+ * what RUNS; `--package` also re-resolves FEATURES for that crate alone, which
1332
+ * fingerprints differently from the `cargo test --workspace --no-run` that
1333
+ * `cargo-test-compile` already paid for, so cargo rebuilds the divergent half
1334
+ * inside the bounded window. Measured on a hosted 3-core macOS runner that
1335
+ * rebuild was 57.9s of a 120s budget — the tests were killed with 264 still to
1336
+ * run while nothing was wrong with them. The two forms select the same tests;
1337
+ * only the filterset reuses the compile target's artifacts.
1338
+ *
1339
+ * nextest.toml singles some tests out with an override, and each such class
1340
+ * breaks a shard in its own way — a `test-group` is scoped to one nextest RUN
1341
+ * so the hash would dissolve it, and a raised `slow-timeout` marks a test whose
1342
+ * cost is not the suite's. Those are lifted OUT of the hash into one target and
1343
+ * the shards run the exact complement, so which tests a shard holds stops
1344
+ * depending on how the hash happened to fall.
1345
+ *
1346
+ * The two filtersets are exact complements, so their union is the crate whatever
1347
+ * either one matches. Every piece uses `--no-tests=pass`: a valid workspace
1348
+ * member may expose no nextest tests, a small suite can leave a declared hash
1349
+ * shard empty, and platform-specific exceptions may not exist on this host.
1350
+ * Manifest discovery proves the package exists and generates the selector from
1351
+ * its Cargo name, so accepting an empty run cannot hide a misspelled package.
1352
+ *
1353
+ * The trade is explicit: a generated target cannot distinguish an intentionally
1354
+ * test-less crate from one whose entire suite stopped matching, so both pass.
1355
+ * Detecting that regression requires a separate coverage policy rather than
1356
+ * making valid empty crates and shards fail execution.
1357
+ *
1358
+ * Pieces chain rather than fan out, like the crates do: cargo flocks one
1359
+ * `target/`, and chaining keeps even the pinned group from overlapping the
1360
+ * shards on a machine-wide resource.
1361
+ */
1240
1362
  /**
1241
1363
  * Root mode keeps `--workspace` and adds `-p` only to make the owning crate
1242
1364
  * explicit in the command Nx attributes to its project. Cargo treats
@@ -1245,14 +1367,31 @@ async function resolveRepoRootCargoWorkspace(packageJsonPaths, workspaceRoot) {
1245
1367
  * Never drop `--workspace`: `-p X` alone re-resolves features for one package
1246
1368
  * and defeats the compile target's shared artifacts.
1247
1369
  */
1248
- async function addRepoRootCargoTestTargets(targets, currentProjectName, projectRoot, workspaceRoot, workspace) {
1370
+ async function addCargoTestTargets(targets, currentProjectName, projectRoot, workspaceRoot, workspace) {
1249
1371
  const targetNames = [];
1250
- const configFile = nextestConfigRelPath(workspaceRoot, '.', PLUGIN_NEXTEST_CONFIG);
1372
+ const configFile = nextestConfigRelPath(workspaceRoot, workspace.projectRoot, PLUGIN_NEXTEST_CONFIG);
1251
1373
  for (const plan of workspace.packages) {
1252
1374
  if (plan.package.projectRoot !== projectRoot) {
1253
1375
  continue;
1254
1376
  }
1255
- const inputs = await cargoPackageTestInputs(workspaceRoot, plan.package.dir, '{workspaceRoot}');
1377
+ const inputRoot = projectRoot === workspace.projectRoot ? '{projectRoot}' : posix.join('{workspaceRoot}', workspace.projectRoot);
1378
+ // A workspace nextest build unifies features across every selected member.
1379
+ // A sibling manifest can therefore change this crate's tests without being
1380
+ // a path dependency. Track those manifests, not unrelated sibling sources.
1381
+ const inputs = [
1382
+ ...new Set([
1383
+ ...(await cargoPackageTestInputs({
1384
+ workspaceRoot,
1385
+ absoluteProjectRoot: join(workspaceRoot, workspace.projectRoot),
1386
+ memberDir: plan.package.dir,
1387
+ inputRoot,
1388
+ })),
1389
+ ...workspace.packages.map((member) => posix.join(inputRoot, member.package.dir, 'Cargo.toml')),
1390
+ ]),
1391
+ {
1392
+ runtime: `bun -e 'console.log(new Bun.CryptoHasher("sha256").update(require("node:fs").readFileSync(process.argv[1])).digest("hex"))' '${PLUGIN_NEXTEST_CONFIG.replaceAll("'", "'\"'\"'")}'`,
1393
+ },
1394
+ ];
1256
1395
  for (const piece of plan.pieces) {
1257
1396
  targetNames.push(piece.targetName);
1258
1397
  targets[piece.targetName] = {
@@ -1261,11 +1400,16 @@ async function addRepoRootCargoTestTargets(targets, currentProjectName, projectR
1261
1400
  inputs,
1262
1401
  dependsOn: [cargoTargetDependency(currentProjectName, piece.previous)],
1263
1402
  options: {
1264
- command: cargoFrozen(`nextest run --workspace -p ${plan.package.name} -E '${piece.selector}'${piece.extra} --no-tests=pass --user-config-file none --config-file ${configFile}`),
1265
- cwd: '.',
1403
+ command: cargoFrozen(`nextest run --workspace${workspace.projectRoot === '.' ? ` -p ${plan.package.name}` : ''} -E '${piece.selector}'${piece.extra} --no-tests=pass --user-config-file none --config-file ${configFile}`),
1404
+ cwd: workspace.projectRoot,
1266
1405
  timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
1267
1406
  killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
1268
1407
  },
1408
+ configurations: {
1409
+ production: {
1410
+ command: cargoFrozen(`nextest run --workspace${workspace.projectRoot === '.' ? ` -p ${plan.package.name}` : ''} --release -E '${piece.selector}'${piece.extra} --no-tests=pass --user-config-file none --config-file ${configFile}`),
1411
+ },
1412
+ },
1269
1413
  };
1270
1414
  }
1271
1415
  }