@smoothbricks/nx-plugin 0.3.12 → 0.3.14

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
@@ -32,7 +32,7 @@ import {
32
32
  CARGO_LINT_CLIPPY_COMMAND,
33
33
  cargoFrozen,
34
34
  } from './cross-check-policy.js';
35
- import { BUILD_OUTPUT_DEPENDENCIES, PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
35
+ import { PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
36
36
 
37
37
  export { CARGO_TEST_COMPILE_TARGET };
38
38
 
@@ -44,30 +44,56 @@ const TYPESCRIPT_TOOLCHAIN_INPUTS = [
44
44
  '{workspaceRoot}/tsconfig.base.json',
45
45
  ];
46
46
 
47
- // The aggregate `build` pulls in platform-suffixed binary targets for THIS
48
- // machine only: `<tool>-<arch>-<os>` names matching the host (for example
49
- // cli-arm64-macos on Apple Silicon) build locally as part of `nx build`, while
50
- // every foreign platform stays publish-workflow-only. nx.json targetDefaults
51
- // cannot express "current platform" — its dependsOn lists are static — so the
52
- // inference plugin owns this edge.
53
- const HOST_PLATFORM_SUFFIX: string | null = (() => {
54
- const os = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : null;
55
- const arch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : null;
56
- return os !== null && arch !== null ? `-${arch}-${os}` : null;
57
- })();
58
-
59
- export function hostPlatformTargetNames(targetNames: Iterable<string>): string[] {
60
- if (HOST_PLATFORM_SUFFIX === null) return [];
47
+ type NapiArchitecture = 'arm64' | 'x64';
48
+ type NapiTargetFamily = 'linux' | 'macos';
49
+
50
+ interface NapiPlatform {
51
+ architecture: NapiArchitecture;
52
+ targetFamily: NapiTargetFamily;
53
+ }
54
+
55
+ function napiPlatform(platform: NodeJS.Platform, architecture: string): NapiPlatform | null {
56
+ const targetFamily = platform === 'darwin' ? 'macos' : platform === 'linux' ? 'linux' : null;
57
+ const targetArchitecture = architecture === 'arm64' ? 'arm64' : architecture === 'x64' ? 'x64' : null;
58
+ return targetFamily !== null && targetArchitecture !== null
59
+ ? { architecture: targetArchitecture, targetFamily }
60
+ : null;
61
+ }
62
+
63
+ function sameNapiPlatform(left: NapiPlatform, right: NapiPlatform | null): boolean {
64
+ return left.architecture === right?.architecture && left.targetFamily === right.targetFamily;
65
+ }
66
+
67
+ function hostPlatformTargetNames(targetNames: Iterable<string>, hostPlatform: NapiPlatform | null): string[] {
68
+ if (hostPlatform === null) return [];
69
+ const suffix = `-${hostPlatform.architecture}-${hostPlatform.targetFamily}`;
61
70
  return [...new Set(targetNames)]
62
71
  .filter(
63
72
  // Binary targets only. A toolchain prerequisite carries the same platform
64
73
  // suffix but produces no artifact: the cross builds that need it depend
65
74
  // on it directly, so the aggregate stays a list of outputs.
66
- (name) => name.endsWith(HOST_PLATFORM_SUFFIX) && !name.startsWith(NAPI_TOOLCHAIN_TARGET_PREFIX),
75
+ (name) => name.endsWith(suffix) && !name.startsWith(NAPI_TOOLCHAIN_TARGET_PREFIX),
67
76
  )
68
77
  .sort();
69
78
  }
70
79
 
80
+ /**
81
+ * The reserved suffixes name targets that EMIT an artifact, and the `build`
82
+ * aggregate is a list of those. Handing Nx the raw `*-<family>` globs let it
83
+ * match on suffix alone, and one namespace collides by construction: a
84
+ * per-crate cargo test runner is named `cargo-test-<crate>`, so any crate whose
85
+ * name ends in an output family — `*-napi`, `*-wasm`, `*-native`, `*-js` — put
86
+ * its RUNNER in the aggregate. The runners are one serialized chain, so a
87
+ * single such crate made `build` pull an entire cargo test suite. Expanding the
88
+ * families here instead of delegating to Nx's matcher keeps the plugin's own
89
+ * `cargo-test-` namespace out of the aggregate however a crate is named.
90
+ */
91
+ function buildOutputTargetNames(targetNames: Iterable<string>): string[] {
92
+ return [...new Set(targetNames)]
93
+ .filter((name) => BUILD_OUTPUT_TARGET_PATTERN.test(name) && !name.startsWith(`${CARGO_TEST_TARGET}-`))
94
+ .sort();
95
+ }
96
+
71
97
  //#region smoo!n/rust-output-target-inference
72
98
  // Cargo workspace inference: a package.json sitting next to a Cargo.toml that
73
99
  // declares [workspace] gets direct cargo-test/test targets, cargo-lint feeding
@@ -91,11 +117,8 @@ const CARGO_INPUTS = [
91
117
  const CARGO_OUTPUT_INPUTS = [...CARGO_INPUTS, '{projectRoot}/package.json', '{workspaceRoot}/bun.lock'];
92
118
  const NAPI_INPUTS = CARGO_OUTPUT_INPUTS;
93
119
 
94
- interface NapiTargetConvention {
95
- architecture: string;
120
+ interface NapiTargetConvention extends NapiPlatform {
96
121
  outputName: string;
97
- targetFamily: 'linux' | 'macos';
98
- useNapiCross: boolean;
99
122
  }
100
123
 
101
124
  const NAPI_TARGET_CONVENTIONS: Readonly<Record<string, NapiTargetConvention>> = {
@@ -103,28 +126,39 @@ const NAPI_TARGET_CONVENTIONS: Readonly<Record<string, NapiTargetConvention>> =
103
126
  architecture: 'arm64',
104
127
  outputName: 'darwin-arm64',
105
128
  targetFamily: 'macos',
106
- useNapiCross: false,
107
129
  },
108
130
  'x86_64-apple-darwin': {
109
131
  architecture: 'x64',
110
132
  outputName: 'darwin-x64',
111
133
  targetFamily: 'macos',
112
- useNapiCross: false,
113
134
  },
114
135
  'aarch64-unknown-linux-gnu': {
115
136
  architecture: 'arm64',
116
137
  outputName: 'linux-arm64-gnu',
117
138
  targetFamily: 'linux',
118
- useNapiCross: true,
119
139
  },
120
140
  'x86_64-unknown-linux-gnu': {
121
141
  architecture: 'x64',
122
142
  outputName: 'linux-x64-gnu',
123
143
  targetFamily: 'linux',
124
- useNapiCross: true,
125
144
  },
126
145
  };
127
146
 
147
+ const NATIVE_LINUX_COMPILER_ENV = Object.freeze({ CC: 'cc', CXX: 'c++' });
148
+ const CROSS_LINUX_COMPILER_ENV = Object.freeze({ TARGET_CC: 'clang', TARGET_CXX: 'clang++' });
149
+
150
+ function usesNapiCross(target: NapiTargetConvention, hostPlatform: NapiPlatform | null): boolean {
151
+ return target.targetFamily === 'linux' && !sameNapiPlatform(target, hostPlatform);
152
+ }
153
+
154
+ function napiCompilerEnv(
155
+ target: NapiPlatform | null,
156
+ hostPlatform: NapiPlatform | null,
157
+ ): Readonly<Record<string, string>> | undefined {
158
+ if (target?.targetFamily !== 'linux') return undefined;
159
+ return sameNapiPlatform(target, hostPlatform) ? NATIVE_LINUX_COMPILER_ENV : CROSS_LINUX_COMPILER_ENV;
160
+ }
161
+
128
162
  const NAPI_TOOLCHAIN_TARGET_PREFIX = 'napi-toolchain-';
129
163
 
130
164
  /**
@@ -296,9 +330,10 @@ async function addPerPackageCargoTestTargets(
296
330
  return packageTargetNames;
297
331
  }
298
332
 
299
- export const createNodesV2: CreateNodesV2 = [
300
- '**/package.json',
301
- async (projectConfigurationFiles, _options, context) => {
333
+ type CreateNodesHandler = CreateNodesV2[1];
334
+
335
+ function createNodesHandler(hostPlatform: NapiPlatform | null): CreateNodesHandler {
336
+ return async (projectConfigurationFiles, _options, context) => {
302
337
  const results: CreateNodesResultV2 = [];
303
338
  const errors: Array<[file: string | null, error: Error]> = [];
304
339
 
@@ -311,7 +346,10 @@ export const createNodesV2: CreateNodesV2 = [
311
346
  results.push([packageJsonPath, {}]);
312
347
  return;
313
348
  }
314
- results.push([packageJsonPath, await createProjectTargets(packageJsonPath, context.workspaceRoot)]);
349
+ results.push([
350
+ packageJsonPath,
351
+ await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform),
352
+ ]);
315
353
  } catch (error) {
316
354
  errors.push([packageJsonPath, error instanceof Error ? error : new Error(String(error))]);
317
355
  }
@@ -323,7 +361,16 @@ export const createNodesV2: CreateNodesV2 = [
323
361
  }
324
362
 
325
363
  return results;
326
- },
364
+ };
365
+ }
366
+
367
+ export function createNodesV2ForPlatform(platform: NodeJS.Platform, architecture: string): CreateNodesV2 {
368
+ return ['**/package.json', createNodesHandler(napiPlatform(platform, architecture))];
369
+ }
370
+
371
+ export const createNodesV2: CreateNodesV2 = [
372
+ '**/package.json',
373
+ (...args) => createNodesHandler(napiPlatform(process.platform, process.arch))(...args),
327
374
  ];
328
375
 
329
376
  function isManagedPackageJsonSource(packageJsonPath: string): boolean {
@@ -343,7 +390,7 @@ interface PackageJson {
343
390
  };
344
391
  }
345
392
 
346
- async function createProjectTargets(packageJsonPath: string, workspaceRoot: string) {
393
+ async function createProjectTargets(packageJsonPath: string, workspaceRoot: string, hostPlatform: NapiPlatform | null) {
347
394
  const projectRoot = dirname(packageJsonPath);
348
395
  const absoluteProjectRoot = join(workspaceRoot, projectRoot);
349
396
  const packageJson = await readPackageJson(join(workspaceRoot, packageJsonPath));
@@ -438,7 +485,7 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
438
485
  }
439
486
 
440
487
  if (napiConfig) {
441
- Object.assign(targets, createNapiTargets(projectRoot, napiConfig));
488
+ Object.assign(targets, createNapiTargets(projectRoot, napiConfig, hostPlatform));
442
489
  if (
443
490
  !('napi-test' in (packageJson.nx?.targets ?? {})) &&
444
491
  existsSync(join(absoluteProjectRoot, 'src/native.test.ts'))
@@ -685,6 +732,37 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
685
732
  }
686
733
  }
687
734
 
735
+ // `build` lists cargo-test-compile beside the host's platform binaries, and
736
+ // every one of those is a `napi build` — another cargo writer on the package's
737
+ // default `target/`, which cargo flocks.
738
+ //
739
+ // Only `cargo-napi` gets the ordering edge. A platform-suffixed target may NOT
740
+ // have one: `validatePlatformTargetDependencies` (package-target-policy.ts:674)
741
+ // walks each platform target's dependency closure and refuses any member of a
742
+ // different family, because the publish flow builds and collects one platform
743
+ // at a time — a `*-macos` collect that reached a familyless sibling would drag
744
+ // in work the macOS runner has no business doing. `cargo-napi` carries no
745
+ // platform suffix, so it is not scanned and the edge is legal there.
746
+ //
747
+ // The platform binaries therefore stay Nx siblings of cargo-test-compile and
748
+ // serialize on cargo's flock instead of on a graph edge. That is the same
749
+ // arrangement `cli-<arch>-<os>` and `napi-<arch>-<os>` already have with each
750
+ // other — both `napi build --release` on one target dir — so this adds a third
751
+ // participant to an existing wait, not a new hazard. The flock makes them wait;
752
+ // it does not corrupt anything, and these are unbounded `nx:run-commands`
753
+ // targets, so the wait is not charged against a test budget.
754
+ const cargoWriterNames = hostPlatformTargetNames(
755
+ [...Object.keys(declaredTargets), ...Object.keys(targets)],
756
+ hostPlatform,
757
+ );
758
+ const cargoNapi = targets['cargo-napi'];
759
+ if (cargoNapi && targets[CARGO_TEST_COMPILE_TARGET]) {
760
+ const dependsOn = cargoNapi.dependsOn ?? [];
761
+ if (!dependsOn.includes(CARGO_TEST_COMPILE_TARGET)) {
762
+ cargoNapi.dependsOn = [...dependsOn, CARGO_TEST_COMPILE_TARGET];
763
+ }
764
+ }
765
+
688
766
  // No `outputs`, deliberately: this aggregate runs no command, so every file
689
767
  // under dist belongs to the concrete target that emitted it. Claiming
690
768
  // `{projectRoot}/dist` here would cache the children's bytes a second time
@@ -699,10 +777,20 @@ async function createProjectTargets(packageJsonPath: string, workspaceRoot: stri
699
777
  targets.build = {
700
778
  executor: 'nx:noop',
701
779
  cache: true,
780
+ // `cargo-napi` is both an output family and a serialized cargo writer, so
781
+ // the two sources overlap; the Set keeps one edge per target while holding
782
+ // the order the families are listed in.
702
783
  dependsOn: [
703
- '^build',
704
- ...BUILD_OUTPUT_DEPENDENCIES,
705
- ...hostPlatformTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
784
+ ...new Set([
785
+ '^build',
786
+ // Compiling the test executables is build work: it is unbounded and
787
+ // cacheable, while every RUNNER is a bounded-exec target reached only
788
+ // through the `test` aggregate. That split is what keeps a cold cargo
789
+ // workspace's compile time out of the bounded test window.
790
+ ...(targets[CARGO_TEST_COMPILE_TARGET] ? [CARGO_TEST_COMPILE_TARGET] : []),
791
+ ...buildOutputTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
792
+ ...cargoWriterNames,
793
+ ]),
706
794
  ],
707
795
  };
708
796
  }
@@ -914,21 +1002,27 @@ function resolveNapiConfig(
914
1002
  return { binaryName, cargoPackage, manifestPath, targets };
915
1003
  }
916
1004
 
917
- function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Record<string, TargetConfiguration> {
1005
+ function createNapiTargets(
1006
+ projectRoot: string,
1007
+ config: ResolvedNapiConfig,
1008
+ hostPlatform: NapiPlatform | null,
1009
+ ): Record<string, TargetConfiguration> {
918
1010
  const commonCommand = `--manifest-path ${config.manifestPath} --package ${config.cargoPackage}`;
919
- const hostPlatformTargetName = HOST_PLATFORM_SUFFIX === null ? null : `napi${HOST_PLATFORM_SUFFIX}`;
1011
+ const hostPlatformTargetName =
1012
+ hostPlatform === null ? null : `napi-${hostPlatform.architecture}-${hostPlatform.targetFamily}`;
920
1013
  let nativeHostTargetName: string | null = null;
921
1014
  if (hostPlatformTargetName !== null) {
922
1015
  for (const triple of config.targets) {
923
1016
  const convention = NAPI_TARGET_CONVENTIONS[triple];
924
1017
  const targetName = convention ? `napi-${convention.architecture}-${convention.targetFamily}` : null;
925
- if (targetName === hostPlatformTargetName && !convention?.useNapiCross) {
1018
+ if (targetName === hostPlatformTargetName && convention && !usesNapiCross(convention, hostPlatform)) {
926
1019
  nativeHostTargetName = targetName;
927
1020
  break;
928
1021
  }
929
1022
  }
930
1023
  }
931
1024
  const targets: Record<string, TargetConfiguration> = {};
1025
+ const hostCompilerEnv = napiCompilerEnv(hostPlatform, hostPlatform);
932
1026
 
933
1027
  // The addon the test suite loads. A dev-profile build shares target/debug
934
1028
  // with cargo-test's dependency graph, so after the tests compile this is
@@ -946,6 +1040,7 @@ function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Rec
946
1040
  options: {
947
1041
  cwd: projectRoot,
948
1042
  command: `napi build --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir .cache/native-debug`,
1043
+ ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
949
1044
  },
950
1045
  };
951
1046
 
@@ -963,13 +1058,14 @@ function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Rec
963
1058
  options: {
964
1059
  cwd: projectRoot,
965
1060
  command: `napi build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir dist/native/host`,
1061
+ ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
966
1062
  },
967
1063
  };
968
1064
  }
969
1065
 
970
1066
  for (const triple of config.targets) {
971
1067
  const convention = NAPI_TARGET_CONVENTIONS[triple];
972
- if (!convention?.useNapiCross) {
1068
+ if (!convention || !usesNapiCross(convention, hostPlatform)) {
973
1069
  continue;
974
1070
  }
975
1071
  // One toolchain target per triple, shared by every cross build that needs
@@ -994,20 +1090,22 @@ function createNapiTargets(projectRoot: string, config: ResolvedNapiConfig): Rec
994
1090
  }
995
1091
  const targetName = `napi-${convention.architecture}-${convention.targetFamily}`;
996
1092
  const outputDirectory = `dist/native/${convention.outputName}`;
997
- const crossFlag = convention.useNapiCross ? ' --use-napi-cross' : '';
1093
+ const useNapiCross = usesNapiCross(convention, hostPlatform);
1094
+ const crossFlag = useNapiCross ? ' --use-napi-cross' : '';
1095
+ const compilerEnv = napiCompilerEnv(convention, hostPlatform);
998
1096
  targets[targetName] = {
999
1097
  executor: 'nx:run-commands',
1000
1098
  cache: true,
1001
- ...(convention.useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
1099
+ ...(useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
1002
1100
  inputs: NAPI_INPUTS,
1003
1101
  outputs: [`{projectRoot}/${outputDirectory}`],
1004
1102
  options: {
1005
1103
  cwd: projectRoot,
1006
1104
  command: `napi build --release --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputDirectory}`,
1007
- // @napi-rs recognizes Clang and supplies its downloaded GNU sysroot
1008
- // and toolchain flags. This keeps sccache enabled while avoiding the
1009
- // old bundled GCC, which rejects sccache's diagnostics-color flag.
1010
- ...(convention.useNapiCross ? { env: { TARGET_CC: 'clang', TARGET_CXX: 'clang++' } } : {}),
1105
+ // Genuine Linux cross-compiles use Clang plus napi-rs's downloaded
1106
+ // GNU sysroot. A native Linux target uses Nix's cc wrapper so C build
1107
+ // scripts resolve the host libc headers instead.
1108
+ ...(compilerEnv ? { env: compilerEnv } : {}),
1011
1109
  },
1012
1110
  };
1013
1111
  }