@smoothbricks/nx-plugin 0.3.9 → 0.3.11

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 (37) hide show
  1. package/README.md +7 -0
  2. package/dist/cross-check-policy.d.ts +65 -0
  3. package/dist/cross-check-policy.d.ts.map +1 -0
  4. package/dist/cross-check-policy.js +64 -0
  5. package/dist/executors/clean-outputs/executor.js +17 -3
  6. package/dist/executors/napi-cross-toolchain/executor.d.ts +42 -0
  7. package/dist/executors/napi-cross-toolchain/executor.d.ts.map +1 -0
  8. package/dist/executors/napi-cross-toolchain/executor.js +126 -0
  9. package/dist/executors/napi-cross-toolchain/schema.d.ts +4 -0
  10. package/dist/executors/napi-cross-toolchain/schema.d.ts.map +1 -0
  11. package/dist/executors/napi-cross-toolchain/schema.js +1 -0
  12. package/dist/generators/create-package/generator.d.ts.map +1 -1
  13. package/dist/generators/create-package/generator.js +77 -5
  14. package/dist/index.d.ts +13 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +122 -12
  17. package/dist/typecheck-test-policy.d.ts.map +1 -1
  18. package/dist/typecheck-test-policy.js +22 -2
  19. package/dist/workspace-config-policy.js +14 -0
  20. package/executors.json +5 -0
  21. package/generators.json +1 -1
  22. package/package.json +6 -1
  23. package/src/cross-check-policy.test.ts +81 -0
  24. package/src/cross-check-policy.ts +70 -0
  25. package/src/executors/clean-outputs/executor.ts +17 -3
  26. package/src/executors/napi-cross-toolchain/executor.test.ts +112 -0
  27. package/src/executors/napi-cross-toolchain/executor.ts +165 -0
  28. package/src/executors/napi-cross-toolchain/schema.json +15 -0
  29. package/src/executors/napi-cross-toolchain/schema.ts +3 -0
  30. package/src/generators/create-package/generator.test.ts +49 -0
  31. package/src/generators/create-package/generator.ts +88 -6
  32. package/src/generators/create-package/schema.d.ts +2 -1
  33. package/src/generators/create-package/schema.json +7 -2
  34. package/src/index.test.ts +92 -14
  35. package/src/index.ts +136 -12
  36. package/src/typecheck-test-policy.ts +24 -2
  37. package/src/workspace-config-policy.ts +14 -0
