@smoothbricks/nx-plugin 0.3.13 → 0.3.14

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.
package/README.md CHANGED
@@ -107,6 +107,34 @@ mode. Smoo validation creates/requires this config for test runners that do not
107
107
  against, but the package root `tsconfig.json` should not reference `./tsconfig.test.json`. Nx runs test typechecking
108
108
  through the inferred `typecheck-tests` target, not through `tsc --build`.
109
109
 
110
+ ## Ensure a Target Before Executing Its Binary
111
+
112
+ `ensureBuilt` checks a target and its task dependencies against Nx's local cache and the daemon's recorded output
113
+ hashes. A full hit returns without running tasks or printing output. A miss runs the task graph through Nx's in-process
114
+ runner with streaming output; only a workspace with the daemon disabled falls back to its checkout-local `nx` CLI.
115
+
116
+ ```typescript
117
+ import { ensureBuilt } from '@smoothbricks/nx-plugin/ensure-built';
118
+
119
+ const result = await ensureBuilt({ target: 'my-cli:build', cwd: workspaceRoot });
120
+ if (result.disposition === 'failed') {
121
+ if (result.signal !== null) {
122
+ process.kill(process.pid, result.signal);
123
+ }
124
+ process.exit(result.exitCode);
125
+ }
126
+ ```
127
+
128
+ The packaged wrapper performs the build check and then replaces itself with the binary, preserving the binary's
129
+ arguments, exit status, and signals:
130
+
131
+ ```bash
132
+ smoothbricks-ensure-built my-cli:build -- ./packages/my-cli/dist/my-cli argument
133
+ ```
134
+
135
+ Pass `--workspace-root <dir>` before `--` when invoking the wrapper outside the workspace. The binary path resolves
136
+ against the caller's current directory.
137
+
110
138
  ## Bun Test Tracing Generator
111
139
 
