@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/dev.ts ADDED
@@ -0,0 +1,821 @@
1
+ // The dev server (plan §4.3/§4.4, chunk 9). Serves the site from a dev
2
+ // staging tree with live rebuild, and NEVER touches the output directory:
3
+ //
4
+ // - builds into a dev staging SIBLING of the output (devStagingDirFor,
5
+ // same filesystem, never /tmp) and serves it in place — the output
6
+ // directory is only ever written by a production build's publish rename;
7
+ // - serves production AND draft routes; each draft page carries the DRAFT
8
+ // banner (build.ts) and link.draft / link.broken are warnings (the dev
9
+ // server serves them, so the links resolve there — plan §5);
10
+ // - a content change → ~100 ms debounced FULL in-process rebuild into a
11
+ // FRESH staging tree; the serve root is swapped only on success, so a
12
+ // failed rebuild prints its diagnostics and the last complete build
13
+ // keeps serving (a half tree is never served — crust rule 1); the
14
+ // watcher (fs.watch recursive, polling fallback) diffs every event
15
+ // against a (mtime, size) baseline taken BEFORE the initial build, so
16
+ // a recursive watch's replay of its pre-watch state (measured under
17
+ // load) and the build's own writes never read as changes, while an edit
18
+ // made even during the initial build is caught;
19
+ // - a code/config change (anything under the config directory that is not
20
+ // content, including the config file itself) → onCodeChange(): the CLI
21
+ // worker exits with sentinel 75 and its wrapper re-execs it, because a
22
+ // fresh process is the only way to re-import transitively imported code;
23
+ // a library caller without a callback gets a printed restart hint. No
24
+ // HMR, ever — the browser does a full reload;
25
+ // - the configured port in use → a `dev.port-in-use` diagnostic (v1 does
26
+ // NOT auto-increment: a silently different port serves the site where
27
+ // the user is not looking — a false pass wearing a success exit);
28
+ // - headers: HTML and public-directory files `no-store`, hashed
29
+ // `assets/<name>-<hash>.<ext>` `public, max-age=31536000, immutable`.
30
+ //
31
+ // URL resolution is the single resolver of plan §4.5's table (E1), shared
32
+ // with the sitemap/canonical machinery via normalizeRequestPath + routeToFile.
33
+
34
+ import { type FSWatcher, watch } from "node:fs";
35
+ import { lstat, readdir, rm, stat } from "node:fs/promises";
36
+ import { devBuild, devRebuild, loadResolvedConfig } from "./build";
37
+ import { BuildError, type Diagnostic, formatDiagnostics } from "./diagnostics";
38
+ import { devStagingDirFor, isCustodianSibling, sweepDeadDevStaging } from "./emit";
39
+ import { filesystemPath as posix } from "./fs-path";
40
+ import { normalizeRequestPath, routeToFile } from "./routes";
41
+ import type { ResolvedSite } from "./types";
42
+
43
+ const REBUILD_DEBOUNCE_MS = 100;
44
+ const POLL_INTERVAL_MS = 500;
45
+
46
+ /** One console line of dev-server output (progress goes to stderr; only the
47
+ * "serving at" URL line goes to stdout, and the CLI writes that one). */
48
+ function log(message: string): void {
49
+ process.stderr.write(`${message}\n`);
50
+ }
51
+
52
+ function messageOf(e: unknown): string {
53
+ return e instanceof Error ? e.message : String(e);
54
+ }
55
+
56
+ function toPosix(p: string): string {
57
+ return p.replace(/\\/g, "/");
58
+ }
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // URL → file resolution (plan §4.5, the E1 table)
62
+ // ---------------------------------------------------------------------------
63
+
64
+ /**
65
+ * The dev server's URL → file resolver — the single resolver of the E1
66
+ * table (plan §4.5), so sitemap, `ctx.url()`, the link validator and this
67
+ * server cannot drift:
68
+ *
69
+ * / → index.html
70
+ * /a → a.html
71
+ * /a/b → a/b.html
72
+ * /a/ → 404 (normalizeRequestPath answers null: empty segment,
73
+ * pinned in v1)
74
+ * /a.html → the SAME file `/a` serves (a.html) — the lenient form;
75
+ * the canonical URL stays extensionless
76
+ * unmatched → the 404 page with HTTP status 404 (never a 200 with a
77
+ * 404 body)
78
+ *
79
+ * Candidates are tried in this order and the first that exists wins:
80
+ * 1. path ending in `.html`: the LITERAL route's file (routeToFile:
81
+ * `/a.html` → `a.html.html`) — a page whose route genuinely ends in
82
+ * `.html` is served at its own URL first (exact beats lenient);
83
+ * 2. path ending in `.html`: the lenient canonical form (suffix stripped,
84
+ * remainder mapped: `/a.html` → `/a` → `a.html`);
85
+ * 3. path not ending in `.html`: the route mapping (`/a` → `a.html`);
86
+ * 4. the literal path itself (`/favicon.txt` → `favicon.txt`) —
87
+ * publicDirectory files and other non-route files land at their
88
+ * literal names; a route mapping always wins over a same-named file.
89
+ */
90
+ function stripHtmlSuffix(route: string): string {
91
+ const stripped = route.slice(0, -".html".length);
92
+ return stripped === "" ? "/" : stripped;
93
+ }
94
+
95
+ /**
96
+ * `routeToFile` re-validates its input and THROWS for routes that can never
97
+ * be routes — and a REQUEST path may legitimately contain one of those off-
98
+ * Windows: `normalizeRequestPath` rejects Windows reserved names (con/nul/
99
+ * aux/com1…) only on win32, where they are devices, but `routeToFile`'s
100
+ * validation rejects them on every platform, where they are ordinary file
101
+ * names. A request for `/con` must therefore skip the route candidates and
102
+ * still try the literal file (a public file named `con` is served), never
103
+ * crash the fetch handler into a 500.
104
+ */
105
+ function routeFileSafe(route: string): string | null {
106
+ try {
107
+ return routeToFile(route);
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+
113
+ function candidateFiles(normalized: string): string[] {
114
+ if (normalized === "/") return ["index.html"];
115
+ const base = normalized.slice(1);
116
+ const out: string[] = [];
117
+ const push = (route: string): void => {
118
+ const file = routeFileSafe(route);
119
+ if (file !== null) out.push(file);
120
+ };
121
+ if (base.endsWith(".html")) {
122
+ push(normalized);
123
+ push(stripHtmlSuffix(normalized));
124
+ out.push(decodeURIComponent(base));
125
+ return out;
126
+ }
127
+ push(normalized);
128
+ // normalizeRequestPath already rejected decoded separators/traversal.
129
+ // Route filenames retain canonical escapes; public files use literal
130
+ // filesystem names, so decode ONCE for this fallback (not recursively).
131
+ out.push(decodeURIComponent(base));
132
+ return out;
133
+ }
134
+
135
+ async function fileExists(dir: string, file: string): Promise<boolean> {
136
+ try {
137
+ return (await stat(posix.join(dir, file))).isFile();
138
+ } catch {
139
+ return false;
140
+ }
141
+ }
142
+
143
+ async function resolveServedFile(serveRoot: string, normalized: string): Promise<string | null> {
144
+ for (const candidate of candidateFiles(normalized)) {
145
+ if (await fileExists(serveRoot, candidate)) return candidate;
146
+ }
147
+ return null;
148
+ }
149
+
150
+ // ---------------------------------------------------------------------------
151
+ // response headers
152
+ // ---------------------------------------------------------------------------
153
+
154
+ /** Content types for the extensions a generated site emits (html/js/css/xml/
155
+ * txt) plus the common public-directory types; anything unknown answers
156
+ * `application/octet-stream` (a guess is a lie, octet-stream is not). */
157
+ const CONTENT_TYPES: Record<string, string> = {
158
+ ".html": "text/html; charset=utf-8",
159
+ ".htm": "text/html; charset=utf-8",
160
+ ".js": "text/javascript; charset=utf-8",
161
+ ".mjs": "text/javascript; charset=utf-8",
162
+ ".css": "text/css; charset=utf-8",
163
+ ".xml": "application/xml; charset=utf-8",
164
+ ".txt": "text/plain; charset=utf-8",
165
+ ".json": "application/json; charset=utf-8",
166
+ ".webmanifest": "application/manifest+json",
167
+ ".pdf": "application/pdf",
168
+ ".svg": "image/svg+xml",
169
+ ".png": "image/png",
170
+ ".jpg": "image/jpeg",
171
+ ".jpeg": "image/jpeg",
172
+ ".gif": "image/gif",
173
+ ".webp": "image/webp",
174
+ ".avif": "image/avif",
175
+ ".ico": "image/x-icon",
176
+ ".woff": "font/woff",
177
+ ".woff2": "font/woff2",
178
+ ".ttf": "font/ttf",
179
+ ".otf": "font/otf",
180
+ ".mp3": "audio/mpeg",
181
+ ".mp4": "video/mp4",
182
+ ".webm": "video/webm",
183
+ };
184
+
185
+ function contentTypeOf(file: string): string {
186
+ const dot = file.lastIndexOf(".");
187
+ if (dot === -1) return "application/octet-stream";
188
+ return CONTENT_TYPES[file.slice(dot).toLowerCase()] ?? "application/octet-stream";
189
+ }
190
+
191
+ /** `assets/<name>-<16-hex-hash>.<ext>` — the hashed-asset naming contract
192
+ * (assets.ts). Only these get the immutable cache: the hash IS the version. */
193
+ const HASHED_ASSET = /^assets\/[A-Za-z0-9_-]+-[0-9a-f]{16}\.[A-Za-z0-9]+$/;
194
+
195
+ function cacheControlOf(file: string): string {
196
+ // Default no-store (HTML, public files, sitemap, robots — the dev server
197
+ // is a preview, not a cache); hashed assets are the only immutable ones.
198
+ return HASHED_ASSET.test(file) ? "public, max-age=31536000, immutable" : "no-store";
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------
202
+ // the watcher
203
+ // ---------------------------------------------------------------------------
204
+
205
+ type WatchKind = "content" | "code";
206
+ type Classifier = (absolutePath: string) => WatchKind | null;
207
+
208
+ /** One file's poll-stamp: mtime (float ms) + size cover edit/create/delete/
209
+ * truncate — the four changes the dev loop must see. */
210
+ interface FileStamp {
211
+ mtime: number;
212
+ size: number;
213
+ }
214
+ type Snapshot = Map<string, FileStamp>;
215
+
216
+ interface DevWatcher {
217
+ stop(): void;
218
+ }
219
+
220
+ /** True iff `path` equals `root` or is below it (component-wise). */
221
+ function isUnder(path: string, root: string): boolean {
222
+ return path === root || path.startsWith(`${root}/`);
223
+ }
224
+
225
+ /**
226
+ * Classify one absolute path:
227
+ * - under content.directory → "content" (a rebuild)
228
+ * - under the output tree, or a CUSTODIAN sibling of it (production
229
+ * staging, dev staging, lock file, out-old — isCustodianSibling) → null:
230
+ * the package's own file traffic (including this process's own staging
231
+ * builds) must never feed back into the watcher as a change;
232
+ * - elsewhere under the config directory (the config file itself, layouts,
233
+ * entrypoints, anything else) → "code" (a worker restart);
234
+ * - anywhere else → null.
235
+ */
236
+ function makeClassifier(resolved: ResolvedSite, outputDir: string): Classifier {
237
+ const outputParent = posix.dirname(outputDir);
238
+ const outputName = posix.basename(outputDir);
239
+ return (absolutePath: string): WatchKind | null => {
240
+ const p = toPosix(absolutePath);
241
+ if (isUnder(p, resolved.content.directory)) return "content";
242
+ if (isUnder(p, outputDir)) return null;
243
+ const rel = posix.relative(outputParent, p);
244
+ if (rel !== "" && !rel.startsWith("..")) {
245
+ const first = rel.split("/")[0];
246
+ if (first === outputName || isCustodianSibling(first)) return null;
247
+ }
248
+ if (isUnder(p, resolved.configDir)) return "code";
249
+ return null;
250
+ };
251
+ }
252
+
253
+ /**
254
+ * Recursive walk recording regular-file (mtime, size) stamps. Symlinks are
255
+ * never followed (the containment story: they never extend a boundary), and
256
+ * a directory that classifies null (the output tree / a custodian sibling)
257
+ * is pruned entirely — nothing below it is an input, so a long dev session
258
+ * does not re-walk its own staging trees on every poll.
259
+ *
260
+ * The SAME walk is the baseline the event watcher verifies against (the
261
+ * watcher section below): one shared Map, taken BEFORE the initial build.
262
+ */
263
+ async function snapshotDir(abs: string, out: Snapshot, classify: Classifier): Promise<void> {
264
+ // Plain readdir (strings) + one lstat per entry: withFileTypes is only a
265
+ // stat-optimization, and lstat is needed anyway (a symlink must be told
266
+ // from a file by lstat, not by a cached dirent).
267
+ let names: string[];
268
+ try {
269
+ names = await readdir(abs);
270
+ } catch {
271
+ return; // vanished between polls — nothing to record
272
+ }
273
+ for (const name of names) {
274
+ const full = posix.join(abs, toPosix(name));
275
+ let st: Awaited<ReturnType<typeof lstat>>;
276
+ try {
277
+ st = await lstat(full);
278
+ } catch {
279
+ continue;
280
+ }
281
+ if (st.isSymbolicLink()) continue;
282
+ if (st.isDirectory()) {
283
+ if (classify(full) === null) continue; // prune: output tree / custodian
284
+ await snapshotDir(full, out, classify);
285
+ } else if (st.isFile()) {
286
+ out.set(full, { mtime: st.mtimeMs, size: st.size });
287
+ }
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Polling watcher: the PRIMARY path on Windows (fs.watch is unreliable
293
+ * there — plan Windows table) and the FALLBACK everywhere else. One diff
294
+ * per poll over each watched root's (mtime, size) walk, compared against
295
+ * the SHARED baseline (taken before the initial build, the same Map the
296
+ * event watcher verifies against — the two backends can therefore hand over
297
+ * without losing state). Added, removed and changed files each produce one
298
+ * classified event (the debouncer upstream coalesces the burst — a rename
299
+ * is seen as remove+add, two events, one rebuild). The baseline is updated
300
+ * IN PLACE (the shared Map keeps its identity across a backend switch).
301
+ */
302
+ function startPolling(
303
+ roots: readonly string[],
304
+ classify: Classifier,
305
+ onEvent: (kind: WatchKind) => void,
306
+ baseline: Snapshot,
307
+ ): DevWatcher {
308
+ let stopped = false;
309
+ const timer = setInterval(() => {
310
+ void (async () => {
311
+ if (stopped) return;
312
+ const next: Snapshot = new Map();
313
+ for (const r of roots) await snapshotDir(r, next, classify);
314
+ for (const [abs, stamp] of next) {
315
+ const old = baseline.get(abs);
316
+ if (old === undefined || old.mtime !== stamp.mtime || old.size !== stamp.size) {
317
+ const kind = classify(abs);
318
+ if (kind !== null) onEvent(kind);
319
+ }
320
+ baseline.set(abs, stamp);
321
+ }
322
+ for (const abs of [...baseline.keys()]) {
323
+ if (!next.has(abs)) {
324
+ const kind = classify(abs);
325
+ if (kind !== null) onEvent(kind);
326
+ baseline.delete(abs);
327
+ }
328
+ }
329
+ })();
330
+ }, POLL_INTERVAL_MS);
331
+ return {
332
+ stop() {
333
+ stopped = true;
334
+ clearInterval(timer);
335
+ },
336
+ };
337
+ }
338
+
339
+ /**
340
+ * fs.watch (recursive) watcher: the PRIMARY path off-Windows. A root that
341
+ * cannot be watched (it is missing) or an error event mid-life makes the
342
+ * whole watcher fall back to polling (a per-root half-watched state would
343
+ * miss changes on the dead root — a false pass in the dev loop).
344
+ *
345
+ * Event VERIFICATION (the replay guard): a recursive inotify watch
346
+ * intermittently REPLAYS its pre-watch state — files that existed when the
347
+ * watch started arrive as events shortly after it is established (measured
348
+ * under load: the whole tree, config file included, delivered at startup).
349
+ * A replay of a file the user never touched must not fire (it would
350
+ * classify the config file as a code change and trigger a spurious
351
+ * rebuild). The truth is the baseline stamp: an event for a file whose
352
+ * (mtime, size) still match the baseline is a replay and is dropped; a
353
+ * stamp that differs is a REAL change (even one made during the initial
354
+ * build, which the pre-build baseline caught); a file absent from the
355
+ * baseline is new and fires. The baseline entry is updated in place when a
356
+ * change is confirmed, so a duplicate delivery of the same change is
357
+ * dropped, and the polling fallback inherits the current baseline.
358
+ * A root-level event (filename empty) is always passed to the classifier —
359
+ * no root replay was observed, and a spurious one costs at most a wasted
360
+ * (identical-output) rebuild, never a wrong serve.
361
+ */
362
+ function startFsWatch(
363
+ roots: readonly string[],
364
+ classify: Classifier,
365
+ onEvent: (kind: WatchKind) => void,
366
+ onUnusable: () => void,
367
+ baseline: Snapshot,
368
+ ): DevWatcher {
369
+ let stopped = false;
370
+ const watchers: FSWatcher[] = [];
371
+ for (const root of roots) {
372
+ let w: FSWatcher;
373
+ try {
374
+ w = watch(root, { recursive: true }, (_eventType, filename) => {
375
+ if (stopped) return;
376
+ // filename is relative to the watch root (measured: Linux reports
377
+ // "a/b/inner.md"); null/undefined/empty means the root itself
378
+ // changed, and a Buffer (the old-style filename) stringifies to the
379
+ // same relative path — anything that is not a clean string is
380
+ // treated as a root event rather than crashing the callback.
381
+ const rel = filename === null || filename === undefined ? "" : String(filename);
382
+ const abs = rel === "" ? root : posix.join(root, toPosix(rel));
383
+ void (async () => {
384
+ if (stopped) return;
385
+ const old = baseline.get(abs);
386
+ if (old !== undefined) {
387
+ // The file was part of the pre-watch state: verify the change
388
+ // against the baseline stamp before believing the event.
389
+ let st: Awaited<ReturnType<typeof lstat>> | null = null;
390
+ try {
391
+ st = await lstat(abs);
392
+ } catch {
393
+ st = null;
394
+ }
395
+ if (st !== null && !st.isSymbolicLink()) {
396
+ const stamp = { mtime: st.mtimeMs, size: st.size };
397
+ if (stamp.mtime === old.mtime && stamp.size === old.size) return; // a replay
398
+ baseline.set(abs, stamp);
399
+ } else {
400
+ baseline.delete(abs); // deleted before the event was processed
401
+ }
402
+ }
403
+ const kind = classify(abs);
404
+ if (kind !== null) onEvent(kind);
405
+ })();
406
+ });
407
+ } catch {
408
+ // a root that cannot be watched (e.g. the content dir is missing)
409
+ // disqualifies the whole event-driven path: close what we opened and
410
+ // let the caller switch to polling
411
+ for (const opened of watchers) {
412
+ try {
413
+ opened.close();
414
+ } catch {
415
+ // already closed
416
+ }
417
+ }
418
+ throw new Error(`fs.watch(${JSON.stringify(root)}) is unavailable`);
419
+ }
420
+ w.on("error", () => {
421
+ if (!stopped) onUnusable();
422
+ });
423
+ watchers.push(w);
424
+ }
425
+ return {
426
+ stop() {
427
+ stopped = true;
428
+ for (const w of watchers) {
429
+ try {
430
+ w.close();
431
+ } catch {
432
+ // already closed
433
+ }
434
+ }
435
+ },
436
+ };
437
+ }
438
+
439
+ /** Polling on win32; otherwise fs.watch with a polling fallback. Both
440
+ * backends diff against the one shared baseline (see startDev). */
441
+ function startWatcher(
442
+ roots: readonly string[],
443
+ classify: Classifier,
444
+ onEvent: (kind: WatchKind) => void,
445
+ baseline: Snapshot,
446
+ ): DevWatcher {
447
+ if (process.platform === "win32") return startPolling(roots, classify, onEvent, baseline);
448
+ let current: DevWatcher | null = null;
449
+ const switchToPolling = (): void => {
450
+ if (current === null) return;
451
+ current.stop();
452
+ current = startPolling(roots, classify, onEvent, baseline);
453
+ };
454
+ try {
455
+ current = startFsWatch(roots, classify, onEvent, switchToPolling, baseline);
456
+ } catch {
457
+ current = null;
458
+ }
459
+ if (current === null) current = startPolling(roots, classify, onEvent, baseline);
460
+ return current;
461
+ }
462
+
463
+ // ---------------------------------------------------------------------------
464
+ // the server
465
+ // ---------------------------------------------------------------------------
466
+
467
+ export interface StartDevOptions {
468
+ /** Path to `site.config.ts`; relative paths resolve against the cwd. */
469
+ readonly configFile: string;
470
+ /** Overrides `dev.hostname` (default "localhost"). */
471
+ readonly hostname?: string;
472
+ /** Overrides `dev.port` (default: ephemeral — 0). */
473
+ readonly port?: number;
474
+ /**
475
+ * Called when a code or config change is detected. The `crust-site dev`
476
+ * CLI worker uses it to `process.exit(75)` — the wrapper re-execs the
477
+ * worker, and a fresh process is the only way to re-import transitively
478
+ * imported code (the config's layouts, its imports). Default: print a
479
+ * restart hint (a library caller running `startDev` in its own process
480
+ * cannot safely be exited by the library).
481
+ */
482
+ readonly onCodeChange?: () => void;
483
+ }
484
+
485
+ export interface DevServer {
486
+ /** The port the server actually bound (an ephemeral port when unset). */
487
+ readonly port: number;
488
+ /** The display hostname (`0.0.0.0`/`::` are shown as `localhost`). */
489
+ readonly hostname: string;
490
+ /**
491
+ * Stop the server: the watcher and any pending rebuild are shut down, the
492
+ * server socket is closed, and the dev staging tree is deleted (it is
493
+ * temporary — a kill in the middle is reclaimed by the next startup's
494
+ * sweepDeadDevStaging).
495
+ */
496
+ stop(): Promise<void>;
497
+ }
498
+
499
+ interface DevState {
500
+ readonly resolved: ResolvedSite;
501
+ readonly outputDir: string;
502
+ readonly configPath: string;
503
+ /** Swapped to the fresh staging tree on every successful rebuild. */
504
+ serveRoot: string;
505
+ rebuilding: boolean;
506
+ /** A content change arrived while a rebuild was running (or queued). */
507
+ pendingRebuild: boolean;
508
+ /** A code/config change arrived while a rebuild was running. */
509
+ codeChangePending: boolean;
510
+ debounceTimer: ReturnType<typeof setTimeout> | null;
511
+ rebuildInFlight: Promise<void> | null;
512
+ stopped: boolean;
513
+ watcher: DevWatcher | null;
514
+ }
515
+
516
+ /** The default onCodeChange: a hint, never a silent no-op. */
517
+ function defaultOnCodeChange(): void {
518
+ log(
519
+ "crust-site dev: code or config changed — this dev server cannot re-import its own code graph in-process. " +
520
+ "Restart it to pick up the change (`crust-site dev` restarts its worker automatically).",
521
+ );
522
+ }
523
+
524
+ /** `0.0.0.0`/`::`/`*` bind every interface; the URL printed to the user is localhost. */
525
+ function displayHost(hostname: string): string {
526
+ return hostname === "0.0.0.0" || hostname === "::" || hostname === "*" ? "localhost" : hostname;
527
+ }
528
+
529
+ function portInUseDiagnostics(port: number, hostname: string): Diagnostic[] {
530
+ return [
531
+ {
532
+ code: "dev.port-in-use",
533
+ severity: "error",
534
+ message:
535
+ `dev port ${port} is already in use (bound hostname ${JSON.stringify(hostname)}). ` +
536
+ `Stop the other process or set dev.port in the config — the dev server does not ` +
537
+ `auto-increment, because a silently different port would serve the site somewhere ` +
538
+ `you are not looking at`,
539
+ },
540
+ ];
541
+ }
542
+
543
+ /**
544
+ * Start the dev server: load + resolve the config, sweep dead dev staging
545
+ * from killed predecessors, run the initial mode-"dev" build, bind the
546
+ * server (EADDRINUSE → `dev.port-in-use`), and start the watcher. Rejects
547
+ * with a BuildError (every diagnostic) when the config is invalid or the
548
+ * initial build fails — in both cases the dev staging is deleted and the
549
+ * output directory has not been touched.
550
+ */
551
+ export async function startDev(options: StartDevOptions): Promise<DevServer> {
552
+ const configFile = options?.configFile ?? "";
553
+ const loaded = await loadResolvedConfig(configFile);
554
+ // A long dev session accumulates one dead-pid staging tree per worker
555
+ // restart; reclaim them before adding our own (a killed process's litter
556
+ // is bounded, never permanent).
557
+ await sweepDeadDevStaging(loaded.resolved.output.directory);
558
+ // The watcher baseline is taken BEFORE the initial build: the (mtime,
559
+ // size) stamps of the pre-watch tree are the reference every later change
560
+ // is diffed against. A pre-build baseline is the only one that also sees
561
+ // an edit made DURING the initial build (a post-build baseline would miss
562
+ // it forever) — and it is what makes the fs.watch replay guard
563
+ // meaningful (a replay of an unmodified file matches it and is dropped).
564
+ const roots = [
565
+ ...new Set([toPosix(loaded.resolved.content.directory), toPosix(loaded.resolved.configDir)]),
566
+ ];
567
+ const classify = makeClassifier(loaded.resolved, posix.resolve(loaded.resolved.output.directory));
568
+ const baseline: Snapshot = new Map();
569
+ for (const r of roots) await snapshotDir(r, baseline, classify);
570
+
571
+ const initial = await devBuild({ configFile });
572
+
573
+ const resolved = initial.resolved;
574
+ const outputDir = posix.resolve(resolved.output.directory);
575
+ // the raw value BINDS; the display form is what the user types in a
576
+ // browser (a 0.0.0.0 bind is announced as localhost)
577
+ const bindHost = options.hostname ?? resolved.dev?.hostname ?? "localhost";
578
+ const hostname = displayHost(bindHost);
579
+ const port = options.port ?? resolved.dev?.port ?? 0;
580
+ const onCodeChange = options.onCodeChange ?? defaultOnCodeChange;
581
+ const prefix = new URL(resolved.site).pathname.replace(/\/$/, "");
582
+
583
+ const state: DevState = {
584
+ resolved,
585
+ outputDir,
586
+ configPath: initial.configPath,
587
+ serveRoot: initial.staging,
588
+ rebuilding: false,
589
+ pendingRebuild: false,
590
+ codeChangePending: false,
591
+ debounceTimer: null,
592
+ rebuildInFlight: null,
593
+ stopped: false,
594
+ watcher: null,
595
+ };
596
+ // The serve root behind the fetch handler: swapped on every successful
597
+ // rebuild, deleted on stop. One mutable cell, read per request.
598
+ const rootRef = { current: initial.staging };
599
+
600
+ const cleanupStaging = async (): Promise<void> => {
601
+ await rm(rootRef.current, { recursive: true, force: true }).catch(() => {});
602
+ };
603
+
604
+ // Bind. EADDRINUSE → `dev.port-in-use` (v1 does not auto-increment). Any
605
+ // other throw or a missing bound port → the staging is deleted and the
606
+ // error rethrown (the output directory is untouched).
607
+ let server: ReturnType<typeof Bun.serve> | undefined;
608
+ let boundPort: number | undefined;
609
+ try {
610
+ server = Bun.serve({
611
+ hostname: bindHost,
612
+ port,
613
+ fetch: (req) => serveRequest(req, rootRef, prefix),
614
+ });
615
+ // bun-types types `port` as `number | undefined` (a unix-socket server
616
+ // has none); a port-bound server always has one, so an undefined here is
617
+ // an engine anomaly — fail honestly, never report a fake port.
618
+ boundPort = server.port;
619
+ if (boundPort === undefined) {
620
+ throw new Error("the dev server bound no port (Bun.serve reported undefined)");
621
+ }
622
+ } catch (e) {
623
+ server?.stop(true);
624
+ if ((e as NodeJS.ErrnoException).code === "EADDRINUSE") {
625
+ await cleanupStaging();
626
+ throw new BuildError(portInUseDiagnostics(port, hostname));
627
+ }
628
+ await cleanupStaging();
629
+ throw e;
630
+ }
631
+
632
+ // The watcher watches the same roots/classifier computed before the build
633
+ // (one shared baseline across both backends).
634
+ state.watcher = startWatcher(
635
+ roots,
636
+ classify,
637
+ (kind) => {
638
+ if (kind === "content") scheduleRebuild();
639
+ else noteCodeChange();
640
+ },
641
+ baseline,
642
+ );
643
+
644
+ return {
645
+ port: boundPort,
646
+ hostname,
647
+ stop: async (): Promise<void> => {
648
+ state.stopped = true;
649
+ if (state.debounceTimer !== null) {
650
+ clearTimeout(state.debounceTimer);
651
+ state.debounceTimer = null;
652
+ }
653
+ state.watcher?.stop();
654
+ if (state.rebuildInFlight !== null) await state.rebuildInFlight;
655
+ server.stop(true);
656
+ await cleanupStaging();
657
+ },
658
+ };
659
+
660
+ function scheduleRebuild(): void {
661
+ if (state.stopped) return;
662
+ if (state.rebuilding) {
663
+ state.pendingRebuild = true;
664
+ return;
665
+ }
666
+ if (state.debounceTimer !== null) clearTimeout(state.debounceTimer);
667
+ state.debounceTimer = setTimeout(() => {
668
+ state.debounceTimer = null;
669
+ if (state.stopped) return;
670
+ state.rebuilding = true;
671
+ state.rebuildInFlight = rebuildLoop();
672
+ }, REBUILD_DEBOUNCE_MS);
673
+ }
674
+
675
+ function noteCodeChange(): void {
676
+ if (state.stopped) return;
677
+ // a code/config change voids any queued content rebuild: the session is
678
+ // about to restart (CLI) or the user is told to (default), and the
679
+ // queued rebuild would only waste a cycle before the exit.
680
+ if (state.debounceTimer !== null) {
681
+ clearTimeout(state.debounceTimer);
682
+ state.debounceTimer = null;
683
+ }
684
+ state.pendingRebuild = false;
685
+ if (state.rebuilding) {
686
+ // let the in-flight rebuild settle (it started before the change
687
+ // landed), then the loop fires the callback
688
+ state.codeChangePending = true;
689
+ return;
690
+ }
691
+ onCodeChange();
692
+ }
693
+
694
+ async function rebuildLoop(): Promise<void> {
695
+ try {
696
+ for (;;) {
697
+ await doRebuild();
698
+ if (state.codeChangePending) {
699
+ state.codeChangePending = false;
700
+ state.pendingRebuild = false;
701
+ onCodeChange();
702
+ return;
703
+ }
704
+ if (state.stopped || !state.pendingRebuild) return;
705
+ state.pendingRebuild = false;
706
+ }
707
+ } finally {
708
+ state.rebuilding = false;
709
+ state.rebuildInFlight = null;
710
+ }
711
+ }
712
+
713
+ async function doRebuild(): Promise<void> {
714
+ const prev = state.serveRoot;
715
+ const next = devStagingDirFor(state.outputDir);
716
+ try {
717
+ const result = await devRebuild(state.resolved, next, state.outputDir);
718
+ if (state.stopped) {
719
+ // stopped mid-rebuild: the tree nobody will serve is deleted here
720
+ await rm(next, { recursive: true, force: true }).catch(() => {});
721
+ return;
722
+ }
723
+ // success: swap the serve root, then delete the previous tree. The
724
+ // swap is a pointer move — readers either see the complete old tree or
725
+ // the complete new one, never a half tree. serveRoot tracks the swap
726
+ // so the NEXT rebuild deletes the tree that was really just served
727
+ // (not the initial one forever — that would leak one staging per
728
+ // rebuild).
729
+ rootRef.current = next;
730
+ state.serveRoot = next;
731
+ await rm(prev, { recursive: true, force: true }).catch(() => {});
732
+ const drafts = result.draftPages.length;
733
+ log(
734
+ `crust-site dev: rebuilt in ${result.durationMs} ms — ${result.pages.length} page` +
735
+ `${result.pages.length === 1 ? "" : "s"}, ${drafts} draft${drafts === 1 ? "" : "s"}`,
736
+ );
737
+ if (result.warnings.length > 0) {
738
+ log(formatDiagnostics(result.warnings, { color: process.stderr.isTTY === true }));
739
+ }
740
+ } catch (e) {
741
+ // failure: delete the half tree and keep serving the last complete
742
+ // build (crust rule 1: the diagnostics are printed, the stale content
743
+ // keeps serving — never a false "rebuilt" line).
744
+ await rm(next, { recursive: true, force: true }).catch(() => {});
745
+ if (e instanceof BuildError) {
746
+ log(`crust-site dev: rebuild failed — the last complete build keeps serving\n`);
747
+ log(formatDiagnostics(e.diagnostics, { color: process.stderr.isTTY === true }));
748
+ } else {
749
+ log(
750
+ `crust-site dev: rebuild failed (${messageOf(e)}) — the last complete build keeps serving`,
751
+ );
752
+ }
753
+ }
754
+ }
755
+ }
756
+
757
+ // ---------------------------------------------------------------------------
758
+ // request handling
759
+ // ---------------------------------------------------------------------------
760
+
761
+ async function serveNotFound(serveRoot: string): Promise<Response> {
762
+ try {
763
+ const buf = await Bun.file(posix.join(serveRoot, "404.html")).arrayBuffer();
764
+ return new Response(buf, {
765
+ status: 404,
766
+ headers: new Headers({
767
+ "content-type": "text/html; charset=utf-8",
768
+ "cache-control": "no-store",
769
+ }),
770
+ });
771
+ } catch {
772
+ // 404.html missing from the serve root is an engine bug (every build
773
+ // emits it) — answer a plain 404 anyway: never a 200 with a 404 body.
774
+ return new Response("Not Found", {
775
+ status: 404,
776
+ headers: new Headers({ "content-type": "text/plain; charset=utf-8" }),
777
+ });
778
+ }
779
+ }
780
+
781
+ async function serveRequest(
782
+ req: Request,
783
+ rootRef: { current: string },
784
+ prefix: string,
785
+ ): Promise<Response> {
786
+ const serveRoot = rootRef.current;
787
+ let normalized: string | null;
788
+ try {
789
+ let pathname = new URL(req.url).pathname;
790
+ // Match the serialized site prefix at a segment boundary, once only.
791
+ // Keep root-relative preview URLs working too. Validate the remaining
792
+ // path normally: stripping a mount must not admit traversal/separators.
793
+ if (prefix !== "" && (pathname === prefix || pathname.startsWith(`${prefix}/`))) {
794
+ pathname = pathname.slice(prefix.length) || "/";
795
+ }
796
+ normalized = normalizeRequestPath(pathname);
797
+ } catch {
798
+ normalized = null;
799
+ }
800
+ if (normalized === null) return serveNotFound(serveRoot);
801
+ const file = await resolveServedFile(serveRoot, normalized);
802
+ if (file === null) return serveNotFound(serveRoot);
803
+ const abs = posix.join(serveRoot, file);
804
+ // containment re-verified on the resolved path (the write-path rule,
805
+ // applied to reads): the resolver only emits clean relative paths, but an
806
+ // upstream bug must 404, not serve outside the tree.
807
+ if (abs !== serveRoot && !abs.startsWith(`${serveRoot}/`)) return serveNotFound(serveRoot);
808
+ let buf: ArrayBuffer;
809
+ try {
810
+ buf = await Bun.file(abs).arrayBuffer();
811
+ } catch {
812
+ return serveNotFound(serveRoot);
813
+ }
814
+ return new Response(buf, {
815
+ status: 200,
816
+ headers: new Headers({
817
+ "content-type": contentTypeOf(file),
818
+ "cache-control": cacheControlOf(file),
819
+ }),
820
+ });
821
+ }