@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/docs/USAGE.md ADDED
@@ -0,0 +1,1128 @@
1
+ # @lariocpt/crust-site — reference
2
+
3
+ `@lariocpt/crust-site` is the crust site generator: a static-site compiler with a
4
+ fenced template API, strict content validation, and a publish contract that
5
+ never corrupts your last good build. It ships as a **plain npm package run
6
+ under Bun**. Bun-native and loaded crust also execute `crust site build|dev`;
7
+ compiled core/mongo retain their redirect. Loaded carries private Bun and the
8
+ site dependency tree in a directory, not a third compiled binary.
9
+
10
+ Native/loaded prefer the compatible installed site belonging to the config's
11
+ project/workspace, including supported hoisted installs. Declared but missing,
12
+ broken or incompatible project dependencies fail without bundled fallback.
13
+ Only loaded falls back when no project site is selected. Runtime commands
14
+ never install packages. Pin the local package for editor types and CI.
15
+ Engine, config and layouts must share one canonical site instance; browser
16
+ asset resolution is separate and project dependencies remain project-owned.
17
+
18
+ Everything on the public surface follows one contract (`contractVersion: 1`):
19
+ additive fields and enum widening are minor changes; renames, removals, and
20
+ narrowing are major; **diagnostic codes are never repurposed**.
21
+
22
+ ---
23
+
24
+ ## Install and requirements
25
+
26
+ - **Bun >= 1.4.** The package is TypeScript source executed by Bun directly
27
+ (`bunx @lariocpt/crust-site build`); there is no compiled artifact and no transpile
28
+ step. The asset pipeline is measured against Bun 1.4.4.
29
+ - **Windows is supported for this package** under plain `bun`/`bunx`. The
30
+ crust *binary* stays linux/darwin-only — see [Windows support](#windows-support).
31
+ - The site URL must be reachable as an absolute `http(s)` URL at build time
32
+ (it is only concatenated into canonical/og tags — nothing is fetched).
33
+
34
+ ```sh
35
+ bun add -d @lariocpt/crust-site # or: bunx @lariocpt/crust-site build (no install)
36
+ ```
37
+
38
+ Run it from the directory that holds `site.config.ts` (or pass the config
39
+ path explicitly):
40
+
41
+ ```sh
42
+ bunx @lariocpt/crust-site build [configFile] # render the site (default configFile: ./site.config.ts)
43
+ bunx @lariocpt/crust-site dev [configFile] # dev server, rebuilds on change
44
+ ```
45
+
46
+ ---
47
+
48
+ ## Quickstart
49
+
50
+ A complete site is one config file, a content directory, and (optionally)
51
+ script/style entrypoints and a public directory. This example is the fixture
52
+ at `tests/fixtures/docs-example/` in the package's repository — the docs gate
53
+ type-checks it and the test suite builds it end to end, so it is known to
54
+ work.
55
+
56
+ `site.config.ts`:
57
+
58
+ ```ts
59
+ import type { LayoutContext } from "@lariocpt/crust-site";
60
+ import { defineSite, html } from "@lariocpt/crust-site";
61
+
62
+ export default defineSite({
63
+ site: "https://example.dev",
64
+ lang: "en",
65
+ content: {
66
+ directory: "content",
67
+ defaultLayout: "base",
68
+ route: ({ relativePath }) => (relativePath === "index" ? "/" : `/${relativePath}`),
69
+ },
70
+ layouts: {
71
+ base: (ctx: LayoutContext) => html`<!doctype html>
72
+ <html lang="en">
73
+ <head>
74
+ <meta charset="utf-8" />
75
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
76
+ <link rel="icon" href="${ctx.publicAsset("favicon.svg")}" />
77
+ ${ctx.head()} ${ctx.stylesheet("site")} ${ctx.script("main")}
78
+ </head>
79
+ <body>
80
+ <main>${ctx.content}</main>
81
+ <footer><a href="${ctx.url("/")}">Home</a></footer>
82
+ </body>
83
+ </html>`,
84
+ },
85
+ assets: {
86
+ styles: { site: "assets/site.css" },
87
+ scripts: { main: "assets/main.ts" },
88
+ publicDirectory: "public",
89
+ },
90
+ output: { directory: "dist" },
91
+ robots: { indexable: true },
92
+ });
93
+ ```
94
+
95
+ Content — every `.md` file needs a `---` frontmatter block with at least a
96
+ `title`:
97
+
98
+ ```markdown
99
+ ---
100
+ title: Home
101
+ description: The home page.
102
+ ---
103
+
104
+ # Welcome
105
+
106
+ Start with the [getting-started guide](./guide/getting-started.md).
107
+ ```
108
+
109
+ Relative `.md` links resolve against the page's **route** (not the source
110
+ path) and are rewritten to the destination route with the site's path
111
+ prefix preserved; a `.md` link to a page
112
+ that does not exist fails the build with `link.broken`.
113
+
114
+ Then build:
115
+
116
+ ```sh
117
+ bunx @lariocpt/crust-site build
118
+ # crust-site: built 2 pages, 2 assets, 29 ms → /path/to/dist
119
+ ```
120
+
121
+ The output tree:
122
+
123
+ ```
124
+ dist/
125
+ ├── index.html # route /
126
+ ├── guide/getting-started.html # route /guide/getting-started
127
+ ├── 404.html # generated, see "The 404 page"
128
+ ├── sitemap.xml
129
+ ├── robots.txt
130
+ ├── favicon.svg # copied verbatim from public/
131
+ └── assets/
132
+ ├── main-8f1a92802d4c9533.js # name + sha256-16 of the final bytes
133
+ └── site-4302d8f61557770f.css
134
+ ```
135
+
136
+ The hashes are stable across machines and working directories (single-file
137
+ entrypoints — see “Assets”); this tree is a real run, and the build test
138
+ asserts the exact names.
139
+
140
+ The draft page (`content/drafts/wip.md`, `draft: true`) is **not** in the
141
+ output — production builds never render drafts. The dev server does, with a
142
+ banner.
143
+
144
+ ---
145
+
146
+ ## Configuration reference
147
+
148
+ `defineSite(config)` validates the whole config at definition time and
149
+ throws a `BuildError` carrying **every** problem found (never just the
150
+ first). Unknown keys at any level are errors, not ignored extras — a typo'd
151
+ key that silently does nothing is a false pass. Relative paths resolve
152
+ against the **config file's directory**, never the process cwd.
153
+
154
+ ```ts
155
+ // The smallest legal config: one layout, one content directory, one output.
156
+ const config = defineSite({
157
+ site: "https://example.dev",
158
+ content: { directory: "content", defaultLayout: "base" },
159
+ layouts: { base: () => html`<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>` },
160
+ output: { directory: "dist" },
161
+ });
162
+ ```
163
+
164
+ ### `site` — required
165
+
166
+ An absolute `http(s)` URL. It **may include a path prefix** (GitHub Pages
167
+ under `/docs`), and must **not** end in `/` — a trailing slash is an error,
168
+ not stripped. The value must already be in canonical form: anything the
169
+ WHATWG parser would silently normalize (padding, a dangling `?` or `#`, the
170
+ default port, an upper-case host, userinfo) is a `config.site` error,
171
+ because `canonicalUrl` is plain concatenation of this value.
172
+
173
+ `canonicalUrl = site + route` (the root route adds the single `/`):
174
+
175
+ ```ts
176
+ canonicalUrl("https://example.dev/docs", "/guide"); // "https://example.dev/docs/guide"
177
+ canonicalUrl("https://example.dev", "/"); // "https://example.dev/"
178
+ ```
179
+
180
+ ### `content` — required
181
+
182
+ | Key | Type | Default | Notes |
183
+ |---|---|---|---|
184
+ | `directory` | path string | — (required) | Relative to the config file; absolute allowed. |
185
+ | `include` | `string[]` | `["**/*.md"]` | Globs run with `cwd = content.directory`. |
186
+ | `exclude` | `string[]` | `[]` | Exclude **wins** over include. |
187
+ | `defaultLayout` | string | — (required) | Must be a key of `layouts`. |
188
+ | `route` | `(arg: { relativePath: string }) => string` | none | Maps a source file to a route. |
189
+ | `parseData` | `(value: unknown, ctx: { sourcePath: string }) => unknown` | none | Data-layer hook; may be async. |
190
+
191
+ Discovery is deterministic: lexicographic (code-unit) order, dotfiles
192
+ excluded unless the include pattern itself starts with `.`, symlinks never
193
+ followed, only `.md` files kept. `relativePath` is posix, relative to
194
+ `content.directory`, extension stripped, case preserved.
195
+
196
+ `route()` **must return an already-normalized route** — there is no
197
+ auto-normalization. A bad return (or a throw) is an error naming the page;
198
+ without `route()` and without frontmatter `route`, a page gets
199
+ `route.missing`.
200
+
201
+ ```ts
202
+ const content: SiteConfig["content"] = {
203
+ directory: "docs",
204
+ defaultLayout: "doc",
205
+ exclude: ["private/**"],
206
+ route: ({ relativePath }) => (relativePath === "index" ? "/" : `/docs/${relativePath}`),
207
+ };
208
+ ```
209
+
210
+ `parseData` receives the page's raw frontmatter `data` (or `{}`) and its
211
+ `sourcePath`; a returned Promise is awaited. It **must resolve to a plain
212
+ object** — a throw, a rejection, or a non-object is `frontmatter.data-invalid`
213
+ located at the `data` key. Without `parseData`, `page.data` is always `{}`
214
+ even when the frontmatter carried `data` — raw data is never passed through
215
+ unvalidated.
216
+
217
+ ```ts
218
+ const content: SiteConfig["content"] = {
219
+ directory: "content",
220
+ defaultLayout: "base",
221
+ parseData: (data) => {
222
+ if (typeof data === "object" && data !== null && "tags" in data) return data;
223
+ return {};
224
+ },
225
+ };
226
+ ```
227
+
228
+ ### `layouts` — required
229
+
230
+ A non-empty registry of layout functions (`name => (ctx) => Html`). A
231
+ non-function value, or an empty registry, is `config.layout-type`; a
232
+ `defaultLayout` (or frontmatter `layout`) naming a key that is not here is
233
+ the same code with the available keys listed.
234
+
235
+ ### `assets` — optional
236
+
237
+ | Key | Notes |
238
+ |---|---|
239
+ | `scripts` | `name → entrypoint path`. |
240
+ | `styles` | `name → entrypoint path`. |
241
+ | `publicDirectory` | Copied to the output root, unhashed. |
242
+
243
+ Names must match `/^[A-Za-z0-9_-]+$/` (`config.asset-name`) and **scripts
244
+ and styles share ONE namespace** — the same name in both maps is
245
+ `config.asset-name-clash`, because there is one manifest and one output
246
+ directory.
247
+
248
+ ### `output` — required
249
+
250
+ | Key | Default | Notes |
251
+ |---|---|---|
252
+ | `directory` | — (required) | Relative to the config file. |
253
+ | `trailingSlash` | `"never"` | v1 accepts only `"never"` (typed as an open union for future widening; any other value is a `config.type` error). |
254
+
255
+ The output directory must not overlap its own inputs
256
+ (`config.output-overlap`): it may not contain or be contained by
257
+ `content.directory` or `assets.publicDirectory`, it may not contain any
258
+ asset entrypoint, and it may not be the config directory itself. An output
259
+ *inside* the project directory (the common `dist/`) is explicitly allowed.
260
+
261
+ ### `sitemap`, `robots`, `dev`, `lang` — optional
262
+
263
+ | Key | Default | Notes |
264
+ |---|---|---|
265
+ | `sitemap` | `true` | Emit `sitemap.xml`. |
266
+ | `robots` | none | `{ indexable: boolean }`; absent means **no `robots.txt` at all**. |
267
+ | `dev.hostname` | `"localhost"` | Dev server bind host. |
268
+ | `dev.port` | ephemeral | Integer 1..65535 (`config.port` otherwise). |
269
+ | `lang` | `"en"` | BCP 47. Stored on the resolved config; the layout hand-writes the `<html lang>` attribute — v1 injects it nowhere. |
270
+
271
+ ### Paths and overlap, programmatically
272
+
273
+ `defineSite` stores raw paths; `resolveConfigPaths(site, configDir)` makes
274
+ them absolute against the config file's directory, and
275
+ `checkOutputOverlap(resolved)` enforces the overlap rules above. `build()`
276
+ runs both for you.
277
+
278
+ ```ts
279
+ const config = defineSite({
280
+ site: "https://example.dev",
281
+ content: { directory: "content", defaultLayout: "base" },
282
+ layouts: { base: () => html`` },
283
+ output: { directory: "dist" },
284
+ });
285
+ const resolved = resolveConfigPaths(config, "/home/me/site");
286
+ checkOutputOverlap(resolved); // throws BuildError with config.output-overlap diagnostics
287
+ ```
288
+
289
+ ---
290
+
291
+ ## Frontmatter
292
+
293
+ Every `.md` file starts with a `---` YAML block: the delimiter is `---` at
294
+ **column 0** (trailing space/tab allowed; `----` is not a delimiter),
295
+ closed by another column-0 `---`. A leading BOM is stripped and CRLF/CR are
296
+ normalized to LF before anything is counted. Parsing uses `yaml`
297
+ (eemeli) with a line counter, so **every error is located with line and
298
+ column in the full file's coordinates**.
299
+
300
+ Built-in keys — everything else is `frontmatter.unknown-key`:
301
+
302
+ | Key | Type | Notes |
303
+ |---|---|---|
304
+ | `title` | non-empty string | **Required.** Missing → `frontmatter.missing-title`. |
305
+ | `description` | non-empty string | Absent → derived from the first paragraph (see below). |
306
+ | `layout` | non-empty string | Must name a key of `layouts`. |
307
+ | `route` | normalized route | Validated at parse time; overrides `content.route`. |
308
+ | `draft` | boolean | Excluded from production builds. |
309
+ | `data` | plain YAML mapping | Reaches `page.data` only through `content.parseData`. |
310
+
311
+ Strictness — all of these are **errors**, collected into one `BuildError`:
312
+ a missing or unclosed block (`frontmatter.missing`), a block that parses but
313
+ is not a mapping (`frontmatter.not-mapping`), YAML syntax errors
314
+ (`frontmatter.parse-error`, all of them), duplicate keys
315
+ (`frontmatter.duplicate-key`, located), unknown keys, non-string keys, and
316
+ bad values (`frontmatter.bad-value`).
317
+
318
+ ```ts
319
+ const parsed = parseFrontmatter("---\ntitle: Hello\n---\n\n# Hello\n", "content/hello.md");
320
+ parsed.frontmatter.title; // "Hello"
321
+ parsed.body; // "\n# Hello\n"
322
+ parsed.bodyStartLine; // 4 — the body's first line, in full-file coordinates
323
+ ```
324
+
325
+ When `description` is absent it is derived from the first **top-level**
326
+ paragraph (whitespace collapsed, cut at 160 chars on a word boundary) and
327
+ the build reports `frontmatter.derived-description` as a **warning naming
328
+ the derived value**. If there is no text to derive from, the description
329
+ stays `""` with a `frontmatter.missing-description` warning — the build
330
+ never claims a derivation that did not happen.
331
+
332
+ ---
333
+
334
+ ## Templates: the `html` runtime
335
+
336
+ Layouts build documents with the `html` tagged template. A tagged template
337
+ cannot enforce rules by inspecting its literal (`html\`<scr${"i"}pt>\``
338
+ defeats any literal check), so the enforcement is a **value-range fence**:
339
+ every interpolated value's character range is recorded (recursively, through
340
+ arbitrary nesting), and a post-render pass over the assembled document
341
+ fails the build when a value range crosses a protected boundary.
342
+
343
+ ### Escaping
344
+
345
+ One escape function, applied to every interpolated value: `& < > " '` →
346
+ entities, with `&` replaced first so emitted entities are never
347
+ double-escaped. A value can never contribute a raw structural character —
348
+ which also kills entity smuggling (`java&#10;script:`) and neutralizes
349
+ RCDATA elements like `<title>`/`<textarea>`.
350
+
351
+ ```ts
352
+ const doc = html`<p>${'a < b & "c"'}</p>`; // <p>a &lt; b &amp; &quot;c&quot;</p>
353
+ ```
354
+
355
+ ### What may be interpolated (`HtmlValue`)
356
+
357
+ `string`, finite `number` (`0` renders `"0"`, never falsy-dropped),
358
+ `false`/`null`/`undefined` (render nothing), `Html`, and arrays of those
359
+ (flattened, joined with no separator). **Everything else throws a
360
+ `render.bad-value` diagnostic before any `toString`/`valueOf` runs**:
361
+ `true`, `NaN`, ±`Infinity`, Promises and other thenables (values are never
362
+ awaited), `Symbol`, `bigint`, functions, class instances, plain objects.
363
+ A value that is its own ancestor (a cycle) is rejected; a shared array used
364
+ twice is legal and renders live. Nesting is capped at depth 64.
365
+
366
+ ```ts
367
+ // The TYPE system already excludes `true` (and objects, and thenables) from
368
+ // HtmlValue; the runtime check is what catches values that arrive untyped —
369
+ // from JS callers or `unknown` frontmatter data:
370
+ try {
371
+ const value: unknown = true;
372
+ finalizeDocument(html`<p>${value as unknown as HtmlValue}</p>`, { siteUrl: "https://example.dev" });
373
+ } catch (e) {
374
+ // BuildError carrying the render.bad-value diagnostic
375
+ }
376
+ ```
377
+
378
+ ### What the fence enforces
379
+
380
+ These are build errors, checked against the final document and the tracked
381
+ ranges (all linear-time scans):
382
+
383
+ | Code | Rule |
384
+ |---|---|
385
+ | `fence.script-body` / `fence.style-body` | A tracked value inside a `<script>`/`<style>` body. Inline script and style are banned outright — all JS/CSS ships as hashed assets. |
386
+ | `fence.comment-value` | A tracked value inside a `<!-- … -->` comment. |
387
+ | `fence.dynamic-tag-name` / `fence.dynamic-attr-name` | An interpolated value in a tag-name or attribute-name position. |
388
+ | `fence.event-handler` | Any `on*` attribute, however it got there. |
389
+ | `fence.unquoted-attribute` | A present attribute value without quotes. |
390
+ | `fence.unterminated` | An opening attribute quote never closed. |
391
+ | `fence.url-attribute` | A URL-bearing attribute (`href src action formaction poster cite background data`) whose tracked value fails the URL policy — so forgetting `url()` is not a hole. |
392
+ | `fence.ping-attr` / `fence.srcdoc-attr` | `ping` and `srcdoc` are banned outright. |
393
+
394
+ Documented **convention only** (a build-time fence cannot enforce them):
395
+ SVG foreign-content semantics, deploy-time response headers, and
396
+ supply-chain trust of what you import.
397
+
398
+ ### The `url()` policy
399
+
400
+ `url(value, opts)` (alias `validateUrl`) is the one policy for anything
401
+ landing in a URL position; `ctx.url(value)` is the same policy with `opts`
402
+ bound to the page. It returns the value unchanged when valid and throws a
403
+ located diagnostic when not. Allowed schemes: `http`, `https`, `mailto`,
404
+ `tel`, `sms`. Rejected before `new URL()` even runs — because a parser that
405
+ "fixes" input is a fence that misses attacks:
406
+
407
+ - control characters and spaces (`url.control-char`),
408
+ - `" ' \` \` and backslash (`url.bad-char`),
409
+ - `&#` and named entity references like `&Tab;` (`url.entity-escape`) —
410
+ browsers decode them before the URL parser runs,
411
+ - protocol-relative `//host/…` (`url.protocol-relative`) — v1 rejects it
412
+ outright rather than guessing the scheme,
413
+ - `http:`/`https:` without the `//` authority form, userinfo, an empty
414
+ host, or any other scheme (`url.scheme`, `url.no-host`, `url.userinfo`).
415
+
416
+ Pure fragments (`#top`) are valid; relative refs must resolve on the site's
417
+ origin. Absolute cross-origin `http(s)` URLs are accepted — external links
418
+ are legitimate.
419
+
420
+ ```ts
421
+ const opts = { siteUrl: "https://example.dev", pageRoute: "/guide" };
422
+ url("https://example.dev/docs/intro", opts); // returned unchanged
423
+ url("mailto:hello@example.dev", opts);
424
+ try {
425
+ url("java\tscript:alert(1)", opts); // url.control-char
426
+ } catch (diagnostic) {
427
+ // a Diagnostic object: { code, message, severity }
428
+ }
429
+ ```
430
+
431
+ The fence re-runs this same policy over every URL-bearing attribute in the
432
+ final output, so a hand-written `href=${value}` that skipped `url()` is
433
+ still caught.
434
+
435
+ ---
436
+
437
+ ## Layouts and the render context
438
+
439
+ A layout is `(ctx: LayoutContext) => Html | Promise<Html>`. The context is
440
+ bound to exactly one render: its helpers close over a fresh per-render
441
+ state object, so dedup is plain per-render state and concurrent renders are
442
+ isolated. Calling a helper **after the render finished** (a captured `ctx`
443
+ used late) throws.
444
+
445
+ | Member | Exact semantics |
446
+ |---|---|
447
+ | `ctx.page` | The page, **deep-frozen** — every mutation throws in strict mode. Carries `route`, `canonicalUrl`, `title`, `description`, `headings`, `data`, `draft`, `links`, `warnings`, `diagnostics`, `sourcePath`, `relativePath`. |
448
+ | `ctx.content` | The page's rendered markdown body (`Html`). |
449
+ | `ctx.site` | `{ url }` — the site base URL, path prefix included. |
450
+ | `ctx.head()` | The head block, see below. |
451
+ | `ctx.stylesheet(name)` / `ctx.script(name)` | The asset tag for a manifest name, see below. |
452
+ | `ctx.url(value)` | The URL policy with this page as base (relative refs resolve against `site + route`, exactly the page's canonical URL). Invalid → diagnostic + this page's render aborts. |
453
+ | `ctx.publicAsset(path)` | The public file's URL, see below. |
454
+ | `ctx.readText(path)` | Confined text read under the config directory, see below. |
455
+
456
+ ```ts
457
+ const page: Layout = (ctx) => html`<!doctype html>
458
+ <html lang="en">
459
+ <head>
460
+ <meta charset="utf-8" />
461
+ ${ctx.head()} ${ctx.stylesheet("site")}
462
+ </head>
463
+ <body class="${ctx.page.draft ? "draft" : ""}">${ctx.content}</body>
464
+ </html>`;
465
+ ```
466
+
467
+ ### `head()`
468
+
469
+ Emits **exactly seven tags**, LF-joined: `<title>`, the description meta,
470
+ the canonical link, `og:title`, `og:description`, `og:url`,
471
+ `og:type=website` (the `og:` values use `property=`, not `name=`). Every
472
+ value goes through the one escaper. It **never emits `charset` or
473
+ `viewport`** — the layout hand-writes those; a later validation step errors
474
+ when the emitted document does not carry exactly one `<meta charset>`, one
475
+ `<title>`, and one `rel="canonical"` (see `metadata.*`). There is no length
476
+ cap: title and description are emitted verbatim (the plan floated
477
+ 128/200-char caps; shipping one would silently rewrite metadata, which this
478
+ package refuses to do).
479
+
480
+ A **second** `head()` call in the same render emits nothing and records
481
+ `head.duplicate` — a build-error diagnostic, not a throw; the page still
482
+ renders.
483
+
484
+ ### `stylesheet(name)` and `script(name)`
485
+
486
+ Both take a **manifest map key** (never a path). The first call for a name
487
+ in a render returns the full tag; repeats return an empty `Html`
488
+ (dedup-per-render, one shared namespace for both helpers). The tag's kind
489
+ follows the **manifest entry's extension** — `.js` → `<script defer src>`,
490
+ `.css` → `<link rel="stylesheet" href>` — never which helper you called:
491
+ the manifest is the source of truth for what the asset's bytes are, so a
492
+ mismatched call still emits the tag the bytes require. Asset URLs are
493
+ absolute against the site (path prefix included). An unknown name records
494
+ `asset.unknown-entrypoint` and aborts that page's render.
495
+
496
+ ### `publicAsset(path)`
497
+
498
+ The argument is a **file path, not a URL** — never percent-decoded, so the
499
+ only traversal vectors are literal ones. Empty, NUL, backslash, a drive
500
+ letter, a leading `/`, or any `..` segment is rejected
501
+ (`public-asset.traversal`) before any filesystem access. It returns
502
+ `site + "/" + encodedPath`, where each segment of the normalized path is
503
+ percent-encoded (slashes remain separators). For example, `logo#dark.svg`
504
+ becomes `logo%23dark.svg`, and a literal `%` becomes `%25`. The literal
505
+ normalized path is recorded for the emitter's existence check and copied
506
+ unchanged: a recorded path that is not a readable file under
507
+ `assets.publicDirectory` is `public-asset.missing` (and no configured
508
+ public directory makes every recorded path missing).
509
+
510
+ ```ts
511
+ const head: Layout = (ctx) => html`<link rel="icon" href="${ctx.publicAsset("favicon.svg")}">`;
512
+ ```
513
+
514
+ ### `readText(path)`
515
+
516
+ The confinement contract: the root is the **realpath of the config
517
+ directory**; the final realpath must stay inside it (a symlink never
518
+ extends a boundary). Literal escapes (absolute, `..`, NUL, backslash, drive
519
+ letter) are rejected before resolution; a path that stays inside but is
520
+ missing, a directory, unreadable, or not valid UTF-8 is `read-text.failed`;
521
+ a size cap of 10 MiB is checked via `stat` **before** the bytes are read
522
+ (`read-text.toobig`; exactly the cap is legal). The final realpath is
523
+ recorded as a dependency of the page's render.
524
+
525
+ ```ts
526
+ const withNotice: Layout = async (ctx) => {
527
+ const notice = await ctx.readText("partials/notice.md");
528
+ return html`<footer>${notice}</footer>`;
529
+ };
530
+ ```
531
+
532
+ ### Failure semantics
533
+
534
+ A helper failure records a page-attributed diagnostic and aborts **that
535
+ page's render only** (its html is null); the pass continues with the other
536
+ pages. A layout that throws → `render.threw` (message and stack); a layout
537
+ returning a non-Html → `render.bad-result`; a fence violation → the fence
538
+ diagnostics re-stamped to the page. The engine never throws out of a render
539
+ pass.
540
+
541
+ ---
542
+
543
+ ## Routing and URLs
544
+
545
+ Routes are file-write inputs, so validation is strict and total:
546
+ `normalizeRoute` **never auto-normalizes** — a route that is not already in
547
+ normal form is an error naming the offender (a generator that quietly
548
+ rewrites routes produces two URLs for one page).
549
+
550
+ Normal form: starts with `/`; each segment is percent-decoded then
551
+ NFKC-normalized (so `%2e%2e` and look-alike characters become the traversal
552
+ they hide behind), re-encoded with the WHATWG path set, joined with single
553
+ slashes, no trailing slash, root is `/`, case preserved. Rejected outright:
554
+ non-strings (`route.invalid`), a query or fragment (`route.query-fragment`),
555
+ `.`/`..` segments (`route.traversal`), and — all `route.shape` — control or
556
+ invisible format characters, backslashes, drive letters, empty segments,
557
+ invalid percent escapes, Windows reserved device names, and anything whose
558
+ normalized form differs from the input.
559
+
560
+ ```ts
561
+ normalizeRoute("/guide/intro", { sourcePath: "content/guide/intro.md" }); // unchanged
562
+ isNormalizedRoute("/a/"); // false — a trailing slash is not a route
563
+ routeToFile("/"); // "index.html"
564
+ routeToFile("/guide/intro"); // "guide/intro.html"
565
+ ```
566
+
567
+ ### The URL ↔ file table (normative)
568
+
569
+ One resolver is shared by the emitter, the sitemap, `ctx.url()`, the link
570
+ validator, and the dev server, so they cannot drift:
571
+
572
+ | URL | File | Notes |
573
+ |---|---|---|
574
+ | `/` | `index.html` | |
575
+ | `/a` | `a.html` | |
576
+ | `/a/b` | `a/b.html` | |
577
+ | `/a/` | — | **404 in v1** (an empty segment is not a route). |
578
+ | `/a.html` | `a.html` | The **lenient form**, answered by the dev server: it serves the same file `/a` serves — unless a page owns the route `/a.html` itself (an exact route beats the lenient form; that page's file is `a.html.html`). The canonical URL stays extensionless. |
579
+ | unmatched | `404.html` | Served with real HTTP 404, never a 200 with a 404 body. |
580
+
581
+ ### Collisions
582
+
583
+ `findRouteCollisions` runs two passes over the route table: exact duplicates
584
+ (`route.duplicate`, naming **all** colliding source files) and a
585
+ case-insensitive pass (`route.case-collision`) that always runs — the same
586
+ config must not build on Linux and half-emit on a case-insensitive
587
+ filesystem. A draft and a page on the same route collide in every mode.
588
+
589
+ The build also checks generated **output paths**, case-insensitively,
590
+ including engine-owned files. Distinct routes such as `/` and `/index`
591
+ both map to `index.html` and fail with `output.collision`; an authored
592
+ `/404` likewise conflicts with the generated 404 page. A failed build
593
+ leaves the previous published output untouched.
594
+
595
+ ```ts
596
+ const diags = findRouteCollisions([
597
+ { route: "/a", sourcePath: "a.md" },
598
+ { route: "/A", sourcePath: "A.md" },
599
+ ]);
600
+ // one route.case-collision diagnostic naming both files
601
+ ```
602
+
603
+ ---
604
+
605
+ ## Markdown
606
+
607
+ The v1 feature list is exact — everything else renders as plain text:
608
+
609
+ - ATX headings (`#` … `######`) with generated `id` slugs, paragraphs,
610
+ bullet and ordered lists, **GFM task-list items** (`- [ ]` / `- [x]`,
611
+ emitted as a disabled checkbox in a `<label>` — GitHub's shape),
612
+ - fenced code blocks (```` ``` ```` and `~~~`, with a `language-` class) and
613
+ indented code blocks, inline code,
614
+ - links, autolinks (`<https://…>`), images, emphasis/strong, GFM
615
+ strikethrough (`~~x~~`), GFM tables, blockquotes, thematic breaks.
616
+
617
+ **Not enabled:** raw HTML (`html: false` — raw HTML in the source is
618
+ **escaped to inert text**, never emitted), linkify, typographer/smart
619
+ quotes, syntax highlighting, footnotes, definition lists.
620
+
621
+ ### Heading ids
622
+
623
+ GitHub-style slugs: lowercase → NFKD with combining marks stripped
624
+ (`"Ünïcödé"` → `unicode`) → whitespace runs to `-` → keep unicode letters,
625
+ digits, `-`, `_` → collapse repeated `-` → trim `-`. An empty slug (an
626
+ emoji-only heading) becomes `section`. Collisions get `-1`/`-2`/… suffixes
627
+ in document order, incremented past ids already taken (`Foo`, `foo-1`,
628
+ `Foo` → `foo`, `foo-1`, `foo-2`). `page.headings[].id` is the final id.
629
+
630
+ ### Internal links and fragments
631
+
632
+ Relative `.md` links resolve against the page's **route**, are stripped of
633
+ `.md`, and are rewritten to the destination route when the destination is a
634
+ page, preserving the configured site's path prefix: with
635
+ `site: "https://example.dev/docs"`, a link to route `/guide` emits
636
+ `href="/docs/guide"`. Fragment suffixes are preserved; validation still
637
+ uses the site-relative route `/guide`. Fragment-only links, external URLs,
638
+ and root-relative `.md` links are not rewritten.
639
+ If the configured pathname starts with `//`, rewritten links and images
640
+ use the full absolute site URL instead, preserving the configured origin
641
+ rather than emitting a protocol-relative destination.
642
+ A destination that is not in the route table is `link.broken`; a
643
+ destination that is a draft is `link.draft`. Both are **errors in a
644
+ production build and warnings in dev** (the dev server renders drafts, so
645
+ the link really resolves there). A link carrying `#fragment` requires the
646
+ destination page's **final emitted HTML** to contain that id
647
+ (`link.missing-fragment`, always an error).
648
+
649
+ Fragment checking scans emitted bytes for **quoted id attributes only**
650
+ (`id="x"` or `id='x'`), and HTML comments are stripped first. The
651
+ quoted-only rule is deliberate: an unquoted `id=x` inside a code sample
652
+ contains no character that escaping would touch, so it survives to the
653
+ output byte-identical to real markup — broadening the scan to unquoted
654
+ values would let code samples false-satisfy fragment checks. A quoted
655
+ `id="x"` can never survive escaping (`&quot;`), so a quoted match is always
656
+ a real attribute. Layouts must quote their ids; a hand-written unquoted id
657
+ is not recognized.
658
+
659
+ ---
660
+
661
+ ## Assets
662
+
663
+ Each declared script/style entrypoint is bundled with **one `Bun.build`
664
+ call per entrypoint into a fresh temp directory** (measured: Bun's `outdir`
665
+ is not cleared between builds, so a naive shared outdir leaks stale files).
666
+ The bundler's output name is never used: the SSG computes
667
+ **sha256 over the final emitted bytes and takes the first 16 hex chars**,
668
+ emitting `assets/<name>-<hash>.<ext>`. Only `.js` and `.css` outputs are
669
+ accepted.
670
+
671
+ An entrypoint that emits **more than one file** — real code-splitting, an
672
+ imported asset (`import logo from "./x.svg"`), JS importing CSS — is
673
+ refused with `asset.entrypoint-chunked`: v1 emits exactly one hashed file
674
+ per declared entrypoint. A bundler failure is `asset.bundle-failed` with
675
+ the bundler's own messages folded in, located when the bundler located
676
+ them. An asset that no page ever passed to `script()`/`stylesheet()` is an
677
+ `asset.unused` **warning**.
678
+
679
+ Two more measured behaviors of the bundler, both pinned by tests:
680
+
681
+ - **Bun prefixes each output with a one-line banner naming the bundled
682
+ file relative to the process cwd** (a `../`-prefixed path when the file
683
+ is outside the cwd — never an absolute path). For a single-file
684
+ entrypoint the banner sits at the head of the file (after a preserved
685
+ hashbang and one blank line, when the entry starts with `#!`) and names
686
+ the entry itself, so the SSG strips it before hashing. A multi-file
687
+ bundle (the entry imports other files, a CSS `@import`s, an npm package
688
+ import) emits one banner per bundled file, and the leading one names a
689
+ dependency, not the entry — the SSG strips those as well: every input
690
+ file of the build is enumerated from Bun's build metafile, whose keys
691
+ carry the same cwd-relative paths as the banners (measured
692
+ byte-identical), so the exact banner line is computable for every
693
+ bundled file. The strip removes any output line byte-identical to a
694
+ computed banner — but only after the file's FIRST line has matched one
695
+ of them, so a bannerless or changed-shape output is never touched: a
696
+ future Bun that changes the banner shape degrades that asset to the old
697
+ cwd-sensitive hash instead of pattern-stripping and corrupting code.
698
+ Result: **every asset, single- or multi-file, is byte-identical — hashes
699
+ included — across builds from any working directory**; no pinning of the
700
+ build's cwd is needed. One honest caveat, pinned by tests: the transpile
701
+ drops every source comment, so a bare comment-shaped line in the output
702
+ can only be a banner or template-literal content — if the latter is
703
+ byte-identical to one of the computed banners, the exact match strips it
704
+ with them (one line of string data changes; the backtick boundaries
705
+ survive, so the code still parses).
706
+ - **The transpile drops every source comment** (leading, mid-file,
707
+ trailing; `//` and `/* */`, CSS included) before the bundle is emitted:
708
+ shipped assets contain no source comments. String data is otherwise
709
+ untouched — a template-literal line that merely looks like a comment
710
+ survives verbatim (the one exception: a line byte-identical to a
711
+ computed banner of a multi-file bundle, per the previous bullet). An
712
+ entry that is only comments or type declarations therefore emits zero
713
+ bytes (and no banner).
714
+
715
+ ```ts
716
+ // Declared once in the config; referenced from layouts by map key.
717
+ // First call in a render emits the tag; the repeat emits "" (dedup per render):
718
+ const head: Layout = (ctx) =>
719
+ html`<head>${ctx.stylesheet("site")}${ctx.stylesheet("site")}</head>`;
720
+ ```
721
+
722
+ ### The public directory
723
+
724
+ `assets.publicDirectory` is copied to the output root **byte-for-byte,
725
+ unhashed** — public files get **no cache-busting** (that is the deal: put a
726
+ fingerprint in the file name yourself if you need one). A configured-but-
727
+ missing directory is `asset.public-missing`; a symlink inside it is
728
+ `asset.public-symlink` (never copied, never silently skipped). A public
729
+ file that would clobber a generated file — exactly, case-only, or inside
730
+ the reserved `assets/` prefix — is `output.collision`.
731
+
732
+ ---
733
+
734
+ ## Output and publish
735
+
736
+ A build writes into a **staging directory that is a sibling of the output**
737
+ (same filesystem — never `/tmp`, because a cross-device rename is `EXDEV`)
738
+ and publishes with two renames: `out → .crust-out-old-…`, then
739
+ `staging → out`. On `EPERM`/`EXDEV` (Windows locked files, cross-device)
740
+ each rename falls back to a recursive copy. **Any failure after the output
741
+ was moved aside restores the previous output** and rethrows — a failed
742
+ build leaves the previous output exactly as it was, and a failed build
743
+ never publishes: every stage collects diagnostics, staging is deleted, and
744
+ the run rejects with a `BuildError` carrying all of them.
745
+
746
+ A build **killed between the two renames** loses nothing: the next build's
747
+ startup sweep restores the orphaned `out-old` tree to the output path
748
+ (crash recovery), and dead processes' staging/lock litter is reclaimed.
749
+
750
+ Concurrent builds of the same output are refused with **`build.busy`**
751
+ (naming the live holder's pid) via a per-output lock file — a second build
752
+ interleaving its renames with the first's is a measured false-pass race.
753
+ Dead holders' locks are reclaimed automatically, so a killed build never
754
+ blocks the output forever.
755
+
756
+ ---
757
+
758
+ ## sitemap.xml and robots.txt
759
+
760
+ The sitemap has one `<url><loc>` per non-draft page (the generated 404 is
761
+ excluded), in lexicographic URL order, and **no `<lastmod>`** — a timestamp
762
+ would make byte-identical rebuilds impossible:
763
+
764
+ ```xml
765
+ <?xml version="1.0" encoding="UTF-8"?>
766
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
767
+ <url><loc>https://example.dev/</loc></url>
768
+ <url><loc>https://example.dev/guide/getting-started</loc></url>
769
+ </urlset>
770
+ ```
771
+
772
+ The `robots.txt` bodies are pinned byte-for-byte. With
773
+ `robots: { indexable: true }` (and the sitemap on):
774
+
775
+ ```
776
+ User-agent: *
777
+ Allow: /
778
+ Sitemap: https://example.dev/sitemap.xml
779
+ ```
780
+
781
+ With `robots: { indexable: false }`:
782
+
783
+ ```
784
+ User-agent: *
785
+ Disallow: /
786
+ ```
787
+
788
+ (no `Sitemap:` line — but the sitemap **file** is still emitted when
789
+ `sitemap: true`; it is a link-checker input for `crust verify-web-links`,
790
+ not just a crawler hint). No `robots` config → no `robots.txt` at all.
791
+
792
+ ---
793
+
794
+ ## The 404 page
795
+
796
+ Every build emits a generated `404.html`, rendered through
797
+ `content.defaultLayout` like any page, with fixed `title: "Not found"`,
798
+ `sourcePath: "<generated>"`, and `route: "/404"`. It is excluded from the
799
+ sitemap and is **not a link target** — a link to `/404` is `link.broken` —
800
+ while its own links are validated like any page's. The dev server serves it
801
+ with a real HTTP 404. There is no config knob in v1 (`output.notFound` is a
802
+ documented v1.1 candidate).
803
+
804
+ ---
805
+
806
+ ## Diagnostics
807
+
808
+ Every problem the package reports is a `Diagnostic`:
809
+
810
+ ```ts
811
+ const d: Diagnostic = {
812
+ code: "link.broken",
813
+ message: 'internal link on line 7 of "content/index.md" points at "/gone"',
814
+ severity: "error",
815
+ sourcePath: "content/index.md", // always posix
816
+ line: 7, // 1-based, in the named file's coordinates
817
+ };
818
+ ```
819
+
820
+ A failed build rejects with a `BuildError` carrying **all** collected
821
+ diagnostics, sorted by `sourcePath`, then `line`, then `code` (code-unit
822
+ order — locale collation would make output machine-dependent). The CLI
823
+ formats each as `severity[code]: message` plus a ` --> path:line:col` line,
824
+ on stderr, with ANSI only when stderr is a TTY.
825
+
826
+ Severity rules that vary by mode: **`link.broken` and `link.draft` are
827
+ errors in a production build and warnings in dev** (the dev server serves
828
+ drafts and shows the rest of the site). `asset.unused`,
829
+ `frontmatter.derived-description`, `frontmatter.missing-description`, and
830
+ `content.no-pages` are warnings everywhere else. Everything else is an
831
+ error in every mode.
832
+
833
+ The full code vocabulary (codes are never repurposed or removed):
834
+
835
+ | Code | Severity | Meaning |
836
+ |---|---|---|
837
+ | `config.unknown-key` | error | A config key that is not in the schema, at any level. |
838
+ | `config.site` | error | `site` is not a canonical absolute http(s) URL (trailing slash, query/fragment, userinfo, non-canonical form). |
839
+ | `config.layout-type` | error | A layout value is not a function, the registry is empty, or `defaultLayout` names no layout. |
840
+ | `config.asset-name-clash` | error | The same asset name is declared in both `assets.scripts` and `assets.styles`. |
841
+ | `config.asset-name` | error | An asset name does not match `/^[A-Za-z0-9_-]+$/`. |
842
+ | `config.output-overlap` | error | The output directory overlaps an input root (content, public dir, entrypoints, or the config dir itself). |
843
+ | `config.port` | error | `dev.port` is not an integer in 1..65535. |
844
+ | `config.load` | error | The config file could not be imported, or its default export is not a `defineSite()` result. |
845
+ | `config.type` | error | A known config key has the wrong type/shape (including `output.trailingSlash` ≠ `"never"`). |
846
+ | `route.invalid` | error | A route is not a string, or `content.route` threw / returned a non-string. |
847
+ | `route.query-fragment` | error | A route contains `?` or `#`. |
848
+ | `route.traversal` | error | A route contains a `.` or `..` segment (raw or hidden by encoding). |
849
+ | `route.shape` | error | A route is not in normalized form (control/format chars, backslash, drive letter, empty segment, bad escape, Windows reserved name, or any needed normalization). |
850
+ | `route.case-collision` | error | Two routes differ only by case — they collide on case-insensitive filesystems. |
851
+ | `route.duplicate` | error | The same route is produced by several files; the message names all of them. |
852
+ | `frontmatter.missing` | error | No column-0 `---` delimiter at the top, or the block is never closed. |
853
+ | `frontmatter.not-mapping` | error | The frontmatter parses but is not a YAML mapping. |
854
+ | `frontmatter.duplicate-key` | error | A frontmatter key appears twice (located). |
855
+ | `frontmatter.unknown-key` | error | A frontmatter key outside the built-ins (or a non-string key). |
856
+ | `frontmatter.missing-title` | error | The required `title` key is absent. |
857
+ | `frontmatter.bad-value` | error | A frontmatter key has the wrong value type/shape. |
858
+ | `frontmatter.parse-error` | error | The block is delimited but is not parseable YAML (all syntax errors reported). |
859
+ | `frontmatter.derived-description` | warning | `description` was absent and derived from the first paragraph; the message carries the derived value. |
860
+ | `frontmatter.missing-description` | warning | `description` absent and there was no text to derive from; it stays `""`. |
861
+ | `content.no-pages` | warning | The content directory produced zero non-draft pages (a production build would emit only the 404). |
862
+ | `frontmatter.data-invalid` | error | `content.parseData` threw, rejected, or returned a non-plain-object. |
863
+ | `route.missing` | error | Neither frontmatter `route` nor `content.route` produced a route for the page. |
864
+ | `layout.unknown` | error | A page's layout names a key that is not in the layouts registry. |
865
+ | `link.invalid` | error | A markdown link/image destination failed the URL policy (the attribute is stripped, so the output stays inert). |
866
+ | `markdown.parse-error` | error | The markdown renderer itself threw (otherwise it treats everything as text). |
867
+ | `link.broken` | error in build / warning in dev | An internal link's destination is not a page of the site (including a link to the generated `/404`). |
868
+ | `link.draft` | error in build / warning in dev | An internal link points at a draft page, which production builds do not render. |
869
+ | `link.missing-fragment` | error | A `#fragment` link whose destination's emitted HTML has no such quoted id. |
870
+ | `metadata.charset-missing` | error | The emitted document has no `<meta charset>` (the layout must hand-write it). |
871
+ | `metadata.charset-duplicate` | error | More than one `<meta charset>`. |
872
+ | `metadata.title-missing` | error | No `<title>` — the layout never called `head()`. |
873
+ | `metadata.title-duplicate` | error | More than one `<title>` (`<svg><title>` icon labels do not count). |
874
+ | `metadata.canonical-duplicate` | error | More than one `rel="canonical"`. |
875
+ | `metadata.head-missing` | error | No `rel="canonical"` — `head()` (the only canonical producer) was never called. |
876
+ | `render.bad-value` | error | An interpolated template value has no safe rendering (thrown before any `toString`). |
877
+ | `render.bad-result` | error | A layout returned (or resolved to) something that is not an `Html`. |
878
+ | `render.threw` | error | The layout (or the render/fence stage) threw; the message carries the error message and stack. |
879
+ | `head.duplicate` | error | `head()` called a second time in one render (the second call emits nothing). |
880
+ | `public-asset.traversal` | error | `publicAsset()` got a path that is empty, absolute, contains `..`, a backslash, a drive letter, or NUL. |
881
+ | `public-asset.missing` | error | A recorded `publicAsset()` path is not a readable file under the public directory. |
882
+ | `read-text.escape` | error | `readText()` resolved (literally or via a symlink) outside the config directory. |
883
+ | `read-text.toobig` | error | A `readText()` file exceeds the 10 MiB cap (checked before reading). |
884
+ | `read-text.failed` | error | A `readText()` path inside the root is missing, a directory, unreadable, or not valid UTF-8. |
885
+ | `fence.script-body` | error | A tracked value inside a `<script>` body. |
886
+ | `fence.style-body` | error | A tracked value inside a `<style>` body. |
887
+ | `fence.comment-value` | error | A tracked value inside an HTML comment. |
888
+ | `fence.dynamic-tag-name` | error | An interpolated value in a tag-name position. |
889
+ | `fence.dynamic-attr-name` | error | An interpolated value in an attribute-name position. |
890
+ | `fence.event-handler` | error | An `on*` event-handler attribute in the output. |
891
+ | `fence.unquoted-attribute` | error | An attribute value without quotes in the output. |
892
+ | `fence.unterminated` | error | An attribute quote opened and never closed. |
893
+ | `fence.url-attribute` | error | A URL-bearing attribute whose tracked value fails the URL policy. |
894
+ | `fence.ping-attr` | error | A `ping` attribute (banned outright). |
895
+ | `fence.srcdoc-attr` | error | A `srcdoc` attribute (banned outright). |
896
+ | `asset.entrypoint-chunked` | error | An entrypoint emitted more than one file (code-splitting / imported assets are not supported in v1). |
897
+ | `asset.bundle-failed` | error | `Bun.build` failed (or emitted nothing usable); the bundler's messages are folded in. |
898
+ | `asset.public-missing` | error | `assets.publicDirectory` is configured but absent or not a directory. |
899
+ | `asset.public-symlink` | error | A symlink inside the public directory (never copied, never silently skipped). |
900
+ | `asset.unknown-entrypoint` | error | `script()`/`stylesheet()` named a manifest key that was never declared. |
901
+ | `asset.unused` | warning | A declared asset that no rendered page ever referenced. |
902
+ | `output.collision` | error | Generated output paths collide (including engine-owned files, exact or case-only), or a public file would overwrite a generated file (exact, case-only, inside the reserved `assets/` prefix, or case-only against another public file). |
903
+ | `content.read-failed` | error | A discovered `.md` file could not be read at parse time. |
904
+ | `content.parse-failed` | error | A non-read failure while parsing a page (an engine bug, labeled honestly). |
905
+ | `output.escape` | error | A resolved write path left the staging directory (defense in depth — an internal-bug tripwire). |
906
+ | `build.busy` | error | Another live build holds the lock for this output. |
907
+ | `dev.port-in-use` | error | The configured dev port is already bound (v1 does not auto-increment). |
908
+ | `url.control-char` | error | A URL contains a control character or space. |
909
+ | `url.bad-char` | error | A URL contains `"`, `'`, a backtick, or a backslash. |
910
+ | `url.entity-escape` | error | A URL contains `&#` or a named entity reference (browsers decode it before the URL parser runs). |
911
+ | `url.protocol-relative` | error | A protocol-relative `//host/…` URL (rejected outright in v1). |
912
+ | `url.scheme` | error | A URL is unparseable or uses a scheme outside `http https mailto tel sms`. |
913
+ | `url.no-host` | error | An `http(s)` URL with an empty host. |
914
+ | `url.userinfo` | error | An `http(s)` URL carrying `user:pass@`. |
915
+
916
+ ---
917
+
918
+ ## CLI
919
+
920
+ ```
921
+ crust-site — the crust site generator (run under Bun)
922
+ usage:
923
+ crust-site build [configFile] render the site into output.directory
924
+ crust-site dev [configFile] start the dev server (rebuilds on change)
925
+ crust-site --help show this help
926
+
927
+ configFile defaults to ./site.config.ts
928
+ exit codes: 0 ok/help, 1 runtime failure, 2 argument error
929
+ ```
930
+
931
+ - **`build`** prints warnings (if any) as formatted diagnostics on stderr,
932
+ then exactly one summary line on stdout
933
+ (`crust-site: built N pages, M assets, T ms → <dir>`), and exits 0. A
934
+ failed build prints **every** collected diagnostic on stderr and exits 1 —
935
+ stdout carries no diagnostics, ever.
936
+ - **`dev`** runs a thin supervisor: it spawns a worker child and restarts
937
+ it when a **code or config change** lands (a fresh process is the only
938
+ way to re-import transitively imported code). A worker death for any
939
+ other reason (initial build failure, port in use, a crash) ends the
940
+ wrapper with that code — a failing build never respawns in a loop.
941
+ Ctrl-C stops the server and exits 130 (SIGTERM → 143).
942
+ - Argument errors (unknown subcommand, a second positional, a flag-shaped
943
+ argument) exit 2 with the usage; `--help`/`-h` exits 0.
944
+
945
+ The crust binary's `site` builtin is only a redirect stub pointing at this
946
+ package (exit 1, never a silent 0, never `sh`'s 127).
947
+
948
+ ---
949
+
950
+ ## Dev server contract
951
+
952
+ `bunx @lariocpt/crust-site dev` serves the site from a **dev staging tree** and
953
+ **never writes to `output.directory`** — the output is only ever written by
954
+ a production build's publish swap.
955
+
956
+ - **Drafts are rendered** in dev, each with a fixed DRAFT banner prepended
957
+ to its body, and `link.draft`/`link.broken` are **warnings** (the links
958
+ really resolve here).
959
+ - **No HMR, ever.** A content change triggers a debounced (~100 ms) full
960
+ in-process rebuild into a fresh staging tree; the serve root is swapped
961
+ only on success, so a failed rebuild prints its diagnostics while the
962
+ **last complete build keeps serving** — a half tree is never served. The
963
+ dev server injects no live-reload client: the browser picks the new tree
964
+ up on a full reload. (v1 rebuilds the whole site in-process; the per-page
965
+ `readText` dependency index is collected but no page-level skipping is
966
+ claimed.)
967
+ - A **code or config change** (anything under the config directory that is
968
+ not content) restarts the dev worker (CLI) or prints a restart hint
969
+ (library use) — never a partial in-process reload.
970
+ - **Headers:** HTML and public-directory files are `no-store`; hashed
971
+ `assets/<name>-<hash>.<ext>` files are `public, max-age=31536000,
972
+ immutable` (the hash is the version).
973
+ - **Watcher:** off Windows, `fs.watch` (recursive) is primary with a
974
+ polling fallback; **on Windows polling is the primary path** (500 ms,
975
+ `fs.watch` is unreliable there). Both backends diff against one shared
976
+ (mtime, size) baseline taken before the initial build, so a watch replay
977
+ of the pre-watch state never fires a spurious rebuild while an edit made
978
+ even during the initial build is caught. The package's own staging/lock
979
+ traffic is never treated as a change.
980
+ - **Port:** `dev.port` (or an ephemeral port when unset). A bound port is
981
+ an error (`dev.port-in-use`) — v1 never auto-increments, because a
982
+ silently different port serves the site where you are not looking.
983
+ - URL resolution is the shared table above, including `/a/` → 404 and the
984
+ lenient `/a.html` form.
985
+ - A configured site prefix such as `/docs` is also served locally:
986
+ `/docs` and `/docs/` serve the home page, and `/docs/guide` serves route
987
+ `/guide`. The prefix is stripped once at a complete path boundary;
988
+ `/docs-extra/guide` does not match it. Root-relative preview URLs remain
989
+ available, and prefixed asset/public-file requests use the same resolver.
990
+
991
+ ---
992
+
993
+ ## Determinism contract
994
+
995
+ A rebuild with unchanged inputs is **byte-identical**:
996
+
997
+ - lexicographic **code-unit** ordering everywhere (never locale collation —
998
+ two machines must not order the same strings differently),
999
+ - pages render sequentially in route order,
1000
+ - no timestamps in any emitted byte (no sitemap `<lastmod>`),
1001
+ - LF-only output; CRLF/CR input is normalized and a leading BOM stripped,
1002
+ - diagnostics are sorted by sourcePath, line, code,
1003
+ - no cwd-sensitivity in any emitted byte: the per-file path banners Bun
1004
+ prepends to bundled asset files embed cwd-relative paths, and the SSG
1005
+ strips every one of them before hashing — single-file and multi-file
1006
+ bundles alike (see “Assets”) — so a rebuild is byte-identical from any
1007
+ working directory. The one residual is a future Bun that changes the
1008
+ banner shape: the strip is an exact match, so it then leaves the bytes
1009
+ untouched, and that asset's hash can become cwd-sensitive again rather
1010
+ than risk a corrupted strip.
1011
+
1012
+ ---
1013
+
1014
+ ## Windows support
1015
+
1016
+ Windows support means **this package under `bun`/`bunx`**. The prebuilt
1017
+ crust binaries stay linux/darwin-only; the `site` builtin in the binary is
1018
+ only a redirect. The package's CI runs its suite on `windows-latest` (the
1019
+ crust release CI only executes linux-x64 — this package does not inherit
1020
+ that blind spot).
1021
+
1022
+ | Area | What the package does |
1023
+ |---|---|
1024
+ | Publish | Copy fallback is mandatory on Windows (locked files → `EPERM`): retry-with-copy, restore-on-failure. |
1025
+ | Case-insensitive FS | The duplicate-route pass runs a case-insensitive pass on top of the exact one, on every platform, and names which route is which. |
1026
+ | Reserved names | `CON`/`NUL`/`PRN`/`AUX`/`COM1-9`/`LPT1-9` and trailing dots/spaces are rejected at route validation (`route.shape`) on every platform, so one config behaves identically everywhere. The dev server rejects them as request paths only on win32, where they are devices; off Windows they are ordinary file names. |
1027
+ | Paths | Internal paths are posix-normalized; `sourcePath` in diagnostics is always posix. |
1028
+ | Determinism | CRLF normalized on input; LF-only output. |
1029
+ | Watcher | Polling is the **primary** path on Windows. |
1030
+ | `readText` | realpath-based containment works on both platforms (junctions included). |
1031
+ | Terminal | Diagnostics degrade gracefully without ANSI (color only when the stream is a TTY). |
1032
+
1033
+ ---
1034
+
1035
+ ## Programmatic API
1036
+
1037
+ ```ts
1038
+ const result = await build({ configFile: "./site.config.ts" });
1039
+ result.contractVersion; // 1
1040
+ result.outputDirectory; // absolute
1041
+ result.pages; // [{ route, sourcePath, file }] — content pages by route; the generated 404 is NOT here
1042
+ result.assets; // { name: "assets/<name>-<hash>.<ext>" }
1043
+ result.durationMs;
1044
+ result.warnings; // every warning-severity diagnostic, sorted
1045
+ ```
1046
+
1047
+ `build()` rejects with a `BuildError` carrying every collected diagnostic
1048
+ when anything failed; the previous output is untouched and staging is
1049
+ deleted.
1050
+
1051
+ ```ts
1052
+ try {
1053
+ await build({ configFile: "./site.config.ts" });
1054
+ } catch (e) {
1055
+ if (e instanceof BuildError) {
1056
+ for (const d of e.diagnostics) console.error(`${d.severity}[${d.code}]: ${d.message}`);
1057
+ } else {
1058
+ throw e;
1059
+ }
1060
+ }
1061
+ ```
1062
+
1063
+ The remaining value exports (`normalizeRoute`, `routeToFile`,
1064
+ `canonicalUrl`, `findRouteCollisions`, `isNormalizedRoute`,
1065
+ `parseFrontmatter`, `html`, `finalizeDocument`, `url`/`validateUrl`,
1066
+ `defineSite`, `resolveConfigPaths`, `checkOutputOverlap`, `BuildError`,
1067
+ `DiagnosticCodes`, `sortDiagnostics`, `contractVersion`) are the same
1068
+ contracts documented above. `renderPage`/`renderAll` are exported for the
1069
+ package's own pipeline wiring — site authors write layouts, they never call
1070
+ the engine (advanced consumers may drive the render engine directly; every
1071
+ type they need is in the table below).
1072
+
1073
+ The exported types, by family (37 in total — the full type surface; nothing
1074
+ else is exported as a type):
1075
+
1076
+ | Family | Types |
1077
+ |---|---|
1078
+ | Build contract | `BuildOptions`, `BuildPage`, `BuildResult` |
1079
+ | Diagnostics | `Diagnostic`, `DiagnosticCode`, `Severity` |
1080
+ | `html` runtime | `Html`, `HtmlValue` |
1081
+ | Render engine | `AssetUsage`, `DeepReadonly<T>`, `FrozenPage`, `Layout`, `LayoutContext`, `PageRender`, `RenderAllOptions`, `RenderAllResult`, `RenderPageOptions` |
1082
+ | Config, content and routes | `AssetsConfig`, `ContentConfig`, `DevConfig`, `FrontmatterResult`, `Heading`, `InternalLink`, `LayoutFn`, `OutputConfig`, `Page`, `PageFrontmatter`, `ResolvedSite`, `RobotsConfig`, `RouteEntry`, `RouteResolution`, `RouteResolver`, `Site`, `SiteConfig`, `TrailingSlash` |
1083
+ | URL policy | `UrlAttribute`, `UrlPolicyOptions` |
1084
+
1085
+ The same list, exactly as a user's file would import it (the docs gate
1086
+ type-checks this fence, so a name removed or renamed upstream fails CI):
1087
+
1088
+ ```ts
1089
+ import type {
1090
+ AssetUsage,
1091
+ AssetsConfig,
1092
+ BuildOptions,
1093
+ BuildPage,
1094
+ BuildResult,
1095
+ ContentConfig,
1096
+ DeepReadonly,
1097
+ DevConfig,
1098
+ Diagnostic,
1099
+ DiagnosticCode,
1100
+ FrontmatterResult,
1101
+ FrozenPage,
1102
+ Heading,
1103
+ Html,
1104
+ HtmlValue,
1105
+ InternalLink,
1106
+ Layout,
1107
+ LayoutContext,
1108
+ LayoutFn,
1109
+ OutputConfig,
1110
+ Page,
1111
+ PageFrontmatter,
1112
+ PageRender,
1113
+ RenderAllOptions,
1114
+ RenderAllResult,
1115
+ RenderPageOptions,
1116
+ ResolvedSite,
1117
+ RobotsConfig,
1118
+ RouteEntry,
1119
+ RouteResolution,
1120
+ RouteResolver,
1121
+ Site,
1122
+ SiteConfig,
1123
+ Severity,
1124
+ TrailingSlash,
1125
+ UrlAttribute,
1126
+ UrlPolicyOptions,
1127
+ } from "@lariocpt/crust-site";
1128
+ ```