@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/render.ts ADDED
@@ -0,0 +1,940 @@
1
+ // The layout render engine (plan §3 "Layout context", §4.6 determinism).
2
+ //
3
+ // A page is rendered by its Layout: a plain function that receives a
4
+ // LayoutContext and returns an Html (or a Promise resolving to one). The
5
+ // context is where the safety model lives:
6
+ //
7
+ // - `page` — a DEEP-FROZEN view of the page (every mutation throws in
8
+ // strict mode). Containers (headings/data/links/warnings/
9
+ // diagnostics) are shallow-COPIED into the view before
10
+ // freezing, so the route table's own page object keeps its
11
+ // original, still-mutable containers (later chunks may
12
+ // append to them); shared leaves (the records, the body
13
+ // Html node) are frozen in place — they are immutable by
14
+ // construction and Object.freeze is idempotent.
15
+ // - `content` — the page's rendered markdown body (trustedHtml: its value
16
+ // ranges are already handed to the fence).
17
+ // - `site` — { url }: the site's base URL (path prefix included).
18
+ //
19
+ // The PER-RENDER head sink (plan §3 — this fixes the "dedup vs pure
20
+ // function" contradiction): every Layout(ctx) invocation gets a FRESH state
21
+ // object; head()/stylesheet()/script()/url()/publicAsset()/readText() close
22
+ // over it, so first-call-vs-repeat dedup is plain per-render state, and
23
+ // concurrent renders are isolated by construction (no module-level state is
24
+ // read or written by the engine — a layout that keeps its OWN module-level
25
+ // state across renders is an author hazard, documented here, not policed).
26
+ // When the render finishes the sink is CLOSED: any helper called afterwards
27
+ // (a captured ctx used late) throws — plan §3 "calling outside a render
28
+ // throws". A helper promise the layout never AWAITED is the author's hazard,
29
+ // and the engine stays honest about it two ways: a readText still pending when
30
+ // the render returned cannot retroactively change the finished result (its
31
+ // realpath lands on the closed, already-collected sink — never on a later
32
+ // page's), and if it then fails, the rejection surfaces UNHANDLED rather than
33
+ // being swallowed here. Swallowing it would turn a real failure into a silent
34
+ // pass (crust rule 1), so the loud crash is the intended behaviour.
35
+ //
36
+ // Helper semantics (pinned by tests/render.test.ts):
37
+ // - head() emits EXACTLY seven tags, LF-joined, no trailing newline:
38
+ // <title>, description meta, canonical link, og:title,
39
+ // og:description, og:url, og:type=website (property=
40
+ // namespace). Every value goes through the html runtime's
41
+ // ONE escaper, so a title with `"` or a newline can never
42
+ // break its attribute (a raw newline inside a QUOTED
43
+ // attribute is legal HTML and is kept as-is). It NEVER emits
44
+ // charset/viewport — the layout hand-writes those (the
45
+ // validation step, chunk 7, errors if they are missing).
46
+ // A SECOND head() call emits nothing and records
47
+ // head.duplicate — a build-error diagnostic, NOT a throw
48
+ // (plan §3); the page still renders.
49
+ // NO LENGTH CAP in v1: title and description are emitted
50
+ // verbatim (the plan floated 128/200 as a minor idea). The
51
+ // decision is to ship none: silently truncating metadata is
52
+ // the kind of quiet rewrite crust rule 1 dislikes, and a
53
+ // too-long <title> is a style problem for the metadata
54
+ // validation pass (chunk 7), where a WARNING can name the
55
+ // page, rather than a silent cut here.
56
+ // - stylesheet()/script() share ONE dedup namespace, mirroring the config's
57
+ // single asset namespace (config.ts rejects a name declared
58
+ // in both maps). The FIRST call for a name emits the tag;
59
+ // repeats emit nothing. The tag's KIND follows the MANIFEST
60
+ // ENTRY'S EXTENSION (`.js` → `<script defer>`, `.css` →
61
+ // `<link rel="stylesheet">`), never which helper was called:
62
+ // the manifest is the one source of truth for what the
63
+ // asset's bytes are, and a helper/ext mismatch (a
64
+ // stylesheet() on a JS entry) must never silently emit a
65
+ // broken tag — it emits the tag the bytes require. An
66
+ // unknown name records asset.unknown-entrypoint (page-
67
+ // attributed) and ABORTS this page's render.
68
+ // - Asset URLs are ABSOLUTE against the site (`site + "/" + file`, prefix
69
+ // included) so a path-prefixed site (GH Pages `/docs/`)
70
+ // serves them correctly; for a prefix-less site this is
71
+ // exactly the root-absolute `/assets/…` form.
72
+ // - url() wraps validateUrl with the PAGE as base: the full site URL
73
+ // (prefix included) is the base, so relative refs resolve
74
+ // against `site + route` — which is EXACTLY the page's
75
+ // canonical URL (url.ts `urlBase({siteUrl, pageRoute}) ===
76
+ // canonicalUrl(site, route)`, pinned by tests). A bare origin
77
+ // would drop the prefix, and pages.ts/markdown.ts use the
78
+ // same full-site base for the same reason. The cross-origin
79
+ // re-check still uses the site's ORIGIN. On failure: record
80
+ // (page-attributed) + abort.
81
+ // - publicAsset(path) is a PATH, not a URL: never percent-decoded,
82
+ // posix-normalized; literal traversal (`..` segments,
83
+ // leading "/", backslashes, drive letters, NUL, empty) is
84
+ // rejected before any filesystem access
85
+ // (public-asset.traversal). The normalized path is recorded
86
+ // for the emitter's existence check (chunk 7).
87
+ // - readText(path) — the confinement contract: root = REALPATH of the
88
+ // config directory; absolute/`..`/NUL/backslash/drive
89
+ // rejected before resolution, then resolve → REALPATH →
90
+ // the result must stay inside the root (a symlink never
91
+ // extends a boundary; a missing file is read-text.failed,
92
+ // NOT an escape — the path stayed inside, there is just
93
+ // nothing there); 10 MiB cap checked via stat before
94
+ // reading; strict UTF-8. The final realpath lands in the
95
+ // render's dependency set (chunk 8's dev invalidation
96
+ // consumes it).
97
+ //
98
+ // Failure semantics (crust rule 1 — never a false pass, never a crash):
99
+ // - a helper failure records a PAGE-ATTRIBUTED diagnostic and aborts
100
+ // THIS page's render only (the result's html is null); renderAll
101
+ // continues with the remaining pages;
102
+ // - a layout that throws (or a Promise that rejects) → render.threw with
103
+ // the error's message AND stack, page-attributed;
104
+ // - a layout returning a non-Html (or a Promise resolving to one) →
105
+ // render.bad-result;
106
+ // - a fence violation from finalizeDocument → the fence diagnostics
107
+ // (codes preserved) re-stamped with the page's sourcePath;
108
+ // - renderPage and renderAll NEVER throw out of the engine.
109
+ //
110
+ // Determinism (plan §4.6): renderAll renders SEQUENTIALLY in lexicographic
111
+ // (code-unit) route order no matter what order the pages arrive in; every
112
+ // render gets a fresh sink; every returned list is sorted; all output is
113
+ // LF-only.
114
+
115
+ import { readFile, realpath, stat } from "node:fs/promises";
116
+ import { posix } from "node:path";
117
+ import type { AssetManifest } from "./assets";
118
+ import { manifestLookup } from "./assets";
119
+ import type { RoutedPage } from "./content";
120
+ import {
121
+ BuildError,
122
+ compareStrings,
123
+ type Diagnostic,
124
+ isDiagnostic,
125
+ sortDiagnostics,
126
+ } from "./diagnostics";
127
+ import { filesystemPath } from "./fs-path";
128
+ import { finalizeDocument, type Html, html, isHtml } from "./html";
129
+ import type { LayoutFn } from "./types";
130
+ import { validateUrl } from "./url";
131
+
132
+ function toPosix(p: string): string {
133
+ return p.replace(/\\/g, "/");
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // Public types
138
+ // ---------------------------------------------------------------------------
139
+
140
+ /**
141
+ * DeepReadonly: the type-level image of the deep freeze renderPage applies
142
+ * to the page it hands a layout. Functions and primitives pass through
143
+ * untouched; arrays and objects map to readonly counterparts (homomorphic
144
+ * mapping, so private members survive).
145
+ */
146
+ export type DeepReadonly<T> = T extends (...args: never[]) => unknown
147
+ ? T
148
+ : T extends readonly (infer U)[]
149
+ ? readonly DeepReadonly<U>[]
150
+ : T extends object
151
+ ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
152
+ : T;
153
+
154
+ /** The read-only page view a LayoutContext exposes. */
155
+ export type FrozenPage = DeepReadonly<RoutedPage>;
156
+
157
+ /**
158
+ * What a layout receives. Everything is bound to ONE render: the sink
159
+ * behind the helpers is created fresh for this Layout(ctx) invocation and
160
+ * closed when the render finishes (a captured ctx used later throws).
161
+ */
162
+ export interface LayoutContext {
163
+ /** The page, deep-frozen: every mutation throws in strict mode. */
164
+ readonly page: FrozenPage;
165
+ /** The rendered markdown body of the page (value ranges already tracked). */
166
+ readonly content: Html;
167
+ /** The site's base URL (may carry a path prefix). */
168
+ readonly site: Readonly<{ readonly url: string }>;
169
+ /**
170
+ * The head block: <title>, description meta, canonical, og:title,
171
+ * og:description, og:url, og:type — in that order, LF-joined, all values
172
+ * escaped. NEVER emits charset/viewport (the layout writes those). A
173
+ * second call in this render emits nothing and records head.duplicate.
174
+ */
175
+ head(): Html;
176
+ /**
177
+ * The stylesheet tag for the manifest entry `name`
178
+ * (<link rel="stylesheet" href="…">). First call per name per render
179
+ * emits the tag, repeats emit nothing. The tag's kind follows the
180
+ * entry's extension. Unknown name: asset.unknown-entrypoint + abort.
181
+ */
182
+ stylesheet(name: string): Html;
183
+ /** Same as stylesheet() for scripts (<script defer src="…"></script>). */
184
+ script(name: string): Html;
185
+ /**
186
+ * Validate a URL against the policy, resolving relative refs against
187
+ * THIS page (site + route, prefix included). Returns the value unchanged
188
+ * when valid; records the policy diagnostic (page-attributed) and aborts
189
+ * the page's render when invalid.
190
+ */
191
+ url(value: string): string;
192
+ /**
193
+ * The public file's URL: site + "/" + segment-encoded normalized path. Literal
194
+ * traversal (`..`, leading "/", backslash, drive letter, NUL, empty) is
195
+ * rejected (public-asset.traversal) and aborts the page's render. The
196
+ * literal normalized path is recorded for the emitter's existence check.
197
+ */
198
+ publicAsset(path: string): string;
199
+ /**
200
+ * Read a text file under the config directory with the confinement
201
+ * contract (realpath must stay inside realpath(configDir); 10 MiB cap;
202
+ * strict UTF-8; the realpath is recorded as a render dependency).
203
+ * Failures record a readText.* diagnostic (page-attributed) and abort
204
+ * the page's render.
205
+ */
206
+ readText(path: string): Promise<string>;
207
+ }
208
+
209
+ /** A layout: a function of the render context. */
210
+ export type Layout = (ctx: LayoutContext) => Html | Promise<Html>;
211
+
212
+ // ---------------------------------------------------------------------------
213
+ // Results
214
+ // ---------------------------------------------------------------------------
215
+
216
+ /** One page's render result. `html` is null when the render was aborted. */
217
+ export interface PageRender {
218
+ /** The deep-frozen page view the layout saw. */
219
+ readonly page: FrozenPage;
220
+ /** The final fenced document, or null when the render was aborted. */
221
+ readonly html: string | null;
222
+ /** Every diagnostic recorded during this render, sorted. */
223
+ readonly diagnostics: Diagnostic[];
224
+ /** readText realpaths (posix, absolute), sorted and unique. */
225
+ readonly deps: string[];
226
+ /** publicAsset paths (posix, output-root-relative), sorted and unique. */
227
+ readonly publicAssets: string[];
228
+ /** The manifest names this page actually emitted tags for, sorted. */
229
+ readonly usedAssets: Readonly<{
230
+ readonly scripts: string[];
231
+ readonly styles: string[];
232
+ }>;
233
+ }
234
+
235
+ /** renderPage options (the shape chunk 7's emitter reuses). */
236
+ export interface RenderPageOptions {
237
+ /** The page with its final route, canonical URL, and resolved layout. */
238
+ readonly page: RoutedPage;
239
+ /** The site's base URL (prefix included, no trailing slash). */
240
+ readonly site: string;
241
+ readonly manifest: AssetManifest;
242
+ readonly layouts: Readonly<Record<string, LayoutFn>>;
243
+ /** The config directory; realpath'd to form the readText root. */
244
+ readonly configDir: string;
245
+ /**
246
+ * The public directory. renderPage itself does not touch it (it only
247
+ * normalizes and records publicAsset paths); the emitter (chunk 7)
248
+ * verifies each recorded path exists under it.
249
+ */
250
+ readonly publicDir?: string;
251
+ }
252
+
253
+ /** renderAll options (everything renderPage needs except the page). */
254
+ export interface RenderAllOptions {
255
+ readonly site: string;
256
+ readonly manifest: AssetManifest;
257
+ readonly layouts: Readonly<Record<string, LayoutFn>>;
258
+ readonly configDir: string;
259
+ readonly publicDir?: string;
260
+ }
261
+
262
+ /** Everything a render pass produced, plus the cross-page asset audit. */
263
+ export interface RenderAllResult {
264
+ /** One render per input page, in lexicographic route order. */
265
+ readonly pages: PageRender[];
266
+ /**
267
+ * asset.unused warnings: manifest names no page ever referenced (one per
268
+ * name, sorted). A warning, never an error (plan §5).
269
+ */
270
+ readonly unusedAssets: Diagnostic[];
271
+ }
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // The per-render sink
275
+ // ---------------------------------------------------------------------------
276
+
277
+ /**
278
+ * The render-scoped state object (plan §3): created fresh for every
279
+ * Layout(ctx) invocation, closed when the render finishes, referenced by no
280
+ * other render. Dedup is plain state on it; nothing here is module-level.
281
+ */
282
+ interface Sink {
283
+ closed: boolean;
284
+ page: FrozenPage;
285
+ siteUrl: string;
286
+ pageRoute: string;
287
+ manifest: AssetManifest;
288
+ diagnostics: Diagnostic[];
289
+ deps: Set<string>;
290
+ publicAssets: Set<string>;
291
+ usedScripts: Set<string>;
292
+ usedStyles: Set<string>;
293
+ /** name → the tag the first call emitted (dedup memory). */
294
+ assetTags: Map<string, Html>;
295
+ headEmitted: boolean;
296
+ }
297
+
298
+ function createSink(page: FrozenPage, siteUrl: string, manifest: AssetManifest): Sink {
299
+ return {
300
+ closed: false,
301
+ page,
302
+ siteUrl,
303
+ pageRoute: page.route,
304
+ manifest,
305
+ diagnostics: [],
306
+ deps: new Set(),
307
+ publicAssets: new Set(),
308
+ usedScripts: new Set(),
309
+ usedStyles: new Set(),
310
+ assetTags: new Map(),
311
+ headEmitted: false,
312
+ };
313
+ }
314
+
315
+ /**
316
+ * The abort marker helpers throw (a helper failure must end THIS page's
317
+ * render, not crash the pass). The diagnostic is already recorded on the
318
+ * sink; the marker only exists to unwind the layout call.
319
+ */
320
+ class RenderAbort extends Error {
321
+ readonly diagnostics: Diagnostic[];
322
+
323
+ constructor(diagnostics: Diagnostic[]) {
324
+ super("render aborted");
325
+ this.name = "RenderAbort";
326
+ this.diagnostics = diagnostics;
327
+ }
328
+ }
329
+
330
+ /** Record a diagnostic and abort the page's render (never returns). */
331
+ function abort(sink: Sink, diagnostic: Diagnostic): never {
332
+ sink.diagnostics.push(diagnostic);
333
+ throw new RenderAbort([diagnostic]);
334
+ }
335
+
336
+ /** A helper called after the render finished is a loud throw (plan §3). */
337
+ function requireOpen(sink: Sink): void {
338
+ if (!sink.closed) return;
339
+ throw new Error(
340
+ "layout context is closed: head()/stylesheet()/script()/url()/publicAsset()/" +
341
+ "readText() may only be called while the page is rendering — a captured " +
342
+ "LayoutContext is not valid after the render finished",
343
+ );
344
+ }
345
+
346
+ function emptyHtml(): Html {
347
+ return html``;
348
+ }
349
+
350
+ // ---------------------------------------------------------------------------
351
+ // The helpers
352
+ // ---------------------------------------------------------------------------
353
+
354
+ /**
355
+ * The per-render head block, EXACTLY (plan §3): <title>, description meta,
356
+ * canonical link, og:title, og:description, og:url, og:type=website — in
357
+ * that order, LF-joined, no trailing newline. Every value is interpolated
358
+ * through the html runtime, so it goes through the ONE escaper: a title
359
+ * with `"`, `<`, `>` or `&` is neutralized, and a newline inside a QUOTED
360
+ * attribute is legal HTML (kept as-is, cannot break the attribute).
361
+ * og:type is the only static value.
362
+ */
363
+ function head(sink: Sink): Html {
364
+ requireOpen(sink);
365
+ if (sink.headEmitted) {
366
+ sink.diagnostics.push({
367
+ code: "head.duplicate",
368
+ severity: "error",
369
+ sourcePath: sink.page.sourcePath,
370
+ message:
371
+ `head() was called a second time for page ${JSON.stringify(sink.page.sourcePath)}; ` +
372
+ "only the first call emits — v1 expects exactly one <title>, one description and one canonical per document",
373
+ });
374
+ return emptyHtml();
375
+ }
376
+ sink.headEmitted = true;
377
+ const { title, description, canonicalUrl } = sink.page;
378
+ return html`<title>${title}</title>
379
+ <meta name="description" content="${description}">
380
+ <link rel="canonical" href="${canonicalUrl}">
381
+ <meta property="og:title" content="${title}">
382
+ <meta property="og:description" content="${description}">
383
+ <meta property="og:url" content="${canonicalUrl}">
384
+ <meta property="og:type" content="website">`;
385
+ }
386
+
387
+ /**
388
+ * The shared-namespace asset tag (see the module header for the pinned
389
+ * decisions: one dedup namespace mirroring the config's, tag kind follows
390
+ * the manifest entry's extension, URLs absolute against the site).
391
+ */
392
+ function assetTag(sink: Sink, name: string): Html {
393
+ requireOpen(sink);
394
+ if (typeof name !== "string") {
395
+ abort(sink, {
396
+ code: "asset.unknown-entrypoint",
397
+ severity: "error",
398
+ sourcePath: sink.page.sourcePath,
399
+ message:
400
+ `script()/stylesheet() require a string asset name, ` +
401
+ `received ${name === null ? "null" : typeof name}`,
402
+ });
403
+ }
404
+ const cached = sink.assetTags.get(name);
405
+ if (cached !== undefined) return emptyHtml();
406
+ const lookup = manifestLookup(sink.manifest, name);
407
+ if (!lookup.found) {
408
+ abort(sink, { ...lookup.diagnostic, sourcePath: sink.page.sourcePath });
409
+ }
410
+ const file = lookup.entry.file;
411
+ const url = `${sink.siteUrl}/${file}`;
412
+ const isJs = file.endsWith(".js");
413
+ const tag = isJs
414
+ ? html`<script defer src="${url}"></script>`
415
+ : html`<link rel="stylesheet" href="${url}">`;
416
+ sink.assetTags.set(name, tag);
417
+ if (isJs) sink.usedScripts.add(name);
418
+ else sink.usedStyles.add(name);
419
+ return tag;
420
+ }
421
+
422
+ /**
423
+ * The URL policy under the ctx name (plan §1 url()). The base is the FULL
424
+ * site URL (path prefix included) — validateUrl resolves relative refs
425
+ * against it and re-checks the ORIGIN — so a prefixed site (GH Pages
426
+ * /docs/) resolves relative refs correctly; passing a bare origin would
427
+ * silently drop the prefix. On failure the policy diagnostic is re-stamped
428
+ * to the page and the page's render aborts.
429
+ */
430
+ function url(sink: Sink, value: string): string {
431
+ requireOpen(sink);
432
+ if (typeof value !== "string") {
433
+ abort(sink, {
434
+ code: "url.scheme",
435
+ severity: "error",
436
+ sourcePath: sink.page.sourcePath,
437
+ message: `url() requires a string, received ${value === null ? "null" : typeof value}`,
438
+ });
439
+ }
440
+ try {
441
+ return validateUrl(value, { siteUrl: sink.siteUrl, pageRoute: sink.pageRoute });
442
+ } catch (d) {
443
+ if (!isDiagnostic(d)) throw d;
444
+ abort(sink, { ...d, sourcePath: sink.page.sourcePath });
445
+ }
446
+ }
447
+
448
+ /**
449
+ * The public-file URL (see the module header for the pinned rules). The
450
+ * argument is a PATH — never percent-decoded — so traversal is judged on
451
+ * the literal text and rejected before any resolution.
452
+ */
453
+ // Function DECLARATION (not a const arrow) on purpose: TypeScript's
454
+ // control-flow analysis only treats a call to a never-returning function
455
+ // declaration as a terminator — a `const f = (): never => …` is not, which
456
+ // would make every `if (bad) fail(…)` below an unproven branch.
457
+ function publicAssetReject(sink: Sink, path: string, reason: string): never {
458
+ return abort(sink, {
459
+ code: "public-asset.traversal",
460
+ severity: "error",
461
+ sourcePath: sink.page.sourcePath,
462
+ message: `publicAsset(${JSON.stringify(String(path))}): ${reason}`,
463
+ });
464
+ }
465
+
466
+ function publicAsset(sink: Sink, path: string): string {
467
+ requireOpen(sink);
468
+ if (typeof path !== "string") {
469
+ publicAssetReject(sink, path, `must be a path string, received ${typeof path}`);
470
+ }
471
+ if (path === "") publicAssetReject(sink, path, "the path is empty");
472
+ if (path.includes("\0")) publicAssetReject(sink, path, "contains a NUL character");
473
+ if (path.includes("\\")) publicAssetReject(sink, path, "contains a backslash (paths are posix)");
474
+ if (/^[A-Za-z]:/.test(path)) publicAssetReject(sink, path, "is a Windows drive-letter path");
475
+ if (path.startsWith("/")) publicAssetReject(sink, path, "is absolute (a leading /)");
476
+ if (path.split("/").includes("..")) publicAssetReject(sink, path, "contains a `..` segment");
477
+ const normalized = posix.normalize(path);
478
+ // Backstop (unreachable after the checks above): the normalized path must
479
+ // be a plain relative path inside the public directory.
480
+ if (normalized === ".." || normalized.startsWith("../")) {
481
+ publicAssetReject(sink, path, "normalizes to a path outside the public directory");
482
+ }
483
+ sink.publicAssets.add(normalized);
484
+ return `${sink.siteUrl}/${normalized.split("/").map(encodeURIComponent).join("/")}`;
485
+ }
486
+
487
+ /** 10 MiB — the readText size cap (plan §1). A file of EXACTLY the cap is legal. */
488
+ const READ_TEXT_MAX_BYTES = 10 * 1024 * 1024;
489
+
490
+ /**
491
+ * The confinement contract (see the module header for the full story):
492
+ * reject before resolution (absolute, `..`, NUL, backslash, drive letter —
493
+ * all read-text.escape), resolve → REALPATH → containment (a symlink that
494
+ * leaves the root is read-text.escape; a missing file is read-text.failed —
495
+ * the path stayed inside, there is just nothing there), stat → isFile and
496
+ * size cap, read → strict UTF-8. The final realpath is recorded in the
497
+ * render's dependency set (chunk 8's dev invalidation consumes it).
498
+ */
499
+ // Function DECLARATION (not a const arrow) on purpose: TypeScript's
500
+ // control-flow analysis only treats a call to a never-returning function
501
+ // declaration as a terminator — a `const f = (): never => …` is not, which
502
+ // would make `let x; try { x = … } catch { fail(…); }` an "x may be
503
+ // unassigned" error (and, worse, paper over the never-guarantee).
504
+ function readTextFail(
505
+ sink: Sink,
506
+ path: string,
507
+ code: "read-text.escape" | "read-text.toobig" | "read-text.failed",
508
+ reason: string,
509
+ ): never {
510
+ return abort(sink, {
511
+ code,
512
+ severity: "error",
513
+ sourcePath: sink.page.sourcePath,
514
+ message: `readText(${JSON.stringify(String(path))}): ${reason}`,
515
+ });
516
+ }
517
+
518
+ async function readText(sink: Sink, root: string, path: string): Promise<string> {
519
+ requireOpen(sink);
520
+ if (typeof path !== "string") {
521
+ readTextFail(sink, path, "read-text.escape", `must be a path string, received ${typeof path}`);
522
+ }
523
+ if (path.includes("\0")) readTextFail(sink, path, "read-text.escape", "contains a NUL character");
524
+ if (path.includes("\\"))
525
+ readTextFail(sink, path, "read-text.escape", "contains a backslash (paths are posix)");
526
+ if (/^[A-Za-z]:/.test(path))
527
+ readTextFail(sink, path, "read-text.escape", "is a Windows drive-letter path");
528
+ if (path.startsWith("/")) {
529
+ readTextFail(
530
+ sink,
531
+ path,
532
+ "read-text.escape",
533
+ "is absolute (readText reads under the config directory only)",
534
+ );
535
+ }
536
+ if (path.split("/").includes(".."))
537
+ readTextFail(sink, path, "read-text.escape", "contains a `..` segment");
538
+
539
+ const target = filesystemPath.join(root, posix.normalize(path));
540
+ let resolved: string;
541
+ try {
542
+ // toPosix on BOTH sides: on Windows realpath returns backslashes, and the
543
+ // containment test below is a posix prefix compare (see renderPage's root).
544
+ resolved = toPosix(await realpath(target));
545
+ } catch (e) {
546
+ const errno = (e as NodeJS.ErrnoException).code;
547
+ readTextFail(
548
+ sink,
549
+ path,
550
+ "read-text.failed",
551
+ errno === "ENOENT" ? "no such file or directory" : `cannot resolve (${errno ?? String(e)})`,
552
+ );
553
+ }
554
+ // Containment: the FINAL realpath must stay inside the realpath'd root —
555
+ // a symlink (or any component) that resolves outside is an escape,
556
+ // because symlinks never extend a boundary (the package-wide rule).
557
+ if (resolved !== root && !resolved.startsWith(`${root}/`)) {
558
+ readTextFail(
559
+ sink,
560
+ path,
561
+ "read-text.escape",
562
+ `resolves to ${JSON.stringify(toPosix(resolved))}, which is outside the root ` +
563
+ `${JSON.stringify(toPosix(root))} (a symlink or path component leaves the boundary)`,
564
+ );
565
+ }
566
+ let st: Awaited<ReturnType<typeof stat>>;
567
+ try {
568
+ st = await stat(resolved);
569
+ } catch (e) {
570
+ const errno = (e as NodeJS.ErrnoException).code;
571
+ readTextFail(sink, path, "read-text.failed", `cannot stat (${errno ?? String(e)})`);
572
+ }
573
+ if (!st.isFile()) {
574
+ readTextFail(sink, path, "read-text.failed", "resolves to a directory, not a regular file");
575
+ }
576
+ if (st.size > READ_TEXT_MAX_BYTES) {
577
+ readTextFail(
578
+ sink,
579
+ path,
580
+ "read-text.toobig",
581
+ `${st.size} bytes exceeds the ${READ_TEXT_MAX_BYTES}-byte (10 MiB) cap`,
582
+ );
583
+ }
584
+ let bytes: Buffer;
585
+ try {
586
+ bytes = await readFile(resolved);
587
+ } catch (e) {
588
+ const errno = (e as NodeJS.ErrnoException).code;
589
+ readTextFail(sink, path, "read-text.failed", `cannot read (${errno ?? String(e)})`);
590
+ }
591
+ let text: string;
592
+ try {
593
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
594
+ } catch {
595
+ readTextFail(sink, path, "read-text.failed", "is not valid UTF-8");
596
+ }
597
+ sink.deps.add(toPosix(resolved));
598
+ return text;
599
+ }
600
+
601
+ // ---------------------------------------------------------------------------
602
+ // The frozen page view + the context
603
+ // ---------------------------------------------------------------------------
604
+
605
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
606
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
607
+ const proto = Object.getPrototypeOf(value);
608
+ return proto === Object.prototype || proto === null;
609
+ }
610
+
611
+ function freezeTree(value: unknown, seen: Set<object>): void {
612
+ if (value === null || typeof value !== "object") return;
613
+ if (seen.has(value)) return; // cycle: already frozen (or being frozen)
614
+ seen.add(value);
615
+ Object.freeze(value);
616
+ // Recurse only into plain containers; class instances (a Date in data, a
617
+ // custom object) are frozen but not entered — their internals are the
618
+ // author's. Html nodes ARE plain objects: their literal/values arrays get
619
+ // frozen too (the runtime only ever reads them — safe, idempotent).
620
+ if (Array.isArray(value)) {
621
+ for (const element of value) freezeTree(element, seen);
622
+ } else if (isPlainObject(value)) {
623
+ for (const element of Object.values(value)) freezeTree(element, seen);
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Build the deep-frozen page view (see the module header for the
629
+ * copy-containers/freeze-leaves strategy and why it matters).
630
+ */
631
+ function freezePageView(page: RoutedPage): FrozenPage {
632
+ const view: Record<string, unknown> = {
633
+ ...page,
634
+ headings: [...page.headings],
635
+ data: { ...page.data },
636
+ links: [...page.links],
637
+ warnings: [...page.warnings],
638
+ diagnostics: [...page.diagnostics],
639
+ };
640
+ freezeTree(view, new Set());
641
+ return view as FrozenPage;
642
+ }
643
+
644
+ function makeContext(sink: Sink, root: string): LayoutContext {
645
+ const ctx: LayoutContext = {
646
+ page: sink.page,
647
+ content: sink.page.body,
648
+ site: Object.freeze({ url: sink.siteUrl }),
649
+ head: () => head(sink),
650
+ stylesheet: (name: string) => assetTag(sink, name),
651
+ script: (name: string) => assetTag(sink, name),
652
+ url: (value: string) => url(sink, value),
653
+ publicAsset: (path: string) => publicAsset(sink, path),
654
+ readText: (path: string) => readText(sink, root, path),
655
+ };
656
+ return Object.freeze(ctx);
657
+ }
658
+
659
+ // ---------------------------------------------------------------------------
660
+ // Error shaping
661
+ // ---------------------------------------------------------------------------
662
+
663
+ function describeValue(value: unknown): string {
664
+ if (value === null) return "null";
665
+ const t = typeof value;
666
+ if (t === "string" || t === "number" || t === "boolean" || t === "bigint") {
667
+ return `a ${t} ${JSON.stringify(value)}`;
668
+ }
669
+ if (t === "symbol") return "a symbol";
670
+ if (t === "undefined") return "undefined";
671
+ if (t === "function") return "a function";
672
+ const name = (value as { constructor?: { name?: unknown } }).constructor?.name;
673
+ return typeof name === "string" && name !== "" ? `an object of type ${name}` : "an object";
674
+ }
675
+
676
+ /**
677
+ * The thenable probe (html.ts contract: detected WITHOUT letting a throwing
678
+ * .then getter escape — a getter failure means "cannot prove safe", which
679
+ * falls through to the bad-result check below, which names it honestly).
680
+ */
681
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
682
+ if (typeof value !== "object" && typeof value !== "function") return false;
683
+ if (value === null) return false;
684
+ try {
685
+ return typeof (value as { then?: unknown }).then === "function";
686
+ } catch {
687
+ return false;
688
+ }
689
+ }
690
+
691
+ /**
692
+ * render.threw with the error's message AND stack (the message carries both).
693
+ * `stage` is a complete subject phrase ("the layout", "the page freeze", …)
694
+ * — the template adds no article of its own.
695
+ */
696
+ function renderThrew(sourcePath: string, error: unknown, stage: string): Diagnostic {
697
+ const message = error instanceof Error ? error.message : String(error);
698
+ const stack = error instanceof Error ? error.stack : undefined;
699
+ return {
700
+ code: "render.threw",
701
+ severity: "error",
702
+ sourcePath,
703
+ message:
704
+ `${stage} for page ${JSON.stringify(sourcePath)} threw: ${message}` +
705
+ (stack !== undefined ? `\n${stack}` : ""),
706
+ };
707
+ }
708
+
709
+ /** render.bad-result naming what the layout actually returned. */
710
+ function badResult(sourcePath: string, result: unknown, wasPromise: boolean): Diagnostic {
711
+ return {
712
+ code: "render.bad-result",
713
+ severity: "error",
714
+ sourcePath,
715
+ message:
716
+ `the layout for page ${JSON.stringify(sourcePath)} ` +
717
+ (wasPromise ? "returned a Promise that resolved to " : "returned ") +
718
+ `${describeValue(result)}; a layout must return an Html ` +
719
+ `(or a Promise that resolves to an Html)`,
720
+ };
721
+ }
722
+
723
+ // ---------------------------------------------------------------------------
724
+ // The engine
725
+ // ---------------------------------------------------------------------------
726
+
727
+ function collect(sink: Sink, page: FrozenPage, html: string | null): PageRender {
728
+ return {
729
+ page,
730
+ html,
731
+ diagnostics: sortDiagnostics(sink.diagnostics),
732
+ deps: [...sink.deps].sort(compareStrings),
733
+ publicAssets: [...sink.publicAssets].sort(compareStrings),
734
+ usedAssets: {
735
+ scripts: [...sink.usedScripts].sort(compareStrings),
736
+ styles: [...sink.usedStyles].sort(compareStrings),
737
+ },
738
+ };
739
+ }
740
+
741
+ /**
742
+ * Render ONE page. Never throws (crust rule 1: a page failure is a located
743
+ * diagnostic on the result, and the build pass must continue); the sink is
744
+ * closed before the result returns, so a captured ctx cannot outlive the
745
+ * render.
746
+ */
747
+ export async function renderPage(opts: RenderPageOptions): Promise<PageRender> {
748
+ const page = opts.page;
749
+
750
+ let frozen: FrozenPage;
751
+ try {
752
+ frozen = freezePageView(page);
753
+ } catch (e) {
754
+ // A hand-crafted page with a throwing getter. Object.freeze never
755
+ // invokes accessors, so freezing the original in place is still safe.
756
+ const fallback = Object.freeze(page) as FrozenPage;
757
+ const sink = createSink(fallback, opts.site, opts.manifest);
758
+ sink.diagnostics.push(renderThrew(page.sourcePath, e, "the page freeze"));
759
+ sink.closed = true;
760
+ return collect(sink, fallback, null);
761
+ }
762
+
763
+ const sink = createSink(frozen, opts.site, opts.manifest);
764
+ let html: string | null = null;
765
+ try {
766
+ // Layout resolution. Chunk 4 (buildRouteTable) already validated the
767
+ // name; this double-check keeps renderPage total for hand-built inputs.
768
+ const layout = opts.layouts[page.layout];
769
+ if (layout === undefined || typeof layout !== "function") {
770
+ const available = Object.keys(opts.layouts).sort(compareStrings).join(", ");
771
+ sink.diagnostics.push({
772
+ code: "layout.unknown",
773
+ severity: "error",
774
+ sourcePath: page.sourcePath,
775
+ message:
776
+ layout === undefined
777
+ ? `layout "${page.layout}" for page ${page.sourcePath} is not a key of the layouts registry (available: ${available})`
778
+ : `layout "${page.layout}" for page ${page.sourcePath} is not a function`,
779
+ });
780
+ return collect(sink, frozen, null);
781
+ }
782
+
783
+ // The readText root: the REALPATH of the config directory (a symlinked
784
+ // config dir must not be able to extend the boundary later). Normalized to
785
+ // posix form: on Windows realpath hands back backslashes while every
786
+ // comparison and join below is posix (the plan's Windows row: internal
787
+ // paths are posix-normalized). A missing config dir is an engine-setup
788
+ // failure, named as such (the layout never ran, so "the layout" would be
789
+ // a false statement — crust rule 1).
790
+ let root: string;
791
+ try {
792
+ root = toPosix(await realpath(opts.configDir));
793
+ } catch (e) {
794
+ sink.diagnostics.push(
795
+ renderThrew(
796
+ page.sourcePath,
797
+ e,
798
+ `the readText root (the config directory realpath ${JSON.stringify(toPosix(opts.configDir))})`,
799
+ ),
800
+ );
801
+ return collect(sink, frozen, null);
802
+ }
803
+ const ctx = makeContext(sink, root);
804
+
805
+ // The registry type (LayoutFn: (...args: never[]) => unknown) is an
806
+ // erased-function placeholder that lets config.ts hold ANY function
807
+ // shape; having checked it is a function above, cast to Layout to
808
+ // call it with the render context.
809
+ const run: Layout = layout as unknown as Layout;
810
+ let result = run(ctx);
811
+ const wasPromise = isThenable(result);
812
+ if (wasPromise) result = await result;
813
+
814
+ if (!isHtml(result)) {
815
+ sink.diagnostics.push(badResult(page.sourcePath, result, wasPromise));
816
+ } else {
817
+ try {
818
+ // The fence runs per page, with the page as base (prefix included,
819
+ // so URL re-checks resolve like the author's url() calls do).
820
+ html = finalizeDocument(result, { siteUrl: opts.site, pageRoute: page.route });
821
+ } catch (e) {
822
+ if (e instanceof BuildError) {
823
+ // Fence violations: codes preserved, re-stamped to the page.
824
+ for (const d of e.diagnostics)
825
+ sink.diagnostics.push({ ...d, sourcePath: page.sourcePath });
826
+ } else if (isDiagnostic(e)) {
827
+ // A render.bad-value thrown by the html runtime mid-finalize.
828
+ sink.diagnostics.push({ ...e, sourcePath: page.sourcePath });
829
+ } else {
830
+ sink.diagnostics.push(renderThrew(page.sourcePath, e, "the render/fence stage"));
831
+ }
832
+ }
833
+ }
834
+ } catch (e) {
835
+ if (!(e instanceof RenderAbort)) {
836
+ if (isDiagnostic(e)) {
837
+ sink.diagnostics.push({ ...e, sourcePath: page.sourcePath });
838
+ } else {
839
+ sink.diagnostics.push(renderThrew(page.sourcePath, e, "the layout"));
840
+ }
841
+ }
842
+ // A RenderAbort's diagnostic is already on the sink.
843
+ } finally {
844
+ sink.closed = true;
845
+ }
846
+ return collect(sink, frozen, html);
847
+ }
848
+
849
+ /**
850
+ * Anything that carries per-page asset usage: a PageRender, or any later
851
+ * document the pipeline renders after the content pages (chunk 7's generated
852
+ * 404 page). The audit takes the LIST, not the render pass, so a caller can
853
+ * feed it exactly the set of documents that will actually be emitted.
854
+ */
855
+ export interface AssetUsage {
856
+ readonly usedAssets: Readonly<{
857
+ readonly scripts: readonly string[];
858
+ readonly styles: readonly string[];
859
+ }>;
860
+ }
861
+
862
+ /**
863
+ * The cross-page asset audit: every manifest name that NO rendered document
864
+ * ever passed to script()/stylesheet() becomes an `asset.unused` WARNING
865
+ * (plan §5: a warning, never an error), one per name, sorted.
866
+ *
867
+ * Exported separately from renderAll because the audit must run over EVERY
868
+ * emitted document: chunk 7 renders the generated 404 page after renderAll,
869
+ * and an asset referenced only there is not unused. Callers pass the full
870
+ * list (content pages + drafts excluded + the 404 render) — extra documents
871
+ * are simply more inputs to the union, which is the point.
872
+ *
873
+ * Note a page whose render ABORTED still counts as having referenced what it
874
+ * called before failing: an abort always carries an error diagnostic, so the
875
+ * build fails anyway and the audit never gets to decide anything about a
876
+ * build that is already dead.
877
+ */
878
+ export function collectUnusedAssets(
879
+ manifest: AssetManifest,
880
+ renders: readonly AssetUsage[],
881
+ ): Diagnostic[] {
882
+ const used = new Set<string>();
883
+ for (const r of renders) {
884
+ for (const n of r.usedAssets.scripts) used.add(n);
885
+ for (const n of r.usedAssets.styles) used.add(n);
886
+ }
887
+ const unusedAssets: Diagnostic[] = [];
888
+ for (const name of [...manifest.keys()].sort(compareStrings)) {
889
+ if (used.has(name)) continue;
890
+ unusedAssets.push({
891
+ code: "asset.unused",
892
+ severity: "warning",
893
+ sourcePath: "",
894
+ message:
895
+ `asset "${name}" is declared but referenced by no page ` +
896
+ "(never passed to script() or stylesheet())",
897
+ });
898
+ }
899
+ return unusedAssets;
900
+ }
901
+
902
+ /**
903
+ * Render EVERY page: sequentially, in lexicographic (code-unit) route
904
+ * order — the determinism contract (plan §4.6), re-sorted here regardless
905
+ * of input order so the pass can never depend on how pages arrived. Each
906
+ * page gets a fresh sink; module-level state inside a layout is the
907
+ * author's hazard (it is not isolated, and two pages sharing it see each
908
+ * other's writes). renderPage never throws; the guard below is the last
909
+ * line of the "never crash the render pass" contract (an engine bug must
910
+ * still surface as a page-attributed render.threw, not a rejected build).
911
+ *
912
+ * The result also carries the cross-page audit (collectUnusedAssets) over
913
+ * exactly the pages this pass rendered; a caller that renders more documents
914
+ * afterwards (chunk 7's 404 page) re-runs the audit over the full list.
915
+ */
916
+ export async function renderAll(
917
+ pages: readonly RoutedPage[],
918
+ opts: RenderAllOptions,
919
+ ): Promise<RenderAllResult> {
920
+ const ordered = [...pages].sort(
921
+ (a, b) => compareStrings(a.route, b.route) || compareStrings(a.sourcePath, b.sourcePath),
922
+ );
923
+ const rendered: PageRender[] = [];
924
+ for (const page of ordered) {
925
+ try {
926
+ rendered.push(await renderPage({ ...opts, page }));
927
+ } catch (e) {
928
+ rendered.push({
929
+ page: Object.freeze(page) as FrozenPage,
930
+ html: null,
931
+ diagnostics: [renderThrew(page.sourcePath, e, "the render engine")],
932
+ deps: [],
933
+ publicAssets: [],
934
+ usedAssets: { scripts: [], styles: [] },
935
+ });
936
+ }
937
+ }
938
+
939
+ return { pages: rendered, unusedAssets: collectUnusedAssets(opts.manifest, rendered) };
940
+ }