@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/build.ts ADDED
@@ -0,0 +1,755 @@
1
+ // The SSG pipeline (plan §4): config → content → route table → assets →
2
+ // render → validate → emit → publish, and nothing else. Every stage COLLECTS diagnostics
3
+ // instead of dying on the first problem (the config.ts convention), so one run
4
+ // reports every problem; the build rejects with a BuildError carrying ALL of
5
+ // them, staging is deleted, and the previous output is untouched (publish is
6
+ // the last step and restores on any mid-swap failure). Warnings never fail.
7
+ //
8
+ // Two entry points share one pipeline (runBuild, mode-parameterized):
9
+ // - build() / buildInternal(): production. Drafts are NOT rendered;
10
+ // link.draft / link.broken are ERRORS (a published site 404s on them);
11
+ // the staging is the production sibling and the run ends with the
12
+ // publish rename under the per-output build lock.
13
+ // - devBuild(): the dev server's build (chunk 9, plan §4.4). Drafts ARE
14
+ // rendered — each with the DRAFT banner prepended to its body — and
15
+ // link.draft / link.broken are WARNINGS (the dev server serves them, so
16
+ // the link really resolves there — plan §5); It takes NO lock and runs NO
17
+ // cleanupStale (the dev process never renames into the output and must
18
+ // never restore an orphan into it), and it never publishes: the result's
19
+ // outputDirectory is the dev staging tree, served in place.
20
+ //
21
+ // Concurrency: the output is LOCKED for the run (emit.acquireBuildLock,
22
+ // claimed before startup recovery and the staging mkdir) — a
23
+ // concurrent build of the same output is refused with build.busy before it
24
+ // can interleave its renames with the holder's (the measured false-pass
25
+ // race: a second build publishing into the first's rename window got rolled
26
+ // back by the first's restore while the second reported success).
27
+ //
28
+ // Determinism (plan §4.6): sequential render in route order (renderAll),
29
+ // lexicographic ordering everywhere, no timestamps in any emitted byte.
30
+
31
+ import { mkdir, rm, stat, writeFile } from "node:fs/promises";
32
+ import { pathToFileURL } from "node:url";
33
+ import { buildAssets, copyPublicDir, publicCollisions } from "./assets";
34
+ import { checkOutputOverlap, resolveConfigPaths } from "./config";
35
+ import {
36
+ buildRouteTable,
37
+ derivePageRoute,
38
+ discoverContent,
39
+ type PrecomputedRoute,
40
+ } from "./content";
41
+ import { BuildError, compareStrings, type Diagnostic, sortDiagnostics } from "./diagnostics";
42
+ import {
43
+ acquireBuildLock,
44
+ cleanupStaleLocked,
45
+ devStagingDirFor,
46
+ type EmitFile,
47
+ notFoundPage,
48
+ publish,
49
+ robotsTxt,
50
+ sitemapXml,
51
+ stagingDirFor,
52
+ writePages,
53
+ } from "./emit";
54
+ import { parseFrontmatter } from "./frontmatter";
55
+ import { filesystemPath as posix } from "./fs-path";
56
+ import { type Html, html, trustedHtml } from "./html";
57
+ import { parsePage } from "./pages";
58
+ import { collectUnusedAssets, renderAll, renderPage } from "./render";
59
+ import { routeToFile } from "./routes";
60
+ import type { FrontmatterResult, Page, ResolvedSite, RouteResolver, Site } from "./types";
61
+ import { type EmittedPage, type KnownRoute, validatePages } from "./validate";
62
+
63
+ function messageOf(e: unknown): string {
64
+ return e instanceof Error ? e.message : String(e);
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // results
69
+ // ---------------------------------------------------------------------------
70
+
71
+ export interface BuildOptions {
72
+ /** Path to `site.config.ts`; relative paths resolve against the cwd. */
73
+ readonly configFile: string;
74
+ }
75
+
76
+ /** One row of the emitted route table. */
77
+ export interface BuildPage {
78
+ readonly route: string;
79
+ /** posix, relative to the config directory. */
80
+ readonly sourcePath: string;
81
+ /** output-root-relative file (routeToFile's mapping). */
82
+ readonly file: string;
83
+ }
84
+
85
+ /**
86
+ * The public build result (contractVersion 1). `assets` maps the declared
87
+ * manifest name to its hashed output-relative path.
88
+ */
89
+ export interface BuildResult {
90
+ readonly contractVersion: 1;
91
+ readonly outputDirectory: string;
92
+ /**
93
+ * The CONTENT pages, sorted by route. The generated 404 page is emitted
94
+ * to the output (and excluded from the sitemap) but is NOT a page here —
95
+ * it is not authored content, so consumers must not expect it in `pages`.
96
+ */
97
+ readonly pages: BuildPage[];
98
+ /** manifest name → `assets/<name>-<hash>.<ext>`, keys sorted. */
99
+ readonly assets: Readonly<Record<string, string>>;
100
+ readonly durationMs: number;
101
+ /** Every warning-severity diagnostic of the run, sorted. */
102
+ readonly warnings: Diagnostic[];
103
+ }
104
+
105
+ /**
106
+ * INTERNAL: the BuildResult plus the per-page readText dependency index
107
+ * (page sourcePath → realpath'd dependency files) and the draft pages (dev
108
+ * mode only — a production build renders no drafts, so its `draftPages` is
109
+ * empty). Never part of the public contract — `build()` projects it away.
110
+ * The v1 dev watcher does FULL rebuilds: it consumes pages/draftPages/
111
+ * warnings/durationMs only, and `pageDeps` stays collected but unused
112
+ * (USAGE.md, "Dev server contract" — no page-level skipping is claimed).
113
+ */
114
+ export interface BuildInternalResult extends BuildResult {
115
+ /**
116
+ * The DRAFT pages this run emitted, sorted by route (empty in a
117
+ * production build — drafts are rendered only in dev mode). Same shape as
118
+ * `pages`.
119
+ */
120
+ readonly draftPages: BuildPage[];
121
+ /**
122
+ * The per-page readText reverse index (page sourcePath → realpath'd
123
+ * dependency files). RESERVED for a future page-level invalidation pass:
124
+ * the v1 dev watcher does full rebuilds and does not consume it yet — it
125
+ * is collected so that pass will have the dependency graph without
126
+ * re-walking every page.
127
+ */
128
+ readonly pageDeps: Readonly<Record<string, string[]>>;
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // config loading
133
+ // ---------------------------------------------------------------------------
134
+
135
+ /**
136
+ * Runtime stand-in for the phantom brand: a `defineSite()` result always
137
+ * carries every resolved key (the optional ones as undefined-stripped or
138
+ * present — defineSite always sets site/content/layouts/assets/output/
139
+ * sitemap/lang). Anything else was hand-made or is not a config at all.
140
+ */
141
+ function looksLikeSite(value: unknown): boolean {
142
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
143
+ const obj = value as Record<string, unknown>;
144
+ return ["site", "content", "layouts", "assets", "output", "sitemap", "lang"].every((key) =>
145
+ Object.hasOwn(obj, key),
146
+ );
147
+ }
148
+
149
+ async function loadSiteConfig(configPath: string): Promise<Site> {
150
+ let mod: Record<string, unknown>;
151
+ try {
152
+ // file URL, not a bare path: Windows drive letters are not valid specifiers.
153
+ mod = (await import(pathToFileURL(configPath).href)) as Record<string, unknown>;
154
+ } catch (e) {
155
+ if (e instanceof BuildError) throw e; // defineSite's own diagnostics stay verbatim
156
+ throw new BuildError([
157
+ {
158
+ code: "config.load",
159
+ severity: "error",
160
+ sourcePath: configPath,
161
+ message: `importing the config file ${JSON.stringify(configPath)} failed: ${messageOf(e)}`,
162
+ },
163
+ ]);
164
+ }
165
+ if (!looksLikeSite(mod.default)) {
166
+ throw new BuildError([
167
+ {
168
+ code: "config.load",
169
+ severity: "error",
170
+ sourcePath: configPath,
171
+ message:
172
+ `the default export of ${JSON.stringify(configPath)} is not a defineSite() result; ` +
173
+ 'the config file must `export default defineSite({ ... })` from "@lariocpt/crust-site"',
174
+ },
175
+ ]);
176
+ }
177
+ return mod.default as Site;
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // publicAsset verification (the emitter half of the public-asset.* contract)
182
+ // ---------------------------------------------------------------------------
183
+
184
+ /**
185
+ * What the existence check reads off a render result. Structural — not the
186
+ * full PageRender — so tests can feed minimal records and the check never
187
+ * depends on render internals.
188
+ */
189
+ export interface PublicAssetRender {
190
+ readonly page: { readonly sourcePath: string };
191
+ readonly publicAssets: readonly string[];
192
+ }
193
+
194
+ /**
195
+ * Verify every publicAsset path the renders recorded. render.ts already
196
+ * rejected malformed paths at RECORD time; this re-validates the recorded
197
+ * shape before ANY filesystem access, so a corrupted or tampered record can
198
+ * never become a stat outside the public directory:
199
+ * - empty, NUL, backslash, drive letter, a leading `/`, or a `..` segment
200
+ * → malformed → reported missing WITHOUT any stat (a plain join+stat
201
+ * would bless the target: `posix.join` drops the public dir for an
202
+ * absolute path, and `..`/backslashes traverse out of it);
203
+ * - well-formed → must be a regular file under the public directory.
204
+ * `publicDir` undefined makes EVERY recorded path missing (there is no
205
+ * directory a file could live in) — a page with a dead reference would be
206
+ * a false pass (crust rule 1).
207
+ */
208
+ export async function verifyPublicAssets(
209
+ publicDir: string | undefined,
210
+ renders: readonly PublicAssetRender[],
211
+ ): Promise<Diagnostic[]> {
212
+ const all: Diagnostic[] = [];
213
+ for (const r of renders) {
214
+ for (const pa of r.publicAssets) {
215
+ const malformed =
216
+ pa === "" ||
217
+ pa.includes("\0") ||
218
+ pa.includes("\\") ||
219
+ /^[A-Za-z]:/.test(pa) ||
220
+ pa.startsWith("/") ||
221
+ pa.split("/").includes("..");
222
+ let isFile = false;
223
+ if (!malformed && publicDir !== undefined) {
224
+ isFile = await stat(posix.join(publicDir, pa))
225
+ .then((s) => s.isFile())
226
+ .catch(() => false);
227
+ }
228
+ if (!isFile) {
229
+ all.push({
230
+ code: "public-asset.missing",
231
+ severity: "error",
232
+ sourcePath: r.page.sourcePath,
233
+ message:
234
+ `publicAsset(${JSON.stringify(pa)}) referenced by the layout is not a file under ` +
235
+ (publicDir !== undefined
236
+ ? `assets.publicDirectory (${JSON.stringify(publicDir)})`
237
+ : "the public directory: assets.publicDirectory is not configured"),
238
+ });
239
+ }
240
+ }
241
+ }
242
+ return all;
243
+ }
244
+
245
+ // ---------------------------------------------------------------------------
246
+ // the pipeline
247
+ // ---------------------------------------------------------------------------
248
+
249
+ /**
250
+ * "build" = a production build: no drafts rendered, link.draft/link.broken are
251
+ * errors, the run ends with the publish rename. "dev" = the dev server's
252
+ * build: drafts rendered with the banner, link.draft/link.broken are warnings,
253
+ * no publish (the result's outputDirectory is the dev staging itself).
254
+ */
255
+ type BuildMode = "build" | "dev";
256
+
257
+ async function runBuild(
258
+ resolved: ResolvedSite,
259
+ staging: string,
260
+ outputDir: string,
261
+ started: number,
262
+ mode: BuildMode,
263
+ ): Promise<BuildInternalResult> {
264
+ const all: Diagnostic[] = [];
265
+
266
+ // content: discover → pre-pass → parse. The pre-pass reads each file ONCE
267
+ // and parses its frontmatter, so every page's route (frontmatter `route`
268
+ // ?? content.route(relativePath), normalized) and draft flag are known
269
+ // BEFORE the first markdown render: a page's relative .md links must
270
+ // resolve against the FULL route table, which only exists once every
271
+ // page's route is derived. Frontmatter problems fold into the collected
272
+ // set (the parse loop skips the file — no Page is created for it) instead
273
+ // of dying, so one run reports every broken page.
274
+ const files = await discoverContent(resolved);
275
+ const frontmatters = new Map<string, FrontmatterResult>();
276
+ const precomputed = new Map<string, PrecomputedRoute>();
277
+ for (const file of files) {
278
+ const sourcePath = posix.relative(resolved.configDir, file.absolutePath);
279
+ let text: string;
280
+ try {
281
+ text = await Bun.file(file.absolutePath).text();
282
+ } catch (e) {
283
+ all.push({
284
+ code: "content.read-failed",
285
+ severity: "error",
286
+ sourcePath,
287
+ message: `reading ${JSON.stringify(sourcePath)} failed: ${messageOf(e)}`,
288
+ });
289
+ continue;
290
+ }
291
+ let parsed: FrontmatterResult;
292
+ try {
293
+ parsed = parseFrontmatter(text, sourcePath);
294
+ } catch (e) {
295
+ // A frontmatter problem is the located BuildError chunk 2 raises —
296
+ // folded into the collected set. A NON-BuildError here is an engine
297
+ // bug, and the read already succeeded, so labeling it
298
+ // content.read-failed would be a lie — content.parse-failed keeps
299
+ // the code true (crust rule 1).
300
+ if (e instanceof BuildError) {
301
+ all.push(...e.diagnostics);
302
+ } else {
303
+ all.push({
304
+ code: "content.parse-failed",
305
+ severity: "error",
306
+ sourcePath,
307
+ message: `parsing ${JSON.stringify(sourcePath)} failed: ${messageOf(e)}`,
308
+ });
309
+ }
310
+ continue;
311
+ }
312
+ frontmatters.set(sourcePath, parsed);
313
+ precomputed.set(
314
+ sourcePath,
315
+ derivePageRoute({
316
+ frontmatterRoute: parsed.frontmatter.route,
317
+ relativePath: file.relativePath,
318
+ sourcePath,
319
+ routeFn: resolved.content.route,
320
+ draft: parsed.frontmatter.draft === true,
321
+ }),
322
+ );
323
+ }
324
+ // The link resolver answers .md candidates from the pre-pass decisions —
325
+ // the route set the route table will replay, with the drafts INCLUDED: the
326
+ // PRODUCTION table excludes drafts, but link resolution must see them so a
327
+ // link to a draft resolves (and step 7 reports link.draft with the right
328
+ // destination) instead of passing silently. A candidate no file derives is
329
+ // null (recorded exists:false — step 7 turns it into link.broken).
330
+ // "external" is never returned: a candidate reaching the resolver is an
331
+ // already-normalized route, and a route is never an external URL.
332
+ const preRoutes = new Map<string, boolean>();
333
+ for (const decision of precomputed.values()) {
334
+ if (decision.route !== undefined) preRoutes.set(decision.route, decision.draft);
335
+ }
336
+ const routeResolver: RouteResolver = (candidate) => {
337
+ const draft = preRoutes.get(candidate);
338
+ return draft === undefined ? null : { route: candidate, exists: true, isDraft: draft };
339
+ };
340
+
341
+ const pages: Page[] = [];
342
+ for (const file of files) {
343
+ const sourcePath = posix.relative(resolved.configDir, file.absolutePath);
344
+ const frontmatter = frontmatters.get(sourcePath);
345
+ if (frontmatter === undefined) continue; // diagnosed in the pre-pass; no Page
346
+ try {
347
+ pages.push(
348
+ await parsePage({
349
+ absolutePath: file.absolutePath,
350
+ relativePath: file.relativePath,
351
+ sourcePath,
352
+ resolvedSite: resolved,
353
+ frontmatter,
354
+ pageRoute: precomputed.get(sourcePath)?.route,
355
+ routeResolver,
356
+ }),
357
+ );
358
+ } catch (e) {
359
+ // With a provided frontmatter parsePage performs no file I/O
360
+ // (renderMarkdown contains its own throws, parseData is caught inside
361
+ // it), so a throw here is an engine bug, not a read failure — recorded,
362
+ // never fatal, and labeled distinct from content.read-failed so the
363
+ // code stays true (crust rule 1).
364
+ if (e instanceof BuildError) {
365
+ all.push(...e.diagnostics);
366
+ } else {
367
+ all.push({
368
+ code: "content.parse-failed",
369
+ severity: "error",
370
+ sourcePath,
371
+ message: `parsing ${JSON.stringify(sourcePath)} failed: ${messageOf(e)}`,
372
+ });
373
+ }
374
+ }
375
+ }
376
+
377
+ const table = buildRouteTable(pages, resolved, precomputed);
378
+ all.push(...table.diagnostics);
379
+
380
+ const assets = await buildAssets(resolved, staging);
381
+ all.push(...assets.diagnostics);
382
+
383
+ const renderOpts = {
384
+ site: resolved.site,
385
+ manifest: assets.manifest,
386
+ layouts: resolved.layouts,
387
+ configDir: resolved.configDir,
388
+ publicDir: resolved.assets.publicDirectory,
389
+ };
390
+ // dev mode renders the drafts too (the dev server serves them, so their
391
+ // links are validated against the full table); each draft's body gets the
392
+ // DRAFT banner prepended — trusted engine markup, so the fence still runs
393
+ // over it like any other document bytes. Production renders no drafts.
394
+ const draftPages =
395
+ mode === "dev" ? table.drafts.map((p) => ({ ...p, body: draftBannerBody(p.body) })) : [];
396
+ const toRender = mode === "dev" ? [...table.pages, ...draftPages] : table.pages;
397
+ const rendered = await renderAll(toRender, renderOpts);
398
+ for (const r of rendered.pages) all.push(...r.diagnostics);
399
+
400
+ // The generated 404 (plan, "Locked decisions" 2): rendered through the same
401
+ // engine and layout registry as every page, after the content pages so the
402
+ // asset audit sees it too (an asset referenced only by the 404 is used).
403
+ const notFound = notFoundPage(resolved.site, resolved.content.defaultLayout);
404
+ const notFoundRender = await renderPage({ ...renderOpts, page: notFound });
405
+ all.push(...notFoundRender.diagnostics);
406
+ all.push(...collectUnusedAssets(assets.manifest, [...rendered.pages, notFoundRender]));
407
+
408
+ // public copy + collisions against EVERY generated path (the copy already
409
+ // landed in staging; a collision is an error, so staging is discarded whole).
410
+ const pub = await copyPublicDir(resolved, staging);
411
+ all.push(...pub.diagnostics);
412
+ const generated = [
413
+ ...toRender.map((p) => ({
414
+ file: routeToFile(p.route),
415
+ producer: `route ${JSON.stringify(p.route)} (${p.sourcePath})`,
416
+ })),
417
+ { file: "404.html", producer: "the generated 404 page" },
418
+ ...(resolved.sitemap ? [{ file: "sitemap.xml", producer: "the generated sitemap" }] : []),
419
+ ...(resolved.robots !== undefined
420
+ ? [{ file: "robots.txt", producer: "the generated robots file" }]
421
+ : []),
422
+ ...[...assets.manifest.entries()].map(([name, e]) => ({
423
+ file: e.file,
424
+ producer: `asset ${JSON.stringify(name)}`,
425
+ })),
426
+ ];
427
+ // Different routes can map to the same file (/ and /index), and engine
428
+ // files have no authored route-table entry. Check the output namespace
429
+ // itself, on every platform, before writePages can silently overwrite.
430
+ const byOutput = new Map<string, typeof generated>();
431
+ for (const entry of generated) {
432
+ const key = entry.file.toLowerCase();
433
+ const group = byOutput.get(key);
434
+ if (group) group.push(entry);
435
+ else byOutput.set(key, [entry]);
436
+ }
437
+ for (const [file, group] of [...byOutput].sort((a, b) => compareStrings(a[0], b[0]))) {
438
+ if (group.length < 2) continue;
439
+ const producers = group
440
+ .map((entry) => `${entry.producer} → ${JSON.stringify(entry.file)}`)
441
+ .sort(compareStrings);
442
+ all.push({
443
+ code: "output.collision",
444
+ severity: "error",
445
+ sourcePath: file,
446
+ message:
447
+ `generated output ${JSON.stringify(file)} has multiple producers ` +
448
+ `(paths are compared case-insensitively): ${producers.join("; ")}`,
449
+ });
450
+ }
451
+ const generatedPaths = generated.map((entry) => entry.file);
452
+ all.push(...publicCollisions(pub.copied, generatedPaths));
453
+
454
+ // publicAsset existence check (render.ts recorded the normalized paths;
455
+ // verifyPublicAssets re-validates the RECORDED shape and stats each one —
456
+ // a path with no file behind it would publish a page with a dead
457
+ // reference: an error, never a silent hole, crust rule 1). No
458
+ // publicDirectory configured makes every recorded path missing.
459
+ all.push(
460
+ ...(await verifyPublicAssets(resolved.assets.publicDirectory, [
461
+ ...rendered.pages,
462
+ notFoundRender,
463
+ ])),
464
+ );
465
+
466
+ if (all.some((d) => d.severity === "error")) throw new BuildError(all);
467
+
468
+ // emit (only reached error-free: every render carried a document)
469
+ const documents = [...rendered.pages, notFoundRender];
470
+ const items: EmitFile[] = [];
471
+ const emitted: EmittedPage[] = [];
472
+ for (const r of documents) {
473
+ if (r.html === null) {
474
+ // renderPage's contract is "null html ⟺ an error diagnostic", and no
475
+ // error was collected — an engine bug must still fail loudly, never
476
+ // publish a hole (crust rule 1).
477
+ all.push({
478
+ code: "render.threw",
479
+ severity: "error",
480
+ sourcePath: r.page.sourcePath,
481
+ message:
482
+ "the render produced no document without recording an error diagnostic; " +
483
+ "this is an engine bug — nothing was published",
484
+ });
485
+ continue;
486
+ }
487
+ items.push({ route: r.page.route, file: routeToFile(r.page.route), html: r.html });
488
+ // step 7's input: the final emitted document plus the links the markdown
489
+ // pass recorded (internal destinations only — external URLs are never
490
+ // in there, so they are never link- or fragment-checked).
491
+ emitted.push({
492
+ route: r.page.route,
493
+ sourcePath: r.page.sourcePath,
494
+ html: r.html,
495
+ links: r.page.links,
496
+ });
497
+ }
498
+ // step 7 (plan §4.7): link/fragment/metadata validation over the FINAL
499
+ // emitted documents, BEFORE anything lands in staging — the fragment check
500
+ // needs the bytes about to be written, and a failed validation must block
501
+ // the publish, not clean up after it. The route set is the production
502
+ // pages AND the drafts, excluding the generated /404 (a link to it is
503
+ // link.broken — the 404 page is not a link target). Errors fall through
504
+ // to the gate below (nothing is published); warnings join
505
+ // BuildResult.warnings.
506
+ const knownRoutes = new Map<string, KnownRoute>();
507
+ for (const p of table.pages) {
508
+ if (p.route !== "/404") knownRoutes.set(p.route, { draft: false });
509
+ }
510
+ for (const p of table.drafts) {
511
+ if (p.route !== "/404") knownRoutes.set(p.route, { draft: true });
512
+ }
513
+ // mode passes through: "build" errors on draft/broken internal links, "dev"
514
+ // warns (plan §5 — the dev server serves drafts, so the links resolve there).
515
+ all.push(...validatePages({ mode, pages: emitted, routes: knownRoutes }));
516
+ if (all.some((d) => d.severity === "error")) throw new BuildError(all);
517
+
518
+ await writePages(staging, items);
519
+ if (resolved.sitemap) {
520
+ await writeFileAt(staging, "sitemap.xml", sitemapXml(table.pages));
521
+ }
522
+ const robots = robotsTxt(resolved.site, resolved.robots, resolved.sitemap);
523
+ if (robots !== null) await writeFileAt(staging, "robots.txt", robots);
524
+
525
+ // The publish rename is the PRODUCTION tail. Dev never renames into the
526
+ // output directory (the dev staging is the served tree, owned by the
527
+ // dev server), so the "dev" mode simply stops here.
528
+ if (mode === "build") await publish(staging, outputDir);
529
+
530
+ const pageDeps: Record<string, string[]> = {};
531
+ for (const r of documents) pageDeps[r.page.sourcePath] = r.deps;
532
+
533
+ return {
534
+ contractVersion: 1,
535
+ // dev: the result IS the staging tree (the dev server serves it in place
536
+ // and owns its lifetime); build: the published output directory.
537
+ outputDirectory: mode === "dev" ? staging : outputDir,
538
+ pages: table.pages.map((p) => ({
539
+ route: p.route,
540
+ sourcePath: p.sourcePath,
541
+ file: routeToFile(p.route),
542
+ })),
543
+ // dev: the drafts this run emitted (banned in production, so this is
544
+ // always [] for mode "build" — the dev watcher and the dev CLI use the
545
+ // list to know which routes carry the banner).
546
+ draftPages: draftPages.map((p) => ({
547
+ route: p.route,
548
+ sourcePath: p.sourcePath,
549
+ file: routeToFile(p.route),
550
+ })),
551
+ assets: Object.fromEntries(
552
+ [...assets.manifest.entries()]
553
+ .sort((a, b) => compareStrings(a[0], b[0]))
554
+ .map(([name, entry]) => [name, entry.file]),
555
+ ),
556
+ durationMs: Math.round(performance.now() - started),
557
+ warnings: sortDiagnostics(all.filter((d) => d.severity === "warning")),
558
+ pageDeps,
559
+ };
560
+ }
561
+
562
+ async function writeFileAt(staging: string, file: string, contents: string): Promise<void> {
563
+ await writeFile(posix.join(staging, file), contents);
564
+ }
565
+
566
+ // ---------------------------------------------------------------------------
567
+ // the DRAFT banner (dev mode only)
568
+ // ---------------------------------------------------------------------------
569
+
570
+ /**
571
+ * The DRAFT banner, prepended to every draft page's BODY in dev mode only
572
+ * (plan §4.4). Engine-owned markup — not authored content, so it is a
573
+ * constant here (byte-stable across rebuilds, which is what keeps the
574
+ * no-lastmod/byte-identical-rebuild contract honest even while a draft
575
+ * exists) and it is trustedHtml (the fence still runs over it like any
576
+ * document bytes). It is static markup with no attributes the fence's
577
+ * url/style/attribute checks could trip on, no event handlers, and no
578
+ * dynamic values.
579
+ *
580
+ * Styled with inline `style=` rules (one per element; no `<style>` block —
581
+ * the fence's style-body rule bans tracked values inside `<style>` ELEMENTS,
582
+ * and `style` is not one of the fence's checked attributes). The banner
583
+ * carries no URL-bearing attribute, no event handler, and no tracked value,
584
+ * so a draft's banner can never open a fence violation the
585
+ * page itself would not have. DEV ONLY: a production build never renders
586
+ * drafts at all, so the banner never reaches the output directory.
587
+ */
588
+ export const DRAFT_BANNER_HTML = `<div data-crust-draft="true"
589
+ style="background:#fff8e1;color:#6d5300;border-bottom:1px solid #e0c05a;padding:8px 16px;font-family:system-ui,sans-serif;font-size:14px">
590
+ <strong>DRAFT</strong> &mdash; this page is marked <code>draft: true</code> and will not be published
591
+ </div>`;
592
+
593
+ /**
594
+ * Wrap a draft page's rendered body with the banner: a template whose first
595
+ * value is the trusted banner and second is the page body. Both values are
596
+ * real Html, so the fence tracks them (the banner contributes no tracked
597
+ * ranges — it is trusted engine markup — while the body's markdown value
598
+ * ranges are tracked exactly as on a normal page).
599
+ */
600
+ function draftBannerBody(body: Html): Html {
601
+ return html`${trustedHtml(DRAFT_BANNER_HTML)}${body}`;
602
+ }
603
+
604
+ /** A config file loaded, resolved and overlap-checked — ready for a run. */
605
+ export interface LoadedConfig {
606
+ /** The config file's absolute posix path (the import specifier source). */
607
+ readonly configPath: string;
608
+ readonly site: Site;
609
+ readonly resolved: ResolvedSite;
610
+ }
611
+
612
+ /**
613
+ * Load + resolve + validate ONE config file. `buildInternal` and `devBuild`
614
+ * both go through this, so the overlap check runs for the dev server too: a
615
+ * config that `build` would refuse is refused by `dev` with the SAME
616
+ * diagnostics (a dev server happily serving an unbuildable site would be a
617
+ * false pass). Relative paths resolve against the process cwd (CLI convention);
618
+ * every stored path then resolves against the CONFIG FILE's directory.
619
+ */
620
+ export async function loadResolvedConfig(configFile: string): Promise<LoadedConfig> {
621
+ const raw = typeof configFile === "string" ? configFile : "";
622
+ if (raw === "") {
623
+ throw new BuildError([
624
+ {
625
+ code: "config.load",
626
+ severity: "error",
627
+ sourcePath: "",
628
+ message: "a configFile path is required (e.g. ./site.config.ts)",
629
+ },
630
+ ]);
631
+ }
632
+ // absolute before anything else: every stored path resolves against the
633
+ // CONFIG FILE's directory, and the import needs a stable specifier.
634
+ const configPath = posix.resolve(process.cwd(), raw);
635
+ const site = await loadSiteConfig(configPath);
636
+ const resolved = resolveConfigPaths(site, posix.dirname(configPath));
637
+ checkOutputOverlap(resolved);
638
+ return { configPath, site, resolved };
639
+ }
640
+
641
+ /**
642
+ * Run the pipeline and return the INTERNAL result (BuildResult + draftPages +
643
+ * pageDeps). Chunk 9's dev watcher imports `devBuild` (same pipeline, dev
644
+ * mode); authors use `build()`.
645
+ */
646
+ export async function buildInternal(options: BuildOptions): Promise<BuildInternalResult> {
647
+ const started = performance.now();
648
+ const loaded = await loadResolvedConfig(options?.configFile ?? "");
649
+
650
+ const resolved = loaded.resolved;
651
+ const outputDir = posix.resolve(resolved.output.directory);
652
+ // Recovery can replace output too: it must not run beside a live publisher.
653
+ const release = await acquireBuildLock(outputDir);
654
+ const staging = stagingDirFor(outputDir);
655
+ try {
656
+ await cleanupStaleLocked(outputDir);
657
+ await mkdir(staging, { recursive: true });
658
+ return await runBuild(resolved, staging, outputDir, started, "build");
659
+ } finally {
660
+ // success moved staging into place (it no longer exists); any failure path
661
+ // — including a publish that restored the old output — leaves staging to
662
+ // delete here. force swallows the already-gone case. Then the lock is
663
+ // released (its file may already be gone — that is fine).
664
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
665
+ await release();
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Build the site (the public entry). Resolves to the BuildResult; rejects
671
+ * with a BuildError carrying EVERY collected diagnostic when anything failed.
672
+ */
673
+ export async function build(options: BuildOptions): Promise<BuildResult> {
674
+ const internal = await buildInternal(options);
675
+ // explicit projection: the public shape is exactly the contract, the
676
+ // internal extras (pageDeps) cannot leak through a stray property.
677
+ return {
678
+ contractVersion: internal.contractVersion,
679
+ outputDirectory: internal.outputDirectory,
680
+ pages: internal.pages,
681
+ assets: internal.assets,
682
+ durationMs: internal.durationMs,
683
+ warnings: internal.warnings,
684
+ };
685
+ }
686
+
687
+ /**
688
+ * The DEV server's build (plan §4.4, chunk 9). Same pipeline as `build()` in
689
+ * mode "dev": drafts ARE rendered (each with the DRAFT banner), and
690
+ * link.draft / link.broken are WARNINGS instead of errors. The differences
691
+ * from a production run, and why each one exists:
692
+ * - the staging is the DEV family (`devStagingDirFor`, `.crust-dev-staging-`),
693
+ * a sibling of the output directory (same filesystem, never /tmp) — the
694
+ * dev server serves it IN PLACE and owns its lifetime;
695
+ * - NO build lock: the dev process never renames into the output, so the
696
+ * lock's naming space stays exclusive to publishing builds and a dev
697
+ * process can neither claim nor be claimed by it;
698
+ * - NO cleanupStale: that startup pass RESTORES orphaned out-old trees INTO
699
+ * the output — a dev process must never write to the output directory,
700
+ * so it never runs it;
701
+ * - NO publish: there is nothing to swap in. The returned
702
+ * `result.outputDirectory` is the dev staging tree itself.
703
+ *
704
+ * On failure the staging is deleted and the BuildError rethrown with every
705
+ * collected diagnostic (the caller — the dev server — formats and reports
706
+ * them, and keeps serving the last complete tree).
707
+ */
708
+ export interface DevBuild {
709
+ /** The dev staging tree (`.crust-dev-staging-<pid>-<nonce>` beside the output). */
710
+ readonly staging: string;
711
+ readonly result: BuildInternalResult;
712
+ /** The resolved config the run used (the dev watcher watches its dirs). */
713
+ readonly resolved: ResolvedSite;
714
+ /** The config file's absolute posix path. */
715
+ readonly configPath: string;
716
+ }
717
+
718
+ /**
719
+ * INTERNAL (the dev server's watcher): re-run the mode-"dev" pipeline into
720
+ * `staging` with an ALREADY-loaded resolved config. The caller (dev.ts)
721
+ * creates `staging` via `devStagingDirFor` and owns its lifetime: on
722
+ * success it serves it, on failure it deletes it. This is deliberately NOT
723
+ * `devBuild`: a content change must rebuild with the config that was loaded
724
+ * when the dev process started — re-importing the config file here would
725
+ * silently apply a config edit in-process, which the dev server refuses to
726
+ * do (config changes mean a worker restart, never a partial reload).
727
+ */
728
+ export async function devRebuild(
729
+ resolved: ResolvedSite,
730
+ staging: string,
731
+ outputDir: string,
732
+ ): Promise<BuildInternalResult> {
733
+ const started = performance.now();
734
+ try {
735
+ await mkdir(staging, { recursive: true });
736
+ return await runBuild(resolved, staging, outputDir, started, "dev");
737
+ } catch (e) {
738
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
739
+ throw e;
740
+ }
741
+ }
742
+
743
+ export async function devBuild(options: { readonly configFile: string }): Promise<DevBuild> {
744
+ const loaded = await loadResolvedConfig(options?.configFile ?? "");
745
+ const resolved = loaded.resolved;
746
+ const outputDir = posix.resolve(resolved.output.directory);
747
+ const staging = devStagingDirFor(outputDir);
748
+ try {
749
+ const result = await devRebuild(resolved, staging, outputDir);
750
+ return { staging, result, resolved, configPath: loaded.configPath };
751
+ } catch (e) {
752
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
753
+ throw e;
754
+ }
755
+ }