@smoothbricks/nx-plugin 0.4.11 → 0.4.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { readdir, readFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
3
4
  import { dirname, join, posix, relative } from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
5
6
 
6
7
  import {
8
+ type CreateNodesContextV2,
7
9
  type CreateNodesResultV2,
8
10
  type CreateNodesV2,
9
11
  readJsonFile,
@@ -21,11 +23,13 @@ import {
21
23
  CARGO_TEST_COMPILE_TARGET,
22
24
  CARGO_TEST_EXCEPTIONS_SUFFIX,
23
25
  CARGO_TEST_TARGET,
26
+ type CargoCrossTestTarget,
24
27
  type CargoInputsCache,
25
28
  cargoPackageTestInputs,
26
29
  cargoTestPackageTargetName,
27
30
  createCargoInputsCache,
28
31
  exceptionalTestFilter,
32
+ listCargoCrossTestTargets,
29
33
  listCargoWorkspacePackages,
30
34
  NEXTEST_REPO_CONFIG_PATH,
31
35
  nextestToolConfigArg,
@@ -37,8 +41,12 @@ import {
37
41
  CARGO_FETCH_TARGET,
38
42
  CARGO_FROZEN_PREFIX,
39
43
  CARGO_LINT_CLIPPY_COMMAND,
44
+ cargoCrossTestArchiveFile,
45
+ cargoCrossTestArchiveTargetName,
46
+ cargoCrossTestTargetName,
40
47
  cargoFrozen,
41
48
  } from './cross-check-policy.js';
49
+ import { hashVersionlessCrateManifests } from './manifest-hash.js';
42
50
  import { isNonSourceDirectory } from './source-directories.js';
43
51
  import { PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
44
52
 
@@ -50,12 +58,69 @@ export const DEPLOY_TARGET = 'deploy';
50
58
  export const DEPLOY_BUILD_TARGET = 'deploy-build';
51
59
 
52
60
  const BUILD_OUTPUT_TARGET_PATTERN = /-(?:js|web|html|css|android|native|napi|bun|wasm)$/;
61
+ /** The workspace-wide manifests a release rewrites: the version of every member, and the lockfile mirror of it. */
62
+ const RELEASE_REWRITTEN_WORKSPACE_INPUTS = ['{workspaceRoot}/package.json', '{workspaceRoot}/bun.lock'];
53
63
  const TYPESCRIPT_TOOLCHAIN_INPUTS = [
54
- '{workspaceRoot}/package.json',
55
- '{workspaceRoot}/bun.lock',
64
+ ...RELEASE_REWRITTEN_WORKSPACE_INPUTS,
56
65
  '{workspaceRoot}/patches/**/*',
57
66
  '{workspaceRoot}/tsconfig.base.json',
58
67
  ];
68
+ /**
69
+ * The same toolchain for a check, with the two release-rewritten files hashed
70
+ * by field instead of by byte.
71
+ *
72
+ * A `json` input is hashed by Nx's own hasher, so this costs no process. The
73
+ * lockfile's `workspaces` section is the mirror of each member's manifest —
74
+ * name, version and dependency specifiers — and every one of those is already
75
+ * hashed from the member's own `package.json`. Dropping that section keeps the
76
+ * resolution table, which is the reason the lockfile is an input at all.
77
+ */
78
+ const VERSIONLESS_TOOLCHAIN_INPUTS = [
79
+ ...TYPESCRIPT_TOOLCHAIN_INPUTS.filter((input) => !RELEASE_REWRITTEN_WORKSPACE_INPUTS.includes(input)),
80
+ { json: '{workspaceRoot}/package.json', excludeFields: ['version'] },
81
+ { json: '{workspaceRoot}/bun.lock', excludeFields: ['workspaces'] },
82
+ ];
83
+
84
+ /**
85
+ * A project's own manifest, hashed without the version a release rewrites.
86
+ *
87
+ * ONLY targets that read source may exclude the raw file. A target that
88
+ * produces a shipped artifact keeps hashing it: Rust embeds its version at
89
+ * compile time through `env!("CARGO_PKG_VERSION")`, so a version-insensitive
90
+ * build hash lets a post-bump `build` hit a pre-bump artifact and ship a
91
+ * binary that reports the previous version. `tsc-js`, `build`, `pack` and
92
+ * every cargo target are therefore left alone.
93
+ */
94
+ const VERSIONLESS_PACKAGE_INPUTS = [
95
+ '!{projectRoot}/package.json',
96
+ { json: '{projectRoot}/package.json', excludeFields: ['version'] },
97
+ ];
98
+
99
+ /**
100
+ * Crate manifests, for the projects that have any.
101
+ *
102
+ * TOML has no `json` input, so this is the one manifest kind the plugin
103
+ * hashes itself — in this process, over bytes it is already reading, during
104
+ * the graph construction that needs the answer.
105
+ *
106
+ * The digest reaches the hash as a literal, with no command behind it. Nx
107
+ * hashes a project's `namedInputs` DEFINITIONS into that project's
108
+ * configuration hash, and that hash is part of every task in the project and
109
+ * of every task that depends on the project — which is exactly the reach the
110
+ * transitive half needs. So the digest is written as an input path that
111
+ * matches no file and is only ever read as a string. It is a positive
112
+ * pattern, never an exclusion: a pattern that matched something unexpected
113
+ * could then only ADD to the hash, never quietly remove a real manifest from
114
+ * it.
115
+ */
116
+ const VERSIONLESS_CRATE_EXCLUSION = '!{projectRoot}/**/Cargo.toml';
117
+ const VERSIONLESS_CRATE_DIGEST_PREFIX = '{projectRoot}/.versionless-crate-manifests/';
118
+
119
+ /** Plugin-owned named inputs: a project's `production`/`default` with the manifest versions ignored. */
120
+ const VERSIONLESS_PRODUCTION_INPUT = 'versionlessProduction';
121
+ const VERSIONLESS_DEFAULT_INPUT = 'versionlessDefault';
122
+ /** `json` inputs with `excludeFields` are Nx 23.2; an older hasher rejects the entry outright. */
123
+ const JSON_INPUT_MINIMUM_NX = [23, 2] as const;
59
124
 
60
125
  const BIOME_CONFIG_FILES = ['biome.json', 'biome.jsonc'];
61
126
  const ESLINT_CONFIG_FILES = [
@@ -134,20 +199,40 @@ function hostPlatformTargetNames(targetNames: Iterable<string>, hostPlatform: Na
134
199
  /**
135
200
  * The reserved suffixes name targets that EMIT an artifact, and the `build`
136
201
  * aggregate is a list of those. Handing Nx the raw `*-<family>` globs let it
137
- * match on suffix alone, and one namespace collides by construction: a
138
- * per-crate cargo test runner is named `cargo-test-<crate>`, so any crate whose
139
- * name ends in an output family — `*-napi`, `*-wasm`, `*-native`, `*-js` — put
140
- * its RUNNER in the aggregate. The runners are one serialized chain, so a
141
- * single such crate made `build` pull an entire cargo test suite. Expanding the
142
- * families here instead of delegating to Nx's matcher keeps the plugin's own
143
- * `cargo-test-` namespace out of the aggregate however a crate is named.
202
+ * match on suffix alone, and a test runner collides by construction whenever
203
+ * its name ends in a family: `*-js`, `*-web`, `*-html`, `*-css`, `*-android`,
204
+ * `*-native`, `*-napi`, `*-bun`, `*-wasm`.
205
+ *
206
+ * Two spellings of the same collision. A per-crate cargo test runner is
207
+ * `cargo-test-<crate>`, so any crate whose name ends in a family put its RUNNER
208
+ * in the aggregate; the runners are one serialized chain, so a single such
209
+ * crate made `build` pull an entire cargo test suite. A bun suite named
210
+ * `test-bun` is the collision without the prefix — a runner reading as
211
+ * "tool=test, output=bun", swept into `build` by suffix alone. That one forced
212
+ * a consumer to hand-declare `build` purely to replace the inferred list.
213
+ *
214
+ * So the rule is the CLASS, not one namespace: a target that RUNS tests is
215
+ * never a build output, however it is spelled. Expanding the families here
216
+ * rather than delegating to Nx's matcher is what makes that expressible.
144
217
  */
145
218
  function buildOutputTargetNames(targetNames: Iterable<string>): string[] {
146
219
  return [...new Set(targetNames)]
147
- .filter((name) => BUILD_OUTPUT_TARGET_PATTERN.test(name) && !name.startsWith(`${CARGO_TEST_TARGET}-`))
220
+ .filter((name) => BUILD_OUTPUT_TARGET_PATTERN.test(name) && !isTestRunnerTargetName(name))
148
221
  .sort();
149
222
  }
150
223
 
224
+ /**
225
+ * A target whose job is to RUN tests. `test`, anything under `test-`/`test:`,
226
+ * and the plugin's own `cargo-test-<crate>` namespace. Deliberately name-based:
227
+ * the aggregate is assembled from declared AND inferred target names, and a
228
+ * declaration carries no marker saying "this executes rather than emits".
229
+ */
230
+ function isTestRunnerTargetName(name: string): boolean {
231
+ return (
232
+ name === 'test' || name.startsWith('test-') || name.startsWith('test:') || name.startsWith(`${CARGO_TEST_TARGET}-`)
233
+ );
234
+ }
235
+
151
236
  //#region smoo!n/rust-output-target-inference
152
237
  // Cargo workspace inference: a package.json sitting next to a Cargo.toml that
153
238
  // declares [workspace] gets direct cargo-test/test targets, cargo-lint feeding
@@ -392,6 +477,106 @@ function createCargoTestArchiveTarget(projectRoot: string, toolConfig: string):
392
477
  };
393
478
  }
394
479
 
480
+ /**
481
+ * One foreign triple's test archive, and the target that EXECUTES it.
482
+ *
483
+ * A target-triple VARIANT of `cargo-test-archive`, not a second mechanism: same
484
+ * `nextest archive --workspace`, same tool config layering, same
485
+ * `--workspace-remap .` on the run — only `--target <triple>` and a distinct
486
+ * archive file are added, because both archives coexist as declared Nx outputs
487
+ * and one path for two triples would let a restored cache serve the wrong
488
+ * machine's binaries.
489
+ *
490
+ * `cargo-nextest` where every other cargo target spells `cargo --frozen`, and
491
+ * that is measured, not stylistic: cargo overwrites `CARGO` with its own path
492
+ * for every subcommand it launches, so `cargo nextest` erases the cross cargo
493
+ * driver a repository exports through `CARGO` — the only seam nextest has for
494
+ * one. Invoking `cargo-nextest` directly leaves that driver intact, and
495
+ * `--frozen` moves onto nextest, which forwards it to both inner cargo calls
496
+ * (measured: `metadata … --frozen` and `test --no-run … --frozen`).
497
+ *
498
+ * The archive target therefore states `CARGO_FETCH_TARGET` and the toolchain
499
+ * runtime inputs itself: both are otherwise attached by matching the
500
+ * `cargo --frozen` prefix in a command, and this command does not carry it.
501
+ *
502
+ * The RUNNER declares no dependency on the archive and is not cached. That is
503
+ * the whole point of splitting the pair: it runs on a machine where the triple
504
+ * is native and the archive arrived as a file, so a dependency edge would ask
505
+ * that machine to cross-build what it was sent, and a cache verdict would be
506
+ * keyed on sources whose binaries it did not build. It is also the one cargo
507
+ * target that needs no cargo: `nextest run --archive-file` extracts prebuilt
508
+ * binaries and never invokes cargo (measured, zero invocations).
509
+ */
510
+ function createCargoCrossTestTargets(
511
+ projectRoot: string,
512
+ toolConfig: string,
513
+ crossTarget: CargoCrossTestTarget,
514
+ archiveInputs: NonNullable<TargetConfiguration['inputs']>,
515
+ ): Record<string, TargetConfiguration> {
516
+ const { target: triple, cargo } = crossTarget;
517
+ const archiveFile = cargoCrossTestArchiveFile(triple);
518
+ const archiveCommand = (profile: string): string =>
519
+ `cargo-nextest nextest archive --workspace${profile} --target ${triple} --frozen ` +
520
+ `--archive-file ${archiveFile} --user-config-file none ${toolConfig}`;
521
+ return {
522
+ [cargoCrossTestArchiveTargetName(triple)]: {
523
+ executor: 'nx:run-commands',
524
+ cache: true,
525
+ // The two runtime inputs every cached cargo target carries, plus the
526
+ // declared driver's own bytes. They are attached elsewhere by matching
527
+ // the `cargo --frozen` prefix in a command, which this one does not
528
+ // spell — and they matter MORE here than anywhere else: the cross
529
+ // environment (SDKROOT, CC_<triple>, ZIG*, and CARGO itself) is what
530
+ // decides whether these bytes are Mach-O at all, so an archive linked
531
+ // against one sysroot must never hash equal to the same sources linked
532
+ // against another.
533
+ inputs: [
534
+ ...archiveInputs,
535
+ ...(cargo === undefined ? [] : [`{projectRoot}/${cargo}`]),
536
+ cargoRuntimeInput(projectRoot, CARGO_ENVIRONMENT_INPUT.runtime),
537
+ cargoRuntimeInput(projectRoot, 'rustc -vV && cargo -V && cargo nextest --version'),
538
+ ],
539
+ outputs: [`{projectRoot}/${archiveFile}`],
540
+ dependsOn: [CARGO_FETCH_TARGET],
541
+ options: {
542
+ commands: [`mkdir -p ${posix.dirname(archiveFile)}`, archiveCommand('')],
543
+ cwd: projectRoot,
544
+ parallel: false,
545
+ // `CARGO` is cargo's own driver variable and the only seam nextest
546
+ // offers: it shells out to `$CARGO metadata` and
547
+ // `$CARGO test --no-run --target <triple>`, so the declared script
548
+ // decides how the foreign link happens without the generated command
549
+ // knowing anything about zig, an SDK, or a sysroot. Target-scoped, so
550
+ // it applies to this archive and to nothing else cargo runs.
551
+ ...(cargo === undefined ? {} : { env: { CARGO: cargo } }),
552
+ },
553
+ configurations: {
554
+ production: {
555
+ commands: [`mkdir -p ${posix.dirname(archiveFile)}`, archiveCommand(' --release')],
556
+ },
557
+ },
558
+ },
559
+ [cargoCrossTestTargetName(triple)]: {
560
+ executor: '@smoothbricks/nx-plugin:bounded-exec',
561
+ cache: false,
562
+ inputs: [],
563
+ outputs: [],
564
+ dependsOn: [],
565
+ options: {
566
+ command:
567
+ `cargo-nextest nextest run --archive-file ${archiveFile} --workspace-remap . ` +
568
+ `--no-tests=pass --user-config-file none ${toolConfig}`,
569
+ cwd: projectRoot,
570
+ timeoutMs: BOUNDED_TEST_TIMEOUT_MS,
571
+ killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
572
+ },
573
+ // The archive already holds the profile it was built with, and nextest
574
+ // rejects `--release` beside `--archive-file`.
575
+ configurations: { production: {} },
576
+ },
577
+ };
578
+ }
579
+
395
580
  function createCargoTestTarget(projectRoot: string): TargetConfiguration {
396
581
  return {
397
582
  executor: '@smoothbricks/nx-plugin:bounded-exec',
@@ -412,6 +597,80 @@ function createCargoTestTarget(projectRoot: string): TargetConfiguration {
412
597
 
413
598
  const PLUGIN_NEXTEST_CONFIG = fileURLToPath(new URL('../nextest.toml', import.meta.url));
414
599
 
600
+ /**
601
+ * How far the versionless manifest treatment reaches in this workspace.
602
+ *
603
+ * The JSON half costs nothing: Nx hashes a `json` input in its own hasher.
604
+ * `null` means even that is off, because the running Nx predates the input
605
+ * type and would reject the entry rather than ignore it — the plugin is
606
+ * published, so an older consumer gets today's inputs instead of a broken
607
+ * hash.
608
+ *
609
+ * The crate half asks nothing of the workspace at all. The digest is computed
610
+ * right here, in the process that is already reading those manifests, and
611
+ * rides into the project's named inputs as a literal — so there is no command
612
+ * to install and nothing to look for before the treatment is safe to declare.
613
+ */
614
+ interface VersionlessManifestPolicy {
615
+ /**
616
+ * Whether a dependency's manifests can be hashed versionlessly too.
617
+ *
618
+ * `{ input, dependencies: true }` resolves the named input in EACH
619
+ * dependency's own context, and Nx throws when a dependency has no
620
+ * definition for it. A project this plugin never inferred — a project.json
621
+ * project with no package.json — has none, so the transitive half is only
622
+ * safe once nx.json defines the name workspace-wide. That definition is what
623
+ * a consumer opts in with; without it the dependency half stays `^production`.
624
+ */
625
+ transitive: boolean;
626
+ }
627
+
628
+ function versionlessManifestPolicy(context: CreateNodesContextV2): VersionlessManifestPolicy | null {
629
+ if (!supportsJsonInputs()) return null;
630
+ return { transitive: context.nxJsonConfiguration.namedInputs?.[VERSIONLESS_PRODUCTION_INPUT] !== undefined };
631
+ }
632
+
633
+ /**
634
+ * The crate manifests' exclusion and the digest that stands in for them, or
635
+ * nothing at all when this process cannot read them.
636
+ *
637
+ * Fail-closed, and the only direction that is safe: excluding the manifests
638
+ * with no digest replacing them would stop a real dependency change from
639
+ * invalidating anything, and neither Nx nor this plugin would say a word.
640
+ * Handing back the empty list leaves the raw manifests in the fileset — one
641
+ * cache miss per release, which is what the workspace has today.
642
+ */
643
+ async function versionlessCrateInputs(projectRoot: string, workspaceRoot: string): Promise<string[]> {
644
+ try {
645
+ const digest = await hashVersionlessCrateManifests(projectRoot, workspaceRoot);
646
+ return [VERSIONLESS_CRATE_EXCLUSION, `${VERSIONLESS_CRATE_DIGEST_PREFIX}${digest}`];
647
+ } catch (error) {
648
+ // Out loud: a silent degrade here reads as "the release stopped costing a
649
+ // rebuild", which is the same thing a wrong hash reads as.
650
+ process.stderr.write(
651
+ `@smoothbricks/nx-plugin: hashing the crate manifests under ${projectRoot} failed (${
652
+ error instanceof Error ? error.message : String(error)
653
+ }); hashing them raw instead, so a release invalidates this project's checks.\n`,
654
+ );
655
+ return [];
656
+ }
657
+ }
658
+
659
+ /**
660
+ * Whether the Nx that is RUNNING understands a `json` input. Read from the
661
+ * loaded module rather than the workspace, because that is the hasher which
662
+ * will receive the entry.
663
+ */
664
+ function supportsJsonInputs(): boolean {
665
+ const version = readJsonFile<{ version?: unknown }>(
666
+ createRequire(import.meta.url).resolve('nx/package.json'),
667
+ ).version;
668
+ if (typeof version !== 'string') return false;
669
+ const [major = 0, minor = 0] = version.split('.', 2).map(Number);
670
+ const [minimumMajor, minimumMinor] = JSON_INPUT_MINIMUM_NX;
671
+ return major > minimumMajor || (major === minimumMajor && minor >= minimumMinor);
672
+ }
673
+
415
674
  type CreateNodesHandler = CreateNodesV2[1];
416
675
 
417
676
  function createNodesHandler(hostPlatform: NapiPlatform | null): CreateNodesHandler {
@@ -424,6 +683,7 @@ function createNodesHandler(hostPlatform: NapiPlatform | null): CreateNodesHandl
424
683
  } catch (error) {
425
684
  throw new AggregateCreateNodesError([[null, error instanceof Error ? error : new Error(String(error))]], results);
426
685
  }
686
+ const versionless = versionlessManifestPolicy(context);
427
687
 
428
688
  await Promise.all(
429
689
  projectConfigurationFiles.map(async (packageJsonPath) => {
@@ -440,7 +700,13 @@ function createNodesHandler(hostPlatform: NapiPlatform | null): CreateNodesHandl
440
700
  }
441
701
  results.push([
442
702
  packageJsonPath,
443
- await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform, cargoWorkspaces),
703
+ await createProjectTargets(
704
+ packageJsonPath,
705
+ context.workspaceRoot,
706
+ hostPlatform,
707
+ cargoWorkspaces,
708
+ versionless,
709
+ ),
444
710
  ]);
445
711
  } catch (error) {
446
712
  errors.push([packageJsonPath, error instanceof Error ? error : new Error(String(error))]);
@@ -484,6 +750,8 @@ interface PackageJson {
484
750
  bin?: unknown;
485
751
  name?: string;
486
752
  napi?: Record<string, unknown>;
753
+ /** npm's own "never published" flag, which is what makes a package a deployable target rather than a library. */
754
+ private?: boolean;
487
755
  scripts?: Record<string, unknown>;
488
756
  nx?: {
489
757
  name?: string;
@@ -514,11 +782,53 @@ function packageBinOutputs(packageJson: PackageJson, packageJsonPath: string): s
514
782
  return [...outputs];
515
783
  }
516
784
 
785
+ /**
786
+ * The deployment manifests wrangler itself looks for, in its own precedence
787
+ * order. Finding one is HALF the detection: a published library ships one to
788
+ * document a Durable Object binding for its consumers, and that manifest is
789
+ * structurally indistinguishable from a deployable worker's — same `name`,
790
+ * `main` and `compatibility_date`. So presence alone cannot mean deployable,
791
+ * and the other half is `private: true` below.
792
+ *
793
+ * Deploy POLICY is deliberately NOT read from the manifest. `smoo.wrangler.stages`
794
+ * belongs to the CLI, which reads it to decide which secrets a stage requires; a
795
+ * second copy in the graph would disagree the first time a stage was added. And
796
+ * which stages CI actually runs is the four-way tag vocabulary in the CLI's
797
+ * `deploy-tags.ts` — every stage, staging only, excluded, production-on-push —
798
+ * that a flag here could express exactly one of. So a private wrangler project
799
+ * gets the target, and the tags alone decide what CI deploys.
800
+ *
801
+ * A worker deployed by some other mechanism declares its own `options.command`,
802
+ * which replaces this one; the tag is what CI reads either way.
803
+ */
804
+ const WRANGLER_CONFIG_FILES = ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml'];
805
+
806
+ /**
807
+ * ONE target that deploys whichever stage it is handed, never a configuration
808
+ * per stage. Pull-request stages are `prN` for unbounded N, so an enumerated
809
+ * `configurations` map cannot describe the surface that actually exists, and a
810
+ * project carrying both spellings would have two ways to say one thing.
811
+ *
812
+ * No `stage-deploy-target` tag either, deliberately: that tag is the repository's
813
+ * statement that CI deploys this project on every stage, and only the repository
814
+ * can make it. A plugin that tagged what it inferred would enrol every private
815
+ * wrangler project in CI deploys by writing the policy it is supposed to read.
816
+ *
817
+ * `{args.stage}` rather than `forwardAllArgs`: run-commands'
818
+ * `interpolateArgsIntoCommand` returns as soon as it sees `{args.` and never
819
+ * appends forwarded arguments, so `nx run web:deploy --stage=pr42` yields
820
+ * exactly one `--stage`, for an arbitrary preview stage no map could enumerate.
821
+ * An omitted stage interpolates to empty and `deploy-stage`'s required
822
+ * `--stage` refuses it, which is the failure we want at the boundary.
823
+ */
824
+ const WRANGLER_DEPLOY_COMMAND = 'smoo wrangler deploy-stage --stage {args.stage}';
825
+
517
826
  async function createProjectTargets(
518
827
  packageJsonPath: string,
519
828
  workspaceRoot: string,
520
829
  hostPlatform: NapiPlatform | null,
521
830
  cargoWorkspaces: readonly CargoWorkspace[],
831
+ versionless: VersionlessManifestPolicy | null,
522
832
  ) {
523
833
  const projectRoot = dirname(packageJsonPath);
524
834
  const absoluteProjectRoot = join(workspaceRoot, projectRoot);
@@ -542,6 +852,22 @@ async function createProjectTargets(
542
852
  const isCargoProject = cargoWorkspace !== undefined;
543
853
  const repoRootPackages = cargoWorkspace?.projectRoot === '.' ? cargoPackagePlans.map((plan) => plan.package) : [];
544
854
  const isRepoRootedCargoProject = cargoWorkspace?.projectRoot === '.';
855
+ // What a check that only READS the manifests hashes instead of their raw
856
+ // bytes. Each piece degrades to today's input on its own: an Nx without
857
+ // `json` inputs gets no treatment at all; crate manifests this process
858
+ // cannot read stay raw; no workspace-wide named input leaves the
859
+ // transitive half `^production`.
860
+ const hasCrateManifests = isCargoProject || existsSync(cargoTomlPath);
861
+ const crateInputs =
862
+ versionless !== null && hasCrateManifests ? await versionlessCrateInputs(projectRoot, workspaceRoot) : [];
863
+ const versionlessProjectInputs = versionless === null ? [] : [...VERSIONLESS_PACKAGE_INPUTS, ...crateInputs];
864
+ const checkInputs = versionless === null ? TYPESCRIPT_TOOLCHAIN_INPUTS : VERSIONLESS_TOOLCHAIN_INPUTS;
865
+ const selfProduction = versionless === null ? 'production' : VERSIONLESS_PRODUCTION_INPUT;
866
+ const selfDefault = versionless === null ? 'default' : VERSIONLESS_DEFAULT_INPUT;
867
+ const dependencyProduction =
868
+ versionless?.transitive === true
869
+ ? { input: VERSIONLESS_PRODUCTION_INPUT, dependencies: true as const }
870
+ : '^production';
545
871
  const napiConfig = resolveNapiConfig(
546
872
  packageJson,
547
873
  packageJsonPath,
@@ -561,6 +887,8 @@ async function createProjectTargets(
561
887
  const hasOrdinaryBuildOutputTarget =
562
888
  hasLibTsconfig || napiConfig !== null || cargoWasmConfig !== null || packageLocalBuildOutputs.ordinary;
563
889
  const hasAnyBuildOutputTarget = hasOrdinaryBuildOutputTarget || packageLocalBuildOutputs.platform;
890
+ const isDeployableWranglerProject =
891
+ packageJson.private === true && WRANGLER_CONFIG_FILES.some((file) => existsSync(join(absoluteProjectRoot, file)));
564
892
 
565
893
  if (hasLibTsconfig) {
566
894
  const executableOutputs = packageBinOutputs(packageJson, packageJsonPath);
@@ -587,7 +915,7 @@ async function createProjectTargets(
587
915
  targets.typecheck = {
588
916
  executor: 'nx:run-commands',
589
917
  cache: true,
590
- inputs: ['production', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.lib.json'],
918
+ inputs: [selfProduction, dependencyProduction, ...checkInputs, '{projectRoot}/tsconfig.lib.json'],
591
919
  outputs: [],
592
920
  dependsOn: ['^*-js', ...(cargoWasmConfig ? ['cargo-wasm'] : [])],
593
921
  options: {
@@ -602,7 +930,7 @@ async function createProjectTargets(
602
930
  targets['typecheck-tests'] = {
603
931
  executor: 'nx:run-commands',
604
932
  cache: true,
605
- inputs: ['default', '^production', ...TYPESCRIPT_TOOLCHAIN_INPUTS, '{projectRoot}/tsconfig.test.json'],
933
+ inputs: [selfDefault, dependencyProduction, ...checkInputs, '{projectRoot}/tsconfig.test.json'],
606
934
  dependsOn: ['typecheck'],
607
935
  options: {
608
936
  command: 'tsc -p tsconfig.test.json --noEmit',
@@ -739,6 +1067,21 @@ async function createProjectTargets(
739
1067
  // `archive.include` lives in the repository's nextest config, so that file
740
1068
  // decides what the archive CONTAINS, not merely how a run behaves.
741
1069
  targets[CARGO_TEST_ARCHIVE_TARGET].inputs = [...workspaceCargoInputs, `{projectRoot}/${NEXTEST_REPO_CONFIG_PATH}`];
1070
+ // One archive per declared foreign triple, from the same inputs and the
1071
+ // same repository nextest config: an archive is the workspace's test
1072
+ // binaries whichever machine they are for, so a change that invalidates
1073
+ // the host archive must invalidate every cross one.
1074
+ for (const crossTarget of listCargoCrossTestTargets(join(workspaceRoot, cargoWorkspaceRoot))) {
1075
+ Object.assign(
1076
+ targets,
1077
+ createCargoCrossTestTargets(
1078
+ cargoWorkspaceRoot,
1079
+ nextestToolConfigArg(workspaceRoot, cargoWorkspaceRoot, PLUGIN_NEXTEST_CONFIG),
1080
+ crossTarget,
1081
+ [...workspaceCargoInputs, `{projectRoot}/${NEXTEST_REPO_CONFIG_PATH}`],
1082
+ ),
1083
+ );
1084
+ }
742
1085
  const aggregateDependencies = cargoWorkspace.packages.flatMap((plan) =>
743
1086
  plan.pieces.map((piece) =>
744
1087
  cargoTargetDependency(projectName, {
@@ -1091,17 +1434,41 @@ async function createProjectTargets(
1091
1434
  // dependent has to re-check liveness, not inherit someone else's cache hit.
1092
1435
  //
1093
1436
  // Both are bases for a package-local declaration to land on, per the merge rules above: a
1094
- // declaration naming `cache`, `inputs` or `dependsOn` REPLACES what is set here, so a project
1095
- // adding a cross-project edge writes `"dependsOn": ["...", "backend:deploy"]` to keep the
1096
- // `deploy-build` edge this adds.
1437
+ // declaration naming `cache`, `inputs` or `dependsOn` REPLACES what is set here and inherits
1438
+ // everything it does not name, while Nx's `"..."` token expands to the inferred list at its
1439
+ // position. So a project adding a cross-project edge writes
1440
+ // `"dependsOn": ["...", "backend:deploy"]` and keeps both the edge below and this command —
1441
+ // measured, not assumed, against an inferred base.
1442
+ //
1443
+ // `deploy` is INFERRED for a private wrangler project rather than patched onto a hand-written
1444
+ // one. The command is a constant of the convention, not of the project: every consumer wrote
1445
+ // the same `nx:run-commands` wrapper around it. `private: true` is the second half of the
1446
+ // detection: a PUBLISHED package's wrangler manifest documents a binding for its consumers,
1447
+ // so inferring a deploy from it would put a live `wrangler deploy` of someone's documentation
1448
+ // one `nx run-many -t deploy` away. A published package that really is deployed declares
1449
+ // `deploy` itself. `deploy-build` stays declaration-driven in the other direction, because
1450
+ // only the project knows what building it means — the plugin supplies its POLICY (cache
1451
+ // honestly) and nothing else.
1097
1452
  if (DEPLOY_BUILD_TARGET in declaredTargets) {
1098
1453
  targets[DEPLOY_BUILD_TARGET] = { cache: true };
1099
1454
  }
1100
- if (DEPLOY_TARGET in declaredTargets) {
1455
+ if (isDeployableWranglerProject) {
1456
+ // Naming only an edge that exists is tidiness, not a guard: Nx tolerates a `dependsOn` on a
1457
+ // target the project lacks — measured, the task just runs alone — and a wrangler worker can
1458
+ // legitimately have no build at all, since wrangler bundles its own TypeScript. Pointing at a
1459
+ // target that is not there would only make `nx graph` claim a prerequisite nothing satisfies.
1460
+ const fileDerivedHalf =
1461
+ DEPLOY_BUILD_TARGET in declaredTargets
1462
+ ? DEPLOY_BUILD_TARGET
1463
+ : hasOrdinaryBuildOutputTarget || 'build' in declaredTargets
1464
+ ? 'build'
1465
+ : null;
1101
1466
  targets[DEPLOY_TARGET] = {
1467
+ executor: 'nx:run-commands',
1102
1468
  cache: false,
1103
1469
  outputs: [],
1104
- ...(DEPLOY_BUILD_TARGET in declaredTargets ? { dependsOn: [DEPLOY_BUILD_TARGET] } : {}),
1470
+ ...(fileDerivedHalf === null ? {} : { dependsOn: [fileDerivedHalf] }),
1471
+ options: { command: WRANGLER_DEPLOY_COMMAND, cwd: projectRoot },
1105
1472
  };
1106
1473
  }
1107
1474
 
@@ -1192,8 +1559,8 @@ async function createProjectTargets(
1192
1559
  dependsOn: validationTargets,
1193
1560
  outputs: [],
1194
1561
  inputs: [
1195
- 'default',
1196
- ...TYPESCRIPT_TOOLCHAIN_INPUTS,
1562
+ selfDefault,
1563
+ ...checkInputs,
1197
1564
  ...[...BIOME_CONFIG_FILES, ...ESLINT_CONFIG_FILES].flatMap((name) => [
1198
1565
  `{workspaceRoot}/${name}`,
1199
1566
  `{projectRoot}/${name}`,
@@ -1210,7 +1577,26 @@ async function createProjectTargets(
1210
1577
 
1211
1578
  return {
1212
1579
  projects: {
1213
- [projectRoot]: { name: projectName, targets },
1580
+ [projectRoot]: {
1581
+ name: projectName,
1582
+ targets,
1583
+ // A named input is what `{ input, dependencies: true }` resolves in
1584
+ // each DEPENDENCY's own context, so the dependency half needs one to
1585
+ // exist per project. A `json` path interpolates `{projectRoot}` per
1586
+ // project, but a `runtime` command does NOT — it reaches the shell
1587
+ // literally — so a crate digest can only name its own root from here.
1588
+ // Nx resolves a named input from the project first and nx.json second,
1589
+ // so a workspace-wide definition still covers projects this plugin
1590
+ // never inferred.
1591
+ ...(versionless === null
1592
+ ? {}
1593
+ : {
1594
+ namedInputs: {
1595
+ [VERSIONLESS_PRODUCTION_INPUT]: ['production', ...versionlessProjectInputs],
1596
+ [VERSIONLESS_DEFAULT_INPUT]: ['default', ...versionlessProjectInputs],
1597
+ },
1598
+ }),
1599
+ },
1214
1600
  },
1215
1601
  };
1216
1602
  }
@@ -1567,6 +1953,7 @@ async function readPackageJson(packageJsonPath: string): Promise<PackageJson> {
1567
1953
  ...('bin' in parsed ? { bin: parsed.bin } : {}),
1568
1954
  ...(typeof parsed.name === 'string' ? { name: parsed.name } : {}),
1569
1955
  ...(isRecord(parsed.napi) ? { napi: parsed.napi } : {}),
1956
+ ...(typeof parsed.private === 'boolean' ? { private: parsed.private } : {}),
1570
1957
  ...(isRecord(parsed.scripts) ? { scripts: parsed.scripts } : {}),
1571
1958
  ...(rawNx
1572
1959
  ? {