@@ -0,0 +1,165 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { homedir } from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ import type { NapiCrossToolchainOptions } from './schema.js';
8
+
9
+ interface NapiCrossToolchainContext {
10
+ root: string;
11
+ projectName?: string;
12
+ projectsConfigurations?: {
13
+ projects: Record<string, { root?: string }>;
14
+ };
15
+ }
16
+
17
+ /** Package-name arch segment of `@napi-rs/cross-toolchain-<host>-target-<arch>`. */
18
+ const TARGET_PACKAGE_ARCH: Readonly<Record<string, string>> = {
19
+ 'aarch64-unknown-linux-gnu': 'aarch64',
20
+ 'x86_64-unknown-linux-gnu': 'x86_64',
21
+ };
22
+
23
+ const HOST_PACKAGE_ARCH: Readonly<Record<string, string>> = {
24
+ arm64: 'arm64',
25
+ x64: 'x64',
26
+ };
27
+
28
+ export type PrewarmOutcome = 'ready' | 'extracted' | 'unsupported-host';
29
+
30
+ export default async function napiCrossToolchainExecutor(
31
+ options: NapiCrossToolchainOptions,
32
+ context: NapiCrossToolchainContext,
33
+ ): Promise<{ success: boolean }> {
34
+ const projectName = context.projectName;
35
+ if (!projectName) {
36
+ throw new Error('@smoothbricks/nx-plugin:napi-cross-toolchain requires a project context.');
37
+ }
38
+ const project = context.projectsConfigurations?.projects[projectName];
39
+ if (!project) {
40
+ throw new Error(`Project ${projectName} was not found in the Nx project graph.`);
41
+ }
42
+ const projectRoot = path.resolve(context.root, project.root ?? '.');
43
+ const triple = options.triple;
44
+
45
+ console.log(`${triple}: ${prewarmCrossToolchain({ projectRoot, triple })}`);
46
+
47
+ return { success: true };
48
+ }
49
+
50
+ /**
51
+ * Extract the pinned cross toolchain into the directory
52
+ * `napi build --use-napi-cross` probes, so its own download never runs.
53
+ *
54
+ * WHY this exists: `@napi-rs/cross-toolchain@1.0.3`'s `download()` uses its own
55
+ * package directory as scratch space — `npm pack` there, unpack, then a
56
+ * non-`force` `rmSync` of the tarball. Under `linker = "isolated"` with
57
+ * `globalStore = true` that directory is the shared Bun store (in CI a
58
+ * host-wide mutable bind mount), so two concurrent `--use-napi-cross` builds of
59
+ * one triple pack the same filename into the same directory and the loser dies
60
+ * with `ENOENT ... lstat '<tarball>'`. Nx runs `cli-x64-linux` and
61
+ * `napi-x64-linux` in one wave, which is exactly that race.
62
+ *
63
+ * Extraction stages into a private sibling directory and lands with `rename`,
64
+ * so racing callers — and repeated runs after a crash — cannot corrupt the
65
+ * result: `rename` replaces an empty directory (napi itself creates one before
66
+ * probing) and fails with ENOTEMPTY against a populated one, which means
67
+ * another caller already won.
68
+ */
69
+ export function prewarmCrossToolchain(options: {
70
+ projectRoot: string;
71
+ triple: string;
72
+ platform?: string;
73
+ hostArch?: string;
74
+ home?: string;
75
+ }): PrewarmOutcome {
76
+ const { projectRoot, triple } = options;
77
+ const targetArch = TARGET_PACKAGE_ARCH[triple];
78
+ if (!targetArch) {
79
+ throw new Error(
80
+ `Unsupported --use-napi-cross triple ${triple}. Supported: ${Object.keys(TARGET_PACKAGE_ARCH).join(', ')}.`,
81
+ );
82
+ }
83
+ const hostArch = HOST_PACKAGE_ARCH[options.hostArch ?? process.arch];
84
+ // napi-rs ships these toolchains for Linux x64 and Linux arm64 hosts only,
85
+ // and refuses `--use-napi-cross` anywhere else. Extracting on a host that can
86
+ // never use the result would only demand pins nothing needs, so leave the
87
+ // unsupported-host diagnostic to the build itself.
88
+ if (!hostArch || (options.platform ?? process.platform) !== 'linux') {
89
+ return 'unsupported-host';
90
+ }
91
+
92
+ const requireFromProject = createRequire(path.join(projectRoot, 'package.json'));
93
+ const targetPackage = `@napi-rs/cross-toolchain-${hostArch}-target-${targetArch}`;
94
+ let targetModule: unknown;
95
+ try {
96
+ targetModule = requireFromProject(targetPackage);
97
+ } catch (error) {
98
+ throw new Error(
99
+ `${targetPackage} is not installed for ${projectRoot}. Add it to optionalDependencies so ${triple} ` +
100
+ 'builds extract the pinned toolchain instead of downloading into the shared Bun store.',
101
+ { cause: error },
102
+ );
103
+ }
104
+ if (
105
+ typeof targetModule !== 'object' ||
106
+ targetModule === null ||
107
+ !('toolchainPath' in targetModule) ||
108
+ typeof targetModule.toolchainPath !== 'string'
109
+ ) {
110
+ throw new Error(`${targetPackage} no longer exports a toolchainPath string.`);
111
+ }
112
+ const tarball = targetModule.toolchainPath;
113
+
114
+ const home = options.home ?? homedir();
115
+ const destination = path.join(home, '.napi-rs', 'cross-toolchain', crossToolchainVersion(requireFromProject), triple);
116
+ const marker = path.join(destination, 'package.json');
117
+ if (existsSync(marker)) {
118
+ return 'ready';
119
+ }
120
+
121
+ mkdirSync(path.dirname(destination), { recursive: true });
122
+ const staging = mkdtempSync(`${destination}.staging-`);
123
+ const command = `tar -xJf ${tarball} -C ${staging}`;
124
+ try {
125
+ execFileSync('tar', ['-xJf', tarball, '-C', staging], { stdio: 'inherit' });
126
+ if (!existsSync(path.join(staging, 'package.json'))) {
127
+ throw new Error(
128
+ `${tarball} did not contain the package.json marker napi probes; the toolchain archive layout changed.`,
129
+ );
130
+ }
131
+ renameSync(staging, destination);
132
+ } catch (error) {
133
+ rmSync(staging, { force: true, recursive: true });
134
+ const code = error instanceof Error && 'code' in error ? error.code : undefined;
135
+ if ((code === 'ENOTEMPTY' || code === 'EEXIST') && existsSync(marker)) {
136
+ return 'ready';
137
+ }
138
+ const status = error instanceof Error && 'status' in error ? error.status : undefined;
139
+ if (status !== undefined) {
140
+ if (error instanceof Error) {
141
+ console.error(error.message);
142
+ }
143
+ throw new Error(`${command} failed with exit code ${typeof status === 'number' ? status : 1}`, { cause: error });
144
+ }
145
+ throw error;
146
+ }
147
+ return 'extracted';
148
+ }
149
+
150
+ /**
151
+ * `napi` derives the extraction directory from `@napi-rs/cross-toolchain`'s own
152
+ * version, so read it from the package the CLI resolves — not from the
153
+ * per-target package, whose version only happens to match today.
154
+ */
155
+ function crossToolchainVersion(requireFromProject: NodeJS.Require): string {
156
+ const cliRequire = createRequire(requireFromProject.resolve('@napi-rs/cli/package.json'));
157
+ const indexPath = cliRequire.resolve('@napi-rs/cross-toolchain');
158
+ const manifest: unknown = JSON.parse(readFileSync(path.join(path.dirname(indexPath), 'package.json'), 'utf-8'));
159
+ const version =
160
+ typeof manifest === 'object' && manifest !== null && 'version' in manifest ? manifest.version : undefined;
161
+ if (typeof version !== 'string' || version.length === 0) {
162
+ throw new Error(`@napi-rs/cross-toolchain resolved at ${indexPath} has no version.`);
163
+ }
164
+ return version;
165
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "$schema": "https://json-schema.org/schema",
3
+ "version": 2,
4
+ "title": "N-API Cross Toolchain Executor",
5
+ "description": "Extract the pinned @napi-rs cross toolchain into ~/.napi-rs so `napi build --use-napi-cross` never downloads it.",
6
+ "type": "object",
7
+ "properties": {
8
+ "triple": {
9
+ "type": "string",
10
+ "description": "Rust target triple to prepare, e.g. x86_64-unknown-linux-gnu."
11
+ }
12
+ },
13
+ "required": ["triple"],
14
+ "additionalProperties": false
15
+ }
@@ -0,0 +1,3 @@
1
+ export interface NapiCrossToolchainOptions {
2
+ triple: string;
3
+ }
@@ -13,6 +13,7 @@ function setupTree(rootName = '@smoothbricks/codebase'): Tree {
13
13
  name: rootName,
14
14
  version: '0.0.0',
15
15
  private: true,
16
+ license: 'MIT',
16
17
  repository: { type: 'git', url: 'git+https://github.com/smoothbricks/codebase.git' },
17
18
  workspaces: ['packages/*'],
18
19
  },
