@smoothbricks/nx-plugin 0.3.14 → 0.4.1

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 (38) hide show
  1. package/README.md +36 -13
  2. package/dist/bin/smoo-nx-exec.d.ts +3 -0
  3. package/dist/bin/smoo-nx-exec.d.ts.map +1 -0
  4. package/dist/bin/{ensure-built.js → smoo-nx-exec.js} +17 -5
  5. package/dist/bounded-test-policy.d.ts.map +1 -1
  6. package/dist/bounded-test-policy.js +5 -2
  7. package/dist/cargo-workspace.d.ts +15 -1
  8. package/dist/cargo-workspace.d.ts.map +1 -1
  9. package/dist/cargo-workspace.js +113 -8
  10. package/dist/ensure-built.d.ts +3 -0
  11. package/dist/ensure-built.d.ts.map +1 -1
  12. package/dist/ensure-built.js +21 -1
  13. package/dist/executors/typescript-emit/executor.d.ts.map +1 -1
  14. package/dist/executors/typescript-emit/executor.js +20 -2
  15. package/dist/executors/typescript-emit/schema.d.ts +1 -0
  16. package/dist/executors/typescript-emit/schema.d.ts.map +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +345 -88
  19. package/dist/package-target-policy.d.ts.map +1 -1
  20. package/dist/package-target-policy.js +2 -1
  21. package/package.json +4 -4
  22. package/src/bin/{ensure-built.ts → smoo-nx-exec.ts} +18 -6
  23. package/src/bounded-test-policy.test.ts +21 -0
  24. package/src/bounded-test-policy.ts +6 -2
  25. package/src/cargo-workspace.test.ts +142 -0
  26. package/src/cargo-workspace.ts +137 -8
  27. package/src/ensure-built.test.ts +121 -21
  28. package/src/ensure-built.ts +23 -1
  29. package/src/executors/typescript-emit/executor.test.ts +37 -1
  30. package/src/executors/typescript-emit/executor.ts +24 -2
  31. package/src/executors/typescript-emit/schema.json +8 -0
  32. package/src/executors/typescript-emit/schema.ts +1 -0
  33. package/src/index.test.ts +177 -10
  34. package/src/index.ts +436 -90
  35. package/src/package-target-policy.test.ts +13 -0
  36. package/src/package-target-policy.ts +2 -1
  37. package/dist/bin/ensure-built.d.ts +0 -3
  38. package/dist/bin/ensure-built.d.ts.map +0 -1
