@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/LICENSE +21 -0
- package/README.md +99 -2
- package/docs/USAGE.md +1128 -0
- package/package.json +33 -4
- package/src/assets.ts +875 -0
- package/src/build-lock.ts +214 -0
- package/src/build.ts +755 -0
- package/src/cli.ts +269 -0
- package/src/config.ts +538 -0
- package/src/content.ts +267 -0
- package/src/dev.ts +821 -0
- package/src/diagnostics.ts +382 -0
- package/src/emit.ts +260 -0
- package/src/fence.ts +593 -0
- package/src/frontmatter.ts +240 -0
- package/src/fs-path.ts +54 -0
- package/src/html.ts +400 -0
- package/src/index.ts +128 -0
- package/src/markdown.ts +444 -0
- package/src/pages.ts +169 -0
- package/src/publication.ts +245 -0
- package/src/render.ts +940 -0
- package/src/routes.ts +363 -0
- package/src/types.ts +250 -0
- package/src/url.ts +273 -0
- package/src/validate.ts +367 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// @lariocpt/crust-site — the crust site generator.
|
|
2
|
+
//
|
|
3
|
+
// The public API (plan: ~/.opencode/plan/crust-site-v1.md):
|
|
4
|
+
//
|
|
5
|
+
// defineSite / resolveConfigPaths / checkOutputOverlap
|
|
6
|
+
// — the config contract (site URL, content, assets, output)
|
|
7
|
+
// normalizeRoute / routeToFile / canonicalUrl / findRouteCollisions
|
|
8
|
+
// — the route table: strict normalization, the URL↔file map,
|
|
9
|
+
// duplicate + case-insensitive collision passes
|
|
10
|
+
// parseFrontmatter — the .md frontmatter contract, with diagnostics located
|
|
11
|
+
// in full-file coordinates
|
|
12
|
+
// html — the fenced template runtime (value-range fence + escaping)
|
|
13
|
+
// Layout/LayoutContext — the layout render engine's types (per-render head
|
|
14
|
+
// sink, deep-frozen page); renderPage/renderAll are
|
|
15
|
+
// exported as documented pipeline wiring (USAGE.md,
|
|
16
|
+
// "Programmatic API") for users who drive the render engine
|
|
17
|
+
// directly — build()/dev import ./render themselves, not
|
|
18
|
+
// through this entry — NOT an author-facing API: authors
|
|
19
|
+
// write layouts, they never call the engine
|
|
20
|
+
// build — the SSG pipeline (Bun.build per entrypoint, render, emit,
|
|
21
|
+
// publish with the rename/copy contract)
|
|
22
|
+
//
|
|
23
|
+
// The kernel here is pure logic: no filesystem, no rendering, no bundling.
|
|
24
|
+
// It deliberately imports NOTHING third-party except `yaml` (located
|
|
25
|
+
// frontmatter positions) and `markdown-it` (raw HTML disabled, the content
|
|
26
|
+
// pipeline in markdown.ts/pages.ts/content.ts); the renderer arrives with
|
|
27
|
+
// the render chunk. The content pipeline's types (Page, Heading,
|
|
28
|
+
// InternalLink, RouteResolver) are public; its functions are internal wiring
|
|
29
|
+
// until build() (chunk 6/8) exposes the pipeline as a whole.
|
|
30
|
+
//
|
|
31
|
+
// Packaging: this ships as a PLAIN npm package run under Bun
|
|
32
|
+
// (`bunx @lariocpt/crust-site build`), not as a compiled binary. A compiled Bun binary
|
|
33
|
+
// cannot resolve bare npm specifiers from files OUTSIDE its own bundle
|
|
34
|
+
// (measured 2026-11-12, Bun 1.4.3/1.4.4 — crust AGENTS.md), and a site's
|
|
35
|
+
// `site.config.ts` and layouts are imported from disk at run time. The crust
|
|
36
|
+
// binary therefore carries only a redirect stub named `site`
|
|
37
|
+
// (crust: src/builtinFns/site.ts) that points back here.
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The version of the BuildResult/diagnostic contract (v1 = 1).
|
|
41
|
+
*
|
|
42
|
+
* Versioning rules (plan, "Locked decisions" 4): additive fields and enum
|
|
43
|
+
* widening are minor; renames/removals/narrowing are major; diagnostic codes
|
|
44
|
+
* are never repurposed; narrow enums are typed as documented-open unions.
|
|
45
|
+
*/
|
|
46
|
+
export type { BuildOptions, BuildPage, BuildResult } from "./build";
|
|
47
|
+
export { build } from "./build";
|
|
48
|
+
export const contractVersion = 1;
|
|
49
|
+
|
|
50
|
+
export { checkOutputOverlap, defineSite, resolveConfigPaths } from "./config";
|
|
51
|
+
export type { Diagnostic, DiagnosticCode, Severity } from "./diagnostics";
|
|
52
|
+
export { BuildError, DiagnosticCodes, sortDiagnostics } from "./diagnostics";
|
|
53
|
+
export { parseFrontmatter } from "./frontmatter";
|
|
54
|
+
export type { Html, HtmlValue } from "./html";
|
|
55
|
+
|
|
56
|
+
// The fenced template runtime (plan §1). Public surface:
|
|
57
|
+
//
|
|
58
|
+
// html — the tagged template. Values are escaped through ONE
|
|
59
|
+
// escaper and their character ranges are tracked;
|
|
60
|
+
// finalizeDocument runs the fence over the result.
|
|
61
|
+
// Html / HtmlValue — the opaque value type and what may be interpolated.
|
|
62
|
+
// finalizeDocument — render + fence in one; a violation throws a BuildError
|
|
63
|
+
// carrying ALL fence diagnostics. The renderer (render
|
|
64
|
+
// chunk) calls it per page.
|
|
65
|
+
// url — the URL policy under its public name. It IS
|
|
66
|
+
// validateUrl: one function, two names, so the plan's
|
|
67
|
+
// `url()` reads naturally at the call site while the
|
|
68
|
+
// explicit name stays available for search and for the
|
|
69
|
+
// fence's cross-references. `ctx.url()` (render chunk)
|
|
70
|
+
// wraps exactly this.
|
|
71
|
+
//
|
|
72
|
+
// NOT public: trustedHtml, renderToString, escapeHtml, isHtml (the brand
|
|
73
|
+
// guard the render engine uses internally), the fence's scanner (fence.ts),
|
|
74
|
+
// isDiagnostic (the registry-membership guard — internal modules and tests
|
|
75
|
+
// import it from ./diagnostics) and collectUnusedAssets (the cross-page
|
|
76
|
+
// asset audit — the build pipeline runs it from ./render) — those are
|
|
77
|
+
// internal wiring, not a contract for site authors. They stay OUT of this
|
|
78
|
+
// file on purpose (exported from their own module for internal use / tests
|
|
79
|
+
// only, never part of the author-facing surface).
|
|
80
|
+
export { finalizeDocument, html } from "./html";
|
|
81
|
+
// The layout render engine (plan §3). The TYPES are part of the public
|
|
82
|
+
// contract (build()'s BuildResult references PageRender; a user's layout is
|
|
83
|
+
// a Layout). renderPage/renderAll are exported as the documented "pipeline
|
|
84
|
+
// wiring" (USAGE.md, "Programmatic API") for consumers who drive the engine
|
|
85
|
+
// directly — build()/dev do NOT import them through this entry, they import
|
|
86
|
+
// ./render — and they are NOT advertised to layout authors: site authors
|
|
87
|
+
// write layouts and never call the engine.
|
|
88
|
+
export type {
|
|
89
|
+
AssetUsage,
|
|
90
|
+
DeepReadonly,
|
|
91
|
+
FrozenPage,
|
|
92
|
+
Layout,
|
|
93
|
+
LayoutContext,
|
|
94
|
+
PageRender,
|
|
95
|
+
RenderAllOptions,
|
|
96
|
+
RenderAllResult,
|
|
97
|
+
RenderPageOptions,
|
|
98
|
+
} from "./render";
|
|
99
|
+
export { renderAll, renderPage } from "./render";
|
|
100
|
+
export {
|
|
101
|
+
canonicalUrl,
|
|
102
|
+
findRouteCollisions,
|
|
103
|
+
isNormalizedRoute,
|
|
104
|
+
normalizeRoute,
|
|
105
|
+
routeToFile,
|
|
106
|
+
} from "./routes";
|
|
107
|
+
export type {
|
|
108
|
+
AssetsConfig,
|
|
109
|
+
ContentConfig,
|
|
110
|
+
DevConfig,
|
|
111
|
+
FrontmatterResult,
|
|
112
|
+
Heading,
|
|
113
|
+
InternalLink,
|
|
114
|
+
LayoutFn,
|
|
115
|
+
OutputConfig,
|
|
116
|
+
Page,
|
|
117
|
+
PageFrontmatter,
|
|
118
|
+
ResolvedSite,
|
|
119
|
+
RobotsConfig,
|
|
120
|
+
RouteEntry,
|
|
121
|
+
RouteResolution,
|
|
122
|
+
RouteResolver,
|
|
123
|
+
Site,
|
|
124
|
+
SiteConfig,
|
|
125
|
+
TrailingSlash,
|
|
126
|
+
} from "./types";
|
|
127
|
+
export type { UrlAttribute, UrlPolicyOptions } from "./url";
|
|
128
|
+
export { validateUrl, validateUrl as url } from "./url";
|
package/src/markdown.ts
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
// The markdown pipeline (plan §2 content contract, §4 steps 1-2).
|
|
2
|
+
//
|
|
3
|
+
// v1 feature list — EXACT (everything else renders as plain text):
|
|
4
|
+
// ATX headings (# .. ######) with generated id slugs, paragraphs, bullet
|
|
5
|
+
// and ordered lists, GFM task-list items (`- [ ]` / `- [x]`, hand-rolled —
|
|
6
|
+
// see taskItems), fenced code blocks (``` and ~~~, `language-` class) and
|
|
7
|
+
// indented code blocks, inline code, links, autolinks, images,
|
|
8
|
+
// emphasis/strong, GFM strikethrough (~~x~~), GFM tables, blockquotes,
|
|
9
|
+
// thematic breaks.
|
|
10
|
+
// NOT enabled: raw HTML (html:false — escaped to inert text), linkify,
|
|
11
|
+
// typographer/smartquotes, syntax highlighting, footnotes, definition lists.
|
|
12
|
+
//
|
|
13
|
+
// Trust story (plan §1: "markdown produces trusted Html"): every text node
|
|
14
|
+
// markdown-it emits is escaped by the renderer itself — html:false means raw
|
|
15
|
+
// HTML in the source renders as visible inert text, and code spans / fences
|
|
16
|
+
// escape their content too. So the whole rendered body goes to
|
|
17
|
+
// `trustedHtml(markup)` with NO value ranges: there is no unescaped
|
|
18
|
+
// author-controlled value inside it for the fence to police.
|
|
19
|
+
//
|
|
20
|
+
// The one author-controlled ATTRIBUTE surface is link/image destinations —
|
|
21
|
+
// in EVERY kind: inline `[x](…)` and `[x][ref]` links, autolinks
|
|
22
|
+
// (markdown-it 14's AUTOLINK_RE admits ANY `scheme:` inside `<…>`,
|
|
23
|
+
// including `javascript:`), images, and links/images nested inside an
|
|
24
|
+
// image's LABEL (the label is re-parsed as its own inline). markdown-it's
|
|
25
|
+
// own safety net turns a `javascript:` link into literal text — safe but
|
|
26
|
+
// SILENT, and crust rule 1 forbids silent handling — so `md.validateLink`
|
|
27
|
+
// is overridden to admit every destination to the token stream, and OUR
|
|
28
|
+
// policy (url.ts `validateUrl`) runs over every href/src in the collect
|
|
29
|
+
// pass: a destination that fails becomes a `link.invalid` diagnostic AND
|
|
30
|
+
// loses its attribute, so the emitted markup is inert even if a caller
|
|
31
|
+
// continues past the error.
|
|
32
|
+
//
|
|
33
|
+
// Line coordinates: block tokens carry `map` ([start, end) lines, 0-based
|
|
34
|
+
// and BODY-relative); the inline token carrying a link carries its own map.
|
|
35
|
+
// File line = bodyStartLine + map[0] (frontmatter's full-file offset). A
|
|
36
|
+
// destination inside a token with no map at all gets `line: undefined` —
|
|
37
|
+
// best-effort by design, never a guessed coordinate.
|
|
38
|
+
|
|
39
|
+
import { posix } from "node:path";
|
|
40
|
+
import type { Options as MdOptions, Renderer, StateCore, Token } from "markdown-it";
|
|
41
|
+
import MarkdownIt from "markdown-it";
|
|
42
|
+
import { type Diagnostic, isDiagnostic } from "./diagnostics";
|
|
43
|
+
import { type Html, trustedHtml } from "./html";
|
|
44
|
+
import { canonicalUrl, normalizeRoute } from "./routes";
|
|
45
|
+
import type { Heading, InternalLink, RouteResolver } from "./types";
|
|
46
|
+
import { validateUrl } from "./url";
|
|
47
|
+
|
|
48
|
+
export interface MarkdownOptions {
|
|
49
|
+
/** posix path used in diagnostics. */
|
|
50
|
+
sourcePath: string;
|
|
51
|
+
/** frontmatter's bodyStartLine: body line 0 is this file line. */
|
|
52
|
+
bodyStartLine: number;
|
|
53
|
+
/**
|
|
54
|
+
* The site's base URL, path prefix INCLUDED (e.g. `https://x.dev/docs`).
|
|
55
|
+
* The URL policy's base for relative refs is this plus `pageRoute`, which is
|
|
56
|
+
* exactly the page's canonical URL — never `new URL(site).origin`, which
|
|
57
|
+
* would drop the prefix (see url.ts).
|
|
58
|
+
*/
|
|
59
|
+
siteUrl: string;
|
|
60
|
+
/** The page's normalized route; base for relative .md resolution. */
|
|
61
|
+
pageRoute?: string;
|
|
62
|
+
/** Route-table lookup for internal .md links (chunk 6 wires the real one). */
|
|
63
|
+
resolveInternal?: RouteResolver;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface MarkdownResult {
|
|
67
|
+
/** The rendered body as trusted markup (see the trust story above). */
|
|
68
|
+
html: Html;
|
|
69
|
+
headings: Heading[];
|
|
70
|
+
/** Internal links for chunk 7's link validation. */
|
|
71
|
+
links: InternalLink[];
|
|
72
|
+
diagnostics: Diagnostic[];
|
|
73
|
+
/** Plain text of the first top-level paragraph ("" when there is none). */
|
|
74
|
+
firstParagraph: string;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* GitHub-style slug: lowercase → NFKD with combining marks stripped
|
|
79
|
+
* ("Ünïcödé" → "unicode") → whitespace runs to `-` → keep only unicode
|
|
80
|
+
* letters, digits, `-` and `_` → collapse repeated `-` → trim `-`.
|
|
81
|
+
* An empty result (emoji-only heading) becomes "" and the caller's
|
|
82
|
+
* collision step substitutes the fallback id "section".
|
|
83
|
+
*/
|
|
84
|
+
export function slugify(text: string): string {
|
|
85
|
+
const stripped = text.trim().toLowerCase().normalize("NFKD").replace(/\p{M}/gu, "");
|
|
86
|
+
const dashed = stripped.replace(/\s+/g, "-");
|
|
87
|
+
// The per-char class keeps unicode letters/digits (and the -/_ that
|
|
88
|
+
// GitHub's slugger also keeps); everything else — punctuation, emoji — dies.
|
|
89
|
+
const kept = [...dashed]
|
|
90
|
+
.filter((ch) => /[\p{L}\p{N}_-]/u.test(ch))
|
|
91
|
+
.join("")
|
|
92
|
+
.replace(/-{2,}/g, "-")
|
|
93
|
+
.replace(/^-+|-+$/g, "");
|
|
94
|
+
return kept;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Final id for one heading: `slugify` output, "section" when empty, and on
|
|
99
|
+
* collision `-1`/`-2`/… in document order (applied AFTER the slug, and
|
|
100
|
+
* incremented past ids that are already taken — "Foo", "foo-1", "Foo" gives
|
|
101
|
+
* foo, foo-1, foo-2).
|
|
102
|
+
*/
|
|
103
|
+
function uniqueId(used: Set<string>, text: string): string {
|
|
104
|
+
const base = slugify(text) === "" ? "section" : slugify(text);
|
|
105
|
+
let candidate = base;
|
|
106
|
+
let n = 0;
|
|
107
|
+
while (used.has(candidate)) {
|
|
108
|
+
n += 1;
|
|
109
|
+
candidate = `${base}-${n}`;
|
|
110
|
+
}
|
|
111
|
+
used.add(candidate);
|
|
112
|
+
return candidate;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Plain text of inline tokens: markdown syntax stripped, entities decoded
|
|
116
|
+
* (markdown-it's entity rule already decoded them into the text tokens). */
|
|
117
|
+
function plainText(children: readonly Token[] | null): string {
|
|
118
|
+
if (!children) return "";
|
|
119
|
+
let out = "";
|
|
120
|
+
for (const t of children) {
|
|
121
|
+
// text_special is markdown-it 14's decoded entity/escape token — its
|
|
122
|
+
// content is the decoded character and belongs in the plain text.
|
|
123
|
+
if (
|
|
124
|
+
t.type === "text" ||
|
|
125
|
+
t.type === "text_special" ||
|
|
126
|
+
t.type === "code_inline" ||
|
|
127
|
+
t.type === "html_inline"
|
|
128
|
+
) {
|
|
129
|
+
out += t.content;
|
|
130
|
+
} else if (t.type === "softbreak" || t.type === "hardbreak") {
|
|
131
|
+
out += " ";
|
|
132
|
+
} else {
|
|
133
|
+
out += plainText(t.children);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
interface RenderState {
|
|
140
|
+
headings: Heading[];
|
|
141
|
+
links: InternalLink[];
|
|
142
|
+
diagnostics: Diagnostic[];
|
|
143
|
+
used: Set<string>;
|
|
144
|
+
firstParagraph: string | null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* GFM task-list items, hand-rolled (markdown-it core has none): a bullet
|
|
149
|
+
* item whose FIRST paragraph starts `[ ] ` / `[x] ` becomes a disabled
|
|
150
|
+
* checkbox input wrapped in a `<label>` — GitHub's own shape. It runs after
|
|
151
|
+
* inline parsing (at that point the marker is plain text — a bare `[x]` is
|
|
152
|
+
* not a link), cutting the marker from the first text token and inserting a
|
|
153
|
+
* custom token the renderer turns into the input. Tight-list paragraphs are
|
|
154
|
+
* hidden; the label/checkbox still render because the paragraph rules emit
|
|
155
|
+
* them even when the `<p>` itself is suppressed.
|
|
156
|
+
*/
|
|
157
|
+
function taskItems(md: MarkdownIt): void {
|
|
158
|
+
md.core.ruler.after("inline", "crust-task-item", (state: StateCore) => {
|
|
159
|
+
const toks = state.tokens;
|
|
160
|
+
for (let i = 1; i + 2 < toks.length; i++) {
|
|
161
|
+
if (toks[i].type !== "paragraph_open" || toks[i - 1].type !== "list_item_open") continue;
|
|
162
|
+
const inline = toks[i + 1];
|
|
163
|
+
if (inline.type !== "inline" || !inline.children) continue;
|
|
164
|
+
const first = inline.children[0];
|
|
165
|
+
if (first?.type !== "text") continue;
|
|
166
|
+
const m = /^\[([ xX])\][ \t]+/.exec(first.content);
|
|
167
|
+
if (!m) continue;
|
|
168
|
+
first.content = first.content.slice(m[0].length);
|
|
169
|
+
const box = new state.Token("crust_task_box", "", 0);
|
|
170
|
+
box.meta = { checked: m[1] !== " " };
|
|
171
|
+
inline.children.unshift(box);
|
|
172
|
+
toks[i].meta = { crustTask: true };
|
|
173
|
+
toks[i].attrSet("class", "task-list-item");
|
|
174
|
+
toks[i + 2].meta = { crustTask: true };
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
md.renderer.rules.crust_task_box = (tokens: Token[], idx: number) =>
|
|
178
|
+
tokens[idx].meta.checked
|
|
179
|
+
? '<input checked="" disabled="" type="checkbox" />'
|
|
180
|
+
: '<input disabled="" type="checkbox" />';
|
|
181
|
+
const open = (
|
|
182
|
+
tokens: Token[],
|
|
183
|
+
idx: number,
|
|
184
|
+
options: MdOptions,
|
|
185
|
+
_env: unknown,
|
|
186
|
+
self: Renderer,
|
|
187
|
+
) => {
|
|
188
|
+
const base = self.renderToken(tokens, idx, options);
|
|
189
|
+
return tokens[idx].meta?.crustTask ? `${base}<label>` : base;
|
|
190
|
+
};
|
|
191
|
+
const close = (
|
|
192
|
+
tokens: Token[],
|
|
193
|
+
idx: number,
|
|
194
|
+
options: MdOptions,
|
|
195
|
+
_env: unknown,
|
|
196
|
+
self: Renderer,
|
|
197
|
+
) => {
|
|
198
|
+
const base = self.renderToken(tokens, idx, options);
|
|
199
|
+
return tokens[idx].meta?.crustTask ? `</label>${base}` : base;
|
|
200
|
+
};
|
|
201
|
+
md.renderer.rules.paragraph_open = open;
|
|
202
|
+
md.renderer.rules.paragraph_close = close;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function buildRenderer(opts: MarkdownOptions, state: RenderState): MarkdownIt {
|
|
206
|
+
const md = new MarkdownIt({
|
|
207
|
+
html: false,
|
|
208
|
+
linkify: false,
|
|
209
|
+
typographer: false,
|
|
210
|
+
langPrefix: "language-",
|
|
211
|
+
});
|
|
212
|
+
// See the trust story in the header: OUR policy, not markdown-it's silent
|
|
213
|
+
// text fallback. Every destination reaches the token stream and is judged
|
|
214
|
+
// in the collect pass below.
|
|
215
|
+
md.validateLink = () => true;
|
|
216
|
+
taskItems(md);
|
|
217
|
+
|
|
218
|
+
/** Judge one link/image destination; mutates the token, records results. */
|
|
219
|
+
const applyDestination = (
|
|
220
|
+
kind: "link" | "image",
|
|
221
|
+
token: Token,
|
|
222
|
+
attr: string,
|
|
223
|
+
line: number | undefined,
|
|
224
|
+
): void => {
|
|
225
|
+
const raw = token.attrGet(attr) ?? "";
|
|
226
|
+
const hash = raw.indexOf("#");
|
|
227
|
+
const path = hash === -1 ? raw : raw.slice(0, hash);
|
|
228
|
+
const fragment = hash === -1 ? null : raw.slice(hash + 1);
|
|
229
|
+
const reject = (why: string): void => {
|
|
230
|
+
const idx = token.attrIndex(attr);
|
|
231
|
+
if (idx >= 0 && token.attrs) token.attrs.splice(idx, 1);
|
|
232
|
+
state.diagnostics.push({
|
|
233
|
+
code: "link.invalid",
|
|
234
|
+
severity: "error",
|
|
235
|
+
sourcePath: opts.sourcePath,
|
|
236
|
+
line,
|
|
237
|
+
message: `${kind} destination ${JSON.stringify(raw)} rejected: ${why}`,
|
|
238
|
+
});
|
|
239
|
+
};
|
|
240
|
+
const checkUrl = (): void => {
|
|
241
|
+
try {
|
|
242
|
+
validateUrl(raw, { siteUrl: opts.siteUrl, pageRoute: opts.pageRoute });
|
|
243
|
+
} catch (d) {
|
|
244
|
+
if (!isDiagnostic(d)) throw d;
|
|
245
|
+
reject(d.message);
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
if (path === "") {
|
|
249
|
+
// Pure fragment: same page, safe by construction (validateUrl agrees).
|
|
250
|
+
// Recorded for chunk 7's fragment check.
|
|
251
|
+
if (kind === "link" && fragment !== null && fragment !== "") {
|
|
252
|
+
state.links.push({
|
|
253
|
+
route: opts.pageRoute ?? "/",
|
|
254
|
+
fragment,
|
|
255
|
+
line: line ?? null,
|
|
256
|
+
exists: true,
|
|
257
|
+
isDraft: false,
|
|
258
|
+
kind: "fragment",
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
const absolute = /^[A-Za-z][A-Za-z0-9+.-]*:/.test(path);
|
|
264
|
+
const rootRelative = path.startsWith("/");
|
|
265
|
+
if (!absolute && !rootRelative && /\.md$/i.test(path)) {
|
|
266
|
+
// Internal .md link: resolved against the page's ROUTE (plan §2),
|
|
267
|
+
// extension stripped — the candidate is a route-shaped path.
|
|
268
|
+
const base = posix.dirname(opts.pageRoute ?? "/");
|
|
269
|
+
const candidateRaw = posix.resolve(base, path).replace(/\.md$/i, "");
|
|
270
|
+
let candidate: string;
|
|
271
|
+
try {
|
|
272
|
+
candidate = normalizeRoute(candidateRaw, { sourcePath: opts.sourcePath });
|
|
273
|
+
} catch (d) {
|
|
274
|
+
if (!isDiagnostic(d)) throw d;
|
|
275
|
+
reject(
|
|
276
|
+
`internal link target ${JSON.stringify(candidateRaw)} is not a valid route: ${d.message}`,
|
|
277
|
+
);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const resolved = opts.resolveInternal ? opts.resolveInternal(candidate) : null;
|
|
281
|
+
if (resolved === "external") {
|
|
282
|
+
checkUrl();
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (resolved !== null) {
|
|
286
|
+
// Routes stay site-relative for validation; browser destinations
|
|
287
|
+
// must include the configured deployment prefix (e.g. /docs).
|
|
288
|
+
const prefix = new URL(opts.siteUrl).pathname.replace(/\/$/, "");
|
|
289
|
+
// A pathname beginning // would become a protocol-relative URL.
|
|
290
|
+
// Keep the full origin for that accepted site-prefix shape.
|
|
291
|
+
const destination = canonicalUrl(
|
|
292
|
+
prefix.startsWith("//") ? opts.siteUrl : prefix,
|
|
293
|
+
resolved.route,
|
|
294
|
+
);
|
|
295
|
+
const value = fragment === null ? destination : `${destination}#${fragment}`;
|
|
296
|
+
try {
|
|
297
|
+
validateUrl(value, { siteUrl: opts.siteUrl, pageRoute: opts.pageRoute });
|
|
298
|
+
} catch (d) {
|
|
299
|
+
if (!isDiagnostic(d)) throw d;
|
|
300
|
+
reject(d.message);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
token.attrSet(attr, value);
|
|
304
|
+
state.links.push({
|
|
305
|
+
route: resolved.route,
|
|
306
|
+
fragment,
|
|
307
|
+
line: line ?? null,
|
|
308
|
+
exists: resolved.exists,
|
|
309
|
+
isDraft: resolved.isDraft,
|
|
310
|
+
kind: "page",
|
|
311
|
+
});
|
|
312
|
+
} else {
|
|
313
|
+
// Not in the route table: recorded with exists:false (chunk 7 turns
|
|
314
|
+
// that into link.broken); the destination stays as written.
|
|
315
|
+
state.links.push({
|
|
316
|
+
route: candidate,
|
|
317
|
+
fragment,
|
|
318
|
+
line: line ?? null,
|
|
319
|
+
exists: false,
|
|
320
|
+
isDraft: false,
|
|
321
|
+
kind: "page",
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
checkUrl();
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Judge every destination in one inline token's children — RECURSIVELY
|
|
331
|
+
* through image labels. markdown-it re-parses an image's label as its own
|
|
332
|
+
* inline (the image token's `children`), so a link — or another image,
|
|
333
|
+
* recursively — inside `` reaches the token stream. The
|
|
334
|
+
* contract is that EVERY destination reaching the token stream is judged:
|
|
335
|
+
* silently skipping a nested one would let a `javascript:` destination hide
|
|
336
|
+
* in an alt attribute (crust rule 1 — no silent handling).
|
|
337
|
+
*/
|
|
338
|
+
const walkInline = (children: readonly Token[], line: number | undefined): void => {
|
|
339
|
+
for (const child of children) {
|
|
340
|
+
if (child.type === "link_open") {
|
|
341
|
+
applyDestination("link", child, "href", line);
|
|
342
|
+
} else if (child.type === "image") {
|
|
343
|
+
applyDestination("image", child, "src", line);
|
|
344
|
+
if (child.children) walkInline(child.children, line);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
md.core.ruler.after("inline", "crust-collect", (core: StateCore) => {
|
|
350
|
+
const toks = core.tokens;
|
|
351
|
+
// A paragraph is the page's first BLOCK-LEVEL paragraph only when it is
|
|
352
|
+
// a direct child of the document. Inside a blockquote, list, or list
|
|
353
|
+
// item its <p> belongs to the container (a loose list item even emits a
|
|
354
|
+
// VISIBLE <p> — the old hidden-flag test let those through, as did every
|
|
355
|
+
// quoted paragraph), not to the page. Containers nest arbitrarily
|
|
356
|
+
// (a list inside a blockquote), hence a stack, not a counter.
|
|
357
|
+
const stack: string[] = [];
|
|
358
|
+
for (let i = 0; i < toks.length; i++) {
|
|
359
|
+
const t = toks[i];
|
|
360
|
+
if (
|
|
361
|
+
t.type === "blockquote_open" ||
|
|
362
|
+
t.type === "list_open" ||
|
|
363
|
+
t.type === "bullet_list_open" ||
|
|
364
|
+
t.type === "ordered_list_open" ||
|
|
365
|
+
t.type === "list_item_open"
|
|
366
|
+
) {
|
|
367
|
+
stack.push(t.type);
|
|
368
|
+
} else if (
|
|
369
|
+
t.type === "blockquote_close" ||
|
|
370
|
+
t.type === "list_close" ||
|
|
371
|
+
// markdown-it 14 emits the kind-specific close (no bare list_close
|
|
372
|
+
// in output), so both must pop or a paragraph after a list is
|
|
373
|
+
// forever "nested" to the stack.
|
|
374
|
+
t.type === "bullet_list_close" ||
|
|
375
|
+
t.type === "ordered_list_close" ||
|
|
376
|
+
t.type === "list_item_close"
|
|
377
|
+
) {
|
|
378
|
+
stack.pop();
|
|
379
|
+
} else if (t.type === "heading_open") {
|
|
380
|
+
const inline = toks[i + 1];
|
|
381
|
+
const text = inline && inline.type === "inline" ? plainText(inline.children) : "";
|
|
382
|
+
const id = uniqueId(state.used, text);
|
|
383
|
+
t.attrSet("id", id);
|
|
384
|
+
state.headings.push({ level: Number(t.tag.slice(1)), id, text });
|
|
385
|
+
} else if (
|
|
386
|
+
t.type === "paragraph_open" &&
|
|
387
|
+
!t.hidden &&
|
|
388
|
+
stack.length === 0 &&
|
|
389
|
+
state.firstParagraph === null
|
|
390
|
+
) {
|
|
391
|
+
const inline = toks[i + 1];
|
|
392
|
+
if (inline && inline.type === "inline") state.firstParagraph = plainText(inline.children);
|
|
393
|
+
} else if (t.type === "inline" && t.children) {
|
|
394
|
+
const line = t.map ? opts.bodyStartLine + t.map[0] : undefined;
|
|
395
|
+
walkInline(t.children, line);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
return md;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Render one page body. The result's `html` is trusted markup (see the
|
|
404
|
+
* header); `diagnostics` carries link.invalid / markdown.parse-error errors
|
|
405
|
+
* in FULL-FILE line coordinates. A markdown-it internal throw never escapes:
|
|
406
|
+
* it becomes a markdown.parse-error diagnostic (at bodyStartLine — the
|
|
407
|
+
* renderer gives no finer coordinate) and an empty body.
|
|
408
|
+
*/
|
|
409
|
+
export function renderMarkdown(body: string, opts: MarkdownOptions): MarkdownResult {
|
|
410
|
+
const state: RenderState = {
|
|
411
|
+
headings: [],
|
|
412
|
+
links: [],
|
|
413
|
+
diagnostics: [],
|
|
414
|
+
used: new Set(),
|
|
415
|
+
firstParagraph: null,
|
|
416
|
+
};
|
|
417
|
+
let markup = "";
|
|
418
|
+
try {
|
|
419
|
+
markup = buildRenderer(opts, state).render(body, {});
|
|
420
|
+
} catch (e) {
|
|
421
|
+
if (isDiagnostic(e)) {
|
|
422
|
+
state.diagnostics.push({
|
|
423
|
+
...e,
|
|
424
|
+
sourcePath: e.sourcePath === "" ? opts.sourcePath : e.sourcePath,
|
|
425
|
+
line: e.line ?? opts.bodyStartLine,
|
|
426
|
+
});
|
|
427
|
+
} else {
|
|
428
|
+
state.diagnostics.push({
|
|
429
|
+
code: "markdown.parse-error",
|
|
430
|
+
severity: "error",
|
|
431
|
+
sourcePath: opts.sourcePath,
|
|
432
|
+
line: opts.bodyStartLine,
|
|
433
|
+
message: `markdown rendering failed: ${e instanceof Error ? e.message : String(e)}`,
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return {
|
|
438
|
+
html: trustedHtml(markup),
|
|
439
|
+
headings: state.headings,
|
|
440
|
+
links: state.links,
|
|
441
|
+
diagnostics: state.diagnostics,
|
|
442
|
+
firstParagraph: state.firstParagraph ?? "",
|
|
443
|
+
};
|
|
444
|
+
}
|