@smoothbricks/nx-plugin 0.5.5 → 0.5.6

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 (43) hide show
  1. package/README.md +50 -11
  2. package/dist/ensure-built-receipt.d.ts +2 -2
  3. package/dist/ensure-built-receipt.d.ts.map +1 -1
  4. package/dist/ensure-built-receipt.js +7 -2
  5. package/dist/ensure-built-witness.d.ts +12 -1
  6. package/dist/ensure-built-witness.d.ts.map +1 -1
  7. package/dist/ensure-built-witness.js +32 -0
  8. package/dist/ensure-built.d.ts +2 -2
  9. package/dist/ensure-built.d.ts.map +1 -1
  10. package/dist/ensure-built.js +27 -5
  11. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  12. package/dist/executors/bounded-exec/executor.js +48 -11
  13. package/dist/executors/bounded-exec/progress.d.ts +1 -3
  14. package/dist/executors/bounded-exec/progress.d.ts.map +1 -1
  15. package/dist/executors/bounded-exec/progress.js +1 -2
  16. package/dist/executors/bounded-exec/runner-hook.d.ts +2 -0
  17. package/dist/executors/bounded-exec/runner-hook.d.ts.map +1 -0
  18. package/dist/executors/bounded-exec/runner-hook.js +301 -0
  19. package/dist/executors/bounded-exec/runner-lifecycle.d.ts +18 -0
  20. package/dist/executors/bounded-exec/runner-lifecycle.d.ts.map +1 -0
  21. package/dist/executors/bounded-exec/runner-lifecycle.js +92 -0
  22. package/dist/producer-receipts.d.ts +24 -1
  23. package/dist/producer-receipts.d.ts.map +1 -1
  24. package/dist/producer-receipts.js +91 -60
  25. package/managed/raw/git-format-staged.yml +16 -3
  26. package/managed/raw/patches/nx@23.2.1.patch +397 -33
  27. package/package.json +2 -2
  28. package/src/ensure-built-receipt.ts +8 -2
  29. package/src/ensure-built-witness.ts +29 -1
  30. package/src/ensure-built.ts +39 -7
  31. package/src/executors/bounded-exec/cargo-progress-host.test.ts +332 -0
  32. package/src/executors/bounded-exec/executor.test.ts +89 -42
  33. package/src/executors/bounded-exec/executor.ts +45 -11
  34. package/src/executors/bounded-exec/progress.test.ts +1 -14
  35. package/src/executors/bounded-exec/progress.ts +2 -5
  36. package/src/executors/bounded-exec/runner-hook.test.ts +193 -0
  37. package/src/executors/bounded-exec/runner-hook.ts +292 -0
  38. package/src/executors/bounded-exec/runner-lifecycle.test.ts +82 -0
  39. package/src/executors/bounded-exec/runner-lifecycle.ts +102 -0
  40. package/src/nx-daemon-start-never.test.ts +137 -0
  41. package/src/producer-receipts.test.ts +99 -0
  42. package/src/producer-receipts.ts +111 -58
  43. package/test-timings.json +4 -0
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Standalone supervisor: <runtime> runner-hook.js <id> <go|cargo> <executable> [args...].
3
+ * The parent requests native JSON output and supplies a private duplex socket on fd 3.
4
+ * Each newline JSON {id,phase} must be echoed exactly after applying the watchdog state.
5
+ * Build is acknowledged before spawn; each native transition is acknowledged before its
6
+ * stdout record is forwarded. Terminal follows child close and drained output, then its
7
+ * acknowledgement closes the channel. The tool receives only descriptors 0, 1, and 2.
8
+ */
9
+ import { spawn } from 'node:child_process';
10
+ import { Socket } from 'node:net';
11
+ function failure(context, error) {
12
+ return new Error(`${context}: ${error instanceof Error ? error.message : String(error)}`);
13
+ }
14
+ // This executable inherits lib es2022; Promise.withResolvers requires es2024.
15
+ function write(stream, bytes) {
16
+ return new Promise((resolve) => {
17
+ stream.write(bytes, (error) => resolve(error ?? null));
18
+ });
19
+ }
20
+ /** Only native stdout records change the lifecycle; arbitrary runner text never does. */
21
+ function nativePhase(runner) {
22
+ const packages = new Set();
23
+ let cargoActive = false;
24
+ return (line) => {
25
+ if (cargoActive || line[0] !== 123)
26
+ return null;
27
+ let event;
28
+ try {
29
+ event = JSON.parse(line.toString('utf8'));
30
+ }
31
+ catch (error) {
32
+ if (error instanceof SyntaxError)
33
+ return null;
34
+ throw error;
35
+ }
36
+ if (typeof event !== 'object' || event === null)
37
+ return null;
38
+ if (runner === 'cargo') {
39
+ if ('reason' in event &&
40
+ event.reason === 'build-finished' &&
41
+ 'success' in event &&
42
+ typeof event.success === 'boolean') {
43
+ // Even a failed build has left compilation. Nothing emitted by a test, doctest,
44
+ // or custom harness can put Cargo back into build or finish this invocation.
45
+ cargoActive = true;
46
+ return 'active';
47
+ }
48
+ return null;
49
+ }
50
+ if (!('Action' in event) || !('Package' in event) || typeof event.Package !== 'string' || 'Test' in event) {
51
+ return null;
52
+ }
53
+ switch (event.Action) {
54
+ case 'start':
55
+ packages.add(event.Package);
56
+ break;
57
+ case 'pass':
58
+ case 'fail':
59
+ case 'skip':
60
+ packages.delete(event.Package);
61
+ break;
62
+ default:
63
+ return null;
64
+ }
65
+ return packages.size === 0 ? 'build' : 'active';
66
+ };
67
+ }
68
+ /** One outstanding phase, acknowledged only after the executor applies its watchdog state. */
69
+ function lifecycle(id, failed) {
70
+ const socket = new Socket({ fd: 3, readable: true, writable: true });
71
+ let pending = null;
72
+ let received = '';
73
+ let error = null;
74
+ let closing = false;
75
+ let phase = null;
76
+ const fail = (cause) => {
77
+ if (error !== null)
78
+ return;
79
+ error = cause;
80
+ const waiting = pending;
81
+ pending = null;
82
+ waiting?.resolve(cause);
83
+ failed(cause);
84
+ socket.destroy();
85
+ };
86
+ socket.on('error', (cause) => fail(failure('lifecycle channel failed', cause)));
87
+ socket.on('end', () => {
88
+ if (!closing)
89
+ fail(new Error('lifecycle channel ended before terminal acknowledgement'));
90
+ });
91
+ socket.on('close', () => {
92
+ if (!closing && error === null)
93
+ fail(new Error('lifecycle channel closed before terminal acknowledgement'));
94
+ });
95
+ socket.on('data', (chunk) => {
96
+ received += chunk.toString('utf8');
97
+ if (pending === null || !pending.message.startsWith(received)) {
98
+ fail(new Error(`unexpected lifecycle acknowledgement: ${JSON.stringify(received)}`));
99
+ }
100
+ else if (received === pending.message) {
101
+ const waiting = pending;
102
+ pending = null;
103
+ received = '';
104
+ waiting.resolve(null);
105
+ }
106
+ });
107
+ return {
108
+ async announce(next) {
109
+ if (error !== null)
110
+ return error;
111
+ if (phase === next)
112
+ return null;
113
+ if (pending !== null)
114
+ throw new Error('concurrent lifecycle announcements');
115
+ const result = await new Promise((resolve) => {
116
+ const message = `${JSON.stringify({ id, phase: next })}\n`;
117
+ pending = { message, resolve };
118
+ socket.write(message, (cause) => {
119
+ if (cause)
120
+ fail(failure('writing lifecycle phase failed', cause));
121
+ });
122
+ });
123
+ if (result === null)
124
+ phase = next;
125
+ return result;
126
+ },
127
+ async close() {
128
+ closing = true;
129
+ if (socket.destroyed)
130
+ return;
131
+ await new Promise((resolve) => {
132
+ socket.once('close', resolve);
133
+ // The shell retains this endpoint for later commands: shutdown/end would poison
134
+ // every inherited reference. Terminal ACK drained our writes; close only ours.
135
+ socket.destroy();
136
+ });
137
+ },
138
+ };
139
+ }
140
+ /** Await each destination write, bounding queued output and preserving its original bytes. */
141
+ async function forward(source, target) {
142
+ try {
143
+ for await (const chunk of source) {
144
+ const bytes = chunk;
145
+ if (!Buffer.isBuffer(bytes))
146
+ throw new Error('child output was not a byte stream');
147
+ const error = await write(target, bytes);
148
+ if (error !== null)
149
+ return error;
150
+ }
151
+ return null;
152
+ }
153
+ catch (error) {
154
+ return failure('reading child output failed', error);
155
+ }
156
+ }
157
+ /** Buffer only possible JSON records; ACK their transition before releasing any of their bytes. */
158
+ async function forwardStdout(source, inspect) {
159
+ let pending = [];
160
+ let start = true;
161
+ let json = false;
162
+ const record = async (line) => {
163
+ const error = await inspect(line);
164
+ return error ?? (await write(process.stdout, line));
165
+ };
166
+ try {
167
+ for await (const chunk of source) {
168
+ const bytes = chunk;
169
+ if (!Buffer.isBuffer(bytes))
170
+ throw new Error('child stdout was not a byte stream');
171
+ let offset = 0;
172
+ while (offset < bytes.length) {
173
+ if (start)
174
+ json = bytes[offset] === 123;
175
+ const newline = bytes.indexOf(10, offset);
176
+ const end = newline === -1 ? bytes.length : newline + 1;
177
+ const piece = bytes.subarray(offset, end);
178
+ let error = null;
179
+ if (json && newline === -1) {
180
+ pending.push(piece);
181
+ }
182
+ else if (json) {
183
+ let line = piece;
184
+ if (pending.length !== 0) {
185
+ pending.push(piece);
186
+ line = Buffer.concat(pending);
187
+ pending = [];
188
+ }
189
+ error = await record(line);
190
+ }
191
+ else {
192
+ error = await write(process.stdout, piece);
193
+ }
194
+ if (error !== null)
195
+ return error;
196
+ start = newline !== -1;
197
+ offset = end;
198
+ }
199
+ }
200
+ return pending.length === 0 ? null : await record(Buffer.concat(pending));
201
+ }
202
+ catch (error) {
203
+ return failure('reading child stdout failed', error);
204
+ }
205
+ }
206
+ /** argv: invocation ID, runner kind, original executable, then its unchanged arguments. */
207
+ async function main([idText, runner, executable, ...args]) {
208
+ const id = Number(idText);
209
+ if (idText === undefined ||
210
+ !/^\d+$/.test(idText) ||
211
+ !Number.isSafeInteger(id) ||
212
+ (runner !== 'go' && runner !== 'cargo') ||
213
+ executable === undefined ||
214
+ executable === '') {
215
+ process.stderr.write('runner-hook: usage: <invocation-id> <go|cargo> <executable> [arguments...]\n');
216
+ process.exitCode = 2;
217
+ return;
218
+ }
219
+ let child = null;
220
+ let failed = false;
221
+ let interrupted = null;
222
+ const fail = (error) => {
223
+ if (failed)
224
+ return;
225
+ failed = true;
226
+ process.exitCode = 1;
227
+ process.stderr.write(`runner-hook: ${error.message}\n`);
228
+ child?.kill('SIGKILL');
229
+ };
230
+ const forwardedSignals = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'];
231
+ const signals = forwardedSignals.map((name) => {
232
+ const listener = () => {
233
+ interrupted = name;
234
+ child?.kill(name);
235
+ };
236
+ process.on(name, listener);
237
+ return { name, listener };
238
+ });
239
+ process.stdout.on('error', fail);
240
+ process.stderr.on('error', fail);
241
+ let channel = null;
242
+ let code = null;
243
+ let exitSignal = null;
244
+ try {
245
+ channel = lifecycle(id, fail);
246
+ const ready = await channel.announce('build');
247
+ if (ready !== null)
248
+ fail(ready);
249
+ if (!failed && interrupted === null) {
250
+ // Descriptor 3 belongs only to this supervisor, never the tool or its descendants.
251
+ const running = spawn(executable, args, { stdio: ['inherit', 'pipe', 'pipe'] });
252
+ child = running;
253
+ const closed = new Promise((resolve) => {
254
+ running.once('close', (status, reason) => {
255
+ code = status;
256
+ exitSignal = reason;
257
+ resolve();
258
+ });
259
+ });
260
+ running.on('error', (error) => fail(failure(`could not run ${JSON.stringify(executable)}`, error)));
261
+ const scan = nativePhase(runner);
262
+ const control = channel;
263
+ const stdout = forwardStdout(running.stdout, async (line) => {
264
+ const next = scan(line);
265
+ return next === null ? null : await control.announce(next);
266
+ }).then((error) => {
267
+ if (error !== null)
268
+ fail(failure('forwarding stdout failed', error));
269
+ });
270
+ const stderr = forward(running.stderr, process.stderr).then((error) => {
271
+ if (error !== null)
272
+ fail(failure('forwarding stderr failed', error));
273
+ });
274
+ await Promise.all([closed, stdout, stderr]);
275
+ }
276
+ else {
277
+ exitSignal = interrupted;
278
+ }
279
+ }
280
+ catch (error) {
281
+ fail(failure('supervisor failed', error));
282
+ }
283
+ // Write callbacks complete only once downstream has accepted every forwarded byte.
284
+ // Flush diagnostics too, before terminal and before re-raising a child's signal.
285
+ for (const error of await Promise.all([write(process.stdout, ''), write(process.stderr, '')])) {
286
+ if (error !== null)
287
+ fail(failure('draining supervisor output failed', error));
288
+ }
289
+ if (channel !== null) {
290
+ const error = await channel.announce('terminal');
291
+ if (error !== null)
292
+ fail(error);
293
+ await channel.close();
294
+ }
295
+ for (const { name, listener } of signals)
296
+ process.off(name, listener);
297
+ process.exitCode = failed ? 1 : (code ?? 1);
298
+ if (!failed && exitSignal !== null)
299
+ process.kill(process.pid, exitSignal);
300
+ }
301
+ await main(process.argv.slice(2));
@@ -0,0 +1,18 @@
1
+ export type RunnerPhase = 'build' | 'active' | 'terminal';
2
+ export interface RunnerPhaseEvent {
3
+ id: number;
4
+ phase: RunnerPhase;
5
+ }
6
+ /** Only complete, direct chains have a known lifecycle. Shell wrappers remain bounded from spawn. */
7
+ export declare function withRunnerLifecycle(command: string): {
8
+ command: string;
9
+ runners: number;
10
+ } | null;
11
+ /** A private supervisor channel, not runner output, grants authority to pause the test clock. */
12
+ export declare function createRunnerLifecycle(runners: number): {
13
+ isTesting: () => boolean;
14
+ error: () => string | null;
15
+ finished: () => boolean;
16
+ accept(line: string): RunnerPhaseEvent | null;
17
+ };
18
+ //# sourceMappingURL=runner-lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner-lifecycle.d.ts","sourceRoot":"","sources":["../../../src/executors/bounded-exec/runner-lifecycle.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,WAAW,GAAG,OAAO,GAAG,QAAQ,GAAG,UAAU,CAAC;AAC1D,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,WAAW,CAAC;CACpB;AAED,qGAAqG;AACrG,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAyChG;AAED,iGAAiG;AACjG,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM;IAKjD,SAAS,QAAM,OAAO;IACtB,KAAK,QAAM,MAAM,GAAG,IAAI;IACxB,QAAQ,QAAM,OAAO;IACrB,MAAM,OAAO,MAAM,GAAG,gBAAgB,GAAG,IAAI;EAmChD"}
@@ -0,0 +1,92 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { shellWord } from '../../runtime-input.js';
3
+ import { invocationSpan, withInvocationFlag } from './cpu-tokens.js';
4
+ import { GO_TEST } from './verdict.js';
5
+ const CARGO_TEST = /^cargo(?:\s+(?:-\S+|\+\S+))*\s+test(?=\s|$)/;
6
+ const MESSAGE_FORMAT = /(?<![\w-])--message-format(?:=|\s+)(?:"[^"]*"|'[^']*'|[^\s]+)/g;
7
+ /** Only complete, direct chains have a known lifecycle. Shell wrappers remain bounded from spawn. */
8
+ export function withRunnerLifecycle(command) {
9
+ // Redirections could replace the private descriptor; newlines/backticks/escapes need a real shell parser.
10
+ if (/[<>\n\r`\\]/.test(command))
11
+ return null;
12
+ let rest = command.trim();
13
+ const parts = [];
14
+ let runners = 0;
15
+ const hook = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? './runner-hook.ts' : './runner-hook.js', import.meta.url));
16
+ while (rest !== '') {
17
+ const kind = rest.search(GO_TEST) === 0 ? 'go' : CARGO_TEST.test(rest) ? 'cargo' : null;
18
+ if (kind === null)
19
+ return null;
20
+ const invocation = kind === 'go' ? GO_TEST : CARGO_TEST;
21
+ const { argsEnd } = invocationSpan(rest, invocation);
22
+ let runner = rest.slice(0, argsEnd).trimEnd();
23
+ if (kind === 'cargo') {
24
+ // Only Cargo's own arguments, never those after the libtest separator, select build reporting.
25
+ const separator = /\s--(?:\s|$)/.exec(runner);
26
+ const end = separator?.index ?? runner.length;
27
+ runner =
28
+ withInvocationFlag(runner.slice(0, end), invocation, MESSAGE_FORMAT, '--message-format=json-render-diagnostics', true) + runner.slice(end);
29
+ }
30
+ // The hook owns an inherited duplex descriptor, which Bun's net.Socket({fd}) does not adopt.
31
+ const runtime = process.versions.bun === undefined ? process.execPath : 'node';
32
+ parts.push(`${shellWord(runtime)} ${shellWord(hook)} ${runners} ${kind} ${runner}`);
33
+ runners += 1;
34
+ rest = rest.slice(argsEnd).trimStart();
35
+ if (rest === '')
36
+ break;
37
+ const separator = /^(?:&&|\|\||;)\s*/.exec(rest);
38
+ if (separator === null)
39
+ return null;
40
+ parts.push(separator[0].trim());
41
+ rest = rest.slice(separator[0].length);
42
+ if (rest === '')
43
+ return null;
44
+ }
45
+ return runners === 0 ? null : { command: parts.join(' '), runners };
46
+ }
47
+ /** A private supervisor channel, not runner output, grants authority to pause the test clock. */
48
+ export function createRunnerLifecycle(runners) {
49
+ let current = 0;
50
+ let phase = 'active'; // Shell and supervisor startup are bounded until their build declaration.
51
+ let failure = null;
52
+ return {
53
+ isTesting: () => failure !== null || phase === 'active' || (phase === 'terminal' && current < runners - 1),
54
+ error: () => failure,
55
+ finished: () => phase === 'terminal' && failure === null,
56
+ accept(line) {
57
+ if (failure !== null)
58
+ return null;
59
+ let event;
60
+ try {
61
+ event = JSON.parse(line);
62
+ }
63
+ catch (error) {
64
+ if (!(error instanceof SyntaxError))
65
+ throw error;
66
+ failure = 'invalid JSON on the runner lifecycle channel';
67
+ return null;
68
+ }
69
+ if (typeof event !== 'object' ||
70
+ event === null ||
71
+ !('id' in event) ||
72
+ !('phase' in event) ||
73
+ typeof event.id !== 'number' ||
74
+ !Number.isSafeInteger(event.id) ||
75
+ event.id < current ||
76
+ event.id >= runners ||
77
+ (event.id === current && phase === 'terminal') ||
78
+ (event.phase !== 'build' && event.phase !== 'active' && event.phase !== 'terminal')) {
79
+ failure = 'invalid or retired invocation on the runner lifecycle channel';
80
+ return null;
81
+ }
82
+ // && and || may skip invocations. A new supervisor can advance only after the previous one ended.
83
+ if (event.id !== current && phase !== 'terminal') {
84
+ failure = 'overlapping invocations on a serial runner lifecycle channel';
85
+ return null;
86
+ }
87
+ current = event.id;
88
+ phase = event.phase;
89
+ return { id: current, phase };
90
+ },
91
+ };
92
+ }
@@ -1,7 +1,12 @@
1
+ import type { NxJsonConfiguration } from 'nx/src/config/nx-json';
1
2
  import type { Task, TaskGraph } from 'nx/src/config/task-graph';
3
+ import type { expandOutputs } from 'nx/src/native';
2
4
  import type { PostTasksExecutionContext, PreTasksExecutionContext } from 'nx/src/project-graph/plugins/public-api';
3
- import { type EnsureBuiltProducerReceipt, type EnsureBuiltReceipt } from './ensure-built.js';
5
+ import type { readModulePackageJsonWithoutFallbacks } from 'nx/src/utils/package-json';
6
+ import { type EnsureBuiltProducerReceipt, type EnsureBuiltProducerTool, type EnsureBuiltReceipt } from './ensure-built.js';
4
7
  import { type ReceiptEvidence } from './ensure-built-receipt.js';
8
+ import { type NodeWitness } from './ensure-built-witness.js';
9
+ import { type GraphInputContractProof } from './graph-input-contract.js';
5
10
  export interface ProducerReceiptsOptions {
6
11
  readonly producerReceipts?: {
7
12
  readonly targets: readonly string[];
@@ -17,6 +22,24 @@ export interface ProducerReceiptsOptions {
17
22
  * is no source or input of the run that publishes it.
18
23
  */
19
24
  export declare const PRODUCER_RECORDS: string;
25
+ /**
26
+ * The installed closure of Nx, this plugin, TypeScript and the local graph plugins as one producer tool: every node of
27
+ * the installation census, and the module namespace each of its resolutions searched. The census is not proved by a
28
+ * stat pass of its own: each of its nodes is stat-ed again as a tool node, a file whose stamp moved since the census
29
+ * read it is read again, and the capture's stability check refuses a tool node that moves before publication.
30
+ *
31
+ * Its value is a function of the closure's node stamps (device, inode, mode, size, mtime and ctime), not of the moment
32
+ * it is taken. So every node is stat-ed on every call, and that is what makes reuse safe: a file whose stamp is the one
33
+ * the census recorded at `record` read it at keeps that census's hash, so an unchanged closure reads no file bytes,
34
+ * while a file rewritten in place, as a developer-linked package's rebuilt `dist` is with no lockfile or
35
+ * `node_modules` change, moves its ctime and is read again. The tool's nodes take the hash this census read
36
+ * ({@link censusFileHashes}) instead of reading each file a second time: a write landing between two reads could make
37
+ * them disagree.
38
+ */
39
+ export declare function installedClosureTool(root: string, nxJson: NxJsonConfiguration, localInputs: GraphInputContractProof | null, record: string, resolvePackage: typeof readModulePackageJsonWithoutFallbacks, expand: typeof expandOutputs, census: {
40
+ readonly start: bigint;
41
+ readonly observed: NodeWitness[];
42
+ }): ReceiptEvidence<EnsureBuiltProducerTool>;
20
43
  export declare function completedProducerTasks(graph: TaskGraph, results: PostTasksExecutionContext['taskResults']): ReceiptEvidence<readonly Task[]>;
21
44
  export declare function producerEnvironmentIdentity(inputs: EnsureBuiltProducerReceipt['inputs']): string;
22
45
  export declare function preTasksExecution(options: ProducerReceiptsOptions | undefined, context: PreTasksExecutionContext): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"producer-receipts.d.ts","sourceRoot":"","sources":["../src/producer-receipts.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAChE,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AC,QAAQ,CAAC,GAAG,MAAM,CAShG;AACD,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,uBAAuB,GAAG,SAAS,EAC5C,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,IAAI,CAAC,CAgDf;AACD,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,uBAAuB,GAAG,SAAS,EAC5C,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC,IAAI,CAAC,CAoIf;AACD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,eAAe,CAAC,kBAAkB,CAAC,CAOrG"}
@@ -5,7 +5,7 @@ import { delimiter, dirname, join, resolve } from 'node:path';
5
5
  import typia from 'typia';
6
6
  import { createWorkspaceNxRequire, parseTargetSelector, providerInputProof, selectorTaskId, } from './ensure-built.js';
7
7
  import { captureProducerSource, producerOutputPaths, providerReceipt, receiptNode, } from './ensure-built-receipt.js';
8
- import { censusStart, graphInstallationIdentity, movedNodes, workspaceSnapshot, } from './ensure-built-witness.js';
8
+ import { censusFileHashes, censusStart, graphInstallationCensus, movedNodes, readInstallationCensus, workspaceSnapshot, writeWitness, } from './ensure-built-witness.js';
9
9
  import { graphInputContractIdentity } from './graph-input-contract.js';
10
10
  /**
11
11
  * Where a checkout keeps its producer records, relative to its root: in its own source tree, never in Nx's
@@ -17,6 +17,11 @@ import { graphInputContractIdentity } from './graph-input-contract.js';
17
17
  * is no source or input of the run that publishes it.
18
18
  */
19
19
  export const PRODUCER_RECORDS = join('.cache', 'producer-receipts');
20
+ /**
21
+ * The installation census the pre-task hook took last, in Nx's workspace-data beside the graph witness: a hash source
22
+ * for the next census ({@link installedClosureTool}), never a proof and never part of a receipt.
23
+ */
24
+ const PRODUCER_INSTALLATION_CENSUS = 'producer-installation-census.json';
20
25
  const runs = new Map();
21
26
  function sha(value) {
22
27
  return createHash('sha256').update(JSON.stringify(value)).digest('hex');
@@ -96,6 +101,80 @@ function targetGraph(root, target, projectGraph) {
96
101
  throw new Error(`Invalid declared producer target ${target}`);
97
102
  return createWorkspaceNxRequire(root)('nx/src/tasks-runner/create-task-graph').createTaskGraph(projectGraph, {}, [selector.project], [selector.target], selector.configuration, {}, false);
98
103
  }
104
+ /**
105
+ * The installed closure of Nx, this plugin, TypeScript and the local graph plugins as one producer tool: every node of
106
+ * the installation census, and the module namespace each of its resolutions searched. The census is not proved by a
107
+ * stat pass of its own: each of its nodes is stat-ed again as a tool node, a file whose stamp moved since the census
108
+ * read it is read again, and the capture's stability check refuses a tool node that moves before publication.
109
+ *
110
+ * Its value is a function of the closure's node stamps (device, inode, mode, size, mtime and ctime), not of the moment
111
+ * it is taken. So every node is stat-ed on every call, and that is what makes reuse safe: a file whose stamp is the one
112
+ * the census recorded at `record` read it at keeps that census's hash, so an unchanged closure reads no file bytes,
113
+ * while a file rewritten in place, as a developer-linked package's rebuilt `dist` is with no lockfile or
114
+ * `node_modules` change, moves its ctime and is read again. The tool's nodes take the hash this census read
115
+ * ({@link censusFileHashes}) instead of reading each file a second time: a write landing between two reads could make
116
+ * them disagree.
117
+ */
118
+ export function installedClosureTool(root, nxJson, localInputs, record, resolvePackage, expand, census) {
119
+ let installationMiss = 'unproved installed module/resolution closure';
120
+ performance.mark('producerReceipts:census:start');
121
+ const installation = graphInstallationCensus(root, nxJson, resolvePackage, expand, localInputs ?? { plugins: [], packages: [], identity: '[]' }, (detail) => {
122
+ installationMiss = detail;
123
+ }, readInstallationCensus(record));
124
+ performance.measure('producerReceipts:census', 'producerReceipts:census:start');
125
+ if (installation === null)
126
+ return { ok: false, detail: `Producer installed module/resolution closure is unproved: ${installationMiss}` };
127
+ writeWitness(record, installation);
128
+ const paths = new Set(installation.nodes.map(({ path }) => path));
129
+ const absent = new Set();
130
+ function namespace(path) {
131
+ let stats;
132
+ try {
133
+ stats = lstatSync(path);
134
+ }
135
+ catch (error) {
136
+ if (error instanceof Error && 'code' in error && ['ENOENT', 'ENOTDIR'].includes(String(error.code))) {
137
+ absent.add(path);
138
+ return;
139
+ }
140
+ throw error;
141
+ }
142
+ paths.add(path);
143
+ if (stats.isSymbolicLink())
144
+ paths.add(realpathSync(path));
145
+ if (stats.isDirectory())
146
+ for (const name of readdirSync(path))
147
+ paths.add(join(path, name));
148
+ }
149
+ const resolutions = [];
150
+ for (const [from, name, target] of installation.resolutions) {
151
+ resolutions.push({ from, name, target });
152
+ for (const directory of createRequire(join(from, 'package.json')).resolve.paths(name) ?? []) {
153
+ namespace(directory);
154
+ const candidate = join(directory, name);
155
+ if (existsSync(candidate))
156
+ namespace(candidate);
157
+ else
158
+ absent.add(candidate);
159
+ }
160
+ }
161
+ const recorded = censusFileHashes(installation);
162
+ const nodes = [...paths].sort().map((path) => receiptNode(path, path, census, recorded));
163
+ return {
164
+ ok: true,
165
+ value: {
166
+ kind: 'module',
167
+ name: 'installed-nx-plugin-closure',
168
+ from: root,
169
+ path: root,
170
+ physicalPath: realpathSync(root),
171
+ nodes,
172
+ missing: [...absent].sort(),
173
+ resolutions,
174
+ sha256: sha(nodes),
175
+ },
176
+ };
177
+ }
99
178
  /** Tool resolution is captured in producer scope; readers inspect its recorded filesystem, not their own environment. */
100
179
  function toolsFor(root, nxJson, projectGraph, bases) {
101
180
  try {
@@ -115,67 +194,12 @@ function toolsFor(root, nxJson, projectGraph, bases) {
115
194
  return { ok: false, detail: proof.runtimeSource.detail };
116
195
  needsCargo ||= Object.values(proof.inputs).some((input) => input.runtime.length > 0);
117
196
  }
118
- let installationMiss = 'unproved installed module/resolution closure';
119
- const identity = graphInstallationIdentity(root, nxJson, load('nx/src/utils/package-json').readModulePackageJson, load('nx/src/native').expandOutputs, local ?? { plugins: [], packages: [], identity: '[]' }, (detail) => {
120
- installationMiss = detail;
121
- });
122
- if (identity === null)
123
- return { ok: false, detail: `Producer installed module/resolution closure is unproved: ${installationMiss}` };
124
- const installation = (() => {
125
- const _io0 = input => Array.isArray(input.nodes) && input.nodes.every(elem => "object" === typeof elem && null !== elem && _io1(elem)) && (Array.isArray(input.resolutions) && input.resolutions.every(elem => Array.isArray(elem) && (elem.length === 3 && "string" === typeof elem[0] && "string" === typeof elem[1] && (null === elem[2] || "string" === typeof elem[2])))) && (null === input.localInputs || "string" === typeof input.localInputs);
126
- const _io1 = input => "string" === typeof input.path && "string" === typeof input.stamp;
127
- const __is = input => "object" === typeof input && null !== input && _io0(input);
128
- return input => { input = JSON.parse(input); return __is(input) ? input : null; };
129
- })()(identity);
130
- if (installation === null)
131
- return { ok: false, detail: 'Invalid installed module closure evidence' };
132
197
  const observed = [];
133
198
  const census = { start: censusStart(), observed };
134
- const paths = new Set(installation.nodes.map(({ path }) => path));
135
- const absent = new Set();
136
- function namespace(path) {
137
- let stats;
138
- try {
139
- stats = lstatSync(path);
140
- }
141
- catch (error) {
142
- if (error instanceof Error && 'code' in error && ['ENOENT', 'ENOTDIR'].includes(String(error.code))) {
143
- absent.add(path);
144
- return;
145
- }
146
- throw error;
147
- }
148
- paths.add(path);
149
- if (stats.isSymbolicLink())
150
- paths.add(realpathSync(path));
151
- if (stats.isDirectory())
152
- for (const name of readdirSync(path))
153
- paths.add(join(path, name));
154
- }
155
- const resolutions = [];
156
- for (const [from, name, target] of installation.resolutions) {
157
- resolutions.push({ from, name, target });
158
- for (const directory of createRequire(join(from, 'package.json')).resolve.paths(name) ?? []) {
159
- namespace(directory);
160
- const candidate = join(directory, name);
161
- if (existsSync(candidate))
162
- namespace(candidate);
163
- else
164
- absent.add(candidate);
165
- }
166
- }
167
- const nodes = [...paths].sort().map((path) => receiptNode(path, path, census));
168
- const module = {
169
- kind: 'module',
170
- name: 'installed-nx-plugin-closure',
171
- from: root,
172
- path: root,
173
- physicalPath: realpathSync(root),
174
- nodes,
175
- missing: [...absent].sort(),
176
- resolutions,
177
- sha256: sha(nodes),
178
- };
199
+ const closure = installedClosureTool(root, nxJson, local, join(data, PRODUCER_INSTALLATION_CENSUS), load('nx/src/utils/package-json').readModulePackageJson, load('nx/src/native').expandOutputs, census);
200
+ if (!closure.ok)
201
+ return closure;
202
+ const module = closure.value;
179
203
  const tools = [module];
180
204
  for (const name of ['nx-runtime', 'bun', 'sh', 'git', ...(needsCargo ? ['rustc', 'cargo'] : [])]) {
181
205
  const candidates = name === 'nx-runtime'
@@ -274,19 +298,26 @@ export async function preTasksExecution(options, context) {
274
298
  return;
275
299
  try {
276
300
  const load = createWorkspaceNxRequire(context.workspaceRoot);
301
+ // A hook that can hold a run for minutes names its phases: Nx reports each measure under NX_PERF_LOGGING.
302
+ performance.mark('producerReceipts:graph:start');
277
303
  const projectGraph = await load('nx/src/project-graph/project-graph').createProjectGraphAsync();
304
+ performance.measure('producerReceipts:graph', 'producerReceipts:graph:start');
278
305
  const bases = new Map();
279
306
  for (const target of targets) {
307
+ performance.mark('producerReceipts:source:start');
280
308
  const graph = targetGraph(context.workspaceRoot, target, projectGraph);
281
309
  const outputs = producerOutputPaths(context.workspaceRoot, Object.values(graph.tasks), load('nx/src/native').expandOutputs);
282
310
  const source = captureProducerSource(context.workspaceRoot, outputs);
311
+ performance.measure('producerReceipts:source', 'producerReceipts:source:start');
283
312
  if (!source.ok) {
284
313
  runs.set(context.id, source);
285
314
  return;
286
315
  }
287
316
  bases.set(target, { graph, source: source.value });
288
317
  }
318
+ performance.mark('producerReceipts:tools:start');
289
319
  const tools = toolsFor(context.workspaceRoot, context.nxJsonConfiguration, projectGraph, [...bases.values()]);
320
+ performance.measure('producerReceipts:tools', 'producerReceipts:tools:start');
290
321
  runs.set(context.id, tools.ok
291
322
  ? {
292
323
  ok: true,