@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/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { parse as parseToml } from 'smol-toml';
8
8
  import { BOUNDED_TEST_KILL_AFTER_MS, BOUNDED_TEST_TIMEOUT_MS } from './bounded-test-policy.js';
9
9
  import { CARGO_TEST_COMPILE_TARGET, CARGO_TEST_EXCEPTIONS_SUFFIX, CARGO_TEST_TARGET, cargoPackageTestInputs, cargoTestPackageTargetName, exceptionalTestFilter, listCargoWorkspacePackages, nextestConfigRelPath, } from './cargo-workspace.js';
10
10
  import { CARGO_CROSS_LINT_COMMAND, CARGO_CROSS_LINT_TARGET, CARGO_FETCH_COMMAND, CARGO_FETCH_TARGET, CARGO_FROZEN_PREFIX, CARGO_LINT_CLIPPY_COMMAND, cargoFrozen, } from './cross-check-policy.js';
11
- import { BUILD_OUTPUT_DEPENDENCIES, PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
11
+ import { PLATFORM_TARGET_GLOBS } from './workspace-config-policy.js';
12
12
  export { CARGO_TEST_COMPILE_TARGET };
13
13
  const BUILD_OUTPUT_TARGET_PATTERN = /-(?:js|web|html|css|android|native|napi|bun|wasm)$/;
14
14
  const TYPESCRIPT_TOOLCHAIN_INPUTS = [
@@ -17,26 +17,42 @@ const TYPESCRIPT_TOOLCHAIN_INPUTS = [
17
17
  '{workspaceRoot}/patches/**/*',
18
18
  '{workspaceRoot}/tsconfig.base.json',
19
19
  ];
20
- // The aggregate `build` pulls in platform-suffixed binary targets for THIS
21
- // machine only: `<tool>-<arch>-<os>` names matching the host (for example
22
- // cli-arm64-macos on Apple Silicon) build locally as part of `nx build`, while
23
- // every foreign platform stays publish-workflow-only. nx.json targetDefaults
24
- // cannot express "current platform" — its dependsOn lists are static — so the
25
- // inference plugin owns this edge.
26
- const HOST_PLATFORM_SUFFIX = (() => {
27
- const os = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : null;
28
- const arch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : null;
29
- return os !== null && arch !== null ? `-${arch}-${os}` : null;
30
- })();
31
- export function hostPlatformTargetNames(targetNames) {
32
- if (HOST_PLATFORM_SUFFIX === null)
20
+ function napiPlatform(platform, architecture) {
21
+ const targetFamily = platform === 'darwin' ? 'macos' : platform === 'linux' ? 'linux' : null;
22
+ const targetArchitecture = architecture === 'arm64' ? 'arm64' : architecture === 'x64' ? 'x64' : null;
23
+ return targetFamily !== null && targetArchitecture !== null
24
+ ? { architecture: targetArchitecture, targetFamily }
25
+ : null;
26
+ }
27
+ function sameNapiPlatform(left, right) {
28
+ return left.architecture === right?.architecture && left.targetFamily === right.targetFamily;
29
+ }
30
+ function hostPlatformTargetNames(targetNames, hostPlatform) {
31
+ if (hostPlatform === null)
33
32
  return [];
33
+ const suffix = `-${hostPlatform.architecture}-${hostPlatform.targetFamily}`;
34
34
  return [...new Set(targetNames)]
35
35
  .filter(
36
36
  // Binary targets only. A toolchain prerequisite carries the same platform
37
37
  // suffix but produces no artifact: the cross builds that need it depend
38
38
  // on it directly, so the aggregate stays a list of outputs.
39
- (name) => name.endsWith(HOST_PLATFORM_SUFFIX) && !name.startsWith(NAPI_TOOLCHAIN_TARGET_PREFIX))
39
+ (name) => name.endsWith(suffix) && !name.startsWith(NAPI_TOOLCHAIN_TARGET_PREFIX))
40
+ .sort();
41
+ }
42
+ /**
43
+ * The reserved suffixes name targets that EMIT an artifact, and the `build`
44
+ * aggregate is a list of those. Handing Nx the raw `*-<family>` globs let it
45
+ * match on suffix alone, and one namespace collides by construction: a
46
+ * per-crate cargo test runner is named `cargo-test-<crate>`, so any crate whose
47
+ * name ends in an output family — `*-napi`, `*-wasm`, `*-native`, `*-js` — put
48
+ * its RUNNER in the aggregate. The runners are one serialized chain, so a
49
+ * single such crate made `build` pull an entire cargo test suite. Expanding the
50
+ * families here instead of delegating to Nx's matcher keeps the plugin's own
51
+ * `cargo-test-` namespace out of the aggregate however a crate is named.
52
+ */
53
+ function buildOutputTargetNames(targetNames) {
54
+ return [...new Set(targetNames)]
55
+ .filter((name) => BUILD_OUTPUT_TARGET_PATTERN.test(name) && !name.startsWith(`${CARGO_TEST_TARGET}-`))
40
56
  .sort();
41
57
  }
42
58
  //#region smoo!n/rust-output-target-inference
@@ -66,27 +82,33 @@ const NAPI_TARGET_CONVENTIONS = {
66
82
  architecture: 'arm64',
67
83
  outputName: 'darwin-arm64',
68
84
  targetFamily: 'macos',
69
- useNapiCross: false,
70
85
  },
71
86
  'x86_64-apple-darwin': {
72
87
  architecture: 'x64',
73
88
  outputName: 'darwin-x64',
74
89
  targetFamily: 'macos',
75
- useNapiCross: false,
76
90
  },
77
91
  'aarch64-unknown-linux-gnu': {
78
92
  architecture: 'arm64',
79
93
  outputName: 'linux-arm64-gnu',
80
94
  targetFamily: 'linux',
81
- useNapiCross: true,
82
95
  },
83
96
  'x86_64-unknown-linux-gnu': {
84
97
  architecture: 'x64',
85
98
  outputName: 'linux-x64-gnu',
86
99
  targetFamily: 'linux',
87
- useNapiCross: true,
88
100
  },
89
101
  };
102
+ const NATIVE_LINUX_COMPILER_ENV = Object.freeze({ CC: 'cc', CXX: 'c++' });
103
+ const CROSS_LINUX_COMPILER_ENV = Object.freeze({ TARGET_CC: 'clang', TARGET_CXX: 'clang++' });
104
+ function usesNapiCross(target, hostPlatform) {
105
+ return target.targetFamily === 'linux' && !sameNapiPlatform(target, hostPlatform);
106
+ }
107
+ function napiCompilerEnv(target, hostPlatform) {
108
+ if (target?.targetFamily !== 'linux')
109
+ return undefined;
110
+ return sameNapiPlatform(target, hostPlatform) ? NATIVE_LINUX_COMPILER_ENV : CROSS_LINUX_COMPILER_ENV;
111
+ }
90
112
  const NAPI_TOOLCHAIN_TARGET_PREFIX = 'napi-toolchain-';
91
113
  /**
92
114
  * Prerequisite target that extracts the cross toolchain one triple needs. The
@@ -235,9 +257,8 @@ async function addPerPackageCargoTestTargets(targets, projectRoot, workspaceRoot
235
257
  }
236
258
  return packageTargetNames;
237
259
  }
238
- export const createNodesV2 = [
239
- '**/package.json',
240
- async (projectConfigurationFiles, _options, context) => {
260
+ function createNodesHandler(hostPlatform) {
261
+ return async (projectConfigurationFiles, _options, context) => {
241
262
  const results = [];
242
263
  const errors = [];
243
264
  await Promise.all(projectConfigurationFiles.map(async (packageJsonPath) => {
@@ -248,7 +269,10 @@ export const createNodesV2 = [
248
269
  results.push([packageJsonPath, {}]);
249
270
  return;
250
271
  }
251
- results.push([packageJsonPath, await createProjectTargets(packageJsonPath, context.workspaceRoot)]);
272
+ results.push([
273
+ packageJsonPath,
274
+ await createProjectTargets(packageJsonPath, context.workspaceRoot, hostPlatform),
275
+ ]);
252
276
  }
253
277
  catch (error) {
254
278
  errors.push([packageJsonPath, error instanceof Error ? error : new Error(String(error))]);
@@ -258,14 +282,21 @@ export const createNodesV2 = [
258
282
  throw new AggregateCreateNodesError(errors, results);
259
283
  }
260
284
  return results;
261
- },
285
+ };
286
+ }
287
+ export function createNodesV2ForPlatform(platform, architecture) {
288
+ return ['**/package.json', createNodesHandler(napiPlatform(platform, architecture))];
289
+ }
290
+ export const createNodesV2 = [
291
+ '**/package.json',
292
+ (...args) => createNodesHandler(napiPlatform(process.platform, process.arch))(...args),
262
293
  ];
263
294
  function isManagedPackageJsonSource(packageJsonPath) {
264
295
  const normalized = packageJsonPath.replaceAll('\\', '/');
265
296
  return normalized.includes('/managed/raw/') || normalized.includes('/managed/templates/');
266
297
  }
267
298
  export default { createNodesV2 };
268
- async function createProjectTargets(packageJsonPath, workspaceRoot) {
299
+ async function createProjectTargets(packageJsonPath, workspaceRoot, hostPlatform) {
269
300
  const projectRoot = dirname(packageJsonPath);
270
301
  const absoluteProjectRoot = join(workspaceRoot, projectRoot);
271
302
  const packageJson = await readPackageJson(join(workspaceRoot, packageJsonPath));
@@ -355,7 +386,7 @@ async function createProjectTargets(packageJsonPath, workspaceRoot) {
355
386
  targets['cargo-wasm'] = createCargoWasmTarget(projectRoot, cargoWasmConfig);
356
387
  }
357
388
  if (napiConfig) {
358
- Object.assign(targets, createNapiTargets(projectRoot, napiConfig));
389
+ Object.assign(targets, createNapiTargets(projectRoot, napiConfig, hostPlatform));
359
390
  if (!('napi-test' in (packageJson.nx?.targets ?? {})) &&
360
391
  existsSync(join(absoluteProjectRoot, 'src/native.test.ts'))) {
361
392
  targets['napi-test'] = createNapiTestTarget(projectRoot, existsSync(join(absoluteProjectRoot, 'bunfig.napi-test.toml')));
@@ -584,6 +615,33 @@ async function createProjectTargets(packageJsonPath, workspaceRoot) {
584
615
  }
585
616
  }
586
617
  }
618
+ // `build` lists cargo-test-compile beside the host's platform binaries, and
619
+ // every one of those is a `napi build` — another cargo writer on the package's
620
+ // default `target/`, which cargo flocks.
621
+ //
622
+ // Only `cargo-napi` gets the ordering edge. A platform-suffixed target may NOT
623
+ // have one: `validatePlatformTargetDependencies` (package-target-policy.ts:674)
624
+ // walks each platform target's dependency closure and refuses any member of a
625
+ // different family, because the publish flow builds and collects one platform
626
+ // at a time — a `*-macos` collect that reached a familyless sibling would drag
627
+ // in work the macOS runner has no business doing. `cargo-napi` carries no
628
+ // platform suffix, so it is not scanned and the edge is legal there.
629
+ //
630
+ // The platform binaries therefore stay Nx siblings of cargo-test-compile and
631
+ // serialize on cargo's flock instead of on a graph edge. That is the same
632
+ // arrangement `cli-<arch>-<os>` and `napi-<arch>-<os>` already have with each
633
+ // other — both `napi build --release` on one target dir — so this adds a third
634
+ // participant to an existing wait, not a new hazard. The flock makes them wait;
635
+ // it does not corrupt anything, and these are unbounded `nx:run-commands`
636
+ // targets, so the wait is not charged against a test budget.
637
+ const cargoWriterNames = hostPlatformTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)], hostPlatform);
638
+ const cargoNapi = targets['cargo-napi'];
639
+ if (cargoNapi && targets[CARGO_TEST_COMPILE_TARGET]) {
640
+ const dependsOn = cargoNapi.dependsOn ?? [];
641
+ if (!dependsOn.includes(CARGO_TEST_COMPILE_TARGET)) {
642
+ cargoNapi.dependsOn = [...dependsOn, CARGO_TEST_COMPILE_TARGET];
643
+ }
644
+ }
587
645
  // No `outputs`, deliberately: this aggregate runs no command, so every file
588
646
  // under dist belongs to the concrete target that emitted it. Claiming
589
647
  // `{projectRoot}/dist` here would cache the children's bytes a second time
@@ -598,10 +656,20 @@ async function createProjectTargets(packageJsonPath, workspaceRoot) {
598
656
  targets.build = {
599
657
  executor: 'nx:noop',
600
658
  cache: true,
659
+ // `cargo-napi` is both an output family and a serialized cargo writer, so
660
+ // the two sources overlap; the Set keeps one edge per target while holding
661
+ // the order the families are listed in.
601
662
  dependsOn: [
602
- '^build',
603
- ...BUILD_OUTPUT_DEPENDENCIES,
604
- ...hostPlatformTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
663
+ ...new Set([
664
+ '^build',
665
+ // Compiling the test executables is build work: it is unbounded and
666
+ // cacheable, while every RUNNER is a bounded-exec target reached only
667
+ // through the `test` aggregate. That split is what keeps a cold cargo
668
+ // workspace's compile time out of the bounded test window.
669
+ ...(targets[CARGO_TEST_COMPILE_TARGET] ? [CARGO_TEST_COMPILE_TARGET] : []),
670
+ ...buildOutputTargetNames([...Object.keys(declaredTargets), ...Object.keys(targets)]),
671
+ ...cargoWriterNames,
672
+ ]),
605
673
  ],
606
674
  };
607
675
  }
@@ -762,21 +830,22 @@ function resolveNapiConfig(packageJson, packageJsonPath, absoluteProjectRoot, is
762
830
  }
763
831
  return { binaryName, cargoPackage, manifestPath, targets };
764
832
  }
765
- function createNapiTargets(projectRoot, config) {
833
+ function createNapiTargets(projectRoot, config, hostPlatform) {
766
834
  const commonCommand = `--manifest-path ${config.manifestPath} --package ${config.cargoPackage}`;
767
- const hostPlatformTargetName = HOST_PLATFORM_SUFFIX === null ? null : `napi${HOST_PLATFORM_SUFFIX}`;
835
+ const hostPlatformTargetName = hostPlatform === null ? null : `napi-${hostPlatform.architecture}-${hostPlatform.targetFamily}`;
768
836
  let nativeHostTargetName = null;
769
837
  if (hostPlatformTargetName !== null) {
770
838
  for (const triple of config.targets) {
771
839
  const convention = NAPI_TARGET_CONVENTIONS[triple];
772
840
  const targetName = convention ? `napi-${convention.architecture}-${convention.targetFamily}` : null;
773
- if (targetName === hostPlatformTargetName && !convention?.useNapiCross) {
841
+ if (targetName === hostPlatformTargetName && convention && !usesNapiCross(convention, hostPlatform)) {
774
842
  nativeHostTargetName = targetName;
775
843
  break;
776
844
  }
777
845
  }
778
846
  }
779
847
  const targets = {};
848
+ const hostCompilerEnv = napiCompilerEnv(hostPlatform, hostPlatform);
780
849
  // The addon the test suite loads. A dev-profile build shares target/debug
781
850
  // with cargo-test's dependency graph, so after the tests compile this is
782
851
  // nearly free — where the release platform build it replaces cost minutes
@@ -793,6 +862,7 @@ function createNapiTargets(projectRoot, config) {
793
862
  options: {
794
863
  cwd: projectRoot,
795
864
  command: `napi build --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir .cache/native-debug`,
865
+ ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
796
866
  },
797
867
  };
798
868
  if (nativeHostTargetName === null) {
@@ -809,12 +879,13 @@ function createNapiTargets(projectRoot, config) {
809
879
  options: {
810
880
  cwd: projectRoot,
811
881
  command: `napi build --release --platform --no-js --dts ${config.binaryName}.napi.d.ts ${commonCommand} --output-dir dist/native/host`,
882
+ ...(hostCompilerEnv ? { env: hostCompilerEnv } : {}),
812
883
  },
813
884
  };
814
885
  }
815
886
  for (const triple of config.targets) {
816
887
  const convention = NAPI_TARGET_CONVENTIONS[triple];
817
- if (!convention?.useNapiCross) {
888
+ if (!convention || !usesNapiCross(convention, hostPlatform)) {
818
889
  continue;
819
890
  }
820
891
  // One toolchain target per triple, shared by every cross build that needs
@@ -838,20 +909,22 @@ function createNapiTargets(projectRoot, config) {
838
909
  }
839
910
  const targetName = `napi-${convention.architecture}-${convention.targetFamily}`;
840
911
  const outputDirectory = `dist/native/${convention.outputName}`;
841
- const crossFlag = convention.useNapiCross ? ' --use-napi-cross' : '';
912
+ const useNapiCross = usesNapiCross(convention, hostPlatform);
913
+ const crossFlag = useNapiCross ? ' --use-napi-cross' : '';
914
+ const compilerEnv = napiCompilerEnv(convention, hostPlatform);
842
915
  targets[targetName] = {
843
916
  executor: 'nx:run-commands',
844
917
  cache: true,
845
- ...(convention.useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
918
+ ...(useNapiCross ? { dependsOn: [napiToolchainTargetName(convention)] } : {}),
846
919
  inputs: NAPI_INPUTS,
847
920
  outputs: [`{projectRoot}/${outputDirectory}`],
848
921
  options: {
849
922
  cwd: projectRoot,
850
923
  command: `napi build --release --platform --no-js --dts ${config.binaryName}.${convention.outputName}.d.ts --target ${triple}${crossFlag} ${commonCommand} --output-dir ${outputDirectory}`,
851
- // @napi-rs recognizes Clang and supplies its downloaded GNU sysroot
852
- // and toolchain flags. This keeps sccache enabled while avoiding the
853
- // old bundled GCC, which rejects sccache's diagnostics-color flag.
854
- ...(convention.useNapiCross ? { env: { TARGET_CC: 'clang', TARGET_CXX: 'clang++' } } : {}),
924
+ // Genuine Linux cross-compiles use Clang plus napi-rs's downloaded
925
+ // GNU sysroot. A native Linux target uses Nix's cc wrapper so C build
926
+ // scripts resolve the host libc headers instead.
927
+ ...(compilerEnv ? { env: compilerEnv } : {}),
855
928
  },
856
929
  };
857
930
  }
package/nextest.toml CHANGED
@@ -37,6 +37,43 @@ slow-timeout = { period = "180s", terminate-after = 1 }
37
37
  [test-groups]
38
38
  real-apfs = { max-threads = 1 }
39
39
 
40
+ # The full-lifecycle real-APFS tests cannot meet the default deadline, and
41
+ # `specs/cowshed/08_testing.md` already contains the arithmetic that proves it.
42
+ #
43
+ # That spec sets the house rule for real-substrate timing: "CI asserts with a 3×
44
+ # multiplier to absorb runner noise". `apfs_integration.rs` measured its lifecycle
45
+ # at 14.8s (Sparse) and 10.6s (Asif) on an IDLE host, so under the repo's own noise
46
+ # model CI needs 44.4s and 31.8s. A 30s deadline was therefore unreachable by
47
+ # construction: the test was not slow, the bound contradicted the spec.
48
+ #
49
+ # Nor is the cost reducible. The same spec's "Attach floor verdict: not
50
+ # flag-reducible" records that `-noverify` saves ~15ms (noise), `-noautofsck`
51
+ # nothing, and `diskutil image attach` exposes no equivalent knobs — the ~235-400ms
52
+ # per attach is inherent to DiskImages + APFS mount + DiskArbitration, and halving
53
+ # it would need DiskImages2 or the diskarbitrationd private API, which the spec
54
+ # explicitly forbids budgets from assuming. The lifecycle attaches once per phase
55
+ # across adopt, mount, clone-under-churn, checkpoint, restore, retire, reclaim, GC
56
+ # and detach, so its floor is a multiple of an irreducible constant.
57
+ #
58
+ # The alternative was splitting the lifecycle into phase-scoped tests so each fits
59
+ # 30s. It loses: every split pays that attach constant again, so the suite's total
60
+ # wall time rises to buy a smaller per-test bound. Splitting Sparse from Asif was
61
+ # worth it because it bought failure ATTRIBUTION; splitting phases buys only a
62
+ # number.
63
+ #
64
+ # 60s is 3× the worst idle measurement (44.4s) rounded up, not a guess. It stays
65
+ # bounded because an unbounded run phase is how a hung test becomes a hung lane.
66
+ # Re-derive it if the idle measurements in `apfs_integration.rs` change.
67
+ #
68
+ # Membership is by name and narrower than the group: the fast `real_apfs_*` unit
69
+ # tests in the lib keep the 30s default — they passed at 4.4s and 7.3s and have no
70
+ # claim on more. This override precedes the group-only one so it wins the
71
+ # first-match for both keys it sets.
72
+ [[profile.default.overrides]]
73
+ filter = 'test(/real_apfs_.*_substrate_lifecycle/)'
74
+ slow-timeout = { period = "60s", terminate-after = 1 }
75
+ test-group = 'real-apfs'
76
+
40
77
  [[profile.default.overrides]]
41
78
  filter = 'test(/real_apfs_/)'
42
79
  test-group = 'real-apfs'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smoothbricks/nx-plugin",
3
- "version": "0.3.12",
3
+ "version": "0.3.14",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "main": "./loader.js",
@@ -43,12 +43,20 @@
43
43
  "import": "./dist/typecheck-test-policy.js",
44
44
  "default": "./dist/typecheck-test-policy.js"
45
45
  },
46
+ "./ensure-built": {
47
+ "types": "./dist/ensure-built.d.ts",
48
+ "import": "./dist/ensure-built.js",
49
+ "default": "./dist/ensure-built.js"
50
+ },
46
51
  "./cross-check-policy": {
47
52
  "types": "./dist/cross-check-policy.d.ts",
48
53
  "import": "./dist/cross-check-policy.js",
49
54
  "default": "./dist/cross-check-policy.js"
50
55
  }
51
56
  },
57
+ "bin": {
58
+ "smoothbricks-ensure-built": "./dist/bin/ensure-built.js"
59
+ },
52
60
  "generators": "./generators.json",
53
61
  "executors": "./executors.json",
54
62
  "scripts": {
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+
5
+ import { describeMiss, ensureBuilt, parseTargetSelector } from '../ensure-built.js';
6
+
7
+ const USAGE =
8
+ 'usage: smoothbricks-ensure-built <project:target[:configuration]> [--workspace-root <dir>] -- <binary> [args...]';
9
+
10
+ /** Argument and environment problems all exit 2, the shell's "usage" code. */
11
+ function usageError(message: string): never {
12
+ process.stderr.write(`smoothbricks-ensure-built: ${message}\n${USAGE}\n`);
13
+ process.exit(2);
14
+ }
15
+
16
+ /**
17
+ * Split `--flag=value` into two tokens so both spellings parse identically.
18
+ * Only leading `--` forms are split: a value may legitimately contain `=`.
19
+ */
20
+ function tokenize(args: readonly string[]): string[] {
21
+ const tokens: string[] = [];
22
+ for (const arg of args) {
23
+ const equals = arg.startsWith('--') ? arg.indexOf('=') : -1;
24
+ if (equals === -1) {
25
+ tokens.push(arg);
26
+ } else {
27
+ tokens.push(arg.slice(0, equals), arg.slice(equals + 1));
28
+ }
29
+ }
30
+ return tokens;
31
+ }
32
+
33
+ function findWorkspaceRoot(from: string): string {
34
+ let directory = from;
35
+ for (;;) {
36
+ if (existsSync(join(directory, 'nx.json'))) {
37
+ return directory;
38
+ }
39
+ const parent = dirname(directory);
40
+ if (parent === directory) {
41
+ return usageError(`no nx.json at or above ${from}; pass --workspace-root`);
42
+ }
43
+ directory = parent;
44
+ }
45
+ }
46
+
47
+ const argv = process.argv.slice(2);
48
+ const separator = argv.indexOf('--');
49
+ if (separator === -1) {
50
+ usageError('missing `--` before the binary to exec');
51
+ }
52
+ const command = argv.slice(separator + 1);
53
+ if (command.length === 0) {
54
+ usageError('no binary given after `--`');
55
+ }
56
+
57
+ let target: string | undefined;
58
+ let workspaceRootArg: string | undefined;
59
+ const tokens = tokenize(argv.slice(0, separator));
60
+ for (let index = 0; index < tokens.length; index += 1) {
61
+ const token = tokens[index];
62
+ if (token === '--workspace-root') {
63
+ index += 1;
64
+ workspaceRootArg = tokens[index] ?? usageError('--workspace-root needs a directory');
65
+ } else if (token.startsWith('-')) {
66
+ usageError(`unknown flag ${token}`);
67
+ } else if (target !== undefined) {
68
+ usageError(`more than one target given: ${target} and ${token}`);
69
+ } else {
70
+ target = token;
71
+ }
72
+ }
73
+ if (target === undefined) {
74
+ usageError('no project:target given');
75
+ }
76
+ if (parseTargetSelector(target) === null) {
77
+ usageError(`'${target}' is not a project:target[:configuration] selector`);
78
+ }
79
+
80
+ // `execve` does no PATH lookup, so a bare name would fail as a missing file in
81
+ // the current directory. Say which mistake was made instead.
82
+ if (!command[0].includes('/')) {
83
+ usageError(`'${command[0]}' must be a path to the binary, not a name to look up on PATH`);
84
+ }
85
+ // Resolved against the directory the user is standing in, not the workspace
86
+ // root: this is their command line, and the exec'd process inherits their cwd.
87
+ const binary = isAbsolute(command[0]) ? command[0] : resolve(process.cwd(), command[0]);
88
+
89
+ const workspaceRoot =
90
+ workspaceRootArg === undefined ? findWorkspaceRoot(process.cwd()) : resolve(process.cwd(), workspaceRootArg);
91
+
92
+ const result = await ensureBuilt({ target, cwd: workspaceRoot }).catch((error: unknown) => {
93
+ process.stderr.write(`smoothbricks-ensure-built: ${error instanceof Error ? error.message : String(error)}\n`);
94
+ process.exit(1);
95
+ });
96
+
97
+ if (result.disposition !== 'hit' && process.env.NX_VERBOSE_LOGGING === 'true') {
98
+ process.stderr.write(`smoothbricks-ensure-built: ran ${target} because ${describeMiss(result.reason)}\n`);
99
+ }
100
+ if (result.disposition === 'failed') {
101
+ if (result.signal !== null) {
102
+ // Re-raise rather than translate, so a build killed by SIGINT leaves this
103
+ // process looking killed by SIGINT to whatever is watching it.
104
+ process.kill(process.pid, result.signal);
105
+ }
106
+ process.exit(result.exitCode);
107
+ }
108
+
109
+ if (process.execve === undefined) {
110
+ throw new Error('smoothbricks-ensure-built needs process.execve, which requires a POSIX host on Node 24+ or Bun');
111
+ }
112
+ // `execve`, not spawn-and-wait: the built binary replaces this process, so it
113
+ // owns the terminal, the signals and the exit status directly, with no wrapper
114
+ // left behind to forward them.
115
+ process.execve(binary, [binary, ...command.slice(1)], process.env);