@smoothbricks/nx-plugin 0.4.1 → 0.4.2

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/src/index.ts CHANGED
@@ -46,6 +46,47 @@ const TYPESCRIPT_TOOLCHAIN_INPUTS = [
46
46
  '{workspaceRoot}/tsconfig.base.json',
47
47
  ];
48
48
 
49
+ const BIOME_CONFIG_FILES = ['biome.json', 'biome.jsonc'];
50
+ const ESLINT_CONFIG_FILES = [
51
+ 'eslint.config.js',
52
+ 'eslint.config.mjs',
53
+ 'eslint.config.cjs',
54
+ 'eslint.config.ts',
55
+ 'eslint.config.mts',
56
+ 'eslint.config.cts',
57
+ ];
58
+
59
+ async function javaScriptSourceFiles(directory: string): Promise<string[]> {
60
+ if (!existsSync(directory)) return [];
61
+ const files: string[] = [];
62
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
63
+ if (entry.isDirectory()) {
64
+ if (entry.name !== 'node_modules' && entry.name !== 'target' && entry.name !== 'dist') {
65
+ files.push(...(await javaScriptSourceFiles(join(directory, entry.name))));
66
+ }
67
+ } else if (entry.isFile() && /\.[cm]?[jt]sx?$/.test(entry.name)) {
68
+ files.push(join(directory, entry.name));
69
+ }
70
+ }
71
+ return files.sort();
72
+ }
73
+
74
+ async function projectLintCommands(projectRoot: string, workspaceRoot: string): Promise<string[]> {
75
+ const commands: string[] = [];
76
+ const absoluteProjectRoot = join(workspaceRoot, projectRoot);
77
+ const quote = (path: string) => `'${path.replaceAll("'", "'\"'\"'")}'`;
78
+ if (BIOME_CONFIG_FILES.some((name) => existsSync(join(workspaceRoot, name)))) {
79
+ commands.push(`biome check --files-ignore-unknown=true ${quote(projectRoot)}`);
80
+ }
81
+ if (ESLINT_CONFIG_FILES.some((name) => existsSync(join(workspaceRoot, name)))) {
82
+ const sourceFiles = await javaScriptSourceFiles(join(absoluteProjectRoot, 'src'));
83
+ if (sourceFiles.length > 0) {
84
+ commands.push(`eslint ${sourceFiles.map((file) => quote(relative(workspaceRoot, file))).join(' ')}`);
85
+ }
86
+ }
87
+ return commands;
88
+ }
89
+
49
90
  type NapiArchitecture = 'arm64' | 'x64';
50
91
  type NapiTargetFamily = 'linux' | 'macos';
51
92
 
@@ -92,7 +133,12 @@ function hostPlatformTargetNames(targetNames: Iterable<string>, hostPlatform: Na
92
133
  */
93
134
  function buildOutputTargetNames(targetNames: Iterable<string>): string[] {
94
135
  return [...new Set(targetNames)]
95
- .filter((name) => BUILD_OUTPUT_TARGET_PATTERN.test(name) && !name.startsWith(`${CARGO_TEST_TARGET}-`))
136
+ .filter(
137
+ (name) =>
138
+ BUILD_OUTPUT_TARGET_PATTERN.test(name) &&
139
+ !name.startsWith(`${CARGO_TEST_TARGET}-`) &&
140
+ !name.startsWith('cargo-lint-'),
141
+ )
96
142
  .sort();
97
143
  }
98
144
 
@@ -127,6 +173,14 @@ const REPO_ROOT_CARGO_OUTPUT_INPUTS = [
127
173
  '{projectRoot}/package.json',
128
174
  '{workspaceRoot}/bun.lock',
129
175
  ];
176
+ const CARGO_ENVIRONMENT_INPUT = {
177
+ 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; })}));'`,
178
+ };
179
+
180
+ function cargoRuntimeInput(projectRoot: string, command: string): { runtime: string } {
181
+ const quotedRoot = `'${projectRoot.replaceAll("'", "'\"'\"'")}'`;
182
+ return { runtime: `cd ${quotedRoot} && ${command}` };
183
+ }
130
184
  const NAPI_INPUTS = CARGO_OUTPUT_INPUTS;
131
185
 
132
186
  interface NapiTargetConvention extends NapiPlatform {
@@ -219,9 +273,9 @@ function createCargoWasmTarget(
219
273
  * Compilation is excluded from the bounded test window: a cold Cargo
220
274
  * workspace can take many minutes to compile while still making progress,
221
275
  * which is not a property of the tests. `cargo test --no-run` pays that cost
222
- * in its own unbounded, cacheable target; the bounded runner then re-invokes
223
- * cargo against a warm target directory, where only the suites' own runtime
224
- * counts against the standard bound.
276
+ * in its own unbounded target. Cargo reuses incremental compilation locally;
277
+ * Nx cannot cache this warming action without restoring shared mutable state.
278
+ * The bounded runner then uses the warm directory for the suites' own runtime.
225
279
  *
226
280
  * Cargo flocks one `target/` per invocation. Nx must not run two cargo
227
281
  * writers on that directory at once — that is a mutex, not a deadlock, and
@@ -233,8 +287,9 @@ function createCargoWasmTarget(
233
287
  function createCargoTestCompileTarget(projectRoot: string): TargetConfiguration {
234
288
  return {
235
289
  executor: 'nx:run-commands',
236
- cache: true,
290
+ cache: false,
237
291
  inputs: CARGO_INPUTS,
292
+ outputs: [],
238
293
  options: {
239
294
  command: cargoFrozen('test --workspace --no-run'),
240
295
  cwd: projectRoot,
@@ -265,106 +320,18 @@ function createCargoTestTarget(projectRoot: string): TargetConfiguration {
265
320
 
266
321
  const PLUGIN_NEXTEST_CONFIG = fileURLToPath(new URL('../nextest.toml', import.meta.url));
267
322
 
268
- /**
269
- * One bounded target per crate; a crate that declares `smoothbricks.test.shards`
270
- * gets one per shard plus one for the tests nextest.toml singles out.
271
- *
272
- * `--workspace -E 'package(X)'` rather than `--package X`. A filterset selects
273
- * what RUNS; `--package` also re-resolves FEATURES for that crate alone, which
274
- * fingerprints differently from the `cargo test --workspace --no-run` that
275
- * `cargo-test-compile` already paid for, so cargo rebuilds the divergent half
276
- * inside the bounded window. Measured on a hosted 3-core macOS runner that
277
- * rebuild was 57.9s of a 120s budget — the tests were killed with 264 still to
278
- * run while nothing was wrong with them. The two forms select the same tests;
279
- * only the filterset reuses the compile target's artifacts.
280
- *
281
- * nextest.toml singles some tests out with an override, and each such class
282
- * breaks a shard in its own way — a `test-group` is scoped to one nextest RUN
283
- * so the hash would dissolve it, and a raised `slow-timeout` marks a test whose
284
- * cost is not the suite's. Those are lifted OUT of the hash into one target and
285
- * the shards run the exact complement, so which tests a shard holds stops
286
- * depending on how the hash happened to fall.
287
- *
288
- * The two filtersets are exact complements, so their union is the crate whatever
289
- * either one matches. Every piece uses `--no-tests=pass`: a valid workspace
290
- * member may expose no nextest tests, a small suite can leave a declared hash
291
- * shard empty, and platform-specific exceptions may not exist on this host.
292
- * Manifest discovery proves the package exists and generates the selector from
293
- * its Cargo name, so accepting an empty run cannot hide a misspelled package.
294
- *
295
- * The trade is explicit: a generated target cannot distinguish an intentionally
296
- * test-less crate from one whose entire suite stopped matching, so both pass.
297
- * Detecting that regression requires a separate coverage policy rather than
298
- * making valid empty crates and shards fail execution.
299
- *
300
- * Pieces chain rather than fan out, like the crates do: cargo flocks one
301
- * `target/`, and chaining keeps even the pinned group from overlapping the
302
- * shards on a machine-wide resource.
303
- */
304
- async function addPerPackageCargoTestTargets(
305
- targets: Record<string, TargetConfiguration>,
306
- projectRoot: string,
307
- workspaceRoot: string,
308
- absoluteProjectRoot: string,
309
- ): Promise<string[]> {
310
- const packages = listCargoWorkspacePackages(absoluteProjectRoot);
311
- if (packages.length === 0) {
312
- return [];
313
- }
314
- const configFile = nextestConfigRelPath(workspaceRoot, projectRoot, PLUGIN_NEXTEST_CONFIG);
315
- const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
316
- const packageTargetNames: string[] = [];
317
- let previous = CARGO_TEST_COMPILE_TARGET;
318
- for (const pkg of packages) {
319
- const inputs = await cargoPackageTestInputs(absoluteProjectRoot, pkg.dir);
320
- const sharded = pkg.testShards > 1;
321
- const pin = sharded && exceptional !== null ? exceptional : null;
322
- const addTarget = (piece: string | undefined, selector: string, extra: string) => {
323
- const targetName = cargoTestPackageTargetName(pkg.name, piece);
324
- packageTargetNames.push(targetName);
325
- targets[targetName] = {
326
- executor: '@smoothbricks/nx-plugin:bounded-exec',
327
- cache: true,
328
- inputs,
329
- dependsOn: [previous],
330
- options: {
331
- command: cargoFrozen(
332
- `nextest run --workspace -E '${selector}'${extra} --no-tests=pass --user-config-file none --config-file ${configFile}`,
333
- ),
334
- cwd: projectRoot,
335
- timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
336
- killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
337
- },
338
- };
339
- previous = targetName;
340
- };
341
- const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
342
- for (let index = 1; index <= pkg.testShards; index += 1) {
343
- // nextest hashes the test name, so a shard holds the same tests whatever
344
- // else the filterset selects and whatever tests are added later.
345
- addTarget(
346
- sharded ? `shard${index}` : undefined,
347
- shardable,
348
- sharded ? ` --partition hash:${index}/${pkg.testShards}` : '',
349
- );
350
- }
351
- if (pin !== null) {
352
- addTarget(CARGO_TEST_EXCEPTIONS_SUFFIX, `package(${pkg.name}) and (${pin})`, '');
353
- }
354
- }
355
- return packageTargetNames;
356
- }
357
-
358
323
  type CreateNodesHandler = CreateNodesV2[1];
359
324
 
360
325
  function createNodesHandler(hostPlatform: NapiPlatform | null): CreateNodesHandler {
361
326
  return async (projectConfigurationFiles, _options, context) => {
362
327
  const results: CreateNodesResultV2 = [];
363
328
  const errors: Array<[file: string | null, error: Error]> = [];
364
- const repoRootCargoWorkspace = await resolveRepoRootCargoWorkspace(
365
- projectConfigurationFiles,
366
- context.workspaceRoot,
367
- );
329
+ let cargoWorkspaces: CargoWorkspace[];
330
+ try {
331
+ cargoWorkspaces = await resolveCargoWorkspaces(projectConfigurationFiles, context.workspaceRoot);
332
+ } catch (error) {
333
+ throw new AggregateCreateNodesError([[null, error instanceof Error ? error : new Error(String(error))]], results);
334
+ }
368
335
 
369
336
  await Promise.all(
370
337
  projectConfigurationFiles.map(async (packageJsonPath) => {
@@ -381,7 +348,7 @@ function createNodesHandler(hostPlatform: NapiPlatform | null): CreateNodesHandl
381
348
  }
382
349
  results.push([
383
350
  packageJsonPath,
384
- await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform, repoRootCargoWorkspace),
351
+ await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform, cargoWorkspaces),
385
352
  ]);
386
353
  } catch (error) {
387
354
  errors.push([packageJsonPath, error instanceof Error ? error : new Error(String(error))]);
@@ -459,7 +426,7 @@ async function createProjectTargets(
459
426
  packageJsonPath: string,
460
427
  workspaceRoot: string,
461
428
  hostPlatform: NapiPlatform | null,
462
- repoRootCargoWorkspace: RepoRootCargoWorkspace | null,
429
+ cargoWorkspaces: readonly CargoWorkspace[],
463
430
  ) {
464
431
  const projectRoot = dirname(packageJsonPath);
465
432
  const absoluteProjectRoot = join(workspaceRoot, projectRoot);
@@ -475,12 +442,14 @@ async function createProjectTargets(
475
442
  const cargoTomlPath = join(absoluteProjectRoot, 'Cargo.toml');
476
443
  const isCargoWorkspace =
477
444
  existsSync(cargoTomlPath) && CARGO_WORKSPACE_PATTERN.test(await readFile(cargoTomlPath, 'utf-8'));
478
- const repoRootPackagePlans =
479
- repoRootCargoWorkspace?.packages.filter((plan) => plan.package.projectRoot === projectRoot) ?? [];
480
- const isRepoRootWorkspaceRoot = repoRootCargoWorkspace !== null && projectRoot === '.';
481
- const isRepoRootCargoProject = isRepoRootWorkspaceRoot || repoRootPackagePlans.length > 0;
482
- const repoRootPackages = repoRootPackagePlans.map((plan) => plan.package);
483
- const isRepoRootedCargoProject = isRepoRootCargoProject && (!isCargoWorkspace || isRepoRootWorkspaceRoot);
445
+ const cargoWorkspace =
446
+ cargoWorkspaces.find((workspace) => workspace.projectRoot === projectRoot) ??
447
+ cargoWorkspaces.find((workspace) => workspace.packages.some((plan) => plan.package.projectRoot === projectRoot));
448
+ const cargoPackagePlans = cargoWorkspace?.packages.filter((plan) => plan.package.projectRoot === projectRoot) ?? [];
449
+ const isCargoWorkspaceRoot = cargoWorkspace?.projectRoot === projectRoot;
450
+ const isCargoProject = cargoWorkspace !== undefined;
451
+ const repoRootPackages = cargoWorkspace?.projectRoot === '.' ? cargoPackagePlans.map((plan) => plan.package) : [];
452
+ const isRepoRootedCargoProject = cargoWorkspace?.projectRoot === '.';
484
453
  const napiConfig = resolveNapiConfig(
485
454
  packageJson,
486
455
  packageJsonPath,
@@ -590,8 +559,8 @@ async function createProjectTargets(
590
559
  }
591
560
  }
592
561
 
593
- // Member crates get their targets from the workspace-root package.json,
594
- // never per-crate — one Nx project per Cargo workspace.
562
+ // Cargo members belong to the deepest containing Nx project. Workspace-wide
563
+ // prerequisites belong once to the project beside the workspace manifest.
595
564
  //
596
565
  // Every cargo tool target below is inferred unconditionally, INCLUDING when
597
566
  // the package already declares that key in `nx.targets`. Nx merges a
@@ -632,42 +601,58 @@ async function createProjectTargets(
632
601
  // Additive intent already has a spelling (`"..."` above), so a plugin-local
633
602
  // additive key would be a second convention beside a working one.
634
603
  //
635
- // The output families (`cargo-wasm`, `napi-*`) and the `test` aggregate stay
636
- // all-or-nothing, because for those the package decides whether the target
637
- // EXISTS — a packaging decision for output families, the bounded-test policy's
638
- // rewrite for `test` — so there is no inferred base to partially override.
639
- const ownsCargoWorkspaceTargets = isCargoWorkspace || isRepoRootWorkspaceRoot;
640
- if (ownsCargoWorkspaceTargets) {
641
- const cargoWorkspaceRoot = isRepoRootWorkspaceRoot ? '.' : projectRoot;
604
+ // The output families (`cargo-wasm`, `napi-*`) stay all-or-nothing: the
605
+ // package decides whether that target EXISTS. The `test` aggregate is inferred
606
+ // for cargo workspaces that do not declare it. A declared `test` gets only a
607
+ // dependsOn base of `^build`/`build` so TypeScript packages that omit dependsOn
608
+ // keep those edges now that targetDefaults.test.dependsOn is forbidden — it
609
+ // replaced inferred cargo-test rather than merging.
610
+ const ownsCargoWorkspaceTargets = isCargoWorkspaceRoot;
611
+ if (ownsCargoWorkspaceTargets && cargoWorkspace) {
612
+ const cargoWorkspaceRoot = cargoWorkspace.projectRoot;
642
613
  targets[CARGO_TEST_COMPILE_TARGET] = createCargoTestCompileTarget(cargoWorkspaceRoot);
643
- const packageTargetNames = isRepoRootWorkspaceRoot
644
- ? await addRepoRootCargoTestTargets(targets, projectName, projectRoot, workspaceRoot, repoRootCargoWorkspace)
645
- : await addPerPackageCargoTestTargets(targets, projectRoot, workspaceRoot, absoluteProjectRoot);
646
- const aggregateDependencies = isRepoRootWorkspaceRoot
647
- ? repoRootCargoWorkspace.packages.flatMap((plan) =>
648
- plan.pieces.map((piece) =>
649
- cargoTargetDependency(projectName, {
650
- projectName: plan.package.projectName,
651
- targetName: piece.targetName,
652
- }),
653
- ),
654
- )
655
- : packageTargetNames;
614
+ const workspaceInputs = [
615
+ ...new Set(
616
+ (
617
+ await Promise.all(
618
+ cargoWorkspace.packages.map((plan) =>
619
+ cargoPackageTestInputs({
620
+ workspaceRoot,
621
+ absoluteProjectRoot: join(workspaceRoot, cargoWorkspaceRoot),
622
+ memberDir: plan.package.dir,
623
+ }),
624
+ ),
625
+ )
626
+ ).flat(),
627
+ ),
628
+ ];
629
+ targets[CARGO_TEST_COMPILE_TARGET].inputs = workspaceInputs.length > 0 ? workspaceInputs : CARGO_INPUTS;
630
+ const aggregateDependencies = cargoWorkspace.packages.flatMap((plan) =>
631
+ plan.pieces.map((piece) =>
632
+ cargoTargetDependency(projectName, {
633
+ projectName: plan.package.projectName,
634
+ targetName: piece.targetName,
635
+ }),
636
+ ),
637
+ );
656
638
  targets[CARGO_TEST_TARGET] =
657
639
  aggregateDependencies.length > 0
658
- ? { executor: 'nx:noop', cache: true, dependsOn: aggregateDependencies }
640
+ ? { executor: 'nx:noop', cache: true, outputs: [], dependsOn: aggregateDependencies }
659
641
  : createCargoTestTarget(cargoWorkspaceRoot);
660
- targets['cargo-lint'] = {
661
- executor: 'nx:run-commands',
662
- cache: true,
663
- inputs: CARGO_INPUTS,
664
- options: {
665
- commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
666
- cwd: cargoWorkspaceRoot,
667
- parallel: false,
668
- },
669
- };
670
- validationTargets.push('cargo-lint');
642
+ if (cargoWorkspace.packages.length === 0) {
643
+ targets['cargo-lint'] = {
644
+ executor: 'nx:run-commands',
645
+ cache: true,
646
+ inputs: CARGO_INPUTS,
647
+ outputs: [],
648
+ options: {
649
+ commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
650
+ cwd: cargoWorkspaceRoot,
651
+ parallel: false,
652
+ },
653
+ };
654
+ validationTargets.push('cargo-lint');
655
+ }
671
656
  // The Linux arm of `cargo-lint`, as its own target. Rationale for the name,
672
657
  // the command and the absent cross test leg lives in ./cross-check-policy.ts.
673
658
  //
@@ -698,7 +683,8 @@ async function createProjectTargets(
698
683
  targets[CARGO_CROSS_LINT_TARGET] = {
699
684
  executor: 'nx:run-commands',
700
685
  cache: true,
701
- inputs: CARGO_INPUTS,
686
+ inputs: workspaceInputs.length > 0 ? workspaceInputs : CARGO_INPUTS,
687
+ outputs: [],
702
688
  options: {
703
689
  command: CARGO_CROSS_LINT_COMMAND,
704
690
  cwd: cargoWorkspaceRoot,
@@ -735,19 +721,62 @@ async function createProjectTargets(
735
721
  };
736
722
  }
737
723
 
738
- if (!isCargoWorkspace && !isRepoRootWorkspaceRoot && repoRootPackagePlans.length > 0 && repoRootCargoWorkspace) {
739
- const packageTargetNames = await addRepoRootCargoTestTargets(
724
+ if (cargoWorkspace) {
725
+ const packageTargetNames = await addCargoTestTargets(
740
726
  targets,
741
727
  projectName,
742
728
  projectRoot,
743
729
  workspaceRoot,
744
- repoRootCargoWorkspace,
730
+ cargoWorkspace,
745
731
  );
746
- targets[CARGO_TEST_TARGET] = {
747
- executor: 'nx:noop',
748
- cache: true,
749
- dependsOn: packageTargetNames,
750
- };
732
+ if (!isCargoWorkspaceRoot) {
733
+ targets[CARGO_TEST_TARGET] = {
734
+ executor: 'nx:noop',
735
+ cache: true,
736
+ outputs: [],
737
+ dependsOn: packageTargetNames,
738
+ };
739
+ }
740
+ for (const plan of cargoPackagePlans) {
741
+ const name = plan.package.name;
742
+ targets[`cargo-lint-${name}`] = {
743
+ executor: 'nx:run-commands',
744
+ cache: true,
745
+ inputs: await cargoPackageTestInputs({
746
+ workspaceRoot,
747
+ absoluteProjectRoot: join(workspaceRoot, cargoWorkspace.projectRoot),
748
+ memberDir: plan.package.dir,
749
+ inputRoot:
750
+ projectRoot === cargoWorkspace.projectRoot
751
+ ? '{projectRoot}'
752
+ : posix.join('{workspaceRoot}', cargoWorkspace.projectRoot),
753
+ }),
754
+ outputs: [],
755
+ options: {
756
+ commands: [
757
+ `cargo fmt -p ${name} --check`,
758
+ cargoFrozen(`clippy -p ${name} --all-targets --target-dir target/cargo-lint-${name} -- -D warnings`),
759
+ ],
760
+ cwd: cargoWorkspace.projectRoot,
761
+ parallel: false,
762
+ },
763
+ };
764
+ }
765
+ const lintPlans = isCargoWorkspaceRoot ? cargoWorkspace.packages : cargoPackagePlans;
766
+ if (lintPlans.length > 0) {
767
+ targets['cargo-lint'] = {
768
+ executor: 'nx:noop',
769
+ cache: true,
770
+ outputs: [],
771
+ dependsOn: lintPlans.map((plan) =>
772
+ cargoTargetDependency(projectName, {
773
+ projectName: plan.package.projectName,
774
+ targetName: `cargo-lint-${plan.package.name}`,
775
+ }),
776
+ ),
777
+ };
778
+ validationTargets.push('cargo-lint');
779
+ }
751
780
  if (!targets.test && !('test' in declaredTargets) && typeof packageJson.scripts?.test !== 'string') {
752
781
  targets.test = {
753
782
  executor: 'nx:noop',
@@ -755,6 +784,19 @@ async function createProjectTargets(
755
784
  dependsOn: [CARGO_TEST_TARGET],
756
785
  };
757
786
  }
787
+ for (const name of [CARGO_TEST_TARGET, 'test']) {
788
+ const target = targets[name];
789
+ if (target?.executor === 'nx:noop') {
790
+ target.outputs = [];
791
+ target.configurations = { production: {} };
792
+ }
793
+ }
794
+ }
795
+
796
+ if ('test' in declaredTargets && targets.test === undefined) {
797
+ targets.test = {
798
+ dependsOn: ['^build', 'build'],
799
+ };
758
800
  }
759
801
 
760
802
  // Every `cargoFrozen` command needs a registry cache holding the whole locked
@@ -800,7 +842,7 @@ async function createProjectTargets(
800
842
  ? CARGO_FETCH_COMMAND
801
843
  : `${CARGO_FETCH_COMMAND} --manifest-path ${manifestPath}`,
802
844
  ),
803
- cwd: isRepoRootWorkspaceRoot ? '.' : projectRoot,
845
+ cwd: projectRoot,
804
846
  // Two fetches into one CARGO_HOME contend on its package-cache flock;
805
847
  // serializing here spends the wait in Nx instead of inside cargo.
806
848
  parallel: false,
@@ -820,9 +862,9 @@ async function createProjectTargets(
820
862
  target.dependsOn = [CARGO_FETCH_TARGET, ...(target.dependsOn ?? [])];
821
863
  }
822
864
  }
823
- } else if (isRepoRootedCargoProject && repoRootCargoWorkspace) {
865
+ } else if (cargoWorkspace) {
824
866
  const rootFetch = cargoTargetDependency(projectName, {
825
- projectName: repoRootCargoWorkspace.rootProjectName,
867
+ projectName: cargoWorkspace.rootProjectName,
826
868
  targetName: CARGO_FETCH_TARGET,
827
869
  });
828
870
  for (const target of Object.values(targets)) {
@@ -838,14 +880,39 @@ async function createProjectTargets(
838
880
  }
839
881
  }
840
882
 
883
+ // Cache verdicts and dedicated artifacts, never Cargo's shared mutable build
884
+ // directories. Resolve tool versions from the command's actual directory.
885
+ for (const [name, target] of Object.entries(targets)) {
886
+ const command: unknown = target.options?.command;
887
+ const commands: unknown = target.options?.commands;
888
+ const text = [
889
+ typeof command === 'string' ? command : '',
890
+ ...(Array.isArray(commands) ? commands.filter((entry) => typeof entry === 'string') : []),
891
+ ].join('\n');
892
+ if (!text.includes(CARGO_FROZEN_PREFIX)) continue;
893
+ target.outputs ??= [];
894
+ if (!target.cache) continue;
895
+ const cwd: unknown = target.options?.cwd;
896
+ const versions = name.startsWith('cargo-lint')
897
+ ? ` && cargo clippy -V${name === CARGO_CROSS_LINT_TARGET ? '' : ' && cargo fmt --version'}`
898
+ : text.includes('nextest run')
899
+ ? ' && cargo nextest --version'
900
+ : '';
901
+ target.inputs = [
902
+ ...(target.inputs ?? CARGO_INPUTS),
903
+ cargoRuntimeInput(typeof cwd === 'string' ? cwd : projectRoot, CARGO_ENVIRONMENT_INPUT.runtime),
904
+ cargoRuntimeInput(typeof cwd === 'string' ? cwd : projectRoot, `rustc -vV && cargo -V${versions}`),
905
+ ];
906
+ }
907
+
841
908
  // Cargo flocks the workspace's default target/. Keep every writer out of the
842
909
  // bounded test window by placing N-API debug builds on the same serialized
843
910
  // chain as the root compile and per-crate runners.
844
911
  const cargoTestCompileDependency: CargoTargetDependency | null = targets[CARGO_TEST_COMPILE_TARGET]
845
912
  ? CARGO_TEST_COMPILE_TARGET
846
- : isRepoRootCargoProject && repoRootCargoWorkspace
913
+ : isCargoProject && cargoWorkspace
847
914
  ? cargoTargetDependency(projectName, {
848
- projectName: repoRootCargoWorkspace.rootProjectName,
915
+ projectName: cargoWorkspace.rootProjectName,
849
916
  targetName: CARGO_TEST_COMPILE_TARGET,
850
917
  })
851
918
  : null;
@@ -856,8 +923,8 @@ async function createProjectTargets(
856
923
  napiDebug.dependsOn = [...dependsOn, cargoTestCompileDependency];
857
924
  }
858
925
  }
859
- if (napiDebug && isRepoRootedCargoProject) {
860
- const firstCargoTest = repoRootPackagePlans.flatMap((plan) => plan.pieces)[0];
926
+ if (napiDebug && cargoWorkspace) {
927
+ const firstCargoTest = cargoPackagePlans.flatMap((plan) => plan.pieces)[0];
861
928
  const firstTarget = firstCargoTest ? targets[firstCargoTest.targetName] : undefined;
862
929
  if (firstCargoTest && firstTarget) {
863
930
  const previous = cargoTargetDependency(projectName, firstCargoTest.previous);
@@ -945,10 +1012,8 @@ async function createProjectTargets(
945
1012
  dependsOn: [
946
1013
  ...new Set([
947
1014
  '^build',
948
- // Compiling the test executables is build work: it is unbounded and
949
- // cacheable, while every RUNNER is a bounded-exec target reached only
950
- // through the `test` aggregate. That split is what keeps a cold cargo
951
- // workspace's compile time out of the bounded test window.
1015
+ // Compiling the test executables is unbounded preparation. Cargo
1016
+ // reuses its incremental state; Nx never restores that shared state.
952
1017
  ...(cargoTestCompileDependency ? [cargoTestCompileDependency] : []),
953
1018
  ...buildOutputTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
954
1019
  ...cargoWriterNames,
@@ -974,10 +1039,27 @@ async function createProjectTargets(
974
1039
  }
975
1040
  }
976
1041
 
977
- if (validationTargets.length > 0) {
1042
+ const lintCommands = await projectLintCommands(projectRoot, workspaceRoot);
1043
+ if (validationTargets.length > 0 || lintCommands.length > 0) {
978
1044
  targets.lint = {
1045
+ executor: lintCommands.length > 0 ? 'nx:run-commands' : 'nx:noop',
979
1046
  cache: true,
980
1047
  dependsOn: validationTargets,
1048
+ outputs: [],
1049
+ inputs: [
1050
+ 'default',
1051
+ ...TYPESCRIPT_TOOLCHAIN_INPUTS,
1052
+ ...[...BIOME_CONFIG_FILES, ...ESLINT_CONFIG_FILES].flatMap((name) => [
1053
+ `{workspaceRoot}/${name}`,
1054
+ `{projectRoot}/${name}`,
1055
+ ]),
1056
+ '{workspaceRoot}/tooling/checks/**/*',
1057
+ ],
1058
+ ...(lintCommands.length > 0
1059
+ ? {
1060
+ options: { commands: lintCommands, cwd: '.', parallel: false },
1061
+ }
1062
+ : {}),
981
1063
  };
982
1064
  }
983
1065
 
@@ -1411,45 +1493,41 @@ function classifyPackageLocalBuildOutputs(packageJson: PackageJson): { ordinary:
1411
1493
  };
1412
1494
  }
1413
1495
 
1414
- interface RepoRootCargoTargetRef {
1496
+ interface CargoTargetRef {
1415
1497
  projectName: string;
1416
1498
  targetName: string;
1417
1499
  }
1418
1500
 
1419
- interface RepoRootCargoTestPiece {
1501
+ interface CargoTestPiece {
1420
1502
  extra: string;
1421
- previous: RepoRootCargoTargetRef;
1503
+ previous: CargoTargetRef;
1422
1504
  selector: string;
1423
1505
  targetName: string;
1424
1506
  }
1425
1507
 
1426
- interface RepoRootCargoPackagePlan {
1508
+ interface CargoPackagePlan {
1427
1509
  package: AttributedCargoWorkspacePackage;
1428
- pieces: RepoRootCargoTestPiece[];
1510
+ pieces: CargoTestPiece[];
1429
1511
  }
1430
1512
 
1431
- interface RepoRootCargoWorkspace {
1432
- packages: RepoRootCargoPackagePlan[];
1513
+ interface CargoWorkspace {
1514
+ packages: CargoPackagePlan[];
1433
1515
  rootProjectName: string;
1516
+ projectRoot: string;
1434
1517
  }
1435
1518
 
1436
1519
  type CargoTargetDependency = NonNullable<TargetConfiguration['dependsOn']>[number];
1437
1520
 
1438
- function cargoTargetDependency(currentProjectName: string, target: RepoRootCargoTargetRef): CargoTargetDependency {
1521
+ function cargoTargetDependency(currentProjectName: string, target: CargoTargetRef): CargoTargetDependency {
1439
1522
  return target.projectName === currentProjectName
1440
1523
  ? target.targetName
1441
1524
  : { projects: [target.projectName], target: target.targetName };
1442
1525
  }
1443
1526
 
1444
- async function resolveRepoRootCargoWorkspace(
1527
+ async function resolveCargoWorkspaces(
1445
1528
  packageJsonPaths: readonly string[],
1446
1529
  workspaceRoot: string,
1447
- ): Promise<RepoRootCargoWorkspace | null> {
1448
- const cargoTomlPath = join(workspaceRoot, 'Cargo.toml');
1449
- if (!existsSync(cargoTomlPath) || !CARGO_WORKSPACE_PATTERN.test(await readFile(cargoTomlPath, 'utf-8'))) {
1450
- return null;
1451
- }
1452
-
1530
+ ): Promise<CargoWorkspace[]> {
1453
1531
  const projects: Array<{ name: string; root: string }> = [];
1454
1532
  for (const packageJsonPath of packageJsonPaths) {
1455
1533
  if (isManagedPackageJsonSource(packageJsonPath) || isBuildOutputPackageJson(packageJsonPath)) {
@@ -1465,48 +1543,95 @@ async function resolveRepoRootCargoWorkspace(
1465
1543
  // createProjectTargets records the path-specific parse failure below.
1466
1544
  }
1467
1545
  }
1468
- const rootProject = projects.find((project) => project.root === '.');
1469
- if (!rootProject) {
1470
- return null;
1471
- }
1472
-
1473
- const attributed = attributeCargoWorkspacePackages(listCargoWorkspacePackages(workspaceRoot), projects);
1474
- const packages: RepoRootCargoPackagePlan[] = [];
1475
- let previous: RepoRootCargoTargetRef = {
1476
- projectName: rootProject.name,
1477
- targetName: CARGO_TEST_COMPILE_TARGET,
1478
- };
1479
- const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
1480
- for (const pkg of attributed) {
1481
- const pieces: RepoRootCargoTestPiece[] = [];
1482
- const sharded = pkg.testShards > 1;
1483
- const pin = sharded && exceptional !== null ? exceptional : null;
1484
- const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
1485
- for (let index = 1; index <= pkg.testShards; index += 1) {
1486
- const targetName = cargoTestPackageTargetName(pkg.name, sharded ? `shard${index}` : undefined);
1487
- pieces.push({
1488
- extra: sharded ? ` --partition hash:${index}/${pkg.testShards}` : '',
1489
- previous,
1490
- selector: shardable,
1491
- targetName,
1492
- });
1493
- previous = { projectName: pkg.projectName, targetName };
1546
+ const workspaces: CargoWorkspace[] = [];
1547
+ for (const rootProject of projects) {
1548
+ const absoluteRoot = join(workspaceRoot, rootProject.root);
1549
+ const manifest = join(absoluteRoot, 'Cargo.toml');
1550
+ if (!existsSync(manifest) || !CARGO_WORKSPACE_PATTERN.test(await readFile(manifest, 'utf-8'))) {
1551
+ continue;
1494
1552
  }
1495
- if (pin !== null) {
1496
- const targetName = cargoTestPackageTargetName(pkg.name, CARGO_TEST_EXCEPTIONS_SUFFIX);
1497
- pieces.push({
1498
- extra: '',
1499
- previous,
1500
- selector: `package(${pkg.name}) and (${pin})`,
1501
- targetName,
1502
- });
1503
- previous = { projectName: pkg.projectName, targetName };
1553
+ const attributed = attributeCargoWorkspacePackages(
1554
+ listCargoWorkspacePackages(absoluteRoot).map((pkg) => ({
1555
+ ...pkg,
1556
+ dir: posix.join(rootProject.root, pkg.dir),
1557
+ })),
1558
+ projects,
1559
+ ).map((pkg) => ({ ...pkg, dir: posix.relative(rootProject.root, pkg.dir) || '.' }));
1560
+ const packages: CargoPackagePlan[] = [];
1561
+ let previous: CargoTargetRef = {
1562
+ projectName: rootProject.name,
1563
+ targetName: CARGO_TEST_COMPILE_TARGET,
1564
+ };
1565
+ const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
1566
+ for (const pkg of attributed) {
1567
+ const pieces: CargoTestPiece[] = [];
1568
+ const sharded = pkg.testShards > 1;
1569
+ const pin = sharded && exceptional !== null ? exceptional : null;
1570
+ const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
1571
+ for (let index = 1; index <= pkg.testShards; index += 1) {
1572
+ const targetName = cargoTestPackageTargetName(pkg.name, sharded ? `shard${index}` : undefined);
1573
+ pieces.push({
1574
+ extra: sharded ? ` --partition hash:${index}/${pkg.testShards}` : '',
1575
+ previous,
1576
+ selector: shardable,
1577
+ targetName,
1578
+ });
1579
+ previous = { projectName: pkg.projectName, targetName };
1580
+ }
1581
+ if (pin !== null) {
1582
+ const targetName = cargoTestPackageTargetName(pkg.name, CARGO_TEST_EXCEPTIONS_SUFFIX);
1583
+ pieces.push({
1584
+ extra: '',
1585
+ previous,
1586
+ selector: `package(${pkg.name}) and (${pin})`,
1587
+ targetName,
1588
+ });
1589
+ previous = { projectName: pkg.projectName, targetName };
1590
+ }
1591
+ packages.push({ package: pkg, pieces });
1504
1592
  }
1505
- packages.push({ package: pkg, pieces });
1593
+ workspaces.push({ packages, rootProjectName: rootProject.name, projectRoot: rootProject.root });
1506
1594
  }
1507
- return { packages, rootProjectName: rootProject.name };
1595
+ return workspaces;
1508
1596
  }
1509
1597
 
1598
+ /**
1599
+ * One bounded target per crate; a crate that declares `smoothbricks.test.shards`
1600
+ * gets one per shard plus one for the tests nextest.toml singles out.
1601
+ *
1602
+ * `--workspace -E 'package(X)'` rather than `--package X`. A filterset selects
1603
+ * what RUNS; `--package` also re-resolves FEATURES for that crate alone, which
1604
+ * fingerprints differently from the `cargo test --workspace --no-run` that
1605
+ * `cargo-test-compile` already paid for, so cargo rebuilds the divergent half
1606
+ * inside the bounded window. Measured on a hosted 3-core macOS runner that
1607
+ * rebuild was 57.9s of a 120s budget — the tests were killed with 264 still to
1608
+ * run while nothing was wrong with them. The two forms select the same tests;
1609
+ * only the filterset reuses the compile target's artifacts.
1610
+ *
1611
+ * nextest.toml singles some tests out with an override, and each such class
1612
+ * breaks a shard in its own way — a `test-group` is scoped to one nextest RUN
1613
+ * so the hash would dissolve it, and a raised `slow-timeout` marks a test whose
1614
+ * cost is not the suite's. Those are lifted OUT of the hash into one target and
1615
+ * the shards run the exact complement, so which tests a shard holds stops
1616
+ * depending on how the hash happened to fall.
1617
+ *
1618
+ * The two filtersets are exact complements, so their union is the crate whatever
1619
+ * either one matches. Every piece uses `--no-tests=pass`: a valid workspace
1620
+ * member may expose no nextest tests, a small suite can leave a declared hash
1621
+ * shard empty, and platform-specific exceptions may not exist on this host.
1622
+ * Manifest discovery proves the package exists and generates the selector from
1623
+ * its Cargo name, so accepting an empty run cannot hide a misspelled package.
1624
+ *
1625
+ * The trade is explicit: a generated target cannot distinguish an intentionally
1626
+ * test-less crate from one whose entire suite stopped matching, so both pass.
1627
+ * Detecting that regression requires a separate coverage policy rather than
1628
+ * making valid empty crates and shards fail execution.
1629
+ *
1630
+ * Pieces chain rather than fan out, like the crates do: cargo flocks one
1631
+ * `target/`, and chaining keeps even the pinned group from overlapping the
1632
+ * shards on a machine-wide resource.
1633
+ */
1634
+
1510
1635
  /**
1511
1636
  * Root mode keeps `--workspace` and adds `-p` only to make the owning crate
1512
1637
  * explicit in the command Nx attributes to its project. Cargo treats
@@ -1515,20 +1640,38 @@ async function resolveRepoRootCargoWorkspace(
1515
1640
  * Never drop `--workspace`: `-p X` alone re-resolves features for one package
1516
1641
  * and defeats the compile target's shared artifacts.
1517
1642
  */
1518
- async function addRepoRootCargoTestTargets(
1643
+ async function addCargoTestTargets(
1519
1644
  targets: Record<string, TargetConfiguration>,
1520
1645
  currentProjectName: string,
1521
1646
  projectRoot: string,
1522
1647
  workspaceRoot: string,
1523
- workspace: RepoRootCargoWorkspace,
1648
+ workspace: CargoWorkspace,
1524
1649
  ): Promise<string[]> {
1525
1650
  const targetNames: string[] = [];
1526
- const configFile = nextestConfigRelPath(workspaceRoot, '.', PLUGIN_NEXTEST_CONFIG);
1651
+ const configFile = nextestConfigRelPath(workspaceRoot, workspace.projectRoot, PLUGIN_NEXTEST_CONFIG);
1527
1652
  for (const plan of workspace.packages) {
1528
1653
  if (plan.package.projectRoot !== projectRoot) {
1529
1654
  continue;
1530
1655
  }
1531
- const inputs = await cargoPackageTestInputs(workspaceRoot, plan.package.dir, '{workspaceRoot}');
1656
+ const inputRoot =
1657
+ projectRoot === workspace.projectRoot ? '{projectRoot}' : posix.join('{workspaceRoot}', workspace.projectRoot);
1658
+ // A workspace nextest build unifies features across every selected member.
1659
+ // A sibling manifest can therefore change this crate's tests without being
1660
+ // a path dependency. Track those manifests, not unrelated sibling sources.
1661
+ const inputs: NonNullable<TargetConfiguration['inputs']> = [
1662
+ ...new Set([
1663
+ ...(await cargoPackageTestInputs({
1664
+ workspaceRoot,
1665
+ absoluteProjectRoot: join(workspaceRoot, workspace.projectRoot),
1666
+ memberDir: plan.package.dir,
1667
+ inputRoot,
1668
+ })),
1669
+ ...workspace.packages.map((member) => posix.join(inputRoot, member.package.dir, 'Cargo.toml')),
1670
+ ]),
1671
+ {
1672
+ runtime: `bun -e 'console.log(new Bun.CryptoHasher("sha256").update(require("node:fs").readFileSync(process.argv[1])).digest("hex"))' '${PLUGIN_NEXTEST_CONFIG.replaceAll("'", "'\"'\"'")}'`,
1673
+ },
1674
+ ];
1532
1675
  for (const piece of plan.pieces) {
1533
1676
  targetNames.push(piece.targetName);
1534
1677
  targets[piece.targetName] = {
@@ -1538,12 +1681,19 @@ async function addRepoRootCargoTestTargets(
1538
1681
  dependsOn: [cargoTargetDependency(currentProjectName, piece.previous)],
1539
1682
  options: {
1540
1683
  command: cargoFrozen(
1541
- `nextest run --workspace -p ${plan.package.name} -E '${piece.selector}'${piece.extra} --no-tests=pass --user-config-file none --config-file ${configFile}`,
1684
+ `nextest run --workspace${workspace.projectRoot === '.' ? ` -p ${plan.package.name}` : ''} -E '${piece.selector}'${piece.extra} --no-tests=pass --user-config-file none --config-file ${configFile}`,
1542
1685
  ),
1543
- cwd: '.',
1686
+ cwd: workspace.projectRoot,
1544
1687
  timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
1545
1688
  killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
1546
1689
  },
1690
+ configurations: {
1691
+ production: {
1692
+ command: cargoFrozen(
1693
+ `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}`,
1694
+ ),
1695
+ },
1696
+ },
1547
1697
  };
1548
1698
  }
1549
1699
  }