@smoothbricks/nx-plugin 0.3.13 → 0.4.0

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.
@@ -0,0 +1,602 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { existsSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { join, resolve } from 'node:path';
6
+
7
+ import type { NxJsonConfiguration } from 'nx/src/config/nx-json';
8
+ import type { ProjectGraph, ProjectGraphProjectNode } from 'nx/src/config/project-graph';
9
+ import type { Task } from 'nx/src/config/task-graph';
10
+ import type { TaskResults } from 'nx/src/tasks-runner/life-cycle';
11
+ import type { NxArgs } from 'nx/src/utils/command-line-utils';
12
+
13
+ interface NxRuntimeModules {
14
+ readonly 'nx/src/config/nx-json': typeof import('nx/src/config/nx-json');
15
+ readonly 'nx/src/daemon/client/client': typeof import('nx/src/daemon/client/client');
16
+ readonly 'nx/src/hasher/hash-task': typeof import('nx/src/hasher/hash-task');
17
+ readonly 'nx/src/hasher/task-hasher': typeof import('nx/src/hasher/task-hasher');
18
+ readonly 'nx/src/project-graph/plugins/tasks-execution-hooks': typeof import('nx/src/project-graph/plugins/tasks-execution-hooks');
19
+ readonly 'nx/src/project-graph/project-graph': typeof import('nx/src/project-graph/project-graph');
20
+ readonly 'nx/src/tasks-runner/cache': typeof import('nx/src/tasks-runner/cache');
21
+ readonly 'nx/src/tasks-runner/create-task-graph': typeof import('nx/src/tasks-runner/create-task-graph');
22
+ readonly 'nx/src/tasks-runner/run-command': typeof import('nx/src/tasks-runner/run-command');
23
+ readonly 'nx/src/tasks-runner/task-env': typeof import('nx/src/tasks-runner/task-env');
24
+ readonly 'nx/src/utils/command-line-utils': typeof import('nx/src/utils/command-line-utils');
25
+ readonly 'nx/src/utils/exit-codes': typeof import('nx/src/utils/exit-codes');
26
+ readonly 'nx/src/utils/perf-logging': typeof import('nx/src/utils/perf-logging');
27
+ readonly 'nx/src/utils/workspace-root': typeof import('nx/src/utils/workspace-root');
28
+ }
29
+
30
+ type WorkspaceNxRequire = <Specifier extends keyof NxRuntimeModules>(
31
+ specifier: Specifier,
32
+ ) => NxRuntimeModules[Specifier];
33
+
34
+ function createWorkspaceNxRequire(workspaceRoot: string): WorkspaceNxRequire {
35
+ const requireFromWorkspace = createRequire(join(workspaceRoot, 'package.json'));
36
+ return function requireNx<Specifier extends keyof NxRuntimeModules>(
37
+ specifier: Specifier,
38
+ ): NxRuntimeModules[Specifier] {
39
+ return requireFromWorkspace(specifier);
40
+ };
41
+ }
42
+
43
+ /**
44
+ * A `project:target` or `project:target:configuration` selector.
45
+ *
46
+ * Configuration belongs in the selector rather than in a separate option
47
+ * because it is part of the cache key: `app:build` and `app:build:production`
48
+ * are two different tasks with two different hashes.
49
+ */
50
+ export interface TargetSelector {
51
+ readonly project: string;
52
+ readonly target: string;
53
+ readonly configuration: string | undefined;
54
+ }
55
+
56
+ /**
57
+ * Why the target could not be replayed from what is already on disk.
58
+ *
59
+ * Every variant names the task that ended the probe: in a dependency graph
60
+ * "something changed" is unactionable, and the useful question is always which
61
+ * of the twelve dependencies moved.
62
+ */
63
+ export type MissReason =
64
+ | { readonly kind: 'uncacheable'; readonly taskId: string }
65
+ | { readonly kind: 'unhashable'; readonly taskId: string }
66
+ | { readonly kind: 'not-cached'; readonly taskId: string }
67
+ | { readonly kind: 'cached-failure'; readonly taskId: string; readonly code: number }
68
+ | { readonly kind: 'stale-outputs'; readonly taskId: string }
69
+ | { readonly kind: 'cache-disabled'; readonly taskId: string }
70
+ | { readonly kind: 'no-daemon'; readonly taskId: string };
71
+
72
+ /**
73
+ * `hit` means nothing ran: every task in the graph was a recorded success and
74
+ * every recorded output is still byte-identical on disk, so the artifacts are
75
+ * what a fresh run would produce.
76
+ *
77
+ * `built` means the work was handed to Nx — which may have restored outputs
78
+ * from the local cache rather than recompiled anything. The line `hit` draws is
79
+ * "did this process have to do work", which is what a CLI wrapper needs in
80
+ * order to decide whether to stay quiet.
81
+ *
82
+ * `failed` is an operational outcome, not an exception: the target ran and did
83
+ * not succeed. A caller re-raises `signal` when there is one and exits with
84
+ * `exitCode` otherwise, so a Ctrl-C during a build stays a Ctrl-C.
85
+ */
86
+ export type EnsureBuiltResult =
87
+ | { readonly disposition: 'hit' }
88
+ | { readonly disposition: 'built'; readonly reason: MissReason }
89
+ | {
90
+ readonly disposition: 'failed';
91
+ readonly reason: MissReason;
92
+ readonly exitCode: number;
93
+ readonly signal: NodeJS.Signals | null;
94
+ };
95
+
96
+ export interface EnsureBuiltOptions {
97
+ /** `project:target` or `project:target:configuration`. */
98
+ readonly target: string;
99
+ /**
100
+ * Nx workspace root. Required rather than discovered: a wrapper script knows
101
+ * its own checkout, and inferring from the caller's directory would silently
102
+ * bind whichever workspace they happen to be standing in.
103
+ */
104
+ readonly cwd: string;
105
+ /**
106
+ * How the run that happens on a miss reports progress. `stream` is the
107
+ * default and the only style offered: this facility fronts multi-minute
108
+ * compiles, and Nx's buffered styles emit nothing until a task finishes, so a
109
+ * silent terminal would read as a hang.
110
+ */
111
+ readonly onMiss?: 'stream';
112
+ }
113
+
114
+ /** A full hit carries no payload, so it is the same value every time. */
115
+ const HIT: EnsureBuiltResult = Object.freeze({ disposition: 'hit' });
116
+
117
+ const NO_TASK_RESULTS: TaskResults = Object.freeze({});
118
+
119
+ export function parseTargetSelector(spec: string): TargetSelector | null {
120
+ const parts = spec.split(':');
121
+ if (parts.length < 2 || parts.length > 3) {
122
+ return null;
123
+ }
124
+ for (const part of parts) {
125
+ if (part.length === 0) {
126
+ return null;
127
+ }
128
+ }
129
+ return { project: parts[0], target: parts[1], configuration: parts[2] };
130
+ }
131
+
132
+ export function describeMiss(reason: MissReason): string {
133
+ switch (reason.kind) {
134
+ case 'uncacheable':
135
+ return `${reason.taskId} is not cacheable, so it must run`;
136
+ case 'unhashable':
137
+ return `${reason.taskId} did not produce a task hash`;
138
+ case 'not-cached':
139
+ return `${reason.taskId} has no cached result for its current inputs`;
140
+ case 'cached-failure':
141
+ return `${reason.taskId} last failed with exit code ${reason.code}`;
142
+ case 'stale-outputs':
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`;
146
+ case 'no-daemon':
147
+ return `the Nx daemon is disabled, so ${reason.taskId} cannot be checked without running it`;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * First reason the task set cannot be replayed, considering only recorded
153
+ * results — no filesystem access. `null` means every task is a recorded
154
+ * success, and the on-disk check is worth paying for.
155
+ *
156
+ * A cached *failure* counts as a miss even though Nx replays one when
157
+ * `NX_CACHE_FAILURES` is set: this facility exists to hand the process over to
158
+ * a binary, and replaying a failed build would hand over a stale one.
159
+ */
160
+ export function firstCacheMiss(
161
+ tasks: readonly Task[],
162
+ cachedCodeByHash: ReadonlyMap<string, number>,
163
+ ): MissReason | null {
164
+ for (const task of tasks) {
165
+ if (!task.cache) {
166
+ return { kind: 'uncacheable', taskId: task.id };
167
+ }
168
+ // A custom hasher is outside Nx's type guarantees and may return an empty
169
+ // value. Without a hash there is no cache key to query.
170
+ if (!task.hash) {
171
+ return { kind: 'unhashable', taskId: task.id };
172
+ }
173
+ const code = cachedCodeByHash.get(task.hash);
174
+ if (code === undefined) {
175
+ return { kind: 'not-cached', taskId: task.id };
176
+ }
177
+ if (code !== 0) {
178
+ return { kind: 'cached-failure', taskId: task.id, code };
179
+ }
180
+ }
181
+ return null;
182
+ }
183
+
184
+ /**
185
+ * First task whose recorded outputs are no longer the bytes on disk.
186
+ *
187
+ * `matches[index]` is the daemon's verdict for `tasks[index]`. A short or
188
+ * ragged array counts as stale rather than as a hit: a missing verdict is not a
189
+ * positive one, and being wrong here means exec'ing a binary that was deleted.
190
+ */
191
+ export function firstStaleOutputs(tasks: readonly Task[], matches: readonly boolean[]): MissReason | null {
192
+ for (let index = 0; index < tasks.length; index += 1) {
193
+ if (matches[index] !== true) {
194
+ return { kind: 'stale-outputs', taskId: tasks[index].id };
195
+ }
196
+ }
197
+ return null;
198
+ }
199
+
200
+ /**
201
+ * Make sure an Nx target's outputs are on disk, doing as little as possible
202
+ * when they already are.
203
+ *
204
+ * "Already built" is the hot path, because a checkout-local CLI wrapper pays it
205
+ * on every invocation. So it never spawns the `nx` CLI: the project graph, the
206
+ * task hashes and the on-disk output verification are daemon round-trips, the
207
+ * cache lookup is a local SQLite read, and Nx's task runner is only invoked
208
+ * once something is known to need running.
209
+ *
210
+ * With the daemon disabled there is no probe to make — hashing would have to
211
+ * build the project graph in this process, and no service holds the recorded
212
+ * output hashes to check the working tree against — so the target is handed to
213
+ * the workspace's own `nx` CLI unconditionally.
214
+ */
215
+ export async function ensureBuilt(options: EnsureBuiltOptions): Promise<EnsureBuiltResult> {
216
+ const selector = parseTargetSelector(options.target);
217
+ if (!selector) {
218
+ throw new Error(`ensureBuilt: '${options.target}' is not a project:target[:configuration] selector`);
219
+ }
220
+ // Resolved before the chdir below, so a relative `cwd` still means what the
221
+ // caller meant.
222
+ const workspaceRoot = resolve(options.cwd);
223
+ const callerCwd = process.cwd();
224
+ const callerEnv = { ...process.env };
225
+ try {
226
+ // `cd <root> && nx run ...` is the invocation whose hashes are in the
227
+ // cache. Everything below — plugin hooks, `runtime` inputs, and the hasher,
228
+ // which keys against `process.cwd()` — has to see the same directory or the
229
+ // probe keys differently from the CLI and never hits.
230
+ process.chdir(workspaceRoot);
231
+ return await ensureBuiltInWorkspace(workspaceRoot, selector, options.onMiss ?? 'stream');
232
+ } finally {
233
+ // Nx configures itself through the environment and this function runs
234
+ // in-process, so without this the caller — and anything it goes on to exec
235
+ // — would inherit NX_WORKSPACE_ROOT_PATH, the stream/prefix flags, and
236
+ // whatever a plugin's preTasksExecution hook injected. The wrapper this
237
+ // replaces got that isolation for free by running Nx in a child.
238
+ process.chdir(callerCwd);
239
+ for (const key of Object.keys(process.env)) {
240
+ if (!(key in callerEnv)) {
241
+ delete process.env[key];
242
+ }
243
+ }
244
+ for (const [key, value] of Object.entries(callerEnv)) {
245
+ if (process.env[key] !== value) {
246
+ process.env[key] = value;
247
+ }
248
+ }
249
+ }
250
+ }
251
+
252
+ async function ensureBuiltInWorkspace(
253
+ workspaceRoot: string,
254
+ selector: TargetSelector,
255
+ onMiss: 'stream',
256
+ ): Promise<EnsureBuiltResult> {
257
+ // The environment has precedence over nx.json. Avoid loading Nx at all on
258
+ // this explicit fallback path, which also lets a deliberately minimal
259
+ // checkout-local CLI stand in for Nx.
260
+ if (process.env.NX_DAEMON === 'false') {
261
+ return runViaCli(workspaceRoot, selector);
262
+ }
263
+ // Nx rejects daemon access when the client package's version differs from
264
+ // the workspace's running daemon. Resolve every runtime module from the
265
+ // target checkout rather than this package's own dependency: a reusable
266
+ // wrapper must keep using the daemon after the workspace takes an Nx patch.
267
+ const requireNx = createWorkspaceNxRequire(workspaceRoot);
268
+ bindWorkspaceRoot(workspaceRoot, requireNx);
269
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
270
+ if (!daemonClient.enabled()) {
271
+ return runViaCli(workspaceRoot, selector);
272
+ }
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
+
284
+ const { readNxJson } = requireNx('nx/src/config/nx-json');
285
+ const { splitArgsIntoNxArgsAndOverrides } = requireNx('nx/src/utils/command-line-utils');
286
+ const { setEnvVarsBasedOnArgs } = requireNx('nx/src/tasks-runner/run-command');
287
+ const hooks = requireNx('nx/src/project-graph/plugins/tasks-execution-hooks');
288
+
289
+ const nxJson = readNxJson();
290
+ // Reproduce `nx run <selector> --outputStyle=<style>` exactly. Task hashes
291
+ // are derived from these arguments, so anything hand-rolled here instead of
292
+ // routed through Nx's own argument normalization would key the cache
293
+ // differently from the CLI and turn every probe into a miss.
294
+ const { nxArgs, overrides } = splitArgsIntoNxArgsAndOverrides(
295
+ { targets: [selector.target], configuration: selector.configuration, outputStyle: onMiss },
296
+ 'run-one',
297
+ { printWarnings: false },
298
+ nxJson,
299
+ );
300
+ const loadDotEnvFiles = process.env.NX_LOAD_DOT_ENV_FILES !== 'false';
301
+ // Sets NX_LOAD_DOT_ENV_FILES and the stream/prefix flags, which the hasher
302
+ // reads through each task's environment. It has to happen before hashing or
303
+ // the probe keys differently from the CLI.
304
+ setEnvVarsBasedOnArgs(nxArgs, loadDotEnvFiles);
305
+
306
+ const runId = randomUUID();
307
+ const startTime = Date.now();
308
+ // Plugin `preTasksExecution` hooks inject environment variables, and declared
309
+ // `env` inputs hash against them. Skipping the hook would not merely cost
310
+ // hits: the run below would then execute with a different environment than
311
+ // the CLI does, record a hash the CLI never looks up, and thrash the cache.
312
+ await hooks.runPreTasksExecution({
313
+ id: runId,
314
+ workspaceRoot,
315
+ nxJsonConfiguration: nxJson,
316
+ argv: process.argv,
317
+ });
318
+
319
+ performance.mark('ensureBuilt:probe:start');
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
+ }
330
+ performance.measure('ensureBuilt:probe', 'ensureBuilt:probe:start');
331
+ const outcome =
332
+ reason === null
333
+ ? { result: HIT, taskResults: NO_TASK_RESULTS }
334
+ : await runTarget(nxJson, nxArgs, overrides, selector, reason, requireNx);
335
+ await hooks.runPostTasksExecution({
336
+ id: runId,
337
+ taskResults: outcome.taskResults,
338
+ workspaceRoot,
339
+ nxJsonConfiguration: nxJson,
340
+ argv: process.argv,
341
+ startTime,
342
+ endTime: Date.now(),
343
+ });
344
+ return outcome.result;
345
+ }
346
+
347
+ /**
348
+ * Nx computes `workspaceRoot` once, at module load, from
349
+ * `NX_WORKSPACE_ROOT_PATH` or the current directory — and its daemon client is
350
+ * a module-level singleton that reads `nx.json` from that root. So the root has
351
+ * to be bound before the first Nx module loads, which is why this module
352
+ * imports Nx dynamically throughout. A static import at the top of the file
353
+ * would bind the caller's launch directory instead.
354
+ */
355
+ function bindWorkspaceRoot(workspaceRoot: string, requireNx: WorkspaceNxRequire): void {
356
+ process.env.NX_WORKSPACE_ROOT_PATH = workspaceRoot;
357
+ if (process.env.NX_PERF_LOGGING === 'true') {
358
+ // Installs Nx's PerformanceObserver, which reports every `performance
359
+ // .measure` this module and Nx itself record. Loading it unconditionally
360
+ // would add an observer to hot paths that never want one.
361
+ requireNx('nx/src/utils/perf-logging');
362
+ }
363
+ const { workspaceRoot: boundRoot } = requireNx('nx/src/utils/workspace-root');
364
+ if (boundRoot !== workspaceRoot) {
365
+ // One process cannot serve two workspaces: the constant and the daemon
366
+ // client singleton are already bound. Say so rather than silently probing
367
+ // the wrong checkout.
368
+ throw new Error(
369
+ `ensureBuilt: Nx is already bound to workspace root ${boundRoot}, cannot switch to ${workspaceRoot}`,
370
+ );
371
+ }
372
+ }
373
+
374
+ /** `null` when the target is already built; otherwise the first reason it is not. */
375
+ async function probe(
376
+ nxJson: NxJsonConfiguration,
377
+ nxArgs: NxArgs,
378
+ overrides: Record<string, unknown>,
379
+ selector: TargetSelector,
380
+ requireNx: WorkspaceNxRequire,
381
+ ): Promise<MissReason | null> {
382
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
383
+ const { createTaskGraph } = requireNx('nx/src/tasks-runner/create-task-graph');
384
+ const { DaemonBasedTaskHasher } = requireNx('nx/src/hasher/task-hasher');
385
+ const { getTaskDetails, hashTasks } = requireNx('nx/src/hasher/hash-task');
386
+ const { getTaskSpecificEnv } = requireNx('nx/src/tasks-runner/task-env');
387
+ const { getCache } = requireNx('nx/src/tasks-runner/cache');
388
+ const { getRunnerOptions } = requireNx('nx/src/tasks-runner/run-command');
389
+
390
+ performance.mark('ensureBuilt:graph:start');
391
+ const { projectGraph } = await daemonClient.getProjectGraphAndSourceMaps();
392
+ requireProject(projectGraph, selector.project);
393
+ const taskGraph = createTaskGraph(
394
+ projectGraph,
395
+ {},
396
+ [selector.project],
397
+ [selector.target],
398
+ selector.configuration,
399
+ overrides,
400
+ false,
401
+ );
402
+ const tasks = Object.values(taskGraph.tasks);
403
+ performance.measure('ensureBuilt:graph', 'ensureBuilt:graph:start');
404
+
405
+ // `isCloudDefault: false` because these options are only read here by the
406
+ // hasher, which looks at `selectivelyHashTsConfig`; the cloud credentials the
407
+ // flag would add belong to the cloud runner, and the run path calls Nx's own
408
+ // `getRunner` to obtain them.
409
+ const runnerOptions = getRunnerOptions('default', nxJson, nxArgs, false);
410
+ const hasher = new DaemonBasedTaskHasher(daemonClient, runnerOptions);
411
+ performance.mark('ensureBuilt:hash:start');
412
+ // Every task, each against its own environment — per-project and per-target
413
+ // `.env` files and custom hashers that read env participate in the hash, so
414
+ // one shared environment would compute keys the CLI never wrote.
415
+ //
416
+ // `hashTasksThatDoNotDependOnOutputsOfOtherTasks` is the wrong helper here
417
+ // even though it is what Nx's runner warms up with: it deliberately skips
418
+ // tasks whose inputs include another task's outputs, leaving them unhashed
419
+ // for the orchestrator to hash once their dependencies finish. In a probe,
420
+ // "already built" means those outputs are already final, so hashing them now
421
+ // is both possible and exactly what the cache was keyed on. Skipping them
422
+ // instead would make every graph that uses `dependentTasksOutputFiles` — the
423
+ // normal shape for a multi-package build — permanently miss.
424
+ const perTaskEnvs: Record<string, NodeJS.ProcessEnv> = {};
425
+ for (const task of tasks) {
426
+ perTaskEnvs[task.id] = getTaskSpecificEnv(task, projectGraph);
427
+ }
428
+ await hashTasks(hasher, projectGraph, taskGraph, perTaskEnvs, getTaskDetails(), tasks);
429
+ performance.measure('ensureBuilt:hash', 'ensureBuilt:hash:start');
430
+
431
+ // Nx's own factory, but deliberately never `init()`ed: that is what makes
432
+ // this a local-only, side-effect-free question. `init()` attaches the remote
433
+ // cache — a network round-trip, and a download is precisely the work this
434
+ // probe exists to detect — and asserts that the cache directory matches the
435
+ // database. Neither matters here: a hit is only declared when the outputs on
436
+ // disk already match, so the cache directory is never read.
437
+ performance.mark('ensureBuilt:cache:start');
438
+ const cache = getCache(runnerOptions);
439
+ const cachedResults = await cache.getBatch(tasks.filter((task) => task.cache && task.hash));
440
+ const cachedCodeByHash = new Map<string, number>();
441
+ for (const [hash, result] of cachedResults) {
442
+ cachedCodeByHash.set(hash, result.code);
443
+ }
444
+ const cacheMiss = firstCacheMiss(tasks, cachedCodeByHash);
445
+ performance.measure('ensureBuilt:cache', 'ensureBuilt:cache:start');
446
+ if (cacheMiss) {
447
+ return cacheMiss;
448
+ }
449
+
450
+ // A cache record only proves the task once succeeded with these inputs. The
451
+ // artifact this facility is about — the binary that is about to be exec'd —
452
+ // lives in the working tree, where anything may have deleted or rewritten it
453
+ // since. Only the daemon can settle that, because it holds the recorded
454
+ // output hashes.
455
+ const withOutputs: Task[] = [];
456
+ const outputEntries: { outputs: string[]; hash: string }[] = [];
457
+ for (const task of tasks) {
458
+ const hash = task.hash;
459
+ if (task.outputs.length === 0 || hash === undefined) {
460
+ continue;
461
+ }
462
+ withOutputs.push(task);
463
+ outputEntries.push({ outputs: task.outputs, hash });
464
+ }
465
+ performance.mark('ensureBuilt:outputs:start');
466
+ const matches = await daemonClient.outputsHashesMatchBatch(outputEntries);
467
+ performance.measure('ensureBuilt:outputs', 'ensureBuilt:outputs:start');
468
+ return firstStaleOutputs(withOutputs, matches);
469
+ }
470
+
471
+ interface CompletedRun {
472
+ readonly result: EnsureBuiltResult;
473
+ readonly taskResults: TaskResults;
474
+ }
475
+
476
+ async function runTarget(
477
+ nxJson: NxJsonConfiguration,
478
+ nxArgs: NxArgs,
479
+ overrides: Record<string, unknown>,
480
+ selector: TargetSelector,
481
+ reason: MissReason,
482
+ requireNx: WorkspaceNxRequire,
483
+ ): Promise<CompletedRun> {
484
+ const { runCommandForTasks } = requireNx('nx/src/tasks-runner/run-command');
485
+ const { createProjectGraphAsync } = requireNx('nx/src/project-graph/project-graph');
486
+ const { signalToCode } = requireNx('nx/src/utils/exit-codes');
487
+ // `runCommandForTasks` derives its own task graph and hashes, so the probe's
488
+ // work is not reusable. That duplication is one daemon round-trip on a path
489
+ // that is about to run a build.
490
+ const projectGraph = await createProjectGraphAsync();
491
+ const { taskResults, completed } = await runCommandForTasks(
492
+ [requireProject(projectGraph, selector.project)],
493
+ projectGraph,
494
+ { nxJson },
495
+ nxArgs,
496
+ overrides,
497
+ selector.project,
498
+ {},
499
+ { excludeTaskDependencies: false, loadDotEnvFiles: process.env.NX_LOAD_DOT_ENV_FILES !== 'false' },
500
+ );
501
+ if (!completed) {
502
+ // Nx's own encoding of an interrupted run: `runCommand` reports
503
+ // `signalToCode('SIGINT')` here. The runner does not surface which signal
504
+ // actually arrived, so there is none to forward — only the code Nx's CLI
505
+ // would have exited with.
506
+ return {
507
+ result: { disposition: 'failed', reason, exitCode: signalToCode('SIGINT'), signal: null },
508
+ taskResults,
509
+ };
510
+ }
511
+ for (const taskResult of Object.values(taskResults)) {
512
+ if (taskResult.status === 'failure' || taskResult.status === 'skipped') {
513
+ return { result: { disposition: 'failed', reason, exitCode: 1, signal: null }, taskResults };
514
+ }
515
+ }
516
+ return { result: { disposition: 'built', reason }, taskResults };
517
+ }
518
+
519
+ /**
520
+ * The daemon-disabled path: hand the target to the workspace's own `nx`, with
521
+ * stdio inherited.
522
+ *
523
+ * Inheriting rather than piping is the point. The wrapper this facility
524
+ * replaces piped Nx's output so it could read a cache marker out of the log and
525
+ * stay silent on a hit — a text heuristic over ANSI-coloured, format-unstable
526
+ * output. Without a daemon there is nothing to be silent about: no cheap probe
527
+ * exists, so the run is unconditional, the output is the run's own, and the
528
+ * child's exit status is forwarded verbatim.
529
+ */
530
+ async function runViaCli(workspaceRoot: string, selector: TargetSelector): Promise<EnsureBuiltResult> {
531
+ const nxCli = join(workspaceRoot, 'node_modules', '.bin', 'nx');
532
+ if (!existsSync(nxCli)) {
533
+ throw new Error(`ensureBuilt: the Nx daemon is disabled and ${nxCli} does not exist`);
534
+ }
535
+ const reason: MissReason = { kind: 'no-daemon', taskId: `${selector.project}:${selector.target}` };
536
+ const targetSpec = selector.configuration
537
+ ? `${selector.project}:${selector.target}:${selector.configuration}`
538
+ : `${selector.project}:${selector.target}`;
539
+ const signalToCode = nxSignalToCode;
540
+ const child = spawn(nxCli, ['run', targetSpec, '--outputStyle=stream'], {
541
+ cwd: workspaceRoot,
542
+ stdio: 'inherit',
543
+ });
544
+ // `Promise.withResolvers` would read better but needs lib es2024; this
545
+ // package inherits lib es2022 from tsconfig.base.json.
546
+ const exit = await new Promise<ChildExit>((settle, reject) => {
547
+ child.once('error', reject);
548
+ child.once('exit', (code, signal) => settle({ code, signal }));
549
+ });
550
+ return cliExitOutcome(reason, exit, signalToCode);
551
+ }
552
+
553
+ function nxSignalToCode(signal: NodeJS.Signals | null): number {
554
+ switch (signal) {
555
+ case 'SIGHUP':
556
+ return 129;
557
+ case 'SIGINT':
558
+ return 130;
559
+ case 'SIGQUIT':
560
+ return 131;
561
+ case 'SIGTERM':
562
+ return 143;
563
+ default:
564
+ return 128;
565
+ }
566
+ }
567
+
568
+ export interface ChildExit {
569
+ readonly code: number | null;
570
+ readonly signal: NodeJS.Signals | null;
571
+ }
572
+
573
+ /**
574
+ * How a child `nx`'s exit becomes a result.
575
+ *
576
+ * A signal is reported as a signal, not flattened into a code, so the caller
577
+ * can re-raise it: a build stopped by Ctrl-C should leave the wrapper looking
578
+ * killed by Ctrl-C to whatever is watching, not merely unsuccessful. The
579
+ * numeric code comes from Nx's own `signalToCode` so it matches what `nx run`
580
+ * would have exited with.
581
+ */
582
+ export function cliExitOutcome(
583
+ reason: MissReason,
584
+ exit: ChildExit,
585
+ signalToCode: (signal: NodeJS.Signals | null) => number,
586
+ ): EnsureBuiltResult {
587
+ if (exit.signal !== null) {
588
+ return { disposition: 'failed', reason, exitCode: signalToCode(exit.signal), signal: exit.signal };
589
+ }
590
+ if (exit.code !== 0) {
591
+ return { disposition: 'failed', reason, exitCode: exit.code ?? 1, signal: null };
592
+ }
593
+ return { disposition: 'built', reason };
594
+ }
595
+
596
+ function requireProject(projectGraph: ProjectGraph, project: string): ProjectGraphProjectNode {
597
+ const node = projectGraph.nodes[project];
598
+ if (!node) {
599
+ throw new Error(`ensureBuilt: no project named '${project}' in this workspace`);
600
+ }
601
+ return node;
602
+ }
@@ -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');