@@ -123,6 +123,7 @@ describe('describeMiss', () => {
123
123
  describeMiss({ kind: 'not-cached', taskId: 'app:build' }),
124
124
  describeMiss({ kind: 'cached-failure', taskId: 'app:build', code: 7 }),
125
125
  describeMiss({ kind: 'stale-outputs', taskId: 'app:build' }),
126
+ describeMiss({ kind: 'cache-disabled', taskId: 'app:build' }),
126
127
  describeMiss({ kind: 'no-daemon', taskId: 'app:build' }),
127
128
  ];
128
129
  for (const reason of reasons) {
@@ -164,11 +165,21 @@ describe('cliExitOutcome', () => {
164
165
 
165
166
  const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
166
167
  const repoRoot = dirname(dirname(packageRoot));
167
- const binEntry = join(packageRoot, 'src', 'bin', 'ensure-built.ts');
168
- const builtBinEntry = join(packageRoot, 'dist', 'bin', 'ensure-built.js');
168
+ const binEntry = join(packageRoot, 'src', 'bin', 'smoo-nx-exec.ts');
169
+ const builtBinEntry = join(packageRoot, 'dist', 'bin', 'smoo-nx-exec.js');
169
170
  const MARKER = 'EXEC_OK';
170
- /** Nx configures itself through these; the exec'd binary must not inherit them. */
171
- const LEAKABLE = ['NX_WORKSPACE_ROOT_PATH', 'NX_STREAM_OUTPUT', 'NX_PREFIX_OUTPUT', 'NX_LOAD_DOT_ENV_FILES'];
171
+ /** Nx keys controlled and reported by the fixture rather than inherited from its parent test task. */
172
+ const NX_ENV_KEYS = [
173
+ 'NX_WORKSPACE_ROOT_PATH',
174
+ 'NX_STREAM_OUTPUT',
175
+ 'NX_PREFIX_OUTPUT',
176
+ 'NX_LOAD_DOT_ENV_FILES',
177
+ 'NX_SKIP_NX_CACHE',
178
+ 'NX_DISABLE_NX_CACHE',
179
+ 'NX_CACHE_DIRECTORY',
180
+ 'NX_WORKSPACE_DATA_DIRECTORY',
181
+ ];
182
+ const SHARED_NX_DIRECTORY_KEYS = ['NX_CACHE_DIRECTORY', 'NX_WORKSPACE_DATA_DIRECTORY'] as const;
172
183
 
173
184
  interface BinRun {
174
185
  readonly code: number | null;
@@ -177,6 +188,33 @@ interface BinRun {
177
188
  readonly stderr: string;
178
189
  }
179
190
 
191
+ function fixtureNxEnvironment(env: Readonly<NodeJS.ProcessEnv> = {}): NodeJS.ProcessEnv {
192
+ const childEnv = { ...process.env };
193
+ for (const key of NX_ENV_KEYS) {
194
+ delete childEnv[key];
195
+ }
196
+ // The parent Nx process may set FORCE_COLOR while the shell exports
197
+ // NO_COLOR. Passing both to Bun emits a warning, which would make a genuine
198
+ // full hit look noisy.
199
+ delete childEnv.NO_COLOR;
200
+ childEnv.CI = '';
201
+ childEnv.NX_DAEMON = 'true';
202
+ for (const [key, value] of Object.entries(env)) {
203
+ if (value === undefined) {
204
+ delete childEnv[key];
205
+ } else {
206
+ childEnv[key] = value;
207
+ }
208
+ }
209
+ // CI shares these directories among the outer Nx tasks. A fixture Nx using
210
+ // either one can replace the orchestrator's project graph while sibling
211
+ // tasks are still running.
212
+ for (const key of SHARED_NX_DIRECTORY_KEYS) {
213
+ delete childEnv[key];
214
+ }
215
+ return childEnv;
216
+ }
217
+
180
218
  /**
181
219
  * The bin is exercised in a child process rather than by calling `ensureBuilt`
182
220
  * directly, for two reasons that are not incidental: Nx binds its workspace
@@ -189,17 +227,9 @@ function runBinWith(
189
227
  entry: string,
190
228
  workspace: string,
191
229
  args: readonly string[],
192
- env: Record<string, string>,
230
+ env: Readonly<NodeJS.ProcessEnv>,
193
231
  ): Promise<BinRun> {
194
- const childEnv = { ...process.env };
195
- for (const key of LEAKABLE) {
196
- delete childEnv[key];
197
- }
198
- // The parent Nx process may set FORCE_COLOR while the shell exports
199
- // NO_COLOR. Passing both to Bun emits a warning, which would make a genuine
200
- // full hit look noisy.
201
- delete childEnv.NO_COLOR;
202
- Object.assign(childEnv, { CI: '', NX_DAEMON: 'true' }, env);
232
+ const childEnv = fixtureNxEnvironment(env);
203
233
  const child = spawn(runtime, [entry, ...args], {
204
234
  cwd: workspace,
205
235
  env: childEnv,
@@ -221,7 +251,7 @@ function runBinWith(
221
251
  });
222
252
  }
223
253
 
224
- function runBin(workspace: string, args: readonly string[], env: Record<string, string> = {}): Promise<BinRun> {
254
+ function runBin(workspace: string, args: readonly string[], env: Readonly<NodeJS.ProcessEnv> = {}): Promise<BinRun> {
225
255
  return runBinWith('bun', binEntry, workspace, args, env);
226
256
  }
227
257
 
@@ -232,7 +262,7 @@ function runBuiltBin(workspace: string, args: readonly string[]): Promise<BinRun
232
262
  function nx(workspace: string, args: readonly string[]): Promise<number | null> {
233
263
  const child = spawn(join(repoRoot, 'node_modules', '.bin', 'nx'), [...args], {
234
264
  cwd: workspace,
235
- env: { ...process.env, CI: '', NX_DAEMON: 'true', NX_WORKSPACE_ROOT_PATH: workspace },
265
+ env: fixtureNxEnvironment({ NX_WORKSPACE_ROOT_PATH: workspace }),
236
266
  stdio: 'ignore',
237
267
  });
238
268
  return new Promise((settle, reject) => {
@@ -241,7 +271,7 @@ function nx(workspace: string, args: readonly string[]): Promise<number | null>
241
271
  });
242
272
  }
243
273
 
244
- describe('smoothbricks-ensure-built', () => {
274
+ describe('smoo-nx-exec', () => {
245
275
  let workspace = '';
246
276
  const report = () => join(workspace, 'report');
247
277
  const marker = () => join(workspace, 'packages', 'app', 'dist', 'marker.txt');
@@ -302,10 +332,10 @@ describe('smoothbricks-ensure-built', () => {
302
332
  await writeFile(join(workspace, 'packages', 'app', 'source.txt'), 'built\n');
303
333
  // Reports what the exec'd process actually inherited: the marker proves
304
334
  // execve happened, the cwd proves it kept the caller's directory, and the
305
- // NX_ lines prove Nx's process-global configuration did not leak into it.
335
+ // NX_ lines prove temporary Nx configuration was removed or restored.
306
336
  await writeFile(
307
337
  report(),
308
- `#!/bin/sh\necho ${MARKER} "$@"\necho "cwd=$PWD"\n${LEAKABLE.map((key) => `echo "${key}=\${${key}:-unset}"`).join('\n')}\n`,
338
+ `#!/bin/sh\necho ${MARKER} "$@"\necho "cwd=$PWD"\n${NX_ENV_KEYS.map((key) => `echo "${key}=\${${key}:-unset}"`).join('\n')}\n`,
309
339
  );
310
340
  await chmod(report(), 0o755);
311
341
  });
@@ -353,11 +383,45 @@ describe('smoothbricks-ensure-built', () => {
353
383
  ]);
354
384
  expect(run.code).toBe(0);
355
385
  expect(run.stdout).toContain(`cwd=${join(workspace, 'packages', 'app')}`);
356
- for (const key of LEAKABLE) {
386
+ for (const key of NX_ENV_KEYS) {
357
387
  expect(run.stdout).toContain(`${key}=unset`);
358
388
  }
359
389
  });
360
390
 
391
+ it('keeps fixture Nx out of CI shared state directories', async () => {
392
+ const run = await runBin(workspace, ['app:build', '--', './report'], {
393
+ NX_CACHE_DIRECTORY: join(workspace, 'shared-cache'),
394
+ NX_WORKSPACE_DATA_DIRECTORY: join(workspace, 'shared-workspace-data'),
395
+ });
396
+ expect(run.code).toBe(0);
397
+ expect(run.stdout).toContain('NX_CACHE_DIRECTORY=unset');
398
+ expect(run.stdout).toContain('NX_WORKSPACE_DATA_DIRECTORY=unset');
399
+ });
400
+
401
+ it('restores the caller cache controls before exec', async () => {
402
+ const run = await runBin(workspace, ['app:build', '--', './report'], {
403
+ NX_SKIP_NX_CACHE: 'caller-skip',
404
+ NX_DISABLE_NX_CACHE: 'caller-disable',
405
+ });
406
+ expect(run.code).toBe(0);
407
+ expect(run.stderr).toBe('');
408
+ expect(run.stdout).toContain('NX_SKIP_NX_CACHE=caller-skip');
409
+ expect(run.stdout).toContain('NX_DISABLE_NX_CACHE=caller-disable');
410
+ });
411
+
412
+ it('honors a user cache bypass outside an Nx task child', async () => {
413
+ const run = await runBin(workspace, ['app:build', '--', './report'], {
414
+ NX_TASK_TARGET_PROJECT: undefined,
415
+ NX_TASK_TARGET_TARGET: undefined,
416
+ NX_SKIP_NX_CACHE: 'true',
417
+ NX_VERBOSE_LOGGING: 'true',
418
+ });
419
+ expect(run.code).toBe(0);
420
+ expect(run.stderr).toContain('the Nx cache is disabled, so app:build must run');
421
+ expect(run.stdout).toContain(MARKER);
422
+ expect(run.stdout).toContain('NX_SKIP_NX_CACHE=true');
423
+ });
424
+
361
425
  it('runs again once a recorded output is gone from the working tree', async () => {
362
426
  await rm(marker());
363
427
  const run = await runBin(workspace, ['app:build', '--', './report'], { NX_VERBOSE_LOGGING: 'true' });
@@ -397,6 +461,42 @@ describe('smoothbricks-ensure-built', () => {
397
461
  expect(run.stdout).toContain(MARKER);
398
462
  });
399
463
 
464
+ it('prints the message from a plain-object Nx rejection', async () => {
465
+ const rejectingWorkspace = await realpath(await mkdtemp(join(tmpdir(), 'ensure-built-rejection-')));
466
+ try {
467
+ await mkdir(join(rejectingWorkspace, 'node_modules', 'nx', 'src', 'daemon', 'client'), { recursive: true });
468
+ await mkdir(join(rejectingWorkspace, 'node_modules', 'nx', 'src', 'utils'), { recursive: true });
469
+ await writeFile(join(rejectingWorkspace, 'package.json'), '{}');
470
+ await writeFile(join(rejectingWorkspace, 'nx.json'), '{}');
471
+ await writeFile(
472
+ join(rejectingWorkspace, 'node_modules', 'nx', 'package.json'),
473
+ JSON.stringify({ name: 'nx', type: 'commonjs' }),
474
+ );
475
+ await writeFile(
476
+ join(rejectingWorkspace, 'node_modules', 'nx', 'src', 'utils', 'workspace-root.js'),
477
+ 'exports.workspaceRoot = process.env.NX_WORKSPACE_ROOT_PATH;\n',
478
+ );
479
+ await writeFile(
480
+ join(rejectingWorkspace, 'node_modules', 'nx', 'src', 'daemon', 'client', 'client.js'),
481
+ [
482
+ 'exports.daemonClient = {',
483
+ ' enabled() {',
484
+ " throw { stack: 'synthetic stack', message: 'daemon belongs to a different workspace' };",
485
+ ' },',
486
+ '};',
487
+ '',
488
+ ].join('\n'),
489
+ );
490
+
491
+ const run = await runBin(rejectingWorkspace, ['app:build', '--', './never-runs']);
492
+ expect(run.code).toBe(1);
493
+ expect(run.stderr).toContain('daemon belongs to a different workspace');
494
+ expect(run.stderr).not.toContain('[object Object]');
495
+ } finally {
496
+ await rm(rejectingWorkspace, { recursive: true, force: true });
497
+ }
498
+ });
499
+
400
500
  it('rejects a malformed invocation with a usage error', async () => {
401
501
  const missingSeparator = await runBin(workspace, ['app:build']);
402
502
  expect(missingSeparator.code).toBe(2);
@@ -412,7 +512,7 @@ describe('smoothbricks-ensure-built', () => {
412
512
  });
413
513
  });
414
514
 
415
- describe('smoothbricks-ensure-built signal forwarding', () => {
515
+ describe('smoo-nx-exec signal forwarding', () => {
416
516
  let workspace = '';
417
517
 
418
518
  // A workspace whose `nx` is a script that kills itself. The daemon-disabled
@@ -66,6 +66,7 @@ export type MissReason =
66
66
  | { readonly kind: 'not-cached'; readonly taskId: string }
67
67
  | { readonly kind: 'cached-failure'; readonly taskId: string; readonly code: number }
68
68
  | { readonly kind: 'stale-outputs'; readonly taskId: string }
69
+ | { readonly kind: 'cache-disabled'; readonly taskId: string }
69
70
  | { readonly kind: 'no-daemon'; readonly taskId: string };
70
71
 
71
72
  /**
@@ -140,6 +141,8 @@ export function describeMiss(reason: MissReason): string {
140
141
  return `${reason.taskId} last failed with exit code ${reason.code}`;
141
142
  case 'stale-outputs':
142
143
  return `${reason.taskId} outputs are missing or modified on disk`;
144
+ case 'cache-disabled':
145
+ return `the Nx cache is disabled, so ${reason.taskId} must run`;
143
146
  case 'no-daemon':
144
147
  return `the Nx daemon is disabled, so ${reason.taskId} cannot be checked without running it`;
145
148
  }
@@ -268,6 +271,16 @@ async function ensureBuiltInWorkspace(
268
271
  return runViaCli(workspaceRoot, selector);
269
272
  }
270
273
 
274
+ // An outer Nx task exports its own cache-bypass setting to the process it
275
+ // launches. That setting describes the outer task, not the nested target:
276
+ // inheriting it makes the inner runner refuse cache writes forever. Outside
277
+ // an Nx task child, however, the same variables are the caller's explicit
278
+ // request to force this target to rebuild and must remain authoritative.
279
+ if (process.env.NX_TASK_TARGET_PROJECT !== undefined || process.env.NX_TASK_TARGET_TARGET !== undefined) {
280
+ delete process.env.NX_SKIP_NX_CACHE;
281
+ delete process.env.NX_DISABLE_NX_CACHE;
282
+ }
283
+
271
284
  const { readNxJson } = requireNx('nx/src/config/nx-json');
272
285
  const { splitArgsIntoNxArgsAndOverrides } = requireNx('nx/src/utils/command-line-utils');
273
286
  const { setEnvVarsBasedOnArgs } = requireNx('nx/src/tasks-runner/run-command');
@@ -304,7 +317,16 @@ async function ensureBuiltInWorkspace(
304
317
  });
305
318
 
306
319
  performance.mark('ensureBuilt:probe:start');
307
- const reason = await probe(nxJson, nxArgs, overrides, selector, requireNx);
320
+ let reason: MissReason | null;
321
+ if (process.env.NX_SKIP_NX_CACHE === 'true' || process.env.NX_DISABLE_NX_CACHE === 'true') {
322
+ const taskId =
323
+ selector.configuration === undefined
324
+ ? `${selector.project}:${selector.target}`
325
+ : `${selector.project}:${selector.target}:${selector.configuration}`;
326
+ reason = { kind: 'cache-disabled', taskId };
327
+ } else {
328
+ reason = await probe(nxJson, nxArgs, overrides, selector, requireNx);
329
+ }
308
330
  performance.measure('ensureBuilt:probe', 'ensureBuilt:probe:start');
309
331
  const outcome =
310
332
  reason === null
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, it } from 'bun:test';
2
2
  import { existsSync } from 'node:fs';
3
- import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { join } from 'node:path';
6
6
 
@@ -69,6 +69,42 @@ describe('@smoothbricks/nx-plugin TypeScript emit executor', () => {
69
69
  }
70
70
  });
71
71
 
72
+ it('makes emitted package bins executable before declaration emit', async () => {
73
+ const root = await mkdtemp(join(tmpdir(), 'smoo-typescript-emit-bin-'));
74
+ const projectRoot = join(root, 'packages/example');
75
+ const emittedBin = join(projectRoot, 'dist/bin/example.js');
76
+ await mkdir(projectRoot, { recursive: true });
77
+ await writeFile(join(projectRoot, 'tsconfig.lib.json'), '{}\n');
78
+
79
+ let executableBeforeDeclarations = false;
80
+ try {
81
+ const result = await runTypeScriptEmit(
82
+ {
83
+ cwd: 'packages/example',
84
+ executableOutputs: ['./dist/bin/example.js'],
85
+ tsConfig: 'tsconfig.lib.json',
86
+ },
87
+ { root },
88
+ async (invocation) => {
89
+ if (invocation.command === 'ttsc') {
90
+ await mkdir(join(projectRoot, 'dist/bin'), { recursive: true });
91
+ await writeFile(emittedBin, '#!/usr/bin/env node\n');
92
+ await chmod(emittedBin, 0o644);
93
+ } else {
94
+ executableBeforeDeclarations = ((await stat(emittedBin)).mode & 0o111) === 0o111;
95
+ }
96
+ return true;
97
+ },
98
+ );
99
+
100
+ expect(result).toEqual({ success: true });
101
+ expect(executableBeforeDeclarations).toBe(true);
102
+ expect((await stat(emittedBin)).mode & 0o111).toBe(0o111);
103
+ } finally {
104
+ await rm(root, { recursive: true, force: true });
105
+ }
106
+ });
107
+
72
108
  it('does not emit declarations when transformed JavaScript fails and still removes its overlay', async () => {
73
109
  const root = await mkdtemp(join(tmpdir(), 'smoo-typescript-emit-'));
74
110
  const projectRoot = join(root, 'packages/example');
@@ -1,8 +1,8 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { once } from 'node:events';
4
- import { rm, writeFile } from 'node:fs/promises';
5
- import { basename, dirname, isAbsolute, join } from 'node:path';
4
+ import { chmod, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
6
 
7
7
  import { readJsonFile } from 'nx/src/devkit-exports.js';
8
8
 
@@ -67,6 +67,8 @@ export async function runTypeScriptEmit(
67
67
  return { success: false };
68
68
  }
69
69
 
70
+ await makePackageBinsExecutable(cwd, options.executableOutputs ?? []);
71
+
70
72
  const declarationsSucceeded = await runner({
71
73
  command: 'tsc',
72
74
  args: ['-p', overlayPath, '--emitDeclarationOnly', '--declaration', '--declarationMap'],
@@ -78,6 +80,26 @@ export async function runTypeScriptEmit(
78
80
  }
79
81
  }
80
82
 
83
+ async function makePackageBinsExecutable(cwd: string, outputs: readonly string[]): Promise<void> {
84
+ for (const output of new Set(outputs)) {
85
+ const outputPath = resolve(cwd, output);
86
+ const projectRelative = relative(cwd, outputPath);
87
+ if (
88
+ projectRelative.length === 0 ||
89
+ projectRelative === '..' ||
90
+ projectRelative.startsWith(`..${sep}`) ||
91
+ isAbsolute(projectRelative)
92
+ ) {
93
+ throw new Error(`Executable output must stay inside the project: ${output}`);
94
+ }
95
+ const outputStat = await stat(outputPath);
96
+ // TypeScript creates emitted files with the process default mode. A package
97
+ // bin that loses its execute bits is present but unusable through
98
+ // node_modules/.bin, so restore the semantic guarantee declared by `bin`.
99
+ await chmod(outputPath, outputStat.mode | 0o111);
100
+ }
101
+ }
102
+
81
103
  async function runCompiler(invocation: CompilerInvocation): Promise<boolean> {
82
104
  const child = spawn(invocation.command, invocation.args, {
83
105
  cwd: invocation.cwd,
@@ -5,6 +5,14 @@
5
5
  "description": "Emit transformer-generated JavaScript with ttsc and declarations with native tsc",
6
6
  "type": "object",
7
7
  "properties": {
8
+ "executableOutputs": {
9
+ "type": "array",
10
+ "description": "Package bin outputs to make executable after JavaScript emit",
11
+ "items": {
12
+ "type": "string"
13
+ },
14
+ "uniqueItems": true
15
+ },
8
16
  "cwd": {
9
17
  "type": "string",
10
18
  "description": "Working directory, relative to the workspace root"
@@ -1,4 +1,5 @@
1
1
  export interface TypeScriptEmitOptions {
2
+ executableOutputs?: string[];
2
3
  cwd: string;
3
4
  tsConfig: string;
4
5
  }
package/src/index.test.ts CHANGED
@@ -62,12 +62,40 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
62
62
  }
63
63
  });
64
64
 
65
+ it('never infers a project from a package.json a build wrote', async () => {
66
+ const workspace = await createWorkspace();
67
+ try {
68
+ await workspace.write('packages/cowshed/package.json', '{"name":"cowshed","private":true}\n');
69
+ // napi's platform build, a dist tree, cargo's target dir, a package cache: every
70
+ // one of these is written by a task, and a graph recomputed while it is being
71
+ // written must not see a second `cowshed` and drop the real one.
72
+ const outputs = [
73
+ 'packages/cowshed/.cache/native-debug/package.json',
74
+ 'packages/cowshed/dist/npm/linux-x64-gnu/package.json',
75
+ 'packages/cowshed/target/debug/build/x/out/package.json',
76
+ 'packages/cowshed/node_modules/dep/package.json',
77
+ ];
78
+ for (const path of outputs) {
79
+ await workspace.write(path, '{"name":"cowshed","private":true}\n');
80
+ }
81
+
82
+ const inferred = await inferTargets(outputs, undefined, workspace.context);
83
+ for (const [, result] of inferred) {
84
+ expect(result).toEqual({});
85
+ }
86
+ const live = await inferProject(workspace, 'packages/cowshed/package.json');
87
+ expect(live?.name).toBe('cowshed');
88
+ } finally {
89
+ await workspace.cleanup();
90
+ }
91
+ });
92
+
65
93
  it('splits transformed JavaScript emit from native declarations and typechecking', async () => {
66
94
  const workspace = await createWorkspace();
67
95
  try {
68
96
  await workspace.write(
69
97
  'packages/example/package.json',
70
- '{"name":"example","scripts":{"test":"bun test --pass-with-no-tests"}}\n',
98
+ '{"name":"example","bin":{"example":"./dist/bin/example.js"},"scripts":{"test":"bun test --pass-with-no-tests"}}\n',
71
99
  );
72
100
  await workspace.write('packages/example/tsconfig.lib.json', '{}\n');
73
101
  await workspace.write('packages/example/tsconfig.test.json', '{}\n');
@@ -76,6 +104,7 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
76
104
 
77
105
  expect(targets['tsc-js']?.executor).toBe('@smoothbricks/nx-plugin:typescript-emit');
78
106
  expect(targets['tsc-js']?.options).toEqual({
107
+ executableOutputs: ['./dist/bin/example.js'],
79
108
  tsConfig: 'tsconfig.lib.json',
80
109
  cwd: 'packages/example',
81
110
  });
@@ -305,9 +334,10 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
305
334
  expect(targets['cargo-test-ferris-wasm']?.dependsOn).toEqual(['cargo-fetch', 'cargo-test-ferris-core']);
306
335
  // `--workspace -E 'package(...)'`, never `--package`: the filterset picks
307
336
  // the same tests without re-resolving features, so the run reuses what
308
- // cargo-test-compile built instead of rebuilding inside the bound.
337
+ // cargo-test-compile built instead of rebuilding inside the bound. A
338
+ // workspace member with no tests is still a successful per-crate target.
309
339
  expect(targets['cargo-test-ferris-core']?.options?.command).toMatch(
310
- /^cargo --frozen nextest run --workspace -E 'package\(ferris-core\)' --user-config-file none --config-file /,
340
+ /^cargo --frozen nextest run --workspace -E 'package\(ferris-core\)' --no-tests=pass --user-config-file none --config-file /,
311
341
  );
312
342
  expect(targets['cargo-test-ferris-core']?.inputs).toEqual([
313
343
  '{projectRoot}/Cargo.toml',
@@ -338,6 +368,143 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
338
368
  }
339
369
  });
340
370
 
371
+ it('attributes one repository-root Cargo workspace across package projects', async () => {
372
+ const workspace = await createWorkspace();
373
+ try {
374
+ await workspace.write('package.json', '{"name":"@axe.sc/codebase"}\n');
375
+ await workspace.write('packages/runtime/package.json', '{"name":"@axe.sc/runtime","nx":{"name":"runtime"}}\n');
376
+ await workspace.write('packages/wasm/package.json', '{"name":"@axe.sc/wasm","nx":{"name":"wasm"}}\n');
377
+ await workspace.write(
378
+ 'packages/native/package.json',
379
+ JSON.stringify({
380
+ name: '@axe.sc/native',
381
+ nx: { name: 'native' },
382
+ napi: {
383
+ binaryName: 'native',
384
+ targets: ['aarch64-apple-darwin'],
385
+ },
386
+ }),
387
+ );
388
+ await workspace.write(
389
+ 'Cargo.toml',
390
+ [
391
+ '[workspace]',
392
+ 'members = ["packages/runtime/crates/*", "packages/wasm", "packages/native/crates/*"]',
393
+ '',
394
+ ].join('\n'),
395
+ );
396
+ await workspace.write('Cargo.lock', 'version = 4\n');
397
+ await workspace.write(
398
+ 'packages/runtime/crates/runtime-core/Cargo.toml',
399
+ '[package]\nname = "runtime-core"\n\n[package.metadata.smoothbricks.test]\nshards = 2\n',
400
+ );
401
+ await workspace.write(
402
+ 'packages/wasm/Cargo.toml',
403
+ [
404
+ '[package]',
405
+ 'name = "runtime-wasm"',
406
+ '',
407
+ '[lib]',
408
+ 'crate-type = ["cdylib", "rlib"]',
409
+ '',
410
+ '[package.metadata.smoothbricks.wasm-bindgen]',
411
+ 'targets = ["web"]',
412
+ '',
413
+ ].join('\n'),
414
+ );
415
+ await workspace.write(
416
+ 'packages/native/crates/native-napi/Cargo.toml',
417
+ '[package]\nname = "native-napi"\n\n[lib]\ncrate-type = ["cdylib"]\n',
418
+ );
419
+
420
+ const inferred = await inferTargets(
421
+ ['package.json', 'packages/runtime/package.json', 'packages/wasm/package.json', 'packages/native/package.json'],
422
+ undefined,
423
+ workspace.context,
424
+ );
425
+ const projects = new Map(inferred.flatMap(([, result]) => Object.entries(result.projects ?? {})));
426
+ const root = projects.get('.')?.targets ?? {};
427
+ const runtime = projects.get('packages/runtime')?.targets ?? {};
428
+ const wasm = projects.get('packages/wasm')?.targets ?? {};
429
+ const native = projects.get('packages/native')?.targets ?? {};
430
+ const rootProject = '@axe.sc/codebase';
431
+ const rootFetch = { projects: [rootProject], target: 'cargo-fetch' };
432
+ const rootCompile = { projects: [rootProject], target: 'cargo-test-compile' };
433
+
434
+ expect(
435
+ [...projects]
436
+ .filter(([, project]) => project.targets?.['cargo-test-compile'])
437
+ .map(([projectRoot]) => projectRoot),
438
+ ).toEqual(['.']);
439
+ expect(root['cargo-fetch']?.options).toEqual({
440
+ commands: ['cargo fetch --locked'],
441
+ cwd: '.',
442
+ parallel: false,
443
+ });
444
+ expect(root['cargo-test-compile']?.options).toMatchObject({
445
+ command: 'cargo --frozen test --workspace --no-run',
446
+ cwd: '.',
447
+ });
448
+ expect(root['cargo-lint']?.options).toMatchObject({ cwd: '.' });
449
+ expect(root['cargo-test']?.dependsOn).toHaveLength(5);
450
+
451
+ expect(runtime['cargo-test-runtime-core-shard1']?.dependsOn).toEqual([
452
+ rootFetch,
453
+ { projects: ['native'], target: 'cargo-test-native-napi' },
454
+ ]);
455
+ expect(runtime['cargo-test-runtime-core-shard2']?.dependsOn).toEqual([
456
+ rootFetch,
457
+ 'cargo-test-runtime-core-shard1',
458
+ ]);
459
+ expect(runtime['cargo-test-runtime-core-exceptions']?.dependsOn).toEqual([
460
+ rootFetch,
461
+ 'cargo-test-runtime-core-shard2',
462
+ ]);
463
+ expect(runtime['cargo-test-runtime-core-shard1']?.options).toMatchObject({ cwd: '.' });
464
+ expect(runtime['cargo-test-runtime-core-shard1']?.options?.command).toContain(
465
+ 'nextest run --workspace -p runtime-core',
466
+ );
467
+ expect(native['cargo-test-native-napi']?.options?.command).toContain('--no-tests=pass');
468
+ expect(runtime['cargo-test']?.dependsOn).toEqual([
469
+ 'cargo-test-runtime-core-shard1',
470
+ 'cargo-test-runtime-core-shard2',
471
+ 'cargo-test-runtime-core-exceptions',
472
+ ]);
473
+ expect(runtime['cargo-lint']).toBeUndefined();
474
+ expect(runtime.clean).toBeUndefined();
475
+
476
+ expect(wasm['cargo-test-runtime-wasm']?.dependsOn).toEqual([
477
+ rootFetch,
478
+ { projects: ['runtime'], target: 'cargo-test-runtime-core-exceptions' },
479
+ ]);
480
+ expect(wasm['cargo-wasm']?.options).toMatchObject({ cwd: '.' });
481
+ expect(wasm['cargo-wasm']?.options?.commands).toContain(
482
+ 'cargo --frozen build --release --target wasm32-unknown-unknown --target-dir target/cargo-wasm -p runtime-wasm',
483
+ );
484
+ expect(wasm['cargo-wasm']?.outputs).toEqual(['{projectRoot}/dist-wasm']);
485
+ expect(wasm['cargo-wasm']?.dependsOn).toEqual([rootFetch, '^build']);
486
+ expect(wasm.build?.dependsOn).toContainEqual(rootCompile);
487
+ expect(wasm.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
488
+
489
+ expect(native['cargo-test-native-napi']?.dependsOn).toEqual([rootFetch, 'napi-debug']);
490
+ expect(native['napi-debug']?.dependsOn).toContainEqual(rootCompile);
491
+ expect(native['napi-debug']?.options).toMatchObject({
492
+ cwd: '.',
493
+ command:
494
+ 'packages/native/node_modules/.bin/napi build --platform --no-js --dts native.napi.d.ts --manifest-path packages/native/crates/native-napi/Cargo.toml --package native-napi --package-json-path packages/native/package.json --output-dir packages/native/.cache/native-debug',
495
+ });
496
+ expect(native['napi-arm64-macos']?.options).toMatchObject({
497
+ cwd: '.',
498
+ command:
499
+ 'packages/native/node_modules/.bin/napi build --release --platform --no-js --dts native.darwin-arm64.d.ts --target aarch64-apple-darwin --manifest-path packages/native/crates/native-napi/Cargo.toml --package native-napi --package-json-path packages/native/package.json --output-dir packages/native/dist/native/darwin-arm64',
500
+ });
501
+ expect(native.build?.dependsOn).toContainEqual(rootCompile);
502
+ expect(native.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
503
+ } finally {
504
+ await workspace.cleanup();
505
+ }
506
+ });
507
+
341
508
  it('scopes each per-crate cargo-test command to exactly one package', async () => {
342
509
  const workspace = await createWorkspace();
343
510
  try {
@@ -512,14 +679,14 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
512
679
  options: {
513
680
  cwd: 'packages/cowshed',
514
681
  command:
515
- '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',
682
+ 'napi build --release --platform --no-js --dts cowshed.napi.d.ts --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --package-json-path package.json --output-dir dist/native/host',
516
683
  },
517
684
  });
518
685
  expect(unservedHostTargets.build?.dependsOn).toEqual(['^build', 'cargo-test-compile', 'cargo-napi', 'tsc-js']);
519
686
  expect(targets['napi-arm64-macos']?.outputs).toEqual(['{projectRoot}/dist/native/darwin-arm64']);
520
687
  expect(targets['napi-arm64-macos']?.options).toMatchObject({
521
688
  command:
522
- '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',
689
+ '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 --package-json-path package.json --output-dir dist/native/darwin-arm64',
523
690
  });
524
691
  expect(targets['napi-arm64-macos']?.options?.env).toBeUndefined();
525
692
  // No cargo-test-compile edge here, on ANY host: a platform target's
@@ -580,7 +747,7 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
580
747
  expect(darwinArm64Targets['napi-arm64-linux']?.dependsOn).toEqual(['napi-toolchain-arm64-linux']);
581
748
  expect(darwinArm64Targets['napi-x64-linux']?.outputs).toEqual(['{projectRoot}/dist/native/linux-x64-gnu']);
582
749
  expect(darwinArm64Targets['napi-x64-linux']?.options?.command).toBe(
583
- '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',
750
+ '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 --package-json-path package.json --output-dir dist/native/linux-x64-gnu',
584
751
  );
585
752
 
586
753
  // The whole rule, stated once per forced host: a triple gets a cross
@@ -650,7 +817,7 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
650
817
  options: {
651
818
  cwd: 'packages/cowshed',
652
819
  command:
653
- 'napi build --platform --no-js --dts cowshed.napi.d.ts --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --output-dir .cache/native-debug',
820
+ 'napi build --platform --no-js --dts cowshed.napi.d.ts --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --package-json-path package.json --output-dir .cache/native-debug',
654
821
  },
655
822
  });
656
823
  expect(targets['cargo-test']?.dependsOn).toEqual(['cargo-test-cowshed-napi']);
@@ -659,7 +826,7 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
659
826
  // not something it inherits from cargo-test-compile's position.
660
827
  expect(targets['cargo-test-cowshed-napi']?.dependsOn).toEqual(['cargo-fetch', 'napi-debug']);
661
828
  expect(targets['cargo-test-cowshed-napi']?.options?.command).toMatch(
662
- /^cargo --frozen nextest run --workspace -E 'package\(cowshed-napi\)' --user-config-file none --config-file /,
829
+ /^cargo --frozen nextest run --workspace -E 'package\(cowshed-napi\)' --no-tests=pass --user-config-file none --config-file /,
663
830
  );
664
831
  expect(targets['napi-test']).toMatchObject({
665
832
  executor: '@smoothbricks/nx-plugin:bounded-exec',
@@ -738,7 +905,7 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
738
905
  // An unsharded crate keeps the bare name and takes no --partition, so
739
906
  // declaring nothing is exactly the old single-target behaviour.
740
907
  expect(targets['cargo-test-small']?.options?.command).toMatch(
741
- /nextest run --workspace -E 'package\(small\)' --user-config-file none/,
908
+ /nextest run --workspace -E 'package\(small\)' --no-tests=pass --user-config-file none/,
742
909
  );
743
910
  // The shards partition the crate MINUS the classes nextest.toml singles
744
911
  // out, i of N. Those are lifted out because a test-group only holds
@@ -751,7 +918,7 @@ describe('@smoothbricks/nx-plugin inferred targets', () => {
751
918
  }
752
919
  for (const index of [1, 2, 3]) {
753
920
  expect(targets[`cargo-test-big-shard${index}`]?.options?.command).toContain(
754
- `--workspace -E 'package(big) and not (${exceptional})' --partition hash:${index}/3`,
921
+ `--workspace -E 'package(big) and not (${exceptional})' --partition hash:${index}/3 --no-tests=pass`,
755
922
  );
756
923
  expect(targets[`cargo-test-big-shard${index}`]?.options?.timeoutMs).toBe(BOUNDED_TEST_TIMEOUT_MS);
757
924
  }