@smoothbricks/nx-plugin 0.4.28 → 0.4.30

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 (158) hide show
  1. package/README.md +277 -89
  2. package/dist/bin/smoo-nx-test-clocks.d.ts +3 -0
  3. package/dist/bin/smoo-nx-test-clocks.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-test-clocks.js +28 -0
  5. package/dist/bounded-test-policy.d.ts +8 -8
  6. package/dist/bounded-test-policy.d.ts.map +1 -1
  7. package/dist/bounded-test-policy.js +18 -30
  8. package/dist/cargo-closure-input.d.ts +23 -0
  9. package/dist/cargo-closure-input.d.ts.map +1 -1
  10. package/dist/cargo-closure-input.js +41 -9
  11. package/dist/cargo-source-hash.d.ts.map +1 -1
  12. package/dist/cargo-source-hash.js +42 -19
  13. package/dist/ensure-built-receipt.d.ts +40 -6
  14. package/dist/ensure-built-receipt.d.ts.map +1 -1
  15. package/dist/ensure-built-receipt.js +297 -159
  16. package/dist/ensure-built-witness.d.ts +65 -4
  17. package/dist/ensure-built-witness.d.ts.map +1 -1
  18. package/dist/ensure-built-witness.js +2237 -23
  19. package/dist/ensure-built.d.ts +99 -1
  20. package/dist/ensure-built.d.ts.map +1 -1
  21. package/dist/ensure-built.js +45 -56
  22. package/dist/executors/bounded-exec/cpu-pool.d.ts +22 -7
  23. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
  24. package/dist/executors/bounded-exec/cpu-pool.js +51 -22
  25. package/dist/executors/bounded-exec/executor.d.ts +12 -3
  26. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  27. package/dist/executors/bounded-exec/executor.js +174 -51
  28. package/dist/executors/bounded-exec/no-space.d.ts +8 -0
  29. package/dist/executors/bounded-exec/no-space.d.ts.map +1 -0
  30. package/dist/executors/bounded-exec/no-space.js +31 -0
  31. package/dist/executors/bounded-exec/ram-temp.d.ts +20 -11
  32. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
  33. package/dist/executors/bounded-exec/ram-temp.js +42 -17
  34. package/dist/executors/bounded-exec/verdict.d.ts +34 -4
  35. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -1
  36. package/dist/executors/bounded-exec/verdict.js +54 -3
  37. package/dist/generators/bun-test-tracing/generator.js +2 -2
  38. package/dist/graph-input-contract.d.ts +102 -0
  39. package/dist/graph-input-contract.d.ts.map +1 -0
  40. package/dist/graph-input-contract.js +637 -0
  41. package/dist/index.d.ts +12 -5
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +17 -3
  44. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  45. package/dist/managed-files/ci-workflow.js +5 -2
  46. package/dist/managed-files/publish-workflow.d.ts +11 -1
  47. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  48. package/dist/owned-installation.d.ts +14 -0
  49. package/dist/owned-installation.d.ts.map +1 -0
  50. package/dist/owned-installation.js +324 -0
  51. package/dist/producer-receipts.d.ts +19 -0
  52. package/dist/producer-receipts.d.ts.map +1 -0
  53. package/dist/producer-receipts.js +926 -0
  54. package/dist/test-backstop.d.ts +9 -0
  55. package/dist/test-backstop.d.ts.map +1 -0
  56. package/dist/test-backstop.js +10 -0
  57. package/dist/test-clock-policy.d.ts +30 -0
  58. package/dist/test-clock-policy.d.ts.map +1 -0
  59. package/dist/test-clock-policy.js +686 -0
  60. package/dist/testing.d.ts +8 -0
  61. package/dist/testing.d.ts.map +1 -1
  62. package/dist/testing.js +66 -1
  63. package/managed/raw/patches/nx@23.2.1.patch +328 -50
  64. package/managed/raw/tooling/direnv/developer-links.ts +148 -29
  65. package/managed/raw/tooling/direnv/devenv.smoo.nix +7 -7
  66. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +14 -5
  67. package/managed/raw/tooling/direnv/linked-snapshots.ts +206 -40
  68. package/managed/raw/tooling/direnv/repo-path +15 -2
  69. package/managed/raw/tooling/direnv/setup-environment.ts +179 -115
  70. package/managed/templates/github/actions/cache-node-modules/action.yml +9 -0
  71. package/managed/templates/github/actions/setup-devenv/action.yml +63 -7
  72. package/nextest.toml +1 -1
  73. package/package.json +25 -9
  74. package/src/__tests__/cargo-closure-fixture.ts +113 -0
  75. package/src/__tests__/counted-cargo.ts +8 -25
  76. package/src/__tests__/directory-change.ts +27 -0
  77. package/src/__tests__/fixture-nx-env.ts +7 -0
  78. package/src/__tests__/owned-installation.ts +14 -0
  79. package/src/__tests__/past-tick.ts +12 -0
  80. package/src/bin/smoo-nx-bound-failures.test.ts +1 -1
  81. package/src/bin/smoo-nx-test-clocks.ts +29 -0
  82. package/src/bounded-test-policy.test.ts +36 -22
  83. package/src/bounded-test-policy.ts +18 -32
  84. package/src/bun-bootstrap.test.ts +1 -1
  85. package/src/cargo-closure-input.property.test.ts +50 -0
  86. package/src/cargo-closure-input.test.ts +73 -121
  87. package/src/cargo-closure-input.ts +47 -8
  88. package/src/cargo-closure-key.test.ts +239 -0
  89. package/src/cargo-resolve-cache.test.ts +168 -31
  90. package/src/cargo-source-hash.test.ts +78 -3
  91. package/src/cargo-source-hash.ts +48 -30
  92. package/src/cross-check-policy.test.ts +2 -2
  93. package/src/ensure-built-receipt.test.ts +111 -16
  94. package/src/ensure-built-receipt.ts +294 -149
  95. package/src/ensure-built-witness.test.ts +306 -13
  96. package/src/ensure-built-witness.ts +255 -24
  97. package/src/ensure-built.test.ts +228 -102
  98. package/src/ensure-built.ts +127 -66
  99. package/src/executors/bounded-exec/cpu-pool.test.ts +134 -32
  100. package/src/executors/bounded-exec/cpu-pool.ts +64 -20
  101. package/src/executors/bounded-exec/cpu-tokens.test.ts +2 -2
  102. package/src/executors/bounded-exec/disk-lease.test.ts +47 -13
  103. package/src/executors/bounded-exec/executor-host.test.ts +74 -52
  104. package/src/executors/bounded-exec/executor.test.ts +343 -97
  105. package/src/executors/bounded-exec/executor.ts +192 -56
  106. package/src/executors/bounded-exec/hang-diagnostics.test.ts +14 -8
  107. package/src/executors/bounded-exec/no-space.ts +40 -0
  108. package/src/executors/bounded-exec/progress.test.ts +1 -1
  109. package/src/executors/bounded-exec/ram-temp-host.test.ts +51 -21
  110. package/src/executors/bounded-exec/ram-temp.test.ts +92 -16
  111. package/src/executors/bounded-exec/ram-temp.ts +49 -20
  112. package/src/executors/bounded-exec/verdict.test.ts +127 -22
  113. package/src/executors/bounded-exec/verdict.ts +78 -3
  114. package/src/generators/bounded-test-targets/generator.test.ts +1 -3
  115. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  116. package/src/generators/bun-test-tracing/generator.ts +2 -2
  117. package/src/graph-input-contract.test.ts +379 -0
  118. package/src/graph-input-contract.ts +627 -0
  119. package/src/index.test.ts +3 -3
  120. package/src/index.ts +24 -3
  121. package/src/linked-snapshots.nx.test.ts +112 -30
  122. package/src/managed-files/ci-workflow.ts +5 -2
  123. package/src/managed-files/publish-workflow.ts +12 -1
  124. package/src/managed-files/repo-path.test.ts +44 -1
  125. package/src/managed-files/setup-devenv-free-disk.test.ts +95 -0
  126. package/src/nextest-code-bound.test.ts +23 -17
  127. package/src/nextest-extraction.test.ts +114 -4
  128. package/src/nextest-partitions.test.ts +7 -1
  129. package/src/nx-cache-restore-mtime.test.ts +2 -2
  130. package/src/nx-daemon-claim.test.ts +10 -8
  131. package/src/nx-daemon-idle-cpu.test.ts +0 -1
  132. package/src/nx-daemon-idle-policy.test.ts +61 -1
  133. package/src/nx-daemon-ignore-files.test.ts +2 -2
  134. package/src/nx-daemon-validity.test.ts +36 -22
  135. package/src/nx-dot-input-policy.test.ts +5 -5
  136. package/src/nx-files-archive-racy.test.ts +1 -1
  137. package/src/nx-incomplete-run-summary.test.ts +1 -1
  138. package/src/nx-plugin-load-errors.test.ts +2 -2
  139. package/src/nx-project-graph-errors.test.ts +70 -0
  140. package/src/nx-skipped-task-exit.test.ts +2 -2
  141. package/src/nx-store-resolution.test.ts +7 -25
  142. package/src/nx-task-output-lease.test.ts +3 -3
  143. package/src/nx-use-local.test.ts +7 -5
  144. package/src/owned-installation.ts +174 -0
  145. package/src/producer-receipts.test.ts +164 -0
  146. package/src/producer-receipts.ts +636 -0
  147. package/src/runtime-input.test.ts +1 -1
  148. package/src/serial-group-wiring.test.ts +4 -4
  149. package/src/task-results.test.ts +18 -16
  150. package/src/test-backstop.ts +11 -0
  151. package/src/test-clock-policy.test.ts +338 -0
  152. package/src/test-clock-policy.ts +708 -0
  153. package/src/test-timings.test.ts +2 -2
  154. package/src/testing.test.ts +5 -5
  155. package/src/testing.ts +67 -1
  156. package/src/typecheck-test-policy.test.ts +1 -1
  157. package/src/typescript-resolution.test.ts +76 -0
  158. package/test-timings.json +8 -0
@@ -0,0 +1,70 @@
1
+ import { expect, it } from 'bun:test';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { mkdir, symlink, writeFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { fixtureNxEnv, withNxFixture } from './__tests__/fixture-nx-env.js';
6
+
7
+ /**
8
+ * Guards the project-graph error hunks of patches/nx@23.2.1.patch (nrwl/nx#37103 carried, with cause chains) against
9
+ * the actual Bun-installed Nx: a createNodes failure names itself without --verbose. Before, `nx run-many` printed
10
+ * only "Failed to process project graph." and a consumer's CI could not say which plugin refused or why.
11
+ */
12
+ const repositoryRoot = join(import.meta.dir, '../../..');
13
+ const nxEntry = join(repositoryRoot, 'node_modules/.bin/nx');
14
+
15
+ const FAILURE = 'fixture.rs names @smoothbricks/nx-plugin/dist/bin/smoo-nx-absent.js, which the plugin does not ship';
16
+ const CAUSE = 'fixture cause of the refusal';
17
+ const STACK_FRAME = /failure\.cjs:\d+:\d+/;
18
+
19
+ for (const command of [
20
+ ['run-many', '-t', 'build'],
21
+ ['show', 'projects', '--json'],
22
+ ]) {
23
+ for (const isolate of ['false', 'true']) {
24
+ it(`names a createNodes failure and its cause for nx ${command[0]} (isolated plugins: ${isolate})`, async () => {
25
+ await withNxFixture('nx-graph-errors-', async ({ workspace, socketDirectory }) => {
26
+ await symlink(join(repositoryRoot, 'node_modules'), join(workspace, 'node_modules'), 'dir');
27
+ await writeFile(join(workspace, 'package.json'), JSON.stringify({ name: 'graph-errors', private: true }));
28
+ await mkdir(join(workspace, 'packages/app'), { recursive: true });
29
+ await writeFile(
30
+ join(workspace, 'packages/app/package.json'),
31
+ JSON.stringify({ name: 'app', scripts: { build: 'true' } }),
32
+ );
33
+ const plugin = join(workspace, 'failure.cjs');
34
+ await writeFile(
35
+ plugin,
36
+ `exports.createNodes = ['**/package.json', () => {
37
+ throw new Error(${JSON.stringify(FAILURE)}, { cause: new Error(${JSON.stringify(CAUSE)}) });
38
+ }];
39
+ `,
40
+ );
41
+ await writeFile(join(workspace, 'nx.json'), JSON.stringify({ plugins: [plugin] }));
42
+ const run = (verbose: boolean) => {
43
+ const env = { ...fixtureNxEnv(workspace, socketDirectory), NX_ISOLATE_PLUGINS: isolate };
44
+ const ran = spawnSync('bun', [nxEntry, ...command], {
45
+ cwd: workspace,
46
+ env: verbose ? { ...env, NX_VERBOSE_LOGGING: 'true' } : env,
47
+ encoding: 'utf8',
48
+ });
49
+ return { status: ran.status, output: `${ran.stdout}${ran.stderr}` };
50
+ };
51
+
52
+ const quiet = run(false);
53
+ expect(quiet.status, quiet.output).toBe(1);
54
+ expect(quiet.output).toContain('Failed to process project graph.');
55
+ expect(quiet.output).toContain(FAILURE);
56
+ expect(quiet.output).toContain(`Caused by: ${CAUSE}`);
57
+ expect(quiet.output).toContain('Pass --verbose to see the stacktraces.');
58
+ expect(quiet.output).not.toMatch(STACK_FRAME);
59
+
60
+ // Verbose keeps the stack frames and the cause chain. Stack text is the runtime's own: under Bun an
61
+ // in-process plugin error's stack (its cause's too) can read as a bare `Error`, so naming the messages is the
62
+ // non-verbose body's job, asserted above for every command and isolation mode.
63
+ const verbose = run(true);
64
+ expect(verbose.status, verbose.output).toBe(1);
65
+ expect(verbose.output).toContain('Caused by:');
66
+ expect(verbose.output).toMatch(STACK_FRAME);
67
+ });
68
+ });
69
+ }
70
+ }
@@ -66,7 +66,7 @@ it('exits 1, not 130, when a failed task leaves a task that depends on it unrun'
66
66
  expect(JSON.parse(await readFile(join(workspace, 'task-results.json'), 'utf8'))).toEqual({ 'p:fail': 'failure' });
67
67
  }
68
68
  });
69
- }, 60_000);
69
+ });
70
70
 
71
71
  it('distinguishes parallel failure bailout from a real interrupt with pending tasks', async () => {
72
72
  for (const interrupt of [false, true]) {
@@ -177,4 +177,4 @@ if (existsSync(wanted)) { watcher.close(); process.exit(1); }
177
177
  }
178
178
  });
179
179
  }
180
- }, 60_000);
180
+ });
@@ -5,7 +5,6 @@ import { createRequire } from 'node:module';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { resolveFromWorkspace } from 'nx/src/utils/installation-directory.js';
7
7
  import { readModulePackageJson } from 'nx/src/utils/package-json.js';
8
- import { guardEvent } from './__tests__/counted-cargo.js';
9
8
  import { fixtureNxEnv, withNxFixture } from './__tests__/fixture-nx-env.js';
10
9
 
11
10
  /**
@@ -58,7 +57,6 @@ it('keeps the source-import edges of the installed Nx, resolving typescript from
58
57
  const child = spawn('node', [join(nx, 'dist/bin/nx.js'), 'graph', `--file=${graphFile}`], {
59
58
  cwd: root,
60
59
  env: fixtureNxEnv(root, socketDirectory),
61
- detached: process.platform !== 'win32',
62
60
  stdio: ['ignore', 'pipe', 'pipe'],
63
61
  });
64
62
  let output = '';
@@ -68,29 +66,13 @@ it('keeps the source-import edges of the installed Nx, resolving typescript from
68
66
  child.stderr?.setEncoding('utf8').on('data', (text: string) => {
69
67
  output += text;
70
68
  });
71
- const { promise: ended, resolve, reject } = Promise.withResolvers<number | null>();
72
- child.once('error', reject);
73
- child.once('close', resolve);
74
- let code: number | null;
75
- try {
76
- code = await guardEvent(
77
- ended,
78
- 'nx graph to close',
79
- () => `pid ${child.pid}, exit ${child.exitCode}, signal ${child.signalCode}\n${output}`,
80
- );
81
- } catch (error) {
82
- if (child.pid !== undefined && child.exitCode === null && child.signalCode === null) {
83
- try {
84
- process.kill(process.platform === 'win32' ? child.pid : -child.pid, 'SIGKILL');
85
- } catch (killError) {
86
- if (!(killError instanceof Error && 'code' in killError && killError.code === 'ESRCH')) {
87
- throw new AggregateError([error, killError], 'could not retire the failed fixture Nx command');
88
- }
89
- }
90
- }
91
- await ended.catch(() => undefined);
92
- throw error;
93
- }
69
+ // The test waits for what it needs, the command's close, however long a loaded host makes the real Nx take: a
70
+ // deadline here measured the host, not the resolution (a 15 s guard failed a land gate at load 20 with the command
71
+ // still running). A command that never closes is the runner's idle-hang backstop's to report.
72
+ const code = await new Promise<number | null>((resolve, reject) => {
73
+ child.once('error', reject);
74
+ child.once('close', resolve);
75
+ });
94
76
  expect(code, output).toBe(0);
95
77
  expect(JSON.parse(await readFile(graphFile, 'utf8'))).toMatchObject({
96
78
  graph: { dependencies: { b: [{ source: 'b', target: 'a', type: 'static' }] } },
@@ -186,7 +186,7 @@ it('leases a target across clients through producer completion, cache capture an
186
186
  await Promise.all(children.map((child) => child.exited));
187
187
  }
188
188
  });
189
- }, 120_000);
189
+ });
190
190
 
191
191
  it('shares ownership across configurations without blocking independent targets, and cancels lock waiters', async () => {
192
192
  const owner = new TaskOutputLeases(2, null, 'output');
@@ -287,7 +287,7 @@ it('refuses an ancestor-owned target before waiting for its output lease', async
287
287
  await child.exited;
288
288
  }
289
289
  });
290
- }, 60_000);
290
+ });
291
291
 
292
292
  it('shares one continuous producer between simultaneous cold clients without waiting for its lifetime lease', async () => {
293
293
  await withNxFixture('nx-task-output-continuous-', async ({ workspace, socketDirectory }) => {
@@ -411,4 +411,4 @@ SharedRunningTask.prototype.waitForTaskToFinish = async function(...args) {
411
411
  await Promise.all(children.map((child) => child.exited));
412
412
  }
413
413
  });
414
- }, 60_000);
414
+ });
@@ -2,7 +2,6 @@ import { expect, it } from 'bun:test';
2
2
  import { spawn } from 'node:child_process';
3
3
  import { chmod, mkdir, readFile, symlink, unlink, writeFile } from 'node:fs/promises';
4
4
  import { delimiter, join } from 'node:path';
5
- import { guardEvent } from './__tests__/counted-cargo.js';
6
5
  import { fixtureNxEnv, withNxFixture } from './__tests__/fixture-nx-env.js';
7
6
 
8
7
  /**
@@ -32,10 +31,13 @@ async function run(
32
31
  child.stderr?.setEncoding('utf8').on('data', (text: string) => {
33
32
  output += text;
34
33
  });
35
- const { promise: ended, resolve, reject } = Promise.withResolvers<number | null>();
36
- child.once('error', reject);
37
- child.once('close', resolve);
38
- const code = await guardEvent(ended, `${command} ${args.join(' ')} to close`, () => output);
34
+ // The test waits for what it needs, the command's close, however long a loaded host makes the real Nx take: a
35
+ // deadline here measured the host, not the daemon's behaviour (a 15 s guard failed SB land gates at load 3 and 80
36
+ // with `oracle-control` still running). A command that never closes is the runner's idle-hang backstop's to report.
37
+ const code = await new Promise<number | null>((resolve, reject) => {
38
+ child.once('error', reject);
39
+ child.once('close', resolve);
40
+ });
39
41
  expect(code, output).toBe(expectedCode);
40
42
  return output;
41
43
  }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * A fixture's own copy of a workspace's Nx installation, and the check that nothing wrote into it.
3
+ *
4
+ * The graph witness binds node stamps (ctime included) of every file in the closure of Nx, this plugin and
5
+ * TypeScript (README "Ancestor directories bind..."). Linked from a workspace, that closure is the host's: on CI
6
+ * its files are hardlinks in the shared Bun store, and any other task that installs, restores or cleans changes their
7
+ * link count, so their ctime, so a fixture's installation identity, between two calls of one test. Where this plugin
8
+ * is a developer link, the closure is also a live checkout that its own author edits and rebuilds while a consumer's
9
+ * test reads it. A fixture must not take an input it does not own.
10
+ *
11
+ * So the closure is copied, exactly as the witness's own census resolves it from the workspace that names it: each
12
+ * package once, with the census's own exclusions (`node_modules`, `.git`, `.nx`), each dependency edge relinked beside
13
+ * its copy as Bun's isolated layout does, the top-level packages' bins in `.bin`. Every copy is a new inode, cloned
14
+ * where the volume allows and written otherwise, so no link count is shared with anything outside its owner.
15
+ *
16
+ * A test file makes one copy, on first use, shared by its fixtures; retiring it fails, naming the changed nodes, if
17
+ * any fixture wrote into it.
18
+ */
19
+ import { constants } from 'node:fs';
20
+ import { cp, mkdir, readFile, rm, symlink } from 'node:fs/promises';
21
+ import { basename, dirname, join, relative } from 'node:path';
22
+ import { expandOutputs } from 'nx/src/native';
23
+ import { readModulePackageJson } from 'nx/src/utils/package-json';
24
+ import typia from 'typia';
25
+ import {
26
+ type GraphInstallationCensus,
27
+ graphInstallationCensus,
28
+ graphInstallationIdentity,
29
+ } from './ensure-built-witness.js';
30
+
31
+ /** The configuration the census resolves: Nx, this plugin and TypeScript. */
32
+ const CENSUS_NX_JSON = { plugins: ['@smoothbricks/nx-plugin'] };
33
+
34
+ /** An installation made under `root`, and its identity when the copy was made. */
35
+ interface OwnedInstallation {
36
+ readonly root: string;
37
+ readonly identity: string;
38
+ }
39
+
40
+ /** The graph witness's installation identity resolved from `root`; an unproved installation fails loudly. */
41
+ function installationIdentity(root: string): string {
42
+ let unproved = 'no detail';
43
+ const identity = graphInstallationIdentity(
44
+ root,
45
+ CENSUS_NX_JSON,
46
+ readModulePackageJson,
47
+ expandOutputs,
48
+ null,
49
+ (detail) => {
50
+ unproved = detail;
51
+ },
52
+ );
53
+ if (identity === null) throw new Error(`the Nx installation resolved from ${root} is unproved: ${unproved}`);
54
+ return identity;
55
+ }
56
+
57
+ /** Copy the installation closure `censusRoot` resolves into `root/node_modules`; `root` is an empty directory the
58
+ * caller owns.
59
+ *
60
+ * Only the closure is read from `censusRoot`, never its proof: that installation is the host's, whose shared store
61
+ * other tasks relink while the census reads it, which changes node stamps and would make every test that copies it
62
+ * fail for the host's work rather than its own. The copy, which the fixture owns, is what gets proved.
63
+ */
64
+ async function makeOwnedInstallation(censusRoot: string, root: string): Promise<OwnedInstallation> {
65
+ let unread = 'no detail';
66
+ const census = graphInstallationCensus(
67
+ censusRoot,
68
+ CENSUS_NX_JSON,
69
+ readModulePackageJson,
70
+ expandOutputs,
71
+ null,
72
+ (detail) => {
73
+ unread = detail;
74
+ },
75
+ );
76
+ if (census === null) throw new Error(`the Nx installation closure of ${censusRoot} cannot be read: ${unread}`);
77
+ const { resolutions } = census;
78
+ const modules = join(root, 'node_modules');
79
+ // Each source package root's copy, inside a store directory whose node_modules also holds its dependency links.
80
+ const copies = new Map<
81
+ string,
82
+ { readonly store: string; readonly copy: string; readonly bin: string | Record<string, string> | undefined }
83
+ >();
84
+ for (const [, , manifest] of resolutions) {
85
+ if (manifest === null || copies.has(dirname(manifest))) continue;
86
+ const { name, bin } = typia.json.assertParse<{ name: string; bin?: string | Record<string, string> }>(
87
+ await readFile(manifest, 'utf8'),
88
+ );
89
+ const store = join(modules, '.store', String(copies.size), 'node_modules');
90
+ copies.set(dirname(manifest), { store, copy: join(store, name), bin });
91
+ }
92
+ const copyOf = (source: string) => {
93
+ const copied = copies.get(source);
94
+ if (copied === undefined) throw new Error(`${source} resolves dependencies but is not in the census`);
95
+ return copied;
96
+ };
97
+ await Promise.all(
98
+ [...copies].map(([source, { copy }]) =>
99
+ cp(source, copy, {
100
+ recursive: true,
101
+ verbatimSymlinks: true,
102
+ mode: constants.COPYFILE_FICLONE,
103
+ filter: (path) => path === source || !['node_modules', '.git', '.nx'].includes(basename(path)),
104
+ }),
105
+ ),
106
+ );
107
+ for (const [from, name, manifest] of resolutions) {
108
+ if (manifest === null) continue;
109
+ const link = join(from === censusRoot ? modules : copyOf(from).store, name);
110
+ await mkdir(dirname(link), { recursive: true });
111
+ await symlink(relative(dirname(link), copyOf(dirname(manifest)).copy), link, 'dir');
112
+ if (from !== censusRoot) continue;
113
+ const { bin } = copyOf(dirname(manifest));
114
+ const commands = typeof bin === 'string' ? { [basename(name)]: bin } : (bin ?? {});
115
+ for (const [command, path] of Object.entries(commands)) {
116
+ await mkdir(join(modules, '.bin'), { recursive: true });
117
+ await symlink(relative(join(modules, '.bin'), join(link, path)), join(modules, '.bin', command));
118
+ }
119
+ }
120
+ return { root, identity: installationIdentity(root) };
121
+ }
122
+
123
+ /**
124
+ * Remove an installation, failing, with the changed nodes named, if its identity is no longer the one it was made
125
+ * with: the proof that its sharers only read it.
126
+ */
127
+ async function retireOwnedInstallation({ root, identity }: OwnedInstallation): Promise<void> {
128
+ try {
129
+ const retired = installationIdentity(root);
130
+ if (retired === identity) return;
131
+ const entries = (census: string) => {
132
+ const { nodes, files } = typia.json.assertParse<GraphInstallationCensus>(census);
133
+ return new Set([
134
+ ...nodes.map(({ path, stamp }) => `${path} ${stamp}`),
135
+ ...files.map(({ path, sha256 }) => `${path} ${sha256}`),
136
+ ]);
137
+ };
138
+ const made = entries(identity);
139
+ const now = entries(retired);
140
+ const changed = [
141
+ ...[...made].filter((entry) => !now.has(entry)).map((entry) => `- ${entry}`),
142
+ ...[...now].filter((entry) => !made.has(entry)).map((entry) => `+ ${entry}`),
143
+ ];
144
+ throw new Error(`a fixture changed the installation it shares, in ${root}:\n${changed.slice(0, 20).join('\n')}`);
145
+ } finally {
146
+ await rm(root, { recursive: true, force: true });
147
+ }
148
+ }
149
+
150
+ /** One test file's installation: made on first use and shared by its fixtures, retired by the file's `afterAll`. */
151
+ export interface TestFileInstallation {
152
+ /** The `node_modules` a fixture workspace links. */
153
+ readonly nodeModules: () => Promise<string>;
154
+ /** Fails if a fixture wrote into the copy; a file that never used it has nothing to retire. */
155
+ readonly retire: () => Promise<void>;
156
+ }
157
+
158
+ /**
159
+ * The installation one test file owns: a copy of the closure `censusRoot` (the workspace whose Nx, plugin and
160
+ * TypeScript the fixtures stand for) resolves, made in the empty directory `makeRoot` creates on first use. Call once
161
+ * per file, at module scope: Bun runs many test files in one process, and each must own its copy.
162
+ */
163
+ export function ownedInstallation(censusRoot: string, makeRoot: () => Promise<string>): TestFileInstallation {
164
+ let made: Promise<OwnedInstallation> | undefined;
165
+ return {
166
+ nodeModules: async () => {
167
+ made ??= makeRoot().then((root) => makeOwnedInstallation(censusRoot, root));
168
+ return join((await made).root, 'node_modules');
169
+ },
170
+ retire: async () => {
171
+ if (made !== undefined) await retireOwnedInstallation(await made);
172
+ },
173
+ };
174
+ }
@@ -0,0 +1,164 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdir, mkdtemp, readdir, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import type { Task, TaskGraph } from 'nx/src/config/task-graph';
8
+ import type { TaskResults } from 'nx/src/tasks-runner/life-cycle';
9
+ import type { EnsureBuiltProducerReceipt } from './ensure-built.js';
10
+ import {
11
+ completedProducerTasks,
12
+ postTasksExecution,
13
+ preTasksExecution,
14
+ producerEnvironmentIdentity,
15
+ readProducerReceipt,
16
+ } from './producer-receipts.js';
17
+
18
+ const repoRoot = dirname(dirname(dirname(dirname(fileURLToPath(import.meta.url)))));
19
+
20
+ const task: Task = {
21
+ id: 'app:build',
22
+ target: { project: 'app', target: 'build' },
23
+ overrides: {},
24
+ outputs: ['dist'],
25
+ cache: false,
26
+ hash: 'actual-nx-hash',
27
+ hashDetails: { command: 'actual-command', nodes: { source: 'actual-source-identity' } },
28
+ };
29
+ const graph: TaskGraph = {
30
+ roots: [task.id],
31
+ tasks: { [task.id]: task },
32
+ dependencies: { [task.id]: [] },
33
+ continuousDependencies: {},
34
+ };
35
+ const inputs: EnsureBuiltProducerReceipt['inputs'] = [
36
+ {
37
+ taskId: task.id,
38
+ overrides: {},
39
+ declared: [],
40
+ expanded: {
41
+ files: [],
42
+ runtime: ['declared-version-recipe'],
43
+ environment: ['DECLARED_ENV'],
44
+ depOutputs: [],
45
+ external: [],
46
+ },
47
+ hashDetails: { command: 'actual-command', nodes: { 'env:DECLARED_ENV': 'producer-value-hash' } },
48
+ files: [],
49
+ },
50
+ ];
51
+
52
+ describe('actual producer completion evidence', () => {
53
+ it('accepts successful uncacheable prerequisites without looking for cache rows', () => {
54
+ const results: TaskResults = { [task.id]: { task, status: 'success', code: 0 } };
55
+ expect(completedProducerTasks(graph, results)).toEqual({ ok: true, value: [task] });
56
+ });
57
+ it('accepts actual Nx successful cache completion statuses, not invented hit receipts', () => {
58
+ const statuses: readonly TaskResults[string]['status'][] = [
59
+ 'local-cache',
60
+ 'local-cache-kept-existing',
61
+ 'remote-cache',
62
+ ];
63
+ for (const status of statuses) {
64
+ const cached: Task = { ...task, cache: true };
65
+ expect(
66
+ completedProducerTasks(
67
+ { ...graph, tasks: { [task.id]: cached } },
68
+ { [task.id]: { task: cached, status, code: 0 } },
69
+ ).ok,
70
+ ).toBe(true);
71
+ }
72
+ });
73
+ it('refuses missing, failed, stopped and skipped completion evidence', () => {
74
+ expect(completedProducerTasks(graph, {}).ok).toBe(false);
75
+ const statuses: readonly TaskResults[string]['status'][] = ['failure', 'stopped', 'skipped'];
76
+ for (const status of statuses)
77
+ expect(completedProducerTasks(graph, { [task.id]: { task, status, code: 0 } }).ok).toBe(false);
78
+ expect(completedProducerTasks(graph, { [task.id]: { task, status: 'success', code: 1 } }).ok).toBe(false);
79
+ });
80
+ it('refuses absent actual hash details, override changes, output changes and configuration changes', () => {
81
+ for (const changed of [
82
+ { ...task, hash: undefined },
83
+ { ...task, hashDetails: undefined },
84
+ { ...task, overrides: { configuration: 'other' } },
85
+ { ...task, outputs: ['different'] },
86
+ { ...task, target: { ...task.target, configuration: 'other' } },
87
+ ]) {
88
+ expect(completedProducerTasks(graph, { [task.id]: { task: changed, status: 'success', code: 0 } }).ok).toBe(
89
+ false,
90
+ );
91
+ }
92
+ });
93
+ it('labels producer Nx runtime/environment identity without reading a consumer environment', () => {
94
+ const identity = producerEnvironmentIdentity(inputs);
95
+ const saved = process.env.DECLARED_ENV;
96
+ process.env.DECLARED_ENV = 'different-consumer-value';
97
+ try {
98
+ expect(producerEnvironmentIdentity(inputs)).toBe(identity);
99
+ } finally {
100
+ if (saved === undefined) delete process.env.DECLARED_ENV;
101
+ else process.env.DECLARED_ENV = saved;
102
+ }
103
+ expect(
104
+ producerEnvironmentIdentity(
105
+ inputs.map((input) => ({
106
+ ...input,
107
+ hashDetails: { ...input.hashDetails, nodes: { 'env:DECLARED_ENV': 'different-actual-producer-hash' } },
108
+ })),
109
+ ),
110
+ ).not.toBe(identity);
111
+ });
112
+ it('disabled producer hooks perform no source, graph or publication work', async () => {
113
+ const context = { id: 'disabled-hook', workspaceRoot: '/not-a-workspace', nxJsonConfiguration: {}, argv: [] };
114
+ await preTasksExecution(undefined, context);
115
+ await postTasksExecution(undefined, { ...context, taskResults: {}, startTime: 10, endTime: 20 });
116
+ });
117
+ it('publishes a refusal beside a published receipt, never over it, and names it in the miss', async () => {
118
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'producer-refusal-')));
119
+ const inherited = process.env.NX_WORKSPACE_DATA_DIRECTORY;
120
+ delete process.env.NX_WORKSPACE_DATA_DIRECTORY;
121
+ try {
122
+ await writeFile(join(root, 'package.json'), JSON.stringify({ name: 'refusal-fixture' }));
123
+ await writeFile(join(root, 'nx.json'), '{}');
124
+ await symlink(join(repoRoot, 'node_modules'), join(root, 'node_modules'), 'dir');
125
+ const data = join(root, '.nx', 'workspace-data');
126
+ await mkdir(data, { recursive: true });
127
+ const name = createHash('sha256').update(JSON.stringify(task.id)).digest('hex');
128
+ const receiptPath = join(data, `producer-receipt-${name}.json`);
129
+ // What an earlier run published; this run's refusal is no evidence about it.
130
+ const published = JSON.stringify({ version: 1, disposition: 'published', receipt: 'an earlier run' });
131
+ await writeFile(receiptPath, published);
132
+ // A run whose pre-execution frame never bound (the sandboxed git failure's shape) refuses its target.
133
+ await postTasksExecution(
134
+ { producerReceipts: { targets: [task.id] } },
135
+ {
136
+ id: 'unbound-frame',
137
+ workspaceRoot: root,
138
+ nxJsonConfiguration: {},
139
+ argv: [],
140
+ taskResults: { [task.id]: { task, status: 'success', code: 0 } },
141
+ startTime: 10,
142
+ endTime: 20,
143
+ },
144
+ );
145
+ expect(await readFile(receiptPath, 'utf8')).toBe(published);
146
+ expect((await readdir(data)).sort()).toEqual([`producer-receipt-${name}.json`, `producer-refusal-${name}.json`]);
147
+ expect(readProducerReceipt(root, task.id)).toEqual({
148
+ ok: false,
149
+ detail:
150
+ "Missing/corrupt producer completion contract; the producer's latest run refused: No bound producer pre-execution frame",
151
+ });
152
+ // With no receipt at all, the miss still says why the latest run published none.
153
+ await rm(receiptPath);
154
+ const missing = readProducerReceipt(root, task.id);
155
+ expect(missing.ok ? 'hit' : missing.detail).toEndWith(
156
+ "; the producer's latest run refused: No bound producer pre-execution frame",
157
+ );
158
+ } finally {
159
+ if (inherited === undefined) delete process.env.NX_WORKSPACE_DATA_DIRECTORY;
160
+ else process.env.NX_WORKSPACE_DATA_DIRECTORY = inherited;
161
+ await rm(root, { recursive: true, force: true });
162
+ }
163
+ });
164
+ });