@lariocpt/crust-site 0.0.0-stage → 0.4.2

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/src/cli.ts ADDED
@@ -0,0 +1,269 @@
1
+ #!/usr/bin/env bun
2
+ // The crust-site CLI — `crust-site build [configFile]` and
3
+ // `crust-site dev [configFile]`.
4
+ //
5
+ // Exit codes 0/1/2 (the parseFlags convention the crust binary uses: 2 for
6
+ // argument errors, 1 for runtime failure, 0 for success and --help).
7
+ //
8
+ // build — run the SSG pipeline. Warnings (if any) print as formatted
9
+ // diagnostics; a success prints one summary line (pages / assets /
10
+ // duration → output directory) and exits 0. A failed build prints
11
+ // EVERY collected diagnostic (`severity[code]: message` +
12
+ // `--> sourcePath:line:col`, ANSI only when stderr is a TTY) and
13
+ // exits 1. Diagnostics never go to stdout: stdout carries the
14
+ // machine-consumed summary (and nothing else on failure).
15
+ // dev — the dev server. The CLI is a thin SUPERVISOR: it spawns a
16
+ // worker child (this same file re-execed with the
17
+ // CRUST_SITE_DEV_WORKER=1 environment marker) and RESTARTS it when
18
+ // it exits with the sentinel code 75 (a code/config change — a
19
+ // fresh process is the only way to re-import transitively imported
20
+ // code). Ctrl-C and SIGTERM are forwarded to the worker and the
21
+ // wrapper exits with the worker's code (130 for a SIGINT death —
22
+ // measured: Bun resolves `exited` with 128+signal for signal
23
+ // deaths). A worker death for ANY other reason (initial build
24
+ // failure, port in use, a crash) ends the wrapper with that code —
25
+ // a failing build must never respawn in a loop.
26
+ //
27
+ // The parser here is self-contained on purpose: this package is shipped to
28
+ // npm and must not import from the crust source tree (which stays
29
+ // zero-dependency). Later chunks extend the shape, not the convention.
30
+
31
+ import { build } from "./build.ts";
32
+ import { startDev } from "./dev.ts";
33
+ import { BuildError, type Diagnostic, formatDiagnostics } from "./diagnostics.ts";
34
+
35
+ const USAGE = `crust-site — the crust site generator (run under Bun)
36
+ usage:
37
+ crust-site build [configFile] render the site into output.directory
38
+ crust-site dev [configFile] start the dev server (rebuilds on change)
39
+ crust-site --help show this help
40
+
41
+ configFile defaults to ./site.config.ts
42
+ exit codes: 0 ok/help, 1 runtime failure, 2 argument error
43
+ `;
44
+
45
+ const COMMANDS = new Set(["build", "dev"]);
46
+ /** The worker marker: set by the wrapper on the child's environment. */
47
+ const WORKER_ENV = "CRUST_SITE_DEV_WORKER";
48
+ /** The worker's sentinel exit: "code/config changed — restart me". */
49
+ const RESTART_EXIT = 75;
50
+ /** The CLI's configFile default (the usage/README contract): the conventional
51
+ * name in the process cwd, resolved by loadResolvedConfig. The LIBRARY's
52
+ * build()/startDev() keep the explicit contract — an omitted configFile there
53
+ * is still a config.load error; only the CLI applies the default. */
54
+ const DEFAULT_CONFIG = "./site.config.ts";
55
+
56
+ function messageOf(e: unknown): string {
57
+ return e instanceof Error ? e.message : String(e);
58
+ }
59
+
60
+ /** One diagnostics block on stderr, ANSI only when stderr is a TTY. */
61
+ function printDiagnostics(diags: readonly Diagnostic[]): void {
62
+ process.stderr.write(`${formatDiagnostics(diags, { color: process.stderr.isTTY === true })}\n`);
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // build
67
+ // ---------------------------------------------------------------------------
68
+
69
+ async function runBuild(configFile: string | undefined): Promise<number> {
70
+ try {
71
+ const result = await build({ configFile: configFile ?? DEFAULT_CONFIG });
72
+ if (result.warnings.length > 0) printDiagnostics(result.warnings);
73
+ const assets = Object.keys(result.assets).length;
74
+ process.stdout.write(
75
+ `crust-site: built ${result.pages.length} page${result.pages.length === 1 ? "" : "s"}, ` +
76
+ `${assets} asset${assets === 1 ? "" : "s"}, ${result.durationMs} ms → ${result.outputDirectory}\n`,
77
+ );
78
+ return 0;
79
+ } catch (e) {
80
+ if (e instanceof BuildError) {
81
+ printDiagnostics(e.diagnostics);
82
+ return 1;
83
+ }
84
+ process.stderr.write(`crust-site: build failed: ${messageOf(e)}\n`);
85
+ return 1;
86
+ }
87
+ }
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // dev: wrapper ↔ worker
91
+ // ---------------------------------------------------------------------------
92
+
93
+ /**
94
+ * The WORKER: start the dev server in-process. A code/config change ends the
95
+ * process with the RESTART_EXIT sentinel (the wrapper re-execs it); every
96
+ * other failure (config load, initial build, port in use) exits 1 with the
97
+ * formatted diagnostics — a failing build never respawns in a loop.
98
+ */
99
+ async function runDevWorker(configFile: string | undefined): Promise<number> {
100
+ let server: Awaited<ReturnType<typeof startDev>>;
101
+ try {
102
+ server = await startDev({
103
+ configFile: configFile ?? DEFAULT_CONFIG,
104
+ onCodeChange: () => process.exit(RESTART_EXIT),
105
+ });
106
+ } catch (e) {
107
+ if (e instanceof BuildError) {
108
+ process.stderr.write(`crust-site: dev failed: ${e.message}\n`);
109
+ printDiagnostics(e.diagnostics);
110
+ } else {
111
+ process.stderr.write(`crust-site: dev failed: ${messageOf(e)}\n`);
112
+ }
113
+ return 1;
114
+ }
115
+ process.stdout.write(
116
+ `crust-site dev: serving http://${server.hostname}:${server.port}/ — ` +
117
+ `Ctrl-C to stop (edits to content rebuild in place, code/config changes restart the worker)\n`,
118
+ );
119
+ // Signal deaths: a clean stop (watcher + server + staging) and the
120
+ // conventional 128+signal code (SIGINT → 130, SIGTERM → 143). The stop is
121
+ // best-effort: a fallback timer exits anyway if it hangs.
122
+ let stopping = false;
123
+ const stopAndExit = (code: number): void => {
124
+ if (stopping) return;
125
+ stopping = true;
126
+ const fallback = setTimeout(() => process.exit(code), 2000);
127
+ fallback.unref?.();
128
+ void server.stop().then(
129
+ () => {
130
+ clearTimeout(fallback);
131
+ process.exit(code);
132
+ },
133
+ () => process.exit(code),
134
+ );
135
+ };
136
+ process.on("SIGINT", () => stopAndExit(130));
137
+ process.on("SIGTERM", () => stopAndExit(143));
138
+ // Run until onCodeChange exits the process or a signal arrives.
139
+ await new Promise<never>(() => {});
140
+ return 130; // unreachable
141
+ }
142
+
143
+ /**
144
+ * The WRAPPER: spawn this file as the worker, forward SIGINT/SIGTERM, and
145
+ * restart on the sentinel. `process.argv[1]` is this script (the bin entry),
146
+ * so the re-exec is `bun <this file> dev [configFile]`.
147
+ */
148
+ async function runDevWrapper(configFile: string | undefined): Promise<number> {
149
+ const script = process.argv[1];
150
+ if (typeof script !== "string" || script === "") {
151
+ process.stderr.write("crust-site: cannot re-exec the dev worker (no script path)\n");
152
+ return 1;
153
+ }
154
+ const args = ["dev", ...(configFile === undefined ? [] : [configFile])];
155
+ for (;;) {
156
+ let shuttingDown = false;
157
+ // Installed BEFORE the spawn: a signal in the spawn window must not
158
+ // orphan a starting worker.
159
+ const forward = (signal: "SIGINT" | "SIGTERM"): void => {
160
+ if (shuttingDown) return;
161
+ shuttingDown = true;
162
+ try {
163
+ child.kill(signal);
164
+ } catch {
165
+ // the child already exited
166
+ }
167
+ };
168
+ const onInt = (): void => forward("SIGINT");
169
+ const onTerm = (): void => forward("SIGTERM");
170
+ process.on("SIGINT", onInt);
171
+ process.on("SIGTERM", onTerm);
172
+ let child: Bun.Subprocess;
173
+ try {
174
+ child = Bun.spawn(
175
+ [
176
+ process.execPath,
177
+ ...(process.env.CRUST_SITE_NO_INSTALL === "1" ? ["--no-install"] : []),
178
+ script,
179
+ ...args,
180
+ ],
181
+ {
182
+ env: { ...process.env, [WORKER_ENV]: "1" },
183
+ stdin: "inherit",
184
+ stdout: "inherit",
185
+ stderr: "inherit",
186
+ },
187
+ );
188
+ } catch (e) {
189
+ process.off("SIGINT", onInt);
190
+ process.off("SIGTERM", onTerm);
191
+ process.stderr.write(`crust-site: could not spawn the dev worker: ${messageOf(e)}\n`);
192
+ return 1;
193
+ }
194
+ const code = await child.exited;
195
+ process.off("SIGINT", onInt);
196
+ process.off("SIGTERM", onTerm);
197
+ // Restart ONLY on the sentinel and only if a signal did not cause the
198
+ // exit: a Ctrl-C that raced the sentinel must end the session, not
199
+ // respawn a server the user asked to stop. (Signal deaths arrive as
200
+ // 128+signal codes — measured: Bun resolves `exited` with 130 for
201
+ // SIGINT, 137 for SIGKILL — so a real exit code is always a number.)
202
+ if (!shuttingDown && code === RESTART_EXIT) {
203
+ process.stderr.write("crust-site dev: code or config changed — restarting the dev worker\n");
204
+ continue;
205
+ }
206
+ return code;
207
+ }
208
+ }
209
+
210
+ async function runDev(configFile: string | undefined): Promise<number> {
211
+ if (process.env[WORKER_ENV] === "1") return runDevWorker(configFile);
212
+ return runDevWrapper(configFile);
213
+ }
214
+
215
+ // ---------------------------------------------------------------------------
216
+ // main
217
+ // ---------------------------------------------------------------------------
218
+
219
+ function main(): number | Promise<number> {
220
+ const argv = process.argv.slice(2);
221
+
222
+ if (argv.length === 0) {
223
+ // A bare invocation has no subcommand — nothing ran, so the answer is
224
+ // the usage and a nonzero code, never a success exit.
225
+ process.stderr.write(USAGE);
226
+ return 2;
227
+ }
228
+
229
+ if (argv[0] === "-h" || argv[0] === "--help") {
230
+ process.stdout.write(USAGE);
231
+ return 0;
232
+ }
233
+
234
+ const [command, ...rest] = argv;
235
+ if (!COMMANDS.has(command)) {
236
+ process.stderr.write(
237
+ `crust-site: unknown subcommand "${command}" (valid: build, dev)\n\n${USAGE}`,
238
+ );
239
+ return 2;
240
+ }
241
+
242
+ // `--help`/`-h` alongside a command is still a help request: the usage
243
+ // goes to stdout and the exit is 0 (the parseFlags convention — help is a
244
+ // success, not an argument error). Checked BEFORE the arity rules so
245
+ // `build --help` is help, not "takes at most one argument".
246
+ if (rest.includes("-h") || rest.includes("--help")) {
247
+ process.stdout.write(USAGE);
248
+ return 0;
249
+ }
250
+
251
+ // `build`/`dev` take AT MOST one positional (the config file). A second
252
+ // one, or a flag-shaped one, is refused rather than dropped: a silently
253
+ // ignored argument is a false pass wearing a success exit.
254
+ if (rest.length > 1 || (rest.length === 1 && rest[0].startsWith("-"))) {
255
+ process.stderr.write(
256
+ `crust-site: ${command} takes at most one argument (configFile)\n\n${USAGE}`,
257
+ );
258
+ return 2;
259
+ }
260
+
261
+ if (command === "build") return runBuild(rest[0]);
262
+ return runDev(rest[0]);
263
+ }
264
+
265
+ void (async () => {
266
+ const result = main();
267
+ const code = typeof result === "number" ? result : await result;
268
+ process.exit(code);
269
+ })();