@smoothbricks/nx-plugin 0.3.14 → 0.4.0

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 (34) hide show
  1. package/README.md +36 -13
  2. package/dist/bin/smoo-nx-exec.d.ts +3 -0
  3. package/dist/bin/smoo-nx-exec.d.ts.map +1 -0
  4. package/dist/bin/{ensure-built.js → smoo-nx-exec.js} +17 -5
  5. package/dist/bounded-test-policy.d.ts.map +1 -1
  6. package/dist/bounded-test-policy.js +5 -2
  7. package/dist/cargo-workspace.d.ts +15 -1
  8. package/dist/cargo-workspace.d.ts.map +1 -1
  9. package/dist/cargo-workspace.js +113 -8
  10. package/dist/ensure-built.d.ts +3 -0
  11. package/dist/ensure-built.d.ts.map +1 -1
  12. package/dist/ensure-built.js +21 -1
  13. package/dist/executors/typescript-emit/executor.d.ts.map +1 -1
  14. package/dist/executors/typescript-emit/executor.js +20 -2
  15. package/dist/executors/typescript-emit/schema.d.ts +1 -0
  16. package/dist/executors/typescript-emit/schema.d.ts.map +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +335 -87
  19. package/package.json +4 -4
  20. package/src/bin/{ensure-built.ts → smoo-nx-exec.ts} +18 -6
  21. package/src/bounded-test-policy.test.ts +21 -0
  22. package/src/bounded-test-policy.ts +6 -2
  23. package/src/cargo-workspace.test.ts +142 -0
  24. package/src/cargo-workspace.ts +137 -8
  25. package/src/ensure-built.test.ts +121 -21
  26. package/src/ensure-built.ts +23 -1
  27. package/src/executors/typescript-emit/executor.test.ts +37 -1
  28. package/src/executors/typescript-emit/executor.ts +24 -2
  29. package/src/executors/typescript-emit/schema.json +8 -0
  30. package/src/executors/typescript-emit/schema.ts +1 -0
  31. package/src/index.test.ts +173 -6
  32. package/src/index.ts +426 -89
  33. package/dist/bin/ensure-built.d.ts +0 -3
  34. package/dist/bin/ensure-built.d.ts.map +0 -1
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { readdir, readFile } from 'node:fs/promises';
3
- import { dirname, join, posix } from 'node:path';
3
+ import { dirname, join, posix, relative } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
 
6
6
  import {
@@ -14,6 +14,8 @@ import { parse as parseToml } from 'smol-toml';
14
14
 
15
15
  import { BOUNDED_TEST_KILL_AFTER_MS, BOUNDED_TEST_TIMEOUT_MS } from './bounded-test-policy.js';
16
16
  import {
17
+ type AttributedCargoWorkspacePackage,
18
+ attributeCargoWorkspacePackages,
17
19
  CARGO_TEST_COMPILE_TARGET,
18
20
  CARGO_TEST_EXCEPTIONS_SUFFIX,
19
21
  CARGO_TEST_TARGET,
@@ -115,6 +117,16 @@ const CARGO_INPUTS = [
115
117
  '!{projectRoot}/**/target/**',
116
118
  ];
117
119
  const CARGO_OUTPUT_INPUTS = [...CARGO_INPUTS, '{projectRoot}/package.json', '{workspaceRoot}/bun.lock'];
120
+ const REPO_ROOT_CARGO_OUTPUT_INPUTS = [
121
+ '{workspaceRoot}/**/*.rs',
122
+ '{workspaceRoot}/**/Cargo.toml',
123
+ '{workspaceRoot}/Cargo.lock',
124
+ '{workspaceRoot}/**/.cargo/config.toml',
125
+ '{workspaceRoot}/scripts/*.sh',
126
+ '!{workspaceRoot}/**/target/**',
127
+ '{projectRoot}/package.json',
128
+ '{workspaceRoot}/bun.lock',
129
+ ];
118
130
  const NAPI_INPUTS = CARGO_OUTPUT_INPUTS;
119
131
 
120
132
  interface NapiTargetConvention extends NapiPlatform {
@@ -170,26 +182,34 @@ export function napiToolchainTargetName(convention: NapiTargetConvention): strin
170
182
  return `${NAPI_TOOLCHAIN_TARGET_PREFIX}${convention.architecture}-${convention.targetFamily}`;
171
183
  }
172
184
 
173
- function createCargoWasmTarget(projectRoot: string, config: ResolvedCargoWasmConfig): TargetConfiguration {
174
- const cargoTargetDirectory = posix.join(posix.dirname(config.manifestPath), 'target/cargo-wasm');
185
+ function createCargoWasmTarget(
186
+ projectRoot: string,
187
+ config: ResolvedCargoWasmConfig,
188
+ repoRooted: boolean,
189
+ ): TargetConfiguration {
190
+ const cargoTargetDirectory = repoRooted
191
+ ? 'target/cargo-wasm'
192
+ : posix.join(posix.dirname(config.manifestPath), 'target/cargo-wasm');
175
193
  const wasmInput = `${cargoTargetDirectory}/wasm32-unknown-unknown/release/${config.libraryName}.wasm`;
194
+ const outputDirectory = repoRooted ? posix.join(projectRoot, config.outputDirectory) : config.outputDirectory;
195
+ const cargoSelection = repoRooted ? `-p ${config.cargoPackage}` : `--manifest-path ${config.manifestPath}`;
176
196
  return {
177
197
  executor: 'nx:run-commands',
178
198
  cache: true,
179
199
  dependsOn: ['^build'],
180
- inputs: CARGO_OUTPUT_INPUTS,
200
+ inputs: repoRooted ? REPO_ROOT_CARGO_OUTPUT_INPUTS : CARGO_OUTPUT_INPUTS,
181
201
  outputs: [`{projectRoot}/${config.outputDirectory}`],
182
202
  options: {
183
203
  commands: [
184
204
  cargoFrozen(
185
- `build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} --manifest-path ${config.manifestPath}`,
205
+ `build --release --target wasm32-unknown-unknown --target-dir ${cargoTargetDirectory} ${cargoSelection}`,
186
206
  ),
187
207
  ...config.targets.map(
188
208
  ({ bindgenTarget, outputName }) =>
189
- `wasm-bindgen --target ${bindgenTarget} --out-dir ${config.outputDirectory}/${outputName} ${wasmInput}`,
209
+ `wasm-bindgen --target ${bindgenTarget} --out-dir ${outputDirectory}/${outputName} ${wasmInput}`,
190
210
  ),
191
211
  ],
192
- cwd: projectRoot,
212
+ cwd: repoRooted ? '.' : projectRoot,
193
213
  parallel: false,
194
214
  },
195
215
  };
@@ -266,11 +286,16 @@ const PLUGIN_NEXTEST_CONFIG = fileURLToPath(new URL('../nextest.toml', import.me
266
286
  * depending on how the hash happened to fall.
267
287
  *
268
288
  * 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.
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.
274
299
  *
275
300
  * Pieces chain rather than fan out, like the crates do: cargo flocks one
276
301
  * `target/`, and chaining keeps even the pinned group from overlapping the
@@ -304,7 +329,7 @@ async function addPerPackageCargoTestTargets(
304
329
  dependsOn: [previous],
305
330
  options: {
306
331
  command: cargoFrozen(
307
- `nextest run --workspace -E '${selector}'${extra} --user-config-file none --config-file ${configFile}`,
332
+ `nextest run --workspace -E '${selector}'${extra} --no-tests=pass --user-config-file none --config-file ${configFile}`,
308
333
  ),
309
334
  cwd: projectRoot,
310
335
  timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
@@ -324,7 +349,7 @@ async function addPerPackageCargoTestTargets(
324
349
  );
325
350
  }
326
351
  if (pin !== null) {
327
- addTarget(CARGO_TEST_EXCEPTIONS_SUFFIX, `package(${pkg.name}) and (${pin})`, ' --no-tests=pass');
352
+ addTarget(CARGO_TEST_EXCEPTIONS_SUFFIX, `package(${pkg.name}) and (${pin})`, '');
328
353
  }
329
354
  }
330
355
  return packageTargetNames;
@@ -336,19 +361,27 @@ function createNodesHandler(hostPlatform: NapiPlatform | null): CreateNodesHandl
336
361
  return async (projectConfigurationFiles, _options, context) => {
337
362
  const results: CreateNodesResultV2 = [];
338
363
  const errors: Array<[file: string | null, error: Error]> = [];
364
+ const repoRootCargoWorkspace = await resolveRepoRootCargoWorkspace(
365
+ projectConfigurationFiles,
366
+ context.workspaceRoot,
367
+ );
339
368
 
340
369
  await Promise.all(
341
370
  projectConfigurationFiles.map(async (packageJsonPath) => {
342
371
  try {
343
- if (isManagedPackageJsonSource(packageJsonPath)) {
372
+ if (isManagedPackageJsonSource(packageJsonPath) || isBuildOutputPackageJson(packageJsonPath)) {
344
373
  // smoo monorepo managed raw/templates are source copies, not projects.
345
374
  // Dogfood trees symlink live paths here; discovering both doubles names.
375
+ // A package.json a build wrote (napi's platform dirs, dist, cargo's
376
+ // target, a package cache) is an artifact, never a project: inferring
377
+ // one races every task that rebuilds the graph against the build that
378
+ // is writing it, and a name collision drops the real project.
346
379
  results.push([packageJsonPath, {}]);
347
380
  return;
348
381
  }
349
382
  results.push([
350
383
  packageJsonPath,
351
- await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform),
384
+ await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform, repoRootCargoWorkspace),
352
385
  ]);
353
386
  } catch (error) {
354
387
  errors.push([packageJsonPath, error instanceof Error ? error : new Error(String(error))]);
@@ -378,9 +411,18 @@ function isManagedPackageJsonSource(packageJsonPath: string): boolean {
378
411
  return normalized.includes('/managed/raw/') || normalized.includes('/managed/templates/');
379
412
  }
380
413
 
414
+ /** Directories only builds write into; a package.json found under one is an output. */
415
+ const BUILD_OUTPUT_SEGMENTS = ['/node_modules/', '/dist/', '/target/', '/.cache/', '/.nx/'];
416
+
417
+ function isBuildOutputPackageJson(packageJsonPath: string): boolean {
418
+ const normalized = `/${packageJsonPath.replaceAll('\\', '/')}`;
419
+ return BUILD_OUTPUT_SEGMENTS.some((segment) => normalized.includes(segment));
420
+ }
421
+
381
422
  export default { createNodesV2 };
382
423
 
383
424
  interface PackageJson {
425
+ bin?: unknown;
384
426
  name?: string;
385
427
  napi?: Record<string, unknown>;
386
428
  scripts?: Record<string, unknown>;
@@ -390,10 +432,42 @@ interface PackageJson {
390
432
  };
391
433
  }
392
434
 
393
- async function createProjectTargets(packageJsonPath: string, workspaceRoot: string, hostPlatform: NapiPlatform | null) {
435
+ function packageBinOutputs(packageJson: PackageJson, packageJsonPath: string): string[] {
436
+ if (packageJson.bin === undefined) {
437
+ return [];
438
+ }
439
+ if (typeof packageJson.bin === 'string') {
440
+ if (packageJson.bin.length === 0) {
441
+ throw new Error(`${packageJsonPath}: bin must not be empty`);
442
+ }
443
+ return [packageJson.bin];
444
+ }
445
+ if (!isRecord(packageJson.bin)) {
446
+ throw new Error(`${packageJsonPath}: bin must be a string or an object of executable paths`);
447
+ }
448
+ const outputs = new Set<string>();
449
+ for (const [name, output] of Object.entries(packageJson.bin)) {
450
+ if (typeof output !== 'string' || output.length === 0) {
451
+ throw new Error(`${packageJsonPath}: bin.${name} must be a non-empty executable path`);
452
+ }
453
+ outputs.add(output);
454
+ }
455
+ return [...outputs];
456
+ }
457
+
458
+ async function createProjectTargets(
459
+ packageJsonPath: string,
460
+ workspaceRoot: string,
461
+ hostPlatform: NapiPlatform | null,
462
+ repoRootCargoWorkspace: RepoRootCargoWorkspace | null,
463
+ ) {
394
464
  const projectRoot = dirname(packageJsonPath);
395
465
  const absoluteProjectRoot = join(workspaceRoot, projectRoot);
396
466
  const packageJson = await readPackageJson(join(workspaceRoot, packageJsonPath));
467
+ const projectName = packageJson.nx?.name ?? packageJson.name;
468
+ if (typeof projectName !== 'string' || projectName.length === 0) {
469
+ throw new Error(`${packageJsonPath} must declare a non-empty package or nx project name`);
470
+ }
397
471
  const targets: Record<string, TargetConfiguration> = {};
398
472
  const validationTargets: string[] = [];
399
473
  const libTsconfigPath = join(absoluteProjectRoot, 'tsconfig.lib.json');
@@ -401,9 +475,26 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
401
475
  const cargoTomlPath = join(absoluteProjectRoot, 'Cargo.toml');
402
476
  const isCargoWorkspace =
403
477
  existsSync(cargoTomlPath) && CARGO_WORKSPACE_PATTERN.test(await readFile(cargoTomlPath, 'utf-8'));
404
- const napiConfig = resolveNapiConfig(packageJson, packageJsonPath, absoluteProjectRoot, isCargoWorkspace);
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);
484
+ const napiConfig = resolveNapiConfig(
485
+ packageJson,
486
+ packageJsonPath,
487
+ absoluteProjectRoot,
488
+ isCargoWorkspace,
489
+ repoRootPackages,
490
+ );
405
491
  const declaredTargets = packageJson.nx?.targets ?? {};
406
- const cargoWasmConfig = await resolveCargoWasmConfig(absoluteProjectRoot, packageJsonPath);
492
+ const cargoWasmConfig = await resolveCargoWasmConfig(
493
+ absoluteProjectRoot,
494
+ packageJsonPath,
495
+ workspaceRoot,
496
+ repoRootPackages,
497
+ );
407
498
  const inferCargoWasm = cargoWasmConfig !== null && !('cargo-wasm' in declaredTargets);
408
499
  const packageLocalBuildOutputs = classifyPackageLocalBuildOutputs(packageJson);
409
500
  const hasOrdinaryBuildOutputTarget =
@@ -411,6 +502,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
411
502
  const hasAnyBuildOutputTarget = hasOrdinaryBuildOutputTarget || packageLocalBuildOutputs.platform;
412
503
 
413
504
  if (hasLibTsconfig) {
505
+ const executableOutputs = packageBinOutputs(packageJson, packageJsonPath);
414
506
  // Dependency packages may publish bundled entries that raw tsc does not produce.
415
507
  // Build every JavaScript output lane before resolving package exports, without pulling
416
508
  // unrelated Wasm, N-API, native, or web outputs onto the compiler critical path.
@@ -426,6 +518,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
426
518
  outputs: inferTypescriptOutputs(libTsconfigPath, packageJsonPath),
427
519
  dependsOn: ['^*-js', ...(cargoWasmConfig ? ['cargo-wasm'] : [])],
428
520
  options: {
521
+ ...(executableOutputs.length > 0 ? { executableOutputs } : {}),
429
522
  tsConfig: 'tsconfig.lib.json',
430
523
  cwd: projectRoot,
431
524
  },
@@ -481,11 +574,11 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
481
574
  }
482
575
 
483
576
  if (inferCargoWasm && cargoWasmConfig) {
484
- targets['cargo-wasm'] = createCargoWasmTarget(projectRoot, cargoWasmConfig);
577
+ targets['cargo-wasm'] = createCargoWasmTarget(projectRoot, cargoWasmConfig, isRepoRootedCargoProject);
485
578
  }
486
579
 
487
580
  if (napiConfig) {
488
- Object.assign(targets, createNapiTargets(projectRoot, napiConfig, hostPlatform));
581
+ Object.assign(targets, createNapiTargets(projectRoot, napiConfig, hostPlatform, isRepoRootedCargoProject));
489
582
  if (
490
583
  !('napi-test' in (packageJson.nx?.targets ?? {})) &&
491
584
  existsSync(join(absoluteProjectRoot, 'src/native.test.ts'))
@@ -543,25 +636,34 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
543
636
  // all-or-nothing, because for those the package decides whether the target
544
637
  // EXISTS — a packaging decision for output families, the bounded-test policy's
545
638
  // rewrite for `test` — so there is no inferred base to partially override.
546
- if (isCargoWorkspace) {
547
- targets[CARGO_TEST_COMPILE_TARGET] = createCargoTestCompileTarget(projectRoot);
548
- const packageTargetNames = await addPerPackageCargoTestTargets(
549
- targets,
550
- projectRoot,
551
- workspaceRoot,
552
- absoluteProjectRoot,
553
- );
639
+ const ownsCargoWorkspaceTargets = isCargoWorkspace || isRepoRootWorkspaceRoot;
640
+ if (ownsCargoWorkspaceTargets) {
641
+ const cargoWorkspaceRoot = isRepoRootWorkspaceRoot ? '.' : projectRoot;
642
+ 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;
554
656
  targets[CARGO_TEST_TARGET] =
555
- packageTargetNames.length > 0
556
- ? { executor: 'nx:noop', cache: true, dependsOn: packageTargetNames }
557
- : createCargoTestTarget(projectRoot);
657
+ aggregateDependencies.length > 0
658
+ ? { executor: 'nx:noop', cache: true, dependsOn: aggregateDependencies }
659
+ : createCargoTestTarget(cargoWorkspaceRoot);
558
660
  targets['cargo-lint'] = {
559
661
  executor: 'nx:run-commands',
560
662
  cache: true,
561
663
  inputs: CARGO_INPUTS,
562
664
  options: {
563
665
  commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
564
- cwd: projectRoot,
666
+ cwd: cargoWorkspaceRoot,
565
667
  parallel: false,
566
668
  },
567
669
  };
@@ -574,7 +676,9 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
574
676
  // governs targets that PRODUCE artifacts, where "does this package ship this
575
677
  // artifact" is a packaging decision no crate manifest can answer. This target
576
678
  // emits nothing — clippy type-checks and discards — so it belongs with
577
- // cargo-lint and cargo-test on the inferred validation side.
679
+ // cargo-lint and cargo-test on the inferred validation side. Repository-root
680
+ // workspaces own it once at the root because `--workspace` already checks
681
+ // every member.
578
682
  //
579
683
  // The discriminator for "has cross-platform Rust" is deliberately the same
580
684
  // `[workspace]` Cargo.toml that already grants cargo-lint, NOT a scan of
@@ -597,7 +701,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
597
701
  inputs: CARGO_INPUTS,
598
702
  options: {
599
703
  command: CARGO_CROSS_LINT_COMMAND,
600
- cwd: projectRoot,
704
+ cwd: cargoWorkspaceRoot,
601
705
  },
602
706
  };
603
707
  if (!targets.test && !('test' in declaredTargets) && typeof packageJson.scripts?.test !== 'string') {
@@ -612,12 +716,12 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
612
716
  targets.mutation = {
613
717
  executor: 'nx:run-commands',
614
718
  cache: false,
615
- options: { command: cargoFrozen('mutants --workspace'), cwd: projectRoot },
719
+ options: { command: cargoFrozen('mutants --workspace'), cwd: cargoWorkspaceRoot },
616
720
  };
617
721
  targets.bench = {
618
722
  executor: 'nx:run-commands',
619
723
  cache: false,
620
- options: { command: cargoFrozen('bench --workspace'), cwd: projectRoot },
724
+ options: { command: cargoFrozen('bench --workspace'), cwd: cargoWorkspaceRoot },
621
725
  };
622
726
  // Target-dir GC. Cargo never removes superseded artifacts, so a busy
623
727
  // workspace grows tens of GB of stale variants no fingerprint references;
@@ -627,10 +731,32 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
627
731
  targets['cargo-sweep'] = {
628
732
  executor: 'nx:run-commands',
629
733
  cache: false,
630
- options: { command: 'cargo sweep --time 7', cwd: projectRoot },
734
+ options: { command: 'cargo sweep --time 7', cwd: cargoWorkspaceRoot },
631
735
  };
632
736
  }
633
737
 
738
+ if (!isCargoWorkspace && !isRepoRootWorkspaceRoot && repoRootPackagePlans.length > 0 && repoRootCargoWorkspace) {
739
+ const packageTargetNames = await addRepoRootCargoTestTargets(
740
+ targets,
741
+ projectName,
742
+ projectRoot,
743
+ workspaceRoot,
744
+ repoRootCargoWorkspace,
745
+ );
746
+ targets[CARGO_TEST_TARGET] = {
747
+ executor: 'nx:noop',
748
+ cache: true,
749
+ dependsOn: packageTargetNames,
750
+ };
751
+ if (!targets.test && !('test' in declaredTargets) && typeof packageJson.scripts?.test !== 'string') {
752
+ targets.test = {
753
+ executor: 'nx:noop',
754
+ cache: true,
755
+ dependsOn: [CARGO_TEST_TARGET],
756
+ };
757
+ }
758
+ }
759
+
634
760
  // Every `cargoFrozen` command needs a registry cache holding the whole locked
635
761
  // graph, and offline cargo checks that at RESOLUTION — so a dev-dependency no
636
762
  // build ever downloaded takes down `cargo --frozen build` just as surely as
@@ -645,6 +771,8 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
645
771
  // frozen target added later is covered without anyone remembering to. The edge
646
772
  // goes on EVERY frozen target, not just the head of the serialization chain,
647
773
  // so re-routing that chain cannot strip a surviving target's precondition.
774
+ // Package-rooted workspaces fetch beside their package.json; members of a
775
+ // repository-root workspace all depend on the root project's one fetch.
648
776
  //
649
777
  // A package that REPLACES one of these `dependsOn` lists drops the edge with
650
778
  // it (see the merge rules above) and gets its cold-cache failure back; `"..."`
@@ -653,9 +781,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
653
781
  if (isCargoWorkspace) {
654
782
  frozenCargoManifests.add('Cargo.toml');
655
783
  }
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.
784
+ if (inferCargoWasm && cargoWasmConfig && !isRepoRootedCargoProject) {
659
785
  frozenCargoManifests.add(cargoWasmConfig.manifestPath);
660
786
  }
661
787
  if (frozenCargoManifests.size > 0) {
@@ -674,7 +800,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
674
800
  ? CARGO_FETCH_COMMAND
675
801
  : `${CARGO_FETCH_COMMAND} --manifest-path ${manifestPath}`,
676
802
  ),
677
- cwd: projectRoot,
803
+ cwd: isRepoRootWorkspaceRoot ? '.' : projectRoot,
678
804
  // Two fetches into one CARGO_HOME contend on its package-cache flock;
679
805
  // serializing here spends the wait in Nx instead of inside cargo.
680
806
  parallel: false,
@@ -690,33 +816,69 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
690
816
  typeof command === 'string' ? command : '',
691
817
  ...(Array.isArray(commands) ? commands.filter((entry) => typeof entry === 'string') : []),
692
818
  ].join('\n');
693
- if (!text.includes(CARGO_FROZEN_PREFIX)) {
694
- continue;
819
+ if (text.includes(CARGO_FROZEN_PREFIX)) {
820
+ target.dependsOn = [CARGO_FETCH_TARGET, ...(target.dependsOn ?? [])];
695
821
  }
696
- const dependsOn = target.dependsOn ?? [];
697
- if (!dependsOn.includes(CARGO_FETCH_TARGET)) {
698
- target.dependsOn = [CARGO_FETCH_TARGET, ...dependsOn];
822
+ }
823
+ } else if (isRepoRootedCargoProject && repoRootCargoWorkspace) {
824
+ const rootFetch = cargoTargetDependency(projectName, {
825
+ projectName: repoRootCargoWorkspace.rootProjectName,
826
+ targetName: CARGO_FETCH_TARGET,
827
+ });
828
+ for (const target of Object.values(targets)) {
829
+ const command: unknown = target.options?.command;
830
+ const commands: unknown = target.options?.commands;
831
+ const text = [
832
+ typeof command === 'string' ? command : '',
833
+ ...(Array.isArray(commands) ? commands.filter((entry) => typeof entry === 'string') : []),
834
+ ].join('\n');
835
+ if (text.includes(CARGO_FROZEN_PREFIX)) {
836
+ target.dependsOn = [rootFetch, ...(target.dependsOn ?? [])];
699
837
  }
700
838
  }
701
839
  }
702
840
 
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.
841
+ // Cargo flocks the workspace's default target/. Keep every writer out of the
842
+ // bounded test window by placing N-API debug builds on the same serialized
843
+ // chain as the root compile and per-crate runners.
844
+ const cargoTestCompileDependency: CargoTargetDependency | null = targets[CARGO_TEST_COMPILE_TARGET]
845
+ ? CARGO_TEST_COMPILE_TARGET
846
+ : isRepoRootCargoProject && repoRootCargoWorkspace
847
+ ? cargoTargetDependency(projectName, {
848
+ projectName: repoRootCargoWorkspace.rootProjectName,
849
+ targetName: CARGO_TEST_COMPILE_TARGET,
850
+ })
851
+ : null;
705
852
  const napiDebug = targets['napi-debug'];
706
- if (napiDebug && targets[CARGO_TEST_COMPILE_TARGET]) {
853
+ if (napiDebug && cargoTestCompileDependency) {
707
854
  const dependsOn = napiDebug.dependsOn ?? [];
708
- if (!dependsOn.includes(CARGO_TEST_COMPILE_TARGET)) {
709
- napiDebug.dependsOn = [...dependsOn, CARGO_TEST_COMPILE_TARGET];
855
+ if (!hasCargoTargetDependency(dependsOn, cargoTestCompileDependency)) {
856
+ napiDebug.dependsOn = [...dependsOn, cargoTestCompileDependency];
710
857
  }
711
858
  }
712
- if (napiDebug) {
859
+ if (napiDebug && isRepoRootedCargoProject) {
860
+ const firstCargoTest = repoRootPackagePlans.flatMap((plan) => plan.pieces)[0];
861
+ const firstTarget = firstCargoTest ? targets[firstCargoTest.targetName] : undefined;
862
+ if (firstCargoTest && firstTarget) {
863
+ const previous = cargoTargetDependency(projectName, firstCargoTest.previous);
864
+ const debugDependencies = napiDebug.dependsOn ?? [];
865
+ if (!hasCargoTargetDependency(debugDependencies, previous)) {
866
+ napiDebug.dependsOn = [...debugDependencies, previous];
867
+ }
868
+ firstTarget.dependsOn = (firstTarget.dependsOn ?? []).map((dependency) =>
869
+ hasCargoTargetDependency([dependency], previous) ? 'napi-debug' : dependency,
870
+ );
871
+ }
872
+ } else if (napiDebug) {
713
873
  for (const [name, target] of Object.entries(targets)) {
714
874
  if (!name.startsWith('cargo-test-') || name === CARGO_TEST_COMPILE_TARGET) {
715
875
  continue;
716
876
  }
717
877
  const dependsOn = target.dependsOn ?? [];
718
878
  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));
879
+ target.dependsOn = dependsOn.map((dependency) =>
880
+ dependency === CARGO_TEST_COMPILE_TARGET ? 'napi-debug' : dependency,
881
+ );
720
882
  }
721
883
  }
722
884
  const cargoTest = targets[CARGO_TEST_TARGET];
@@ -733,8 +895,8 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
733
895
  }
734
896
 
735
897
  // `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.
898
+ // every one of those is a `napi build` — another cargo writer on the
899
+ // workspace's default `target/`, which cargo flocks.
738
900
  //
739
901
  // Only `cargo-napi` gets the ordering edge. A platform-suffixed target may NOT
740
902
  // have one: `validatePlatformTargetDependencies` (package-target-policy.ts:674)
@@ -756,10 +918,10 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
756
918
  hostPlatform,
757
919
  );
758
920
  const cargoNapi = targets['cargo-napi'];
759
- if (cargoNapi && targets[CARGO_TEST_COMPILE_TARGET]) {
921
+ if (cargoNapi && cargoTestCompileDependency) {
760
922
  const dependsOn = cargoNapi.dependsOn ?? [];
761
- if (!dependsOn.includes(CARGO_TEST_COMPILE_TARGET)) {
762
- cargoNapi.dependsOn = [...dependsOn, CARGO_TEST_COMPILE_TARGET];
923
+ if (!hasCargoTargetDependency(dependsOn, cargoTestCompileDependency)) {
924
+ cargoNapi.dependsOn = [...dependsOn, cargoTestCompileDependency];
763
925
  }
764
926
  }
765
927
 
@@ -787,7 +949,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
787
949
  // cacheable, while every RUNNER is a bounded-exec target reached only
788
950
  // through the `test` aggregate. That split is what keeps a cold cargo
789
951
  // workspace's compile time out of the bounded test window.
790
- ...(targets[CARGO_TEST_COMPILE_TARGET] ? [CARGO_TEST_COMPILE_TARGET] : []),
952
+ ...(cargoTestCompileDependency ? [cargoTestCompileDependency] : []),
791
953
  ...buildOutputTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
792
954
  ...cargoWriterNames,
793
955
  ]),
@@ -819,11 +981,6 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
819
981
  };
820
982
  }
821
983
 
822
- const projectName = packageJson.nx?.name ?? packageJson.name;
823
- if (typeof projectName !== 'string' || projectName.length === 0) {
824
- throw new Error(`${packageJsonPath} must declare a non-empty package or nx project name`);
825
- }
826
-
827
984
  return {
828
985
  projects: {
829
986
  [projectRoot]: { name: projectName, targets },
@@ -832,6 +989,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
832
989
  }
833
990
 
834
991
  interface ResolvedCargoWasmConfig {
992
+ cargoPackage: string;
835
993
  libraryName: string;
836
994
  manifestPath: string;
837
995
  outputDirectory: string;
@@ -850,16 +1008,21 @@ const WASM_BINDGEN_OUTPUT_NAMES: Readonly<Record<string, string>> = {
850
1008
  async function resolveCargoWasmConfig(
851
1009
  absoluteProjectRoot: string,
852
1010
  packageJsonPath: string,
1011
+ workspaceRoot: string,
1012
+ repoRootPackages: readonly AttributedCargoWorkspacePackage[],
853
1013
  ): Promise<ResolvedCargoWasmConfig | null> {
854
- const manifestPaths = ['Cargo.toml'];
855
- const cratesDirectory = join(absoluteProjectRoot, 'crates');
856
- if (existsSync(cratesDirectory)) {
857
- const crateEntries = await readdir(cratesDirectory, { withFileTypes: true });
858
- for (const entry of crateEntries.sort((left, right) => left.name.localeCompare(right.name))) {
859
- if (entry.isDirectory()) {
860
- const manifestPath = posix.join('crates', entry.name, 'Cargo.toml');
861
- if (existsSync(join(absoluteProjectRoot, manifestPath))) {
862
- manifestPaths.push(manifestPath);
1014
+ const manifestPaths = repoRootPackages.map((pkg) => posix.join(pkg.dir, 'Cargo.toml'));
1015
+ if (manifestPaths.length === 0) {
1016
+ manifestPaths.push('Cargo.toml');
1017
+ const cratesDirectory = join(absoluteProjectRoot, 'crates');
1018
+ if (existsSync(cratesDirectory)) {
1019
+ const crateEntries = await readdir(cratesDirectory, { withFileTypes: true });
1020
+ for (const entry of crateEntries.sort((left, right) => left.name.localeCompare(right.name))) {
1021
+ if (entry.isDirectory()) {
1022
+ const manifestPath = posix.join('crates', entry.name, 'Cargo.toml');
1023
+ if (existsSync(join(absoluteProjectRoot, manifestPath))) {
1024
+ manifestPaths.push(manifestPath);
1025
+ }
863
1026
  }
864
1027
  }
865
1028
  }
@@ -867,7 +1030,8 @@ async function resolveCargoWasmConfig(
867
1030
 
868
1031
  const resolved: ResolvedCargoWasmConfig[] = [];
869
1032
  for (const manifestPath of manifestPaths) {
870
- const absoluteManifestPath = join(absoluteProjectRoot, manifestPath);
1033
+ const absoluteManifestPath =
1034
+ repoRootPackages.length > 0 ? join(workspaceRoot, manifestPath) : join(absoluteProjectRoot, manifestPath);
871
1035
  if (!existsSync(absoluteManifestPath)) {
872
1036
  continue;
873
1037
  }
@@ -931,7 +1095,13 @@ async function resolveCargoWasmConfig(
931
1095
  );
932
1096
  }
933
1097
 
934
- resolved.push({ libraryName: rawLibraryName, manifestPath, outputDirectory, targets });
1098
+ resolved.push({
1099
+ cargoPackage: packageName,
1100
+ libraryName: rawLibraryName,
1101
+ manifestPath,
1102
+ outputDirectory,
1103
+ targets,
1104
+ });
935
1105
  }
936
1106
 
937
1107
  if (resolved.length > 1) {
@@ -967,12 +1137,13 @@ function resolveNapiConfig(
967
1137
  packageJsonPath: string,
968
1138
  absoluteProjectRoot: string,
969
1139
  isCargoWorkspace: boolean,
1140
+ repoRootPackages: readonly AttributedCargoWorkspacePackage[],
970
1141
  ): ResolvedNapiConfig | null {
971
1142
  if (!packageJson.napi) {
972
1143
  return null;
973
1144
  }
974
- if (!isCargoWorkspace) {
975
- throw new Error(`${packageJsonPath}: napi target inference requires a Cargo workspace beside package.json`);
1145
+ if (!isCargoWorkspace && repoRootPackages.length === 0) {
1146
+ throw new Error(`${packageJsonPath}: napi target inference requires a Cargo workspace containing this project`);
976
1147
  }
977
1148
 
978
1149
  const binaryName = packageJson.napi.binaryName;
@@ -995,8 +1166,12 @@ function resolveNapiConfig(
995
1166
  }
996
1167
 
997
1168
  const cargoPackage = `${binaryName}-napi`;
998
- const manifestPath = `crates/${cargoPackage}/Cargo.toml`;
999
- if (!existsSync(join(absoluteProjectRoot, manifestPath))) {
1169
+ const rootMember = repoRootPackages.find((pkg) => pkg.name === cargoPackage);
1170
+ const manifestPath = rootMember ? posix.join(rootMember.dir, 'Cargo.toml') : `crates/${cargoPackage}/Cargo.toml`;
1171
+ const absoluteManifestPath = rootMember
1172
+ ? join(absoluteProjectRoot, relative(dirname(packageJsonPath), manifestPath))
1173
+ : join(absoluteProjectRoot, manifestPath);
1174
+ if (!existsSync(absoluteManifestPath)) {
1000
1175
  throw new Error(`${packageJsonPath}: inferred N-API crate is missing at ${manifestPath}`);
1001
1176
  }
1002
1177
  return { binaryName, cargoPackage, manifestPath, targets };
@@ -1006,8 +1181,12 @@ function createNapiTargets(
1006
1181
  projectRoot: string,
1007
1182
  config: ResolvedNapiConfig,
1008
1183
  hostPlatform: NapiPlatform | null,
1184
+ repoRooted: boolean,
1009
1185
  ): Record<string, TargetConfiguration> {
1010
1186
  const commonCommand = `--manifest-path ${config.manifestPath} --package ${config.cargoPackage}`;
1187
+ const cargoInputs = repoRooted ? REPO_ROOT_CARGO_OUTPUT_INPUTS : NAPI_INPUTS;
1188
+ const cargoCwd = repoRooted ? '.' : projectRoot;
1189
+ const outputPath = (projectOutput: string) => (repoRooted ? posix.join(projectRoot, projectOutput) : projectOutput);
1011
1190
  const hostPlatformTargetName =
1012
1191
  hostPlatform === null ? null : `napi-${hostPlatform.architecture}-${hostPlatform.targetFamily}`;
1013
1192
  let nativeHostTargetName: string | null = null;
@@ -1035,11 +1214,11 @@ function createNapiTargets(
1035
1214
  executor: 'nx:run-commands',
1036
1215
  cache: true,
1037
1216
  dependsOn: ['^build'],
1038
- inputs: NAPI_INPUTS,
1217
+ inputs: cargoInputs,
1039
1218
  outputs: ['{projectRoot}/.cache/native-debug'],
1040
1219
  options: {
1041
- cwd: projectRoot,
1042
- command: `napi build --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir .cache/native-debug`,
1220
+ cwd: cargoCwd,
1221
+ command: `napi build --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir ${outputPath('.cache/native-debug')}`,
1043
1222
  ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
1044
1223
  },
1045
1224
  };
@@ -1053,11 +1232,11 @@ function createNapiTargets(
1053
1232
  executor: 'nx:run-commands',
1054
1233
  cache: true,
1055
1234
  dependsOn: ['^build'],
1056
- inputs: NAPI_INPUTS,
1235
+ inputs: cargoInputs,
1057
1236
  outputs: ['{projectRoot}/dist/native/host'],
1058
1237
  options: {
1059
- cwd: projectRoot,
1060
- command: `napi build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir dist/native/host`,
1238
+ cwd: cargoCwd,
1239
+ command: `napi build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir ${outputPath('dist/native/host')}`,
1061
1240
  ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
1062
1241
  },
1063
1242
  };
@@ -1097,11 +1276,11 @@ function createNapiTargets(
1097
1276
  executor: 'nx:run-commands',
1098
1277
  cache: true,
1099
1278
  ...(useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
1100
- inputs: NAPI_INPUTS,
1279
+ inputs: cargoInputs,
1101
1280
  outputs: [`{projectRoot}/${outputDirectory}`],
1102
1281
  options: {
1103
- cwd: projectRoot,
1104
- command: `napi build --release --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputDirectory}`,
1282
+ cwd: cargoCwd,
1283
+ command: `napi build --release --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputPath(outputDirectory)}`,
1105
1284
  // Genuine Linux cross-compiles use Clang plus napi-rs's downloaded
1106
1285
  // GNU sysroot. A native Linux target uses Nix's cc wrapper so C build
1107
1286
  // scripts resolve the host libc headers instead.
@@ -1146,6 +1325,7 @@ async function readPackageJson(packageJsonPath: string): Promise<PackageJson> {
1146
1325
  }
1147
1326
  const rawNx = isRecord(parsed.nx) ? parsed.nx : undefined;
1148
1327
  return {
1328
+ ...('bin' in parsed ? { bin: parsed.bin } : {}),
1149
1329
  ...(typeof parsed.name === 'string' ? { name: parsed.name } : {}),
1150
1330
  ...(isRecord(parsed.napi) ? { napi: parsed.napi } : {}),
1151
1331
  ...(isRecord(parsed.scripts) ? { scripts: parsed.scripts } : {}),
@@ -1221,3 +1401,160 @@ function classifyPackageLocalBuildOutputs(packageJson: PackageJson): { ordinary:
1221
1401
  ),
1222
1402
  };
1223
1403
  }
1404
+
1405
+ interface RepoRootCargoTargetRef {
1406
+ projectName: string;
1407
+ targetName: string;
1408
+ }
1409
+
1410
+ interface RepoRootCargoTestPiece {
1411
+ extra: string;
1412
+ previous: RepoRootCargoTargetRef;
1413
+ selector: string;
1414
+ targetName: string;
1415
+ }
1416
+
1417
+ interface RepoRootCargoPackagePlan {
1418
+ package: AttributedCargoWorkspacePackage;
1419
+ pieces: RepoRootCargoTestPiece[];
1420
+ }
1421
+
1422
+ interface RepoRootCargoWorkspace {
1423
+ packages: RepoRootCargoPackagePlan[];
1424
+ rootProjectName: string;
1425
+ }
1426
+
1427
+ type CargoTargetDependency = NonNullable<TargetConfiguration['dependsOn']>[number];
1428
+
1429
+ function cargoTargetDependency(currentProjectName: string, target: RepoRootCargoTargetRef): CargoTargetDependency {
1430
+ return target.projectName === currentProjectName
1431
+ ? target.targetName
1432
+ : { projects: [target.projectName], target: target.targetName };
1433
+ }
1434
+
1435
+ async function resolveRepoRootCargoWorkspace(
1436
+ packageJsonPaths: readonly string[],
1437
+ workspaceRoot: string,
1438
+ ): Promise<RepoRootCargoWorkspace | null> {
1439
+ const cargoTomlPath = join(workspaceRoot, 'Cargo.toml');
1440
+ if (!existsSync(cargoTomlPath) || !CARGO_WORKSPACE_PATTERN.test(await readFile(cargoTomlPath, 'utf-8'))) {
1441
+ return null;
1442
+ }
1443
+
1444
+ const projects: Array<{ name: string; root: string }> = [];
1445
+ for (const packageJsonPath of packageJsonPaths) {
1446
+ if (isManagedPackageJsonSource(packageJsonPath) || isBuildOutputPackageJson(packageJsonPath)) {
1447
+ continue;
1448
+ }
1449
+ try {
1450
+ const packageJson = await readPackageJson(join(workspaceRoot, packageJsonPath));
1451
+ const name = packageJson.nx?.name ?? packageJson.name;
1452
+ if (typeof name === 'string' && name.length > 0) {
1453
+ projects.push({ name, root: dirname(packageJsonPath) });
1454
+ }
1455
+ } catch {
1456
+ // createProjectTargets records the path-specific parse failure below.
1457
+ }
1458
+ }
1459
+ const rootProject = projects.find((project) => project.root === '.');
1460
+ if (!rootProject) {
1461
+ return null;
1462
+ }
1463
+
1464
+ const attributed = attributeCargoWorkspacePackages(listCargoWorkspacePackages(workspaceRoot), projects);
1465
+ const packages: RepoRootCargoPackagePlan[] = [];
1466
+ let previous: RepoRootCargoTargetRef = {
1467
+ projectName: rootProject.name,
1468
+ targetName: CARGO_TEST_COMPILE_TARGET,
1469
+ };
1470
+ const exceptional = exceptionalTestFilter(PLUGIN_NEXTEST_CONFIG);
1471
+ for (const pkg of attributed) {
1472
+ const pieces: RepoRootCargoTestPiece[] = [];
1473
+ const sharded = pkg.testShards > 1;
1474
+ const pin = sharded && exceptional !== null ? exceptional : null;
1475
+ const shardable = pin === null ? `package(${pkg.name})` : `package(${pkg.name}) and not (${pin})`;
1476
+ for (let index = 1; index <= pkg.testShards; index += 1) {
1477
+ const targetName = cargoTestPackageTargetName(pkg.name, sharded ? `shard${index}` : undefined);
1478
+ pieces.push({
1479
+ extra: sharded ? ` --partition hash:${index}/${pkg.testShards}` : '',
1480
+ previous,
1481
+ selector: shardable,
1482
+ targetName,
1483
+ });
1484
+ previous = { projectName: pkg.projectName, targetName };
1485
+ }
1486
+ if (pin !== null) {
1487
+ const targetName = cargoTestPackageTargetName(pkg.name, CARGO_TEST_EXCEPTIONS_SUFFIX);
1488
+ pieces.push({
1489
+ extra: '',
1490
+ previous,
1491
+ selector: `package(${pkg.name}) and (${pin})`,
1492
+ targetName,
1493
+ });
1494
+ previous = { projectName: pkg.projectName, targetName };
1495
+ }
1496
+ packages.push({ package: pkg, pieces });
1497
+ }
1498
+ return { packages, rootProjectName: rootProject.name };
1499
+ }
1500
+
1501
+ /**
1502
+ * Root mode keeps `--workspace` and adds `-p` only to make the owning crate
1503
+ * explicit in the command Nx attributes to its project. Cargo treats
1504
+ * `--workspace -p X` as the full workspace selection, so `-p` is inert for
1505
+ * feature resolution; the nextest filterset is what narrows the tests that run.
1506
+ * Never drop `--workspace`: `-p X` alone re-resolves features for one package
1507
+ * and defeats the compile target's shared artifacts.
1508
+ */
1509
+ async function addRepoRootCargoTestTargets(
1510
+ targets: Record<string, TargetConfiguration>,
1511
+ currentProjectName: string,
1512
+ projectRoot: string,
1513
+ workspaceRoot: string,
1514
+ workspace: RepoRootCargoWorkspace,
1515
+ ): Promise<string[]> {
1516
+ const targetNames: string[] = [];
1517
+ const configFile = nextestConfigRelPath(workspaceRoot, '.', PLUGIN_NEXTEST_CONFIG);
1518
+ for (const plan of workspace.packages) {
1519
+ if (plan.package.projectRoot !== projectRoot) {
1520
+ continue;
1521
+ }
1522
+ const inputs = await cargoPackageTestInputs(workspaceRoot, plan.package.dir, '{workspaceRoot}');
1523
+ for (const piece of plan.pieces) {
1524
+ targetNames.push(piece.targetName);
1525
+ targets[piece.targetName] = {
1526
+ executor: '@smoothbricks/nx-plugin:bounded-exec',
1527
+ cache: true,
1528
+ inputs,
1529
+ dependsOn: [cargoTargetDependency(currentProjectName, piece.previous)],
1530
+ options: {
1531
+ command: cargoFrozen(
1532
+ `nextest run --workspace -p ${plan.package.name} -E '${piece.selector}'${piece.extra} --no-tests=pass --user-config-file none --config-file ${configFile}`,
1533
+ ),
1534
+ cwd: '.',
1535
+ timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
1536
+ killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
1537
+ },
1538
+ };
1539
+ }
1540
+ }
1541
+ return targetNames;
1542
+ }
1543
+
1544
+ function hasCargoTargetDependency(
1545
+ dependencies: readonly CargoTargetDependency[],
1546
+ expected: CargoTargetDependency,
1547
+ ): boolean {
1548
+ if (typeof expected === 'string') {
1549
+ return dependencies.includes(expected);
1550
+ }
1551
+ return dependencies.some(
1552
+ (dependency) =>
1553
+ typeof dependency !== 'string' &&
1554
+ dependency.target === expected.target &&
1555
+ Array.isArray(dependency.projects) &&
1556
+ Array.isArray(expected.projects) &&
1557
+ dependency.projects.length === expected.projects.length &&
1558
+ dependency.projects.every((project, index) => project === expected.projects?.[index]),
1559
+ );
1560
+ }