@@ -124,6 +125,54 @@ describe('create-package generator', () => {
124
125
  });
125
126
  });
126
127
 
128
+ describe('rust-crate variant', () => {
129
+ it('creates a Cargo workspace whose generic targets are inferred by the plugin', async () => {
130
+ const tree = setupTree();
131
+ await generator(tree, { name: 'ferris', variant: 'rust-crate' });
132
+
133
+ const pkg = readJson(tree, 'packages/ferris/package.json');
134
+ expect(pkg).toEqual({
135
+ name: '@smoothbricks/ferris',
136
+ version: '0.0.0',
137
+ private: true,
138
+ scripts: { test: 'nx run ferris:test --outputStyle=stream' },
139
+ nx: { name: 'ferris' },
140
+ });
141
+
142
+ const workspace = tree.read('packages/ferris/Cargo.toml', 'utf-8');
143
+ expect(workspace).toContain('[workspace]');
144
+ expect(workspace).toContain('members = ["crates/ferris"]');
145
+ expect(workspace).toContain('edition = "2024"');
146
+ expect(workspace).toContain('license = "MIT"');
147
+ expect(workspace).toContain('repository = "git+https://github.com/smoothbricks/codebase.git"');
148
+
149
+ const crate = tree.read('packages/ferris/crates/ferris/Cargo.toml', 'utf-8');
150
+ expect(crate).toContain('[package]');
151
+ expect(crate).toContain('name = "ferris"');
152
+ expect(crate).toContain('version.workspace = true');
153
+ expect(tree.read('packages/ferris/crates/ferris/src/lib.rs', 'utf-8')).toBe('#![forbid(unsafe_code)]\n');
154
+ expect(tree.exists('packages/ferris/tsconfig.json')).toBe(false);
155
+ });
156
+
157
+ it('declares tool-native wasm metadata for cross-platform output inference', async () => {
158
+ const tree = setupTree();
159
+ await generator(tree, { name: 'ferris', variant: 'rust-crate', wasm: true });
160
+
161
+ const crate = tree.read('packages/ferris/crates/ferris/Cargo.toml', 'utf-8');
162
+ expect(crate).toContain('crate-type = ["cdylib", "rlib"]');
163
+ expect(crate).toContain('[package.metadata.smoothbricks.wasm-bindgen]');
164
+ expect(crate).toContain('targets = ["web", "nodejs"]');
165
+ expect(crate).toContain('out-dir = "dist-wasm"');
166
+ });
167
+
168
+ it('refuses npm publication flags on Cargo packages', async () => {
169
+ const tree = setupTree();
170
+ await expect(generator(tree, { name: 'ferris', variant: 'rust-crate', public: true })).rejects.toThrow(
171
+ 'rust-crate does not use npm publication metadata',
172
+ );
173
+ });
174
+ });
175
+
127
176
  it('rejects existing package', async () => {
128
177
  const tree = setupTree();
129
178
  tree.write('packages/existing/package.json', '{}');
@@ -1,11 +1,11 @@
1
- // Scaffold a new TypeScript workspace package. Invoked by `smoo g ts-lib <name>`.
1
+ // Scaffold TypeScript libraries and Rust workspaces through one convention-owned generator.
2
2
  // CLI wiring: packages/cli/src/generate/index.ts (variant registry)
3
3
  import { readJson, type Tree, writeJson } from 'nx/src/devkit-exports.js';
4
4
 
5
5
  import type { CreatePackageGeneratorSchema } from './schema.js';
6
6
 
7
7
  export default async function generator(tree: Tree, schema: CreatePackageGeneratorSchema): Promise<void> {
8
- const rootPkg = readJson<{ name?: string; repository?: unknown }>(tree, 'package.json');
8
+ const rootPkg = readJson<{ name?: string; license?: string; repository?: unknown }>(tree, 'package.json');
9
9
  const scope = extractScope(rootPkg.name);
10
10
  const packageName = scope ? `${scope}/${schema.name}` : schema.name;
11
11
  const projectRoot = `packages/${schema.name}`;
@@ -13,8 +13,15 @@ export default async function generator(tree: Tree, schema: CreatePackageGenerat
13
13
  if (tree.exists(`${projectRoot}/package.json`)) {
14
14
  throw new Error(`Package already exists at ${projectRoot}`);
15
15
  }
16
+ if (schema.variant === 'ts-lib' && schema.wasm) {
17
+ throw new Error('wasm output metadata is only available for rust-crate');
18
+ }
16
19
 
17
- writeCommonFiles(tree, schema, packageName, projectRoot, rootPkg);
20
+ if (schema.variant === 'rust-crate') {
21
+ writeRustFiles(tree, schema, packageName, projectRoot, rootPkg);
22
+ } else {
23
+ writeTypeScriptFiles(tree, schema, packageName, projectRoot, rootPkg);
24
+ }
18
25
  }
19
26
 
20
27
  function extractScope(name: string | undefined): string | null {
@@ -23,14 +30,14 @@ function extractScope(name: string | undefined): string | null {
23
30
  return match?.[1] ?? null;
24
31
  }
25
32
 
26
- function writeCommonFiles(
33
+ function writeTypeScriptFiles(
27
34
  tree: Tree,
28
35
  schema: CreatePackageGeneratorSchema,
29
36
  packageName: string,
30
37
  projectRoot: string,
31
38
  rootPkg: { name?: string; repository?: unknown },
32
39
  ): void {
33
- const packageJson = buildPackageJson(schema, packageName, projectRoot, rootPkg);
40
+ const packageJson = buildTypeScriptPackageJson(schema, packageName, projectRoot, rootPkg);
34
41
  writeJson(tree, `${projectRoot}/package.json`, packageJson);
35
42
 
36
43
  writeJson(tree, `${projectRoot}/tsconfig.json`, {
@@ -82,7 +89,7 @@ function writeCommonFiles(
82
89
  tree.write(`${projectRoot}/src/index.ts`, '');
83
90
  }
84
91
 
85
- function buildPackageJson(
92
+ function buildTypeScriptPackageJson(
86
93
  schema: CreatePackageGeneratorSchema,
87
94
  packageName: string,
88
95
  projectRoot: string,
@@ -154,6 +161,81 @@ function buildPackageJson(
154
161
 
155
162
  return packageJson;
156
163
  }
164
+
165
+ function writeRustFiles(
166
+ tree: Tree,
167
+ schema: CreatePackageGeneratorSchema,
168
+ packageName: string,
169
+ projectRoot: string,
170
+ rootPkg: { license?: string; repository?: unknown },
171
+ ): void {
172
+ if (schema.public) {
173
+ throw new Error('rust-crate does not use npm publication metadata; publish Rust crates through Cargo policy');
174
+ }
175
+
176
+ const crateName = schema.name;
177
+ const crateRoot = `${projectRoot}/crates/${crateName}`;
178
+ writeJson(tree, `${projectRoot}/package.json`, {
179
+ name: packageName,
180
+ version: '0.0.0',
181
+ private: true,
182
+ scripts: {
183
+ test: `nx run ${schema.name}:test --outputStyle=stream`,
184
+ },
185
+ nx: {
186
+ name: schema.name,
187
+ },
188
+ });
189
+
190
+ const repository = repositoryUrl(rootPkg.repository);
191
+ const workspacePackage = [
192
+ '[workspace]',
193
+ 'resolver = "3"',
194
+ `members = ["crates/${crateName}"]`,
195
+ '',
196
+ '[workspace.package]',
197
+ 'version = "0.0.0"',
198
+ 'edition = "2024"',
199
+ `license = ${JSON.stringify(rootPkg.license ?? 'UNLICENSED')}`,
200
+ 'publish = false',
201
+ ...(repository === null ? [] : [`repository = ${JSON.stringify(repository)}`]),
202
+ '',
203
+ ];
204
+ tree.write(`${projectRoot}/Cargo.toml`, workspacePackage.join('\n'));
205
+
206
+ const crateManifest = [
207
+ '[package]',
208
+ `name = ${JSON.stringify(crateName)}`,
209
+ 'version.workspace = true',
210
+ 'edition.workspace = true',
211
+ 'license.workspace = true',
212
+ 'publish.workspace = true',
213
+ ...(schema.wasm
214
+ ? [
215
+ '',
216
+ '[lib]',
217
+ 'crate-type = ["cdylib", "rlib"]',
218
+ '',
219
+ '[package.metadata.smoothbricks.wasm-bindgen]',
220
+ 'targets = ["web", "nodejs"]',
221
+ 'out-dir = "dist-wasm"',
222
+ ]
223
+ : []),
224
+ '',
225
+ ];
226
+ tree.write(`${crateRoot}/Cargo.toml`, crateManifest.join('\n'));
227
+ tree.write(`${crateRoot}/src/lib.rs`, '#![forbid(unsafe_code)]\n');
228
+ }
229
+
230
+ function repositoryUrl(repository: unknown): string | null {
231
+ if (typeof repository === 'string') {
232
+ return repository;
233
+ }
234
+ if (!isRecord(repository)) {
235
+ return null;
236
+ }
237
+ return typeof repository.url === 'string' ? repository.url : null;
238
+ }
157
239
  function isRecord(value: unknown): value is Record<string, unknown> {
158
240
  return value !== null && typeof value === 'object' && !Array.isArray(value);
159
241
  }
@@ -1,5 +1,6 @@
1
1
  export interface CreatePackageGeneratorSchema {
2
2
  name: string;
3
- variant: 'ts-lib';
3
+ variant: 'ts-lib' | 'rust-crate';
4
4
  public?: boolean;
5
+ wasm?: boolean;
5
6
  }
@@ -11,12 +11,17 @@
11
11
  "variant": {
12
12
  "type": "string",
13
13
  "description": "Package variant to scaffold.",
14
- "enum": ["ts-lib"],
14
+ "enum": ["ts-lib", "rust-crate"],
15
15
  "default": "ts-lib"
16
16
  },
17
17
  "public": {
18
18
  "type": "boolean",
19
- "description": "Configure for npm publication (license, publishConfig, npm:public tag).",
19
+ "description": "Configure a TypeScript package for npm publication (license, publishConfig, npm:public tag).",
20
+ "default": false
21
+ },
22
+ "wasm": {
23
+ "type": "boolean",
24
+ "description": "For rust-crate, scaffold wasm-bindgen metadata for web and Node.js output families.",
20
25
  "default": false
21
26
  }
22
27
  },
package/src/index.test.ts CHANGED
@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os';
4
4
  import { dirname, join } from 'node:path';
5
5
 
6
6
  import type { CreateNodesContextV2, TargetConfiguration } from 'nx/src/devkit-exports.js';
7
+ import { CARGO_CROSS_LINT_TARGET } from './cross-check-policy.js';
7
8
  import { createNodesV2 } from './index.js';
8
9
  import { BUILD_OUTPUT_DEPENDENCIES } from './workspace-config-policy.js';
9
10
 
@@ -249,7 +250,15 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
249
250
 
250
251
  // Even a cdylib crate named *-wasm infers no cargo-wasm: rust output
251
252
  // targets are declared package-locally, never derived from crate metadata.
252
- expect(Object.keys(targets).sort()).toEqual(['bench', 'cargo-lint', 'cargo-test', 'lint', 'mutation', 'test']);
253
+ expect(Object.keys(targets).sort()).toEqual([
254
+ 'bench',
255
+ 'cargo-lint',
256
+ 'cargo-lint-cross',
257
+ 'cargo-test',
258
+ 'lint',
259
+ 'mutation',
260
+ 'test',
261
+ ]);
253
262
  expect(targets['cargo-test']?.executor).toBe('@smoothbricks/nx-plugin:bounded-exec');
254
263
  expect(targets['cargo-test']?.options).toMatchObject({
255
264
  command: 'cargo test --workspace',
@@ -268,6 +277,15 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
268
277
  commands: ['cargo fmt --all --check', 'cargo clippy --workspace --all-targets -- -D warnings'],
269
278
  });
270
279
  expect(targets.lint?.dependsOn).toEqual(['cargo-lint']);
280
+ expect(targets[CARGO_CROSS_LINT_TARGET]?.options).toMatchObject({
281
+ command: 'cargo clippy --workspace --all-targets --target x86_64-unknown-linux-gnu -- -D warnings',
282
+ cwd: 'packages/ferris',
283
+ });
284
+ expect(targets[CARGO_CROSS_LINT_TARGET]?.cache).toBe(true);
285
+ // The cross gate must never join the lint aggregate: `bun run lint`, and
286
+ // CI's own already-native Linux lint, would then require the opt-in 0.4 GiB
287
+ // cross toolchain to run at all.
288
+ expect(targets.lint?.dependsOn).not.toContain(CARGO_CROSS_LINT_TARGET);
271
289
  expect(targets.test?.executor).toBe('@smoothbricks/nx-plugin:bounded-exec');
272
290
  expect(targets.test?.options).toMatchObject({
273
291
  command: 'cargo test --workspace',
@@ -351,6 +369,12 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
351
369
  JSON.stringify({
352
370
  name: 'cowshed',
353
371
  scripts: { test: 'nx run cowshed:test --outputStyle=stream' },
372
+ nx: {
373
+ targets: {
374
+ 'cli-arm64-macos': { executor: 'nx:run-commands', options: { command: 'true' } },
375
+ 'cli-x64-linux': { executor: 'nx:run-commands', options: { command: 'true' } },
376
+ },
377
+ },
354
378
  napi: {
355
379
  binaryName: 'cowshed',
356
380
  targets: [
@@ -377,35 +401,89 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
377
401
 
378
402
  expect(targets['cargo-wasm']).toBeUndefined();
379
403
  expect(targets['tsc-js']?.outputs).toEqual(['{projectRoot}/dist/ts']);
380
- expect(targets['cargo-napi']).toMatchObject({
381
- executor: 'nx:run-commands',
382
- cache: true,
383
- dependsOn: ['^build'],
384
- outputs: ['{projectRoot}/dist/native/host'],
385
- options: {
386
- cwd: 'packages/cowshed',
387
- command:
388
- 'napi build --release --platform --no-js --dts cowshed.napi.d.ts --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --output-dir dist/native/host',
389
- },
390
- });
404
+ // Match the production host suffix so both native-platform and dedicated
405
+ // cargo-napi host-provider regimes are covered on every runner.
406
+ const hostOs = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : null;
407
+ const hostArch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : null;
408
+ const hostSuffix = hostOs !== null && hostArch !== null ? `-${hostArch}-${hostOs}` : null;
409
+ const hostPlatformNapiTarget = hostSuffix === null ? null : `napi${hostSuffix}`;
410
+ const nativeHostProvider = hostPlatformNapiTarget?.endsWith('-macos') ? hostPlatformNapiTarget : null;
411
+ const hostProvider = nativeHostProvider ?? 'cargo-napi';
412
+ const hostProviders = ['cargo-napi', nativeHostProvider].filter(
413
+ (name): name is string => name !== null && targets[name] !== undefined,
414
+ );
415
+ expect(hostProviders).toHaveLength(1);
416
+ expect(hostProviders[0]).toBe(hostProvider);
417
+ if (hostProvider === 'cargo-napi') {
418
+ expect(targets['cargo-napi']).toMatchObject({
419
+ executor: 'nx:run-commands',
420
+ cache: true,
421
+ dependsOn: ['^build'],
422
+ outputs: ['{projectRoot}/dist/native/host'],
423
+ options: {
424
+ cwd: 'packages/cowshed',
425
+ command:
426
+ 'napi build --release --platform --no-js --dts cowshed.napi.d.ts --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --output-dir dist/native/host',
427
+ },
428
+ });
429
+ } else {
430
+ expect(targets['cargo-napi']).toBeUndefined();
431
+ }
391
432
  expect(targets['napi-arm64-macos']?.outputs).toEqual(['{projectRoot}/dist/native/darwin-arm64']);
392
433
  expect(targets['napi-arm64-macos']?.options).toMatchObject({
393
434
  command:
394
435
  'napi build --release --platform --no-js --dts cowshed.darwin-arm64.d.ts --target aarch64-apple-darwin --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --output-dir dist/native/darwin-arm64',
395
436
  });
396
437
  expect(targets['napi-arm64-macos']?.options?.env).toBeUndefined();
438
+ expect(targets['napi-arm64-macos']?.dependsOn).toBeUndefined();
439
+ expect(targets['napi-toolchain-arm64-linux']).toEqual({
440
+ executor: '@smoothbricks/nx-plugin:napi-cross-toolchain',
441
+ cache: false,
442
+ options: { triple: 'aarch64-unknown-linux-gnu' },
443
+ });
444
+ expect(targets['napi-toolchain-x64-linux']).toEqual({
445
+ executor: '@smoothbricks/nx-plugin:napi-cross-toolchain',
446
+ cache: false,
447
+ options: { triple: 'x86_64-unknown-linux-gnu' },
448
+ });
449
+ expect(targets['napi-x64-linux']?.dependsOn).toEqual(['napi-toolchain-x64-linux']);
450
+ expect(targets['napi-arm64-linux']?.dependsOn).toEqual(['napi-toolchain-arm64-linux']);
451
+ expect(targets['napi-toolchain-x64-macos']).toBeUndefined();
397
452
  expect(targets['napi-x64-linux']?.outputs).toEqual(['{projectRoot}/dist/native/linux-x64-gnu']);
398
453
  expect(targets['napi-x64-linux']?.options).toMatchObject({
399
454
  command:
400
455
  'napi build --release --platform --no-js --dts cowshed.linux-x64-gnu.d.ts --target x86_64-unknown-linux-gnu --use-napi-cross --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --output-dir dist/native/linux-x64-gnu',
401
456
  env: { TARGET_CC: 'clang', TARGET_CXX: 'clang++' },
402
457
  });
403
- expect(targets.build?.dependsOn).toEqual(buildOutputDependencies);
458
+ // The aggregate build pulls in exactly the HOST's platform-suffixed
459
+ // targets (publish still owns foreign platforms).
460
+ const hostNapiTargets = [
461
+ 'cli-arm64-macos',
462
+ 'cli-x64-linux',
463
+ 'napi-arm64-macos',
464
+ 'napi-x64-macos',
465
+ 'napi-arm64-linux',
466
+ 'napi-x64-linux',
467
+ ]
468
+ .filter((name) => hostSuffix !== null && name.endsWith(hostSuffix))
469
+ .sort();
470
+ expect(targets.build?.dependsOn).toEqual([...buildOutputDependencies, ...hostNapiTargets]);
471
+ const platformBuildDependencies = (targets.build?.dependsOn ?? []).filter(
472
+ (dependency): dependency is string =>
473
+ typeof dependency === 'string' && /-(?:arm64|x64)-(?:macos|linux)$/.test(dependency),
474
+ );
475
+ if (hostSuffix !== null) {
476
+ for (const name of platformBuildDependencies) {
477
+ expect(name.endsWith(hostSuffix)).toBe(true);
478
+ }
479
+ } else {
480
+ expect(platformBuildDependencies).toEqual([]);
481
+ }
404
482
  expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
405
483
  expect(targets['napi-test']).toMatchObject({
406
484
  executor: '@smoothbricks/nx-plugin:bounded-exec',
407
485
  cache: true,
408
- dependsOn: ['cargo-test', 'cargo-napi', 'tsc-js', '^build', 'build'],
486
+ dependsOn: ['cargo-test', hostProvider, 'tsc-js', '^build', 'build'],
409
487
  options: {
410
488
  command: 'bun test --config=../bunfig.toml --timeout=30000 native.test.ts',
411
489
  cwd: 'packages/cowshed/src',