112
140
  Configure a package for the Bun test tracing + no-emit test typechecking pattern used in this repo.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=ensure-built.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ensure-built.d.ts","sourceRoot":"","sources":["../../src/bin/ensure-built.ts"],"names":[],"mappings":""}
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { describeMiss, ensureBuilt, parseTargetSelector } from '../ensure-built.js';
5
+ const USAGE = 'usage: smoothbricks-ensure-built <project:target[:configuration]> [--workspace-root <dir>] -- <binary> [args...]';
6
+ /** Argument and environment problems all exit 2, the shell's "usage" code. */
7
+ function usageError(message) {
8
+ process.stderr.write(`smoothbricks-ensure-built: ${message}\n${USAGE}\n`);
9
+ process.exit(2);
10
+ }
11
+ /**
12
+ * Split `--flag=value` into two tokens so both spellings parse identically.
13
+ * Only leading `--` forms are split: a value may legitimately contain `=`.
14
+ */
15
+ function tokenize(args) {
16
+ const tokens = [];
17
+ for (const arg of args) {
18
+ const equals = arg.startsWith('--') ? arg.indexOf('=') : -1;
19
+ if (equals === -1) {
20
+ tokens.push(arg);
21
+ }
22
+ else {
23
+ tokens.push(arg.slice(0, equals), arg.slice(equals + 1));
24
+ }
25
+ }
26
+ return tokens;
27
+ }
28
+ function findWorkspaceRoot(from) {
29
+ let directory = from;
30
+ for (;;) {
31
+ if (existsSync(join(directory, 'nx.json'))) {
32
+ return directory;
33
+ }
34
+ const parent = dirname(directory);
35
+ if (parent === directory) {
36
+ return usageError(`no nx.json at or above ${from}; pass --workspace-root`);
37
+ }
38
+ directory = parent;
39
+ }
40
+ }
41
+ const argv = process.argv.slice(2);
42
+ const separator = argv.indexOf('--');
43
+ if (separator === -1) {
44
+ usageError('missing `--` before the binary to exec');
45
+ }
46
+ const command = argv.slice(separator + 1);
47
+ if (command.length === 0) {
48
+ usageError('no binary given after `--`');
49
+ }
50
+ let target;
51
+ let workspaceRootArg;
52
+ const tokens = tokenize(argv.slice(0, separator));
53
+ for (let index = 0; index < tokens.length; index += 1) {
54
+ const token = tokens[index];
55
+ if (token === '--workspace-root') {
56
+ index += 1;
57
+ workspaceRootArg = tokens[index] ?? usageError('--workspace-root needs a directory');
58
+ }
59
+ else if (token.startsWith('-')) {
60
+ usageError(`unknown flag ${token}`);
61
+ }
62
+ else if (target !== undefined) {
63
+ usageError(`more than one target given: ${target} and ${token}`);
64
+ }
65
+ else {
66
+ target = token;
67
+ }
68
+ }
69
+ if (target === undefined) {
70
+ usageError('no project:target given');
71
+ }
72
+ if (parseTargetSelector(target) === null) {
73
+ usageError(`'${target}' is not a project:target[:configuration] selector`);
74
+ }
75
+ // `execve` does no PATH lookup, so a bare name would fail as a missing file in
76
+ // the current directory. Say which mistake was made instead.
77
+ if (!command[0].includes('/')) {
78
+ usageError(`'${command[0]}' must be a path to the binary, not a name to look up on PATH`);
79
+ }
80
+ // Resolved against the directory the user is standing in, not the workspace
81
+ // root: this is their command line, and the exec'd process inherits their cwd.
82
+ const binary = isAbsolute(command[0]) ? command[0] : resolve(process.cwd(), command[0]);
83
+ const workspaceRoot = workspaceRootArg === undefined ? findWorkspaceRoot(process.cwd()) : resolve(process.cwd(), workspaceRootArg);
84
+ const result = await ensureBuilt({ target, cwd: workspaceRoot }).catch((error) => {
85
+ process.stderr.write(`smoothbricks-ensure-built: ${error instanceof Error ? error.message : String(error)}\n`);
86
+ process.exit(1);
87
+ });
88
+ if (result.disposition !== 'hit' && process.env.NX_VERBOSE_LOGGING === 'true') {
89
+ process.stderr.write(`smoothbricks-ensure-built: ran ${target} because ${describeMiss(result.reason)}\n`);
90
+ }
91
+ if (result.disposition === 'failed') {
92
+ if (result.signal !== null) {
93
+ // Re-raise rather than translate, so a build killed by SIGINT leaves this
94
+ // process looking killed by SIGINT to whatever is watching it.
95
+ process.kill(process.pid, result.signal);
96
+ }
97
+ process.exit(result.exitCode);
98
+ }
99
+ if (process.execve === undefined) {
100
+ throw new Error('smoothbricks-ensure-built needs process.execve, which requires a POSIX host on Node 24+ or Bun');
101
+ }
102
+ // `execve`, not spawn-and-wait: the built binary replaces this process, so it
103
+ // owns the terminal, the signals and the exit status directly, with no wrapper
104
+ // left behind to forward them.
105
+ process.execve(binary, [binary, ...command.slice(1)], process.env);
@@ -0,0 +1,133 @@
1
+ import type { Task } from 'nx/src/config/task-graph';
2
+ /**
3
+ * A `project:target` or `project:target:configuration` selector.
4
+ *
5
+ * Configuration belongs in the selector rather than in a separate option
6
+ * because it is part of the cache key: `app:build` and `app:build:production`
7
+ * are two different tasks with two different hashes.
8
+ */
9
+ export interface TargetSelector {
10
+ readonly project: string;
11
+ readonly target: string;
12
+ readonly configuration: string | undefined;
13
+ }
14
+ /**
15
+ * Why the target could not be replayed from what is already on disk.
16
+ *
17
+ * Every variant names the task that ended the probe: in a dependency graph
18
+ * "something changed" is unactionable, and the useful question is always which
19
+ * of the twelve dependencies moved.
20
+ */
21
+ export type MissReason = {
22
+ readonly kind: 'uncacheable';
23
+ readonly taskId: string;
24
+ } | {
25
+ readonly kind: 'unhashable';
26
+ readonly taskId: string;
27
+ } | {
28
+ readonly kind: 'not-cached';
29
+ readonly taskId: string;
30
+ } | {
31
+ readonly kind: 'cached-failure';
32
+ readonly taskId: string;
33
+ readonly code: number;
34
+ } | {
35
+ readonly kind: 'stale-outputs';
36
+ readonly taskId: string;
37
+ } | {
38
+ readonly kind: 'no-daemon';
39
+ readonly taskId: string;
40
+ };
41
+ /**
42
+ * `hit` means nothing ran: every task in the graph was a recorded success and
43
+ * every recorded output is still byte-identical on disk, so the artifacts are
44
+ * what a fresh run would produce.
45
+ *
46
+ * `built` means the work was handed to Nx — which may have restored outputs
47
+ * from the local cache rather than recompiled anything. The line `hit` draws is
48
+ * "did this process have to do work", which is what a CLI wrapper needs in
49
+ * order to decide whether to stay quiet.
50
+ *
51
+ * `failed` is an operational outcome, not an exception: the target ran and did
52
+ * not succeed. A caller re-raises `signal` when there is one and exits with
53
+ * `exitCode` otherwise, so a Ctrl-C during a build stays a Ctrl-C.
54
+ */
55
+ export type EnsureBuiltResult = {
56
+ readonly disposition: 'hit';
57
+ } | {
58
+ readonly disposition: 'built';
59
+ readonly reason: MissReason;
60
+ } | {
61
+ readonly disposition: 'failed';
62
+ readonly reason: MissReason;
63
+ readonly exitCode: number;
64
+ readonly signal: NodeJS.Signals | null;
65
+ };
66
+ export interface EnsureBuiltOptions {
67
+ /** `project:target` or `project:target:configuration`. */
68
+ readonly target: string;
69
+ /**
70
+ * Nx workspace root. Required rather than discovered: a wrapper script knows
71
+ * its own checkout, and inferring from the caller's directory would silently
72
+ * bind whichever workspace they happen to be standing in.
73
+ */
74
+ readonly cwd: string;
75
+ /**
76
+ * How the run that happens on a miss reports progress. `stream` is the
77
+ * default and the only style offered: this facility fronts multi-minute
78
+ * compiles, and Nx's buffered styles emit nothing until a task finishes, so a
79
+ * silent terminal would read as a hang.
80
+ */
81
+ readonly onMiss?: 'stream';
82
+ }
83
+ export declare function parseTargetSelector(spec: string): TargetSelector | null;
84
+ export declare function describeMiss(reason: MissReason): string;
85
+ /**
86
+ * First reason the task set cannot be replayed, considering only recorded
87
+ * results — no filesystem access. `null` means every task is a recorded
88
+ * success, and the on-disk check is worth paying for.
89
+ *
90
+ * A cached *failure* counts as a miss even though Nx replays one when
91
+ * `NX_CACHE_FAILURES` is set: this facility exists to hand the process over to
92
+ * a binary, and replaying a failed build would hand over a stale one.
93
+ */
94
+ export declare function firstCacheMiss(tasks: readonly Task[], cachedCodeByHash: ReadonlyMap<string, number>): MissReason | null;
95
+ /**
96
+ * First task whose recorded outputs are no longer the bytes on disk.
97
+ *
98
+ * `matches[index]` is the daemon's verdict for `tasks[index]`. A short or
99
+ * ragged array counts as stale rather than as a hit: a missing verdict is not a
100
+ * positive one, and being wrong here means exec'ing a binary that was deleted.
101
+ */
102
+ export declare function firstStaleOutputs(tasks: readonly Task[], matches: readonly boolean[]): MissReason | null;
103
+ /**
104
+ * Make sure an Nx target's outputs are on disk, doing as little as possible
105
+ * when they already are.
106
+ *
107
+ * "Already built" is the hot path, because a checkout-local CLI wrapper pays it
108
+ * on every invocation. So it never spawns the `nx` CLI: the project graph, the
109
+ * task hashes and the on-disk output verification are daemon round-trips, the
110
+ * cache lookup is a local SQLite read, and Nx's task runner is only invoked
111
+ * once something is known to need running.
112
+ *
113
+ * With the daemon disabled there is no probe to make — hashing would have to
114
+ * build the project graph in this process, and no service holds the recorded
115
+ * output hashes to check the working tree against — so the target is handed to
116
+ * the workspace's own `nx` CLI unconditionally.
117
+ */
118
+ export declare function ensureBuilt(options: EnsureBuiltOptions): Promise<EnsureBuiltResult>;
119
+ export interface ChildExit {
120
+ readonly code: number | null;
121
+ readonly signal: NodeJS.Signals | null;
122
+ }
123
+ /**
124
+ * How a child `nx`'s exit becomes a result.
125
+ *
126
+ * A signal is reported as a signal, not flattened into a code, so the caller
127
+ * can re-raise it: a build stopped by Ctrl-C should leave the wrapper looking
128
+ * killed by Ctrl-C to whatever is watching, not merely unsuccessful. The
129
+ * numeric code comes from Nx's own `signalToCode` so it matches what `nx run`
130
+ * would have exited with.
131
+ */
132
+ export declare function cliExitOutcome(reason: MissReason, exit: ChildExit, signalToCode: (signal: NodeJS.Signals | null) => number): EnsureBuiltResult;
133
+ //# sourceMappingURL=ensure-built.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ensure-built.d.ts","sourceRoot":"","sources":["../src/ensure-built.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAkCrD;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5C;AAED;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,GAClB;IAAE,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACzD;IAAE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACxD;IAAE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IA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