vantage-md 0.5.5 → 0.5.7

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/dist/react.js CHANGED
@@ -1,1836 +1,2239 @@
1
- import { memo, useState, useRef, useMemo, useEffect, useCallback } from 'react';
2
- import ReactMarkdown from 'react-markdown';
3
- import remarkGfm from 'remark-gfm';
4
- import remarkMath from 'remark-math';
5
- import rehypeRaw from 'rehype-raw';
6
- import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
7
- import rehypeHighlight from 'rehype-highlight';
8
- import rehypeKatex from 'rehype-katex';
9
- import rehypeSlug from 'rehype-slug';
10
- import YAML from 'yaml';
11
- import { parse } from 'smol-toml';
12
- import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
13
- import { unified } from 'unified';
14
- import remarkParse from 'remark-parse';
15
- import remarkRehype from 'remark-rehype';
16
- import rehypeStringify from 'rehype-stringify';
17
-
18
- // src/MarkdownViewer.tsx
19
-
20
- // src/rehypeSourceLines.ts
21
- var BLOCK_TAGS = /* @__PURE__ */ new Set([
22
- "p",
23
- "h1",
24
- "h2",
25
- "h3",
26
- "h4",
27
- "h5",
28
- "h6",
29
- "li",
30
- "blockquote",
31
- "pre",
32
- "table",
33
- "tr",
34
- "ul",
35
- "ol",
36
- "hr",
37
- "div"
1
+ import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import ReactMarkdown from "react-markdown";
3
+ import remarkGfm from "remark-gfm";
4
+ import remarkMath from "remark-math";
5
+ import rehypeRaw from "rehype-raw";
6
+ import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
7
+ import rehypeHighlight from "rehype-highlight";
8
+ import rehypeKatex from "rehype-katex";
9
+ import rehypeSlug from "rehype-slug";
10
+ import { visit } from "unist-util-visit";
11
+ import YAML from "yaml";
12
+ import { parse } from "smol-toml";
13
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
14
+ import { unified } from "unified";
15
+ import remarkParse from "remark-parse";
16
+ import remarkRehype from "remark-rehype";
17
+ import rehypeStringify from "rehype-stringify";
18
+ //#region src/rehypeSourceLines.ts
19
+ const BLOCK_TAGS = /* @__PURE__ */ new Set([
20
+ "p",
21
+ "h1",
22
+ "h2",
23
+ "h3",
24
+ "h4",
25
+ "h5",
26
+ "h6",
27
+ "li",
28
+ "blockquote",
29
+ "pre",
30
+ "table",
31
+ "tr",
32
+ "ul",
33
+ "ol",
34
+ "hr",
35
+ "div"
38
36
  ]);
39
- function visit(node, offset) {
40
- if ("children" in node) {
41
- for (const child of node.children) {
42
- if (child.type === "element") {
43
- if (BLOCK_TAGS.has(child.tagName) && child.position?.start?.line) {
44
- child.properties = child.properties || {};
45
- child.properties["dataSourceLine"] = child.position.start.line + offset;
46
- }
47
- visit(child, offset);
48
- }
49
- }
50
- }
37
+ function visit$1(node, offset) {
38
+ if ("children" in node) {
39
+ for (const child of node.children) if (child.type === "element") {
40
+ if (BLOCK_TAGS.has(child.tagName) && child.position?.start?.line) {
41
+ child.properties = child.properties || {};
42
+ child.properties["dataSourceLine"] = child.position.start.line + offset;
43
+ }
44
+ visit$1(child, offset);
45
+ }
46
+ }
51
47
  }
52
- var rehypeSourceLines = (options) => {
53
- const offset = options?.offset ?? 0;
54
- return (tree) => {
55
- visit(tree, offset);
56
- };
48
+ const rehypeSourceLines = (options) => {
49
+ const offset = options?.offset ?? 0;
50
+ return (tree) => {
51
+ visit$1(tree, offset);
52
+ };
57
53
  };
58
- var rehypeSourceLines_default = rehypeSourceLines;
59
-
60
- // src/vantageDirectives.ts
61
- var VANTAGE_TONES = [
62
- "note",
63
- "tip",
64
- "important",
65
- "warning",
66
- "caution",
67
- "muted"
54
+ //#endregion
55
+ //#region src/rehypeVantageAlerts.ts
56
+ /**
57
+ * GFM alerts — `> [!WARNING]` — compiled into `data-vantage-alert`.
58
+ *
59
+ * `remark-gfm` does not implement alerts, so until this plugin existed a
60
+ * `> [!WARNING]` rendered as an ordinary blockquote with the literal marker
61
+ * visible as its first words. Worse than merely unstyled: `@tailwindcss/typography`
62
+ * italicises blockquotes and draws `open-quote`/`close-quote` around the first
63
+ * paragraph, so a callout came out as an italic *quotation* whose opening words
64
+ * were `"[!WARNING]`. That was the "Known gaps" entry in
65
+ * `docs/reference/inline-markup.md` and OQ-10, filed rather than fixed, while
66
+ * `styleGuide.ts` went on telling every agent to write them.
67
+ *
68
+ * The tokens are deliberately the ones the `tone` vocabulary already resolves —
69
+ * an alert *is* the six-colour light/dark treatment `tone` shipped, which is
70
+ * exactly what the gap entry said whoever fixed this should do rather than
71
+ * building a second palette. `[!WARNING]` and `<!-- vantage: block tone=warning -->`
72
+ * therefore agree by construction, and adding a theme still touches one
73
+ * custom-property block.
74
+ *
75
+ * **This runs in the shared pipeline, so all four renderers get it** — the live
76
+ * viewer, the package's exported viewer, the static export and the CLI checker's
77
+ * `renderMarkdown`. That is what makes an injected title element acceptable here
78
+ * where the collapse caret's glyph had to be drawn in CSS: the caret is injected
79
+ * by app JS that may never run, and this is not (D5).
80
+ *
81
+ * ## What it does not do
82
+ *
83
+ * It does not touch a blockquote that carries no marker, and an unrecognised
84
+ * marker (`[!HINT]`) is left exactly as it was — visible literal text, which is
85
+ * the honest rendering of something GitHub also would not style. Silently
86
+ * swallowing it would hide a typo that reads as a callout on neither renderer.
87
+ */
88
+ /**
89
+ * The five GFM alert kinds, lowercased.
90
+ *
91
+ * Deliberately *not* re-derived from `VANTAGE_TONES`: that list carries a sixth
92
+ * token, `muted`, which is ours and is not an alert word. The overlap is the
93
+ * point — the five that coincide share a palette — but the two vocabularies are
94
+ * closed by different authorities and a change to one must not silently move the
95
+ * other. A test asserts the five are a subset of the tones.
96
+ */
97
+ const VANTAGE_ALERTS = [
98
+ "note",
99
+ "tip",
100
+ "important",
101
+ "warning",
102
+ "caution"
68
103
  ];
69
- var VANTAGE_EMPHASIS = ["strong", "normal", "quiet"];
70
- var VANTAGE_BADGES = [
71
- "draft",
72
- "stale",
73
- "blocked",
74
- "done",
75
- "wip"
104
+ /** The visible label per kind. Title case, as GitHub renders it. */
105
+ const ALERT_TITLES = {
106
+ note: "Note",
107
+ tip: "Tip",
108
+ important: "Important",
109
+ warning: "Warning",
110
+ caution: "Caution"
111
+ };
112
+ /**
113
+ * The marker, anchored and requiring the rest of its line to be empty.
114
+ *
115
+ * GFM puts the marker alone on the blockquote's first line, and holding to that
116
+ * is what keeps a paragraph that merely *begins* with bracketed text from being
117
+ * eaten. The trailing newline is optional only for the degenerate blockquote
118
+ * whose entire content is the marker.
119
+ *
120
+ * Measured against the real chain rather than assumed: `remark-parse` reads
121
+ * `[!TIP]` as a shortcut link reference, and because no definition matches,
122
+ * `mdast-util-to-hast` puts it back as **one** leading text node —
123
+ * `"[!TIP]\nThe generalization: "` — not as a `[`/label/`]` triple. So a single
124
+ * anchored test on the first text node is enough, and the plugin does not have
125
+ * to reassemble the marker across siblings.
126
+ */
127
+ const MARKER = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\][ \t]*(?:\r?\n|$)/;
128
+ /** The first child, if it is an element. */
129
+ function firstElement(node) {
130
+ const child = node.children.find((c) => c.type === "element" || c.type === "text" && c.value.trim() !== "");
131
+ return child?.type === "element" ? child : void 0;
132
+ }
133
+ /**
134
+ * Compile `> [!KIND]` blockquotes into `data-vantage-alert="kind"`.
135
+ *
136
+ * Order in the chain matters twice, and both are stated in `pipeline.ts`:
137
+ *
138
+ * - **after `rehypeSourceLines`**, so the injected title carries no
139
+ * `data-source-line`. That is what keeps it out of `anchorBlockWithin`, which
140
+ * filters candidates to those with a finite line — otherwise a review comment
141
+ * on an alert would anchor to the word "Warning" instead of to the prose.
142
+ * - **before `rehypeSanitize`**, so nothing reaches the DOM the schema has not
143
+ * passed. `dataVantageAlert` is allowlisted there by name *and* value, like
144
+ * every other `data-vantage-*` attribute.
145
+ */
146
+ function rehypeVantageAlerts() {
147
+ return (tree) => {
148
+ visit(tree, "element", (node) => {
149
+ if (node.tagName !== "blockquote") return;
150
+ const paragraph = firstElement(node);
151
+ if (paragraph === void 0 || paragraph.tagName !== "p") return;
152
+ const lead = paragraph.children[0];
153
+ if (lead === void 0 || lead.type !== "text") return;
154
+ const match = MARKER.exec(lead.value);
155
+ if (match === null) return;
156
+ const kind = match[1].toLowerCase();
157
+ lead.value = lead.value.slice(match[0].length);
158
+ if (lead.value === "" && paragraph.children.length === 1) node.children = node.children.filter((c) => c !== paragraph);
159
+ node.properties = {
160
+ ...node.properties,
161
+ dataVantageAlert: kind
162
+ };
163
+ node.children.unshift({
164
+ type: "element",
165
+ tagName: "div",
166
+ properties: { className: ["vantage-alert-title"] },
167
+ children: [{
168
+ type: "text",
169
+ value: ALERT_TITLES[kind]
170
+ }]
171
+ });
172
+ });
173
+ };
174
+ }
175
+ //#endregion
176
+ //#region src/vantageDirectives.ts
177
+ /**
178
+ * The `tone` vocabulary: GitHub's alert words plus `muted`.
179
+ *
180
+ * Semantic, never chromatic (P2, Ledger OQ-3). A document says what a section
181
+ * *is*; the theme decides what that looks like, which is what lets one document
182
+ * render correctly in light, in dark, and in themes that do not exist yet.
183
+ */
184
+ const VANTAGE_TONES = [
185
+ "note",
186
+ "tip",
187
+ "important",
188
+ "warning",
189
+ "caution",
190
+ "muted"
76
191
  ];
77
- var VANTAGE_COLLAPSED = ["true", "false"];
78
- var VANTAGE_RUNS = ["start", "middle", "end", "only"];
79
- var VANTAGE_STYLE_TARGETS = [
80
- "p",
81
- "h1",
82
- "h2",
83
- "h3",
84
- "h4",
85
- "h5",
86
- "h6",
87
- "li",
88
- "blockquote",
89
- "pre",
90
- "table",
91
- "tr",
92
- "ul",
93
- "ol",
94
- "hr",
95
- "div"
192
+ /** How much the block should pull the eye — separate from `tone` on purpose. */
193
+ const VANTAGE_EMPHASIS = [
194
+ "strong",
195
+ "normal",
196
+ "quiet"
96
197
  ];
97
- var VANTAGE_ANCHOR_TARGETS = [
98
- "p",
99
- "h1",
100
- "h2",
101
- "h3",
102
- "h4",
103
- "h5",
104
- "h6",
105
- "li",
106
- "blockquote",
107
- "pre",
108
- "table"
198
+ /** A small chip beside the heading. */
199
+ const VANTAGE_BADGES = [
200
+ "draft",
201
+ "stale",
202
+ "blocked",
203
+ "done",
204
+ "wip"
109
205
  ];
110
- var STYLE_KEYS = {
111
- tone: VANTAGE_TONES,
112
- emphasis: VANTAGE_EMPHASIS,
113
- badge: VANTAGE_BADGES,
114
- collapsed: VANTAGE_COLLAPSED
206
+ /**
207
+ * `collapsed` is a token, not a flag: `false` is the default written down.
208
+ *
209
+ * It stamps nothing on its own. Its one real effect is overriding a
210
+ * `collapsed=true` earlier in the same merged directive run — last key wins — so
211
+ * it is in the vocabulary rather than being an unknown value that drops. It
212
+ * cannot cancel an *enclosing* collapsed section: a nested heading is a hidden
213
+ * member of the outer group by design (A3), and the outer run is stamped before
214
+ * any inner directive has been resolved.
215
+ */
216
+ const VANTAGE_COLLAPSED = ["true", "false"];
217
+ /**
218
+ * Where a block sits in a stamped run, so section-wide CSS can join its members
219
+ * without an adjacent-sibling combinator.
220
+ *
221
+ * Not cosmetic. Review mode inserts comment cards as siblings *inside* a
222
+ * stamped run (`useReviewHighlights`), so `[tone] + [tone]` severs at every
223
+ * commented paragraph and bleeds across the boundary between two adjacent runs
224
+ * of different tone. An attribute survives both.
225
+ */
226
+ const VANTAGE_RUNS = [
227
+ "start",
228
+ "middle",
229
+ "end",
230
+ "only"
231
+ ];
232
+ /**
233
+ * The tags a `section`/`block` directive may stamp.
234
+ *
235
+ * Deliberately `rehypeSourceLines`'s `BLOCK_TAGS`: a stamped block should also
236
+ * be a block with a `data-source-line`, so the styling surface and the anchor
237
+ * surface coincide. It also keeps an inline directive from stamping the `<em>`
238
+ * that happens to follow it inside a paragraph.
239
+ *
240
+ * It lives here rather than in the plugin because the CLI checker has to answer
241
+ * "will this directive stamp anything?" from an mdast tree with no hast in
242
+ * sight. A checker with its own copy of this list is a checker that calls a
243
+ * working directive an orphan, or stays silent about a dead one (D5).
244
+ */
245
+ const VANTAGE_STYLE_TARGETS = [
246
+ "p",
247
+ "h1",
248
+ "h2",
249
+ "h3",
250
+ "h4",
251
+ "h5",
252
+ "h6",
253
+ "li",
254
+ "blockquote",
255
+ "pre",
256
+ "table",
257
+ "tr",
258
+ "ul",
259
+ "ol",
260
+ "hr",
261
+ "div"
262
+ ];
263
+ /**
264
+ * The tags an `oq` directive may stamp — strictly the tags the review system
265
+ * can resolve an anchor on (`ANCHOR_TAGS` in the app's `MarkdownViewer`, and the
266
+ * block map in `useReviewHighlights`). `ul`, `ol`, `tr`, `hr` and `div` are in
267
+ * neither, so a button on one of them would build an anchor no review pass can
268
+ * find — the "mis-wired button" D6 forbids.
269
+ *
270
+ * The gap between this list and `VANTAGE_STYLE_TARGETS` is why an `oq`
271
+ * directive at column 0 above a list silently does nothing: the target is the
272
+ * `<ul>`, not the `<li>`. The checker says so.
273
+ */
274
+ const VANTAGE_ANCHOR_TARGETS = [
275
+ "p",
276
+ "h1",
277
+ "h2",
278
+ "h3",
279
+ "h4",
280
+ "h5",
281
+ "h6",
282
+ "li",
283
+ "blockquote",
284
+ "pre",
285
+ "table"
286
+ ];
287
+ VANTAGE_ANCHOR_TARGETS.filter((tag) => tag !== "pre" && tag !== "table");
288
+ const STYLE_KEYS = {
289
+ tone: VANTAGE_TONES,
290
+ emphasis: VANTAGE_EMPHASIS,
291
+ badge: VANTAGE_BADGES,
292
+ collapsed: VANTAGE_COLLAPSED
115
293
  };
116
- var DIRECTIVE_VOCABULARY = {
117
- section: STYLE_KEYS,
118
- block: STYLE_KEYS,
119
- oq: { id: null, leaning: null }
294
+ /**
295
+ * Name → key → the closed value set for that key.
296
+ *
297
+ * `section` and `block` share their keys: they differ in *extent*, not in what
298
+ * they can say. `oq`'s two keys are the design's only values with no closed set
299
+ * — `id` is a token an author chose and `leaning` is a sentence (§8.3) — so
300
+ * neither can be value-allowlisted, which is recorded here as `null` rather
301
+ * than left to a caller to guess.
302
+ */
303
+ const DIRECTIVE_VOCABULARY = {
304
+ section: STYLE_KEYS,
305
+ block: STYLE_KEYS,
306
+ oq: {
307
+ id: null,
308
+ leaning: null
309
+ }
120
310
  };
121
- var WS = /[ \t\r\n]*/y;
122
- var SENTINEL_PREFIX = /^[ \t\r\n]*vantage:/;
123
- var NAME = /[a-z][a-z0-9-]*/y;
124
- var UNQUOTED = /[A-Za-z0-9_.:#-]+/y;
125
- var QUOTED = /"[^"]*"/y;
311
+ /**
312
+ * `ws` is `[ \t\r\n]` — the design's grammar leaves it undefined, and `\n` has
313
+ * to be in the set because a directive may legally wrap: a multi-line comment
314
+ * is one node whose value contains the newlines.
315
+ */
316
+ const WS = /[ \t\r\n]*/y;
317
+ const SENTINEL_PREFIX = /^[ \t\r\n]*vantage:/;
318
+ const NAME = /[a-z][a-z0-9-]*/y;
319
+ const UNQUOTED = /[A-Za-z0-9_.:#-]+/y;
320
+ /**
321
+ * A quoted value holds anything but a `"`, `--` included: measured through the
322
+ * real chain, `leaning="a--b"` reaches the tree intact, because HTML5 closes a
323
+ * comment on `-->` or `--!>` and on nothing else. There is deliberately **no**
324
+ * `--` restriction here. What a quoted value cannot hold is a terminator: a
325
+ * `-->` inside one ends the comment early and spills the tail into the document
326
+ * as literal text, which is a finding for the checker rather than a rule here —
327
+ * by the time this function runs, the truncation has already happened.
328
+ */
329
+ const QUOTED = /"[^"]*"/y;
330
+ /** The whole non-whitespace run at `offset`, capped, for a quotable message. */
126
331
  function token(comment, offset) {
127
- const rest = comment.slice(offset);
128
- const end = rest.search(/[ \t\r\n]/);
129
- const word = end === -1 ? rest : rest.slice(0, end);
130
- return word.length > 24 ? `${word.slice(0, 24)}\u2026` : word;
332
+ const rest = comment.slice(offset);
333
+ const end = rest.search(/[ \t\r\n]/);
334
+ const word = end === -1 ? rest : rest.slice(0, end);
335
+ return word.length > 24 ? `${word.slice(0, 24)}…` : word;
131
336
  }
337
+ /** The sticky match at `offset`, or `null` if the pattern does not apply. */
132
338
  function matchAt(pattern, comment, offset) {
133
- pattern.lastIndex = offset;
134
- const match = pattern.exec(comment);
135
- return match === null ? null : match[0];
339
+ pattern.lastIndex = offset;
340
+ const match = pattern.exec(comment);
341
+ return match === null ? null : match[0];
136
342
  }
343
+ /** How much whitespace sits at `offset`. `WS` matches everywhere, empty. */
137
344
  function skipWhitespace(comment, offset) {
138
- return matchAt(WS, comment, offset)?.length ?? 0;
345
+ return matchAt(WS, comment, offset)?.length ?? 0;
139
346
  }
140
347
  function malformed(reason, offset) {
141
- return { kind: "malformed", reason, offset };
348
+ return {
349
+ kind: "malformed",
350
+ reason,
351
+ offset
352
+ };
142
353
  }
354
+ /**
355
+ * Parse one comment's **inner** text — the value of a hast `comment` node, with
356
+ * `<!--` and `-->` already stripped. `null` means "no sentinel, not ours".
357
+ *
358
+ * Hand-rolled rather than one regular expression, because a repeated capture
359
+ * group keeps only its last match and the checker needs an offset per token to
360
+ * point at the character that broke.
361
+ */
143
362
  function parseVantageDirective(comment) {
144
- const sentinel = SENTINEL_PREFIX.exec(comment);
145
- if (sentinel === null) return null;
146
- let at = sentinel[0].length;
147
- at += skipWhitespace(comment, at);
148
- const nameOffset = at;
149
- const name = matchAt(NAME, comment, at);
150
- if (name === null) {
151
- return malformed("no directive name after `vantage:`", at);
152
- }
153
- at += name.length;
154
- const pairs = [];
155
- while (at < comment.length) {
156
- const gap = skipWhitespace(comment, at);
157
- at += gap;
158
- if (at >= comment.length) break;
159
- if (gap === 0) {
160
- return malformed(`\`${token(comment, at)}\` needs a space before it`, at);
161
- }
162
- const keyOffset = at;
163
- const key = matchAt(NAME, comment, at);
164
- if (key === null) {
165
- return malformed(
166
- `\`${token(comment, at)}\` is not a \`key=value\` pair`,
167
- at
168
- );
169
- }
170
- at += key.length;
171
- if (comment[at] !== "=") {
172
- return malformed(`\`${key}\` is not followed by \`=value\``, at);
173
- }
174
- at += 1;
175
- const valueOffset = at;
176
- const quoted = matchAt(QUOTED, comment, at);
177
- if (quoted !== null) {
178
- at += quoted.length;
179
- pairs.push({
180
- key,
181
- value: quoted.slice(1, -1),
182
- keyOffset,
183
- valueOffset,
184
- quoted: true
185
- });
186
- continue;
187
- }
188
- const unquoted = matchAt(UNQUOTED, comment, at);
189
- if (unquoted === null) {
190
- const found = token(comment, at);
191
- return malformed(
192
- found === "" ? `\`${key}=\` has no value` : `\`${found}\` is not a valid value for \`${key}\``,
193
- at
194
- );
195
- }
196
- at += unquoted.length;
197
- pairs.push({ key, value: unquoted, keyOffset, valueOffset, quoted: false });
198
- }
199
- return { kind: "directive", name, nameOffset, pairs };
363
+ const sentinel = SENTINEL_PREFIX.exec(comment);
364
+ if (sentinel === null) return null;
365
+ let at = sentinel[0].length;
366
+ at += skipWhitespace(comment, at);
367
+ const nameOffset = at;
368
+ const name = matchAt(NAME, comment, at);
369
+ if (name === null) return malformed("no directive name after `vantage:`", at);
370
+ at += name.length;
371
+ const pairs = [];
372
+ while (at < comment.length) {
373
+ const gap = skipWhitespace(comment, at);
374
+ at += gap;
375
+ if (at >= comment.length) break;
376
+ if (gap === 0) return malformed(`\`${token(comment, at)}\` needs a space before it`, at);
377
+ const keyOffset = at;
378
+ const key = matchAt(NAME, comment, at);
379
+ if (key === null) return malformed(`\`${token(comment, at)}\` is not a \`key=value\` pair`, at);
380
+ at += key.length;
381
+ if (comment[at] !== "=") return malformed(`\`${key}\` is not followed by \`=value\``, at);
382
+ at += 1;
383
+ const valueOffset = at;
384
+ const quoted = matchAt(QUOTED, comment, at);
385
+ if (quoted !== null) {
386
+ at += quoted.length;
387
+ pairs.push({
388
+ key,
389
+ value: quoted.slice(1, -1),
390
+ keyOffset,
391
+ valueOffset,
392
+ quoted: true
393
+ });
394
+ continue;
395
+ }
396
+ const unquoted = matchAt(UNQUOTED, comment, at);
397
+ if (unquoted === null) {
398
+ const found = token(comment, at);
399
+ return malformed(found === "" ? `\`${key}=\` has no value` : `\`${found}\` is not a valid value for \`${key}\``, at);
400
+ }
401
+ at += unquoted.length;
402
+ pairs.push({
403
+ key,
404
+ value: unquoted,
405
+ keyOffset,
406
+ valueOffset,
407
+ quoted: false
408
+ });
409
+ }
410
+ return {
411
+ kind: "directive",
412
+ name,
413
+ nameOffset,
414
+ pairs
415
+ };
200
416
  }
201
-
202
- // src/rehypeVantageDirectives.ts
203
- var STYLE_TARGET_TAGS = new Set(VANTAGE_STYLE_TARGETS);
204
- var ANCHOR_TARGET_TAGS = new Set(VANTAGE_ANCHOR_TARGETS);
205
- var HEADING_DEPTHS = /* @__PURE__ */ new Map([
206
- ["h1", 1],
207
- ["h2", 2],
208
- ["h3", 3],
209
- ["h4", 4],
210
- ["h5", 5],
211
- ["h6", 6]
212
- ]);
213
- var RANGE_PROPERTIES = /* @__PURE__ */ new Map([
214
- ["tone", "dataVantageTone"],
215
- ["emphasis", "dataVantageEmphasis"]
417
+ //#endregion
418
+ //#region src/rehypeVantageDirectives.ts
419
+ /**
420
+ * What a `section`/`block` and an `oq` directive may stamp.
421
+ *
422
+ * Both lists live in `vantageDirectives.ts`, with the reasoning for each tag,
423
+ * because the CLI checker resolves the same question over mdast and must reach
424
+ * the same answer (D5).
425
+ */
426
+ const STYLE_TARGET_TAGS = new Set(VANTAGE_STYLE_TARGETS);
427
+ const ANCHOR_TARGET_TAGS = new Set(VANTAGE_ANCHOR_TARGETS);
428
+ const HEADING_DEPTHS = /* @__PURE__ */ new Map([
429
+ ["h1", 1],
430
+ ["h2", 2],
431
+ ["h3", 3],
432
+ ["h4", 4],
433
+ ["h5", 5],
434
+ ["h6", 6]
216
435
  ]);
217
- var POINT_PROPERTIES = /* @__PURE__ */ new Map([["badge", "dataVantageBadge"]]);
218
- var RUN_PROPERTY = "dataVantageRun";
219
- var OQ_PROPERTY = "dataVantageOq";
220
- var LEANING_PROPERTY = "dataVantageLeaning";
221
- var COLLAPSED_PROPERTY = "dataVantageCollapsed";
222
- var COLLAPSE_GROUP_PROPERTY = "dataVantageCollapseGroup";
223
- var COLLAPSE_TOGGLE_PROPERTY = "dataVantageCollapseToggle";
224
- var MAX_LEANING = 500;
436
+ /**
437
+ * Key → hast property, for the keys that treat a whole run.
438
+ *
439
+ * A camelCase hast property serialises to the kebab-case attribute, so
440
+ * `dataVantageTone` is `data-vantage-tone` in every renderer.
441
+ *
442
+ * `tone` and `emphasis` describe what a section *is* and how loud it is, so
443
+ * every block in the range wears them: the tone rule is a slice of one
444
+ * continuous line down the section, and the weight applies to all of its prose.
445
+ *
446
+ * `collapsed` is not here because it is not one property on one block: it puts a
447
+ * toggle on the heading and a collapsed flag plus a group id on every block the
448
+ * heading hides, which `stampStyle` does with the three properties below.
449
+ */
450
+ const RANGE_PROPERTIES = /* @__PURE__ */ new Map([["tone", "dataVantageTone"], ["emphasis", "dataVantageEmphasis"]]);
451
+ /**
452
+ * Key → hast property, for the keys that mark one block: the directive's target.
453
+ *
454
+ * `badge` is the asymmetry in the vocabulary and the reason this second map
455
+ * exists. It is not a treatment of a run but a single chip — "a small chip after
456
+ * the heading text" (§4.3), drawn as `[data-vantage-badge]::after` — so a
457
+ * section-wide stamp paints the word once per paragraph, list, table and fence
458
+ * under the heading instead of once beside it.
459
+ *
460
+ * The chip is fixed here rather than in the stylesheet, because narrowing the
461
+ * CSS to `:is(h1, …, h6)` would silently draw nothing for the two placements
462
+ * that legitimately badge a non-heading — `block badge=…` on a paragraph, and a
463
+ * `section` that degraded onto one (A1) — and would leave an attribute stamped
464
+ * on every block that says something untrue about it.
465
+ */
466
+ const POINT_PROPERTIES = /* @__PURE__ */ new Map([["badge", "dataVantageBadge"]]);
467
+ const RUN_PROPERTY = "dataVantageRun";
468
+ const OQ_PROPERTY = "dataVantageOq";
469
+ const LEANING_PROPERTY = "dataVantageLeaning";
470
+ /**
471
+ * The three properties `collapsed=true` stamps across a section.
472
+ *
473
+ * The heading takes a *different* attribute from the blocks it hides, and that
474
+ * asymmetry is the whole design (A3): a nested `###` inside a collapsed `##` is
475
+ * both a hidden member of the outer group and the toggle for its own, so one
476
+ * shared attribute would make it permanently invisible and unreachable by
477
+ * either toggle. There is no `<details>` and no wrapper — the run stays a flat
478
+ * list of siblings, which is what keeps review comment cards, the typography
479
+ * plugin's `h2 + *` margin resets and the anchor surface working.
480
+ *
481
+ * Hiding is CSS, and that CSS is gated on two markers the toggle JS sets — the
482
+ * prose container's readiness, and an armed marker on each block whose group it
483
+ * gave a caret (`docs/reference/inline-markup.md`, "Collapse without a wrapper"). A renderer without the JS
484
+ * — the CLI checker's HTML, an external consumer of this package — shows every
485
+ * block, and so does any block that ended up with no control.
486
+ */
487
+ const COLLAPSED_PROPERTY = "dataVantageCollapsed";
488
+ const COLLAPSE_GROUP_PROPERTY = "dataVantageCollapseGroup";
489
+ const COLLAPSE_TOGGLE_PROPERTY = "dataVantageCollapseToggle";
490
+ /** A review-comment body, not prose. Bounds the attribute; 500 is generous. */
491
+ const MAX_LEANING = 500;
492
+ /**
493
+ * Nodes that may sit between a directive and its target.
494
+ *
495
+ * A whitespace-only `text` node always does — measured, with or without a blank
496
+ * line in the source. Comments do too, and an unrelated `<!-- TODO -->` must not
497
+ * break the chain: it is invisible in every renderer and deleted by the
498
+ * sanitiser, so letting it change a directive's meaning would make behaviour
499
+ * depend on something no reader can see.
500
+ */
225
501
  function isSkippable(node) {
226
- if (node.type === "comment" || node.type === "doctype") return true;
227
- if (node.type === "text") return node.value.trim() === "";
228
- return false;
502
+ if (node.type === "comment" || node.type === "doctype") return true;
503
+ if (node.type === "text") return node.value.trim() === "";
504
+ return false;
229
505
  }
230
506
  function headingDepth(node) {
231
- if (node.type !== "element") return void 0;
232
- return HEADING_DEPTHS.get(node.tagName);
507
+ if (node.type !== "element") return void 0;
508
+ return HEADING_DEPTHS.get(node.tagName);
233
509
  }
234
510
  function setProperty(element, property, value) {
235
- element.properties = element.properties ?? {};
236
- element.properties[property] = value;
511
+ element.properties = element.properties ?? {};
512
+ element.properties[property] = value;
237
513
  }
514
+ /**
515
+ * Where a member sits in a stamped run: `only` for a lone block, otherwise
516
+ * `start`, `middle`, `end`. See `VANTAGE_RUNS`.
517
+ */
238
518
  function runValue(index, length) {
239
- if (length === 1) return "only";
240
- if (index === 0) return "start";
241
- return index === length - 1 ? "end" : "middle";
519
+ if (length === 1) return "only";
520
+ if (index === 0) return "start";
521
+ return index === length - 1 ? "end" : "middle";
242
522
  }
523
+ /** The closed value set for one key, or `undefined` when the key is unknown. */
243
524
  function vocabularyOf(name, key) {
244
- return DIRECTIVE_VOCABULARY[name]?.[key];
525
+ return DIRECTIVE_VOCABULARY[name]?.[key];
245
526
  }
246
527
  function accepts(name, key, value) {
247
- const values = vocabularyOf(name, key);
248
- if (values === void 0) return false;
249
- return values === null || values.includes(value);
528
+ const values = vocabularyOf(name, key);
529
+ if (values === void 0) return false;
530
+ return values === null || values.includes(value);
250
531
  }
532
+ /**
533
+ * The nodes one style directive reaches, as indexes into its own parent's
534
+ * children — never outside that array, so a directive inside a blockquote or a
535
+ * list item cannot stamp past it.
536
+ *
537
+ * Position picks the target (the next sibling element); the name picks how far
538
+ * the stamp goes. `section` before a heading takes the heading and every
539
+ * following sibling until the first heading of the same or shallower depth;
540
+ * `section` before anything else degrades to that one block, and `block` is
541
+ * always that one block. A heading nested inside a stamped `blockquote` or
542
+ * `li` does not end the section: the walk never descends.
543
+ */
251
544
  function styleRange(children, targetIndex, name) {
252
- const range = [targetIndex];
253
- const depth = name === "section" ? headingDepth(children[targetIndex]) : void 0;
254
- if (depth === void 0) return range;
255
- for (let i = targetIndex + 1; i < children.length; i++) {
256
- const node = children[i];
257
- const nodeDepth = headingDepth(node);
258
- if (nodeDepth !== void 0 && nodeDepth <= depth) break;
259
- if (node.type === "element" && STYLE_TARGET_TAGS.has(node.tagName)) {
260
- range.push(i);
261
- }
262
- }
263
- return range;
545
+ const range = [targetIndex];
546
+ const depth = name === "section" ? headingDepth(children[targetIndex]) : void 0;
547
+ if (depth === void 0) return range;
548
+ for (let i = targetIndex + 1; i < children.length; i++) {
549
+ const node = children[i];
550
+ const nodeDepth = headingDepth(node);
551
+ if (nodeDepth !== void 0 && nodeDepth <= depth) break;
552
+ if (node.type === "element" && STYLE_TARGET_TAGS.has(node.tagName)) range.push(i);
553
+ }
554
+ return range;
264
555
  }
556
+ /**
557
+ * Whether this directive collapses its section — three ways to say no.
558
+ *
559
+ * `collapsed=false` stamps nothing: it is the default written down, and "not
560
+ * collapsed" is not a thing an attribute can usefully say. Its only effect is
561
+ * upstream of here — `stampRun` merges a run of comments last-key-wins, so a
562
+ * `false` cancels a `true` in the *same* run. It does not cancel an *enclosing*
563
+ * section: `styleRange` walks the outer heading's whole sibling span before any
564
+ * inner directive is resolved, and a nested heading being a hidden member of the
565
+ * outer group is the design (A3), not an oversight.
566
+ *
567
+ * A `block` scope is **dropped**, and so is a `section` that degraded onto
568
+ * a non-heading, because both would hide a lone paragraph with nothing left
569
+ * behind to reveal it — content that is simply gone, which is the P1/D8 failure
570
+ * the readiness gate exists to prevent. Only a heading can be a summary.
571
+ */
265
572
  function collapsesSection(name, pairs, target) {
266
- if (name !== "section") return false;
267
- if (pairs.get("collapsed") !== "true") return false;
268
- return headingDepth(target) !== void 0;
573
+ if (name !== "section") return false;
574
+ if (pairs.get("collapsed") !== "true") return false;
575
+ return headingDepth(target) !== void 0;
269
576
  }
270
577
  function stampStyle(children, targetIndex, name, pairs, state) {
271
- const target = children[targetIndex];
272
- if (!STYLE_TARGET_TAGS.has(target.tagName)) return;
273
- const rangeStamps = [];
274
- const targetStamps = [];
275
- for (const [key, value] of pairs) {
276
- if (!accepts(name, key, value)) continue;
277
- const rangeProperty = RANGE_PROPERTIES.get(key);
278
- if (rangeProperty !== void 0) {
279
- rangeStamps.push([rangeProperty, value]);
280
- continue;
281
- }
282
- const pointProperty = POINT_PROPERTIES.get(key);
283
- if (pointProperty !== void 0) targetStamps.push([pointProperty, value]);
284
- }
285
- const collapses = collapsesSection(name, pairs, target);
286
- if (rangeStamps.length === 0 && targetStamps.length === 0 && !collapses) {
287
- return;
288
- }
289
- const range = styleRange(children, targetIndex, name);
290
- const group = collapses && range.length > 1 ? String(state.nextGroup++) : void 0;
291
- for (let i = 0; i < range.length; i++) {
292
- const element = children[range[i]];
293
- for (const [property, value] of rangeStamps) {
294
- setProperty(element, property, value);
295
- }
296
- if (i === 0) {
297
- for (const [property, value] of targetStamps) {
298
- setProperty(element, property, value);
299
- }
300
- }
301
- if (rangeStamps.length > 0) {
302
- setProperty(element, RUN_PROPERTY, runValue(i, range.length));
303
- }
304
- if (group === void 0) continue;
305
- if (i === 0) {
306
- setProperty(element, COLLAPSE_TOGGLE_PROPERTY, group);
307
- } else {
308
- setProperty(element, COLLAPSED_PROPERTY, "true");
309
- setProperty(element, COLLAPSE_GROUP_PROPERTY, group);
310
- }
311
- }
578
+ const target = children[targetIndex];
579
+ if (!STYLE_TARGET_TAGS.has(target.tagName)) return;
580
+ const rangeStamps = [];
581
+ const targetStamps = [];
582
+ for (const [key, value] of pairs) {
583
+ if (!accepts(name, key, value)) continue;
584
+ const rangeProperty = RANGE_PROPERTIES.get(key);
585
+ if (rangeProperty !== void 0) {
586
+ rangeStamps.push([rangeProperty, value]);
587
+ continue;
588
+ }
589
+ const pointProperty = POINT_PROPERTIES.get(key);
590
+ if (pointProperty !== void 0) targetStamps.push([pointProperty, value]);
591
+ }
592
+ const collapses = collapsesSection(name, pairs, target);
593
+ if (rangeStamps.length === 0 && targetStamps.length === 0 && !collapses) return;
594
+ const range = styleRange(children, targetIndex, name);
595
+ const group = collapses && range.length > 1 ? String(state.nextGroup++) : void 0;
596
+ for (let i = 0; i < range.length; i++) {
597
+ const element = children[range[i]];
598
+ for (const [property, value] of rangeStamps) setProperty(element, property, value);
599
+ if (i === 0) for (const [property, value] of targetStamps) setProperty(element, property, value);
600
+ if (rangeStamps.length > 0) setProperty(element, RUN_PROPERTY, runValue(i, range.length));
601
+ if (group === void 0) continue;
602
+ if (i === 0) setProperty(element, COLLAPSE_TOGGLE_PROPERTY, group);
603
+ else {
604
+ setProperty(element, COLLAPSED_PROPERTY, "true");
605
+ setProperty(element, COLLAPSE_GROUP_PROPERTY, group);
606
+ }
607
+ }
312
608
  }
313
609
  function stampOq(target, pairs) {
314
- setProperty(target, OQ_PROPERTY, "true");
315
- const leaning = pairs.get("leaning");
316
- if (leaning === void 0) return;
317
- const text = leaning.replace(/\s+/g, " ").trim().slice(0, MAX_LEANING);
318
- if (text !== "") setProperty(target, LEANING_PROPERTY, text);
610
+ setProperty(target, OQ_PROPERTY, "true");
611
+ const leaning = pairs.get("leaning");
612
+ if (leaning === void 0) return;
613
+ const text = leaning.replace(/\s+/g, " ").trim().slice(0, MAX_LEANING);
614
+ if (text !== "") setProperty(target, LEANING_PROPERTY, text);
319
615
  }
616
+ /**
617
+ * Merge one run of directives onto one target, then stamp.
618
+ *
619
+ * Merging is defined on the tree, not on the source: every directive comment up
620
+ * to the target merges, last-key-wins, whether or not blank lines separate
621
+ * them. Measured — adjacent comments and comments separated by a blank line
622
+ * produce byte-identical trees, so a rule that told them apart would have to
623
+ * re-read line numbers to do it.
624
+ */
320
625
  function stampRun(children, targetIndex, run, state) {
321
- const target = children[targetIndex];
322
- const style = /* @__PURE__ */ new Map();
323
- const oq = /* @__PURE__ */ new Map();
324
- let styleName;
325
- let hasOq = false;
326
- for (const directive of run) {
327
- if (directive.name === "section" || directive.name === "block") {
328
- styleName = directive.name;
329
- for (const pair of directive.pairs) style.set(pair.key, pair.value);
330
- } else if (directive.name === "oq") {
331
- hasOq = true;
332
- for (const pair of directive.pairs) oq.set(pair.key, pair.value);
333
- }
334
- }
335
- if (styleName !== void 0) {
336
- stampStyle(children, targetIndex, styleName, style, state);
337
- }
338
- if (hasOq && ANCHOR_TARGET_TAGS.has(target.tagName)) {
339
- stampOq(target, oq);
340
- }
626
+ const target = children[targetIndex];
627
+ const style = /* @__PURE__ */ new Map();
628
+ const oq = /* @__PURE__ */ new Map();
629
+ let styleName;
630
+ let hasOq = false;
631
+ for (const directive of run) if (directive.name === "section" || directive.name === "block") {
632
+ styleName = directive.name;
633
+ for (const pair of directive.pairs) style.set(pair.key, pair.value);
634
+ } else if (directive.name === "oq") {
635
+ hasOq = true;
636
+ for (const pair of directive.pairs) oq.set(pair.key, pair.value);
637
+ }
638
+ if (styleName !== void 0) stampStyle(children, targetIndex, styleName, style, state);
639
+ if (hasOq && ANCHOR_TARGET_TAGS.has(target.tagName)) stampOq(target, oq);
341
640
  }
641
+ /** A directive comment, or `undefined` for anything else — malformed included. */
342
642
  function directiveOf(node) {
343
- if (node.type !== "comment") return void 0;
344
- const parsed = parseVantageDirective(node.value);
345
- return parsed !== null && parsed.kind === "directive" ? parsed : void 0;
643
+ if (node.type !== "comment") return void 0;
644
+ const parsed = parseVantageDirective(node.value);
645
+ return parsed !== null && parsed.kind === "directive" ? parsed : void 0;
346
646
  }
647
+ /**
648
+ * One left-to-right pass over a parent's children, recursing into elements.
649
+ *
650
+ * The whole tree, not just the root: `rehype-raw` leaves comment nodes inside
651
+ * `blockquote`, inside `li`, inside `td` and inline inside `p`, and the real
652
+ * Open Questions layout puts the `oq` directive inside a list item — so a
653
+ * root-only walk finds none of them.
654
+ *
655
+ * Pass order is also what resolves a nested section: an inner heading's
656
+ * directive necessarily sits at a higher child index than the outer directive
657
+ * that ranged over it, so each property is simply last-write-wins.
658
+ */
347
659
  function processChildren(parent, state) {
348
- const children = parent.children;
349
- let i = 0;
350
- while (i < children.length) {
351
- const node = children[i];
352
- if (node.type === "element") {
353
- processChildren(node, state);
354
- i++;
355
- continue;
356
- }
357
- const first = directiveOf(node);
358
- if (first === void 0) {
359
- i++;
360
- continue;
361
- }
362
- const run = [first];
363
- let j = i + 1;
364
- let targetIndex = -1;
365
- for (; j < children.length; j++) {
366
- const next = children[j];
367
- if (next.type === "element") {
368
- targetIndex = j;
369
- break;
370
- }
371
- if (!isSkippable(next)) break;
372
- const directive = directiveOf(next);
373
- if (directive !== void 0) run.push(directive);
374
- }
375
- if (targetIndex >= 0) stampRun(children, targetIndex, run, state);
376
- i = j;
377
- }
660
+ const children = parent.children;
661
+ let i = 0;
662
+ while (i < children.length) {
663
+ const node = children[i];
664
+ if (node.type === "element") {
665
+ processChildren(node, state);
666
+ i++;
667
+ continue;
668
+ }
669
+ const first = directiveOf(node);
670
+ if (first === void 0) {
671
+ i++;
672
+ continue;
673
+ }
674
+ const run = [first];
675
+ let j = i + 1;
676
+ let targetIndex = -1;
677
+ for (; j < children.length; j++) {
678
+ const next = children[j];
679
+ if (next.type === "element") {
680
+ targetIndex = j;
681
+ break;
682
+ }
683
+ if (!isSkippable(next)) break;
684
+ const directive = directiveOf(next);
685
+ if (directive !== void 0) run.push(directive);
686
+ }
687
+ if (targetIndex >= 0) stampRun(children, targetIndex, run, state);
688
+ i = j;
689
+ }
378
690
  }
379
- var rehypeVantageDirectives = () => {
380
- return (tree) => {
381
- processChildren(tree, { nextGroup: 1 });
382
- };
691
+ const rehypeVantageDirectives = () => {
692
+ return (tree) => {
693
+ processChildren(tree, { nextGroup: 1 });
694
+ };
383
695
  };
384
- var rehypeVantageDirectives_default = rehypeVantageDirectives;
385
-
386
- // src/rehypeVantageMathStamps.ts
387
- var CARRIED_KEY = "vantageDisplayMathStamps";
696
+ //#endregion
697
+ //#region src/rehypeVantageMathStamps.ts
698
+ /**
699
+ * Where the snapshot lives between the two halves.
700
+ *
701
+ * `file.data` rather than a closure or a module-level map: `buildPipeline` is
702
+ * allowed to be built once and run over many documents, and per-file state is
703
+ * the only kind that cannot leak from one of those to the next.
704
+ */
705
+ const CARRIED_KEY = "vantageDisplayMathStamps";
388
706
  function classNames(node) {
389
- const value = node.properties?.className;
390
- return Array.isArray(value) ? value.map(String) : [];
707
+ const value = node.properties?.className;
708
+ return Array.isArray(value) ? value.map(String) : [];
391
709
  }
710
+ /**
711
+ * A `<pre>` `rehype-katex` will replace — its own condition, restated.
712
+ *
713
+ * `language-math` is the only class to test: `rehype-katex` keys the
714
+ * pre-as-scope branch on it, and the sanitiser strips the `math-display` that
715
+ * `remark-math` also emits (measured — a stamped fence arrives here with
716
+ * `className: ["language-math"]` alone).
717
+ */
392
718
  function isDisplayMath(node) {
393
- if (node.type !== "element" || node.tagName !== "pre") return false;
394
- return node.children.some(
395
- (child) => child.type === "element" && child.tagName === "code" && classNames(child).includes("language-math")
396
- );
719
+ if (node.type !== "element" || node.tagName !== "pre") return false;
720
+ return node.children.some((child) => child.type === "element" && child.tagName === "code" && classNames(child).includes("language-math"));
397
721
  }
722
+ /**
723
+ * What is worth carrying: everything this pipeline stamped itself.
724
+ *
725
+ * Deliberately not the whole property bag. `className`, `style` and `id` belong
726
+ * to the element KaTeX is about to build, and copying a `<pre>`'s onto a
727
+ * `<span class="katex-display">` would fight it.
728
+ */
398
729
  function carriedProperties(properties) {
399
- const carried = {};
400
- for (const [key, value] of Object.entries(properties ?? {})) {
401
- if (key === "dataSourceLine" || key.startsWith("dataVantage")) {
402
- carried[key] = value;
403
- }
404
- }
405
- return carried;
730
+ const carried = {};
731
+ for (const [key, value] of Object.entries(properties ?? {})) if (key === "dataSourceLine" || key.startsWith("dataVantage")) carried[key] = value;
732
+ return carried;
406
733
  }
407
734
  function collect(parent, out) {
408
- const children = parent.children;
409
- for (let i = 0; i < children.length; i++) {
410
- const node = children[i];
411
- if (node.type !== "element") continue;
412
- if (isDisplayMath(node)) {
413
- const properties = carriedProperties(node.properties);
414
- if (Object.keys(properties).length > 0) {
415
- out.push({
416
- parent,
417
- anchor: i === 0 ? void 0 : children[i - 1],
418
- properties
419
- });
420
- }
421
- continue;
422
- }
423
- collect(node, out);
424
- }
735
+ const children = parent.children;
736
+ for (let i = 0; i < children.length; i++) {
737
+ const node = children[i];
738
+ if (node.type !== "element") continue;
739
+ if (isDisplayMath(node)) {
740
+ const properties = carriedProperties(node.properties);
741
+ if (Object.keys(properties).length > 0) out.push({
742
+ parent,
743
+ anchor: i === 0 ? void 0 : children[i - 1],
744
+ properties
745
+ });
746
+ continue;
747
+ }
748
+ collect(node, out);
749
+ }
425
750
  }
426
751
  function reapply(carried) {
427
- for (const { parent, anchor, properties } of carried) {
428
- const siblings = parent.children;
429
- let index = 0;
430
- if (anchor !== void 0) {
431
- const at = siblings.indexOf(anchor);
432
- if (at === -1) continue;
433
- index = at + 1;
434
- }
435
- const replacement = siblings[index];
436
- if (replacement === void 0 || replacement.type !== "element") continue;
437
- if (!classNames(replacement).some((name) => name.startsWith("katex"))) {
438
- continue;
439
- }
440
- replacement.properties ??= {};
441
- for (const [key, value] of Object.entries(properties)) {
442
- replacement.properties[key] ??= value;
443
- }
444
- }
752
+ for (const { parent, anchor, properties } of carried) {
753
+ const siblings = parent.children;
754
+ let index = 0;
755
+ if (anchor !== void 0) {
756
+ const at = siblings.indexOf(anchor);
757
+ if (at === -1) continue;
758
+ index = at + 1;
759
+ }
760
+ const replacement = siblings[index];
761
+ if (replacement === void 0 || replacement.type !== "element") continue;
762
+ if (!classNames(replacement).some((name) => name.startsWith("katex"))) continue;
763
+ replacement.properties ??= {};
764
+ for (const [key, value] of Object.entries(properties)) replacement.properties[key] ??= value;
765
+ }
445
766
  }
446
- var rehypeCaptureMathStamps = () => {
447
- return (tree, file) => {
448
- const carried = [];
449
- collect(tree, carried);
450
- file.data[CARRIED_KEY] = carried;
451
- };
767
+ /** Snapshot every stamped display-math block. Register before `rehypeKatex`. */
768
+ const rehypeCaptureMathStamps = () => {
769
+ return (tree, file) => {
770
+ const carried = [];
771
+ collect(tree, carried);
772
+ file.data[CARRIED_KEY] = carried;
773
+ };
452
774
  };
453
- var rehypeRestoreMathStamps = () => {
454
- return (_tree, file) => {
455
- const carried = file.data[CARRIED_KEY];
456
- delete file.data[CARRIED_KEY];
457
- if (Array.isArray(carried)) reapply(carried);
458
- };
775
+ /** Re-apply the snapshot. Register immediately after `rehypeKatex`. */
776
+ const rehypeRestoreMathStamps = () => {
777
+ return (_tree, file) => {
778
+ const carried = file.data[CARRIED_KEY];
779
+ delete file.data[CARRIED_KEY];
780
+ if (Array.isArray(carried)) reapply(carried);
781
+ };
459
782
  };
460
- var SAFE_STYLE_PROPERTIES = [
461
- // Box metrics. `top`/`right`/`bottom`/`left` are inert now that `position` is
462
- // banned, and they stay only because dropping them would fail the whole
463
- // attribute for a document that writes one — the all-or-nothing rule below
464
- // makes every removal a behaviour change. They buy an attacker nothing that
465
- // negative `margin` does not already buy.
466
- "height",
467
- "min-height",
468
- "max-height",
469
- "width",
470
- "min-width",
471
- "max-width",
472
- "top",
473
- "bottom",
474
- "left",
475
- "right",
476
- "margin",
477
- "margin-top",
478
- "margin-right",
479
- "margin-bottom",
480
- "margin-left",
481
- "padding",
482
- "padding-top",
483
- "padding-right",
484
- "padding-bottom",
485
- "padding-left",
486
- // Rules and boxes.
487
- "border",
488
- "border-style",
489
- "border-color",
490
- "border-width",
491
- "border-top-width",
492
- "border-right-width",
493
- "border-bottom-width",
494
- "border-left-width",
495
- "border-top-style",
496
- "border-right-style",
497
- "border-bottom-style",
498
- "border-left-style",
499
- "border-top-color",
500
- "border-right-color",
501
- "border-bottom-color",
502
- "border-left-color",
503
- "border-radius",
504
- // Typography.
505
- "color",
506
- "background-color",
507
- "font",
508
- "font-size",
509
- "font-style",
510
- "font-weight",
511
- "font-family",
512
- "font-variant",
513
- "line-height",
514
- "letter-spacing",
515
- "word-spacing",
516
- "text-align",
517
- "text-decoration",
518
- "text-indent",
519
- "white-space",
520
- "vertical-align",
521
- "list-style-type",
522
- // Flow.
523
- "display",
524
- "float",
525
- "clear",
526
- "opacity",
527
- "overflow"
528
- ];
529
- var VALUE = `[^;:()"'\\\\]*`;
530
- var DECLARATION = `(?:(?:${SAFE_STYLE_PROPERTIES.join("|")})\\s*:${VALUE})`;
531
- var SAFE_STYLE = new RegExp(
532
- `^\\s*(?:${DECLARATION};\\s*)*${DECLARATION}?$`,
533
- "i"
534
- );
535
- var COLLAPSE_GROUP_ID = /^[0-9]+$/;
536
- var sanitizeSchema = {
537
- ...defaultSchema,
538
- tagNames: [
539
- ...defaultSchema.tagNames || [],
540
- // KaTeX MathML elements
541
- "math",
542
- "semantics",
543
- "mrow",
544
- "mi",
545
- "mo",
546
- "mn",
547
- "msup",
548
- "msub",
549
- "mfrac",
550
- "mover",
551
- "munder",
552
- "msqrt",
553
- "mroot",
554
- "mtable",
555
- "mtr",
556
- "mtd",
557
- "mtext",
558
- "mspace",
559
- "annotation",
560
- // Other
561
- "figure",
562
- "figcaption",
563
- "summary",
564
- "details"
565
- ],
566
- attributes: {
567
- ...defaultSchema.attributes,
568
- "*": [
569
- ...defaultSchema.attributes?.["*"] || [],
570
- "className",
571
- ["style", SAFE_STYLE],
572
- "dataSourceLine",
573
- // What `rehypeVantageDirectives` compiles a `<!-- vantage: … -->` comment
574
- // into, named individually — never by a `data-vantage-*` wildcard, which
575
- // would readmit whatever a future bug emits and whatever a document
576
- // hand-writes as raw HTML.
577
- //
578
- // The value lists are the belt to the plugin's braces: the vocabulary is
579
- // closed in the plugin *and* here, imported from the one module that
580
- // defines it, so even if a refactor let an unvalidated value reach the
581
- // tree the sanitiser still refuses it.
582
- ["dataVantageTone", ...VANTAGE_TONES],
583
- ["dataVantageEmphasis", ...VANTAGE_EMPHASIS],
584
- ["dataVantageBadge", ...VANTAGE_BADGES],
585
- ["dataVantageCollapsed", ...VANTAGE_COLLAPSED],
586
- // The other half of `collapsed`: which group a hidden block belongs to,
587
- // and which group a heading toggles. Both are plugin-minted counters with
588
- // no vocabulary to allowlist, so they take a pattern instead —
589
- // `hast-util-sanitize` accepts a `RegExp` in place of a literal value.
590
- // A pattern rather than a bare name because the JS interpolates the value
591
- // into a selector: anything but digits has no business reaching it.
592
- ["dataVantageCollapseGroup", COLLAPSE_GROUP_ID],
593
- ["dataVantageCollapseToggle", COLLAPSE_GROUP_ID],
594
- ["dataVantageRun", ...VANTAGE_RUNS],
595
- ["dataVantageOq", "true"],
596
- // The design's one genuinely free-text value: the body of a review
597
- // comment, so it cannot be value-allowlisted and this entry is name-only.
598
- // Two defences remain rather than three — `hast` escapes the value on
599
- // serialisation and React sets it through the DOM property path, so it
600
- // cannot break out of the attribute — and the honest record of that is in
601
- // the design doc rather than a third layer implied here.
602
- "dataVantageLeaning"
603
- ],
604
- code: [...defaultSchema.attributes?.code || [], "className"],
605
- span: [
606
- ...defaultSchema.attributes?.span || [],
607
- "className",
608
- ["style", SAFE_STYLE]
609
- ],
610
- div: [
611
- ...defaultSchema.attributes?.div || [],
612
- "className",
613
- ["style", SAFE_STYLE]
614
- ],
615
- a: [...defaultSchema.attributes?.a || [], "id", "className"],
616
- math: ["xmlns"],
617
- annotation: ["encoding"],
618
- img: [...defaultSchema.attributes?.img || [], "loading"],
619
- td: [...defaultSchema.attributes?.td || [], ["style", SAFE_STYLE]],
620
- th: [...defaultSchema.attributes?.th || [], ["style", SAFE_STYLE]]
621
- }
783
+ //#endregion
784
+ //#region src/sanitize.ts
785
+ /**
786
+ * Sanitization schema for the rendering pipeline.
787
+ * Allows GFM, KaTeX MathML, syntax highlighting classes, and
788
+ * data-source-line attributes while blocking XSS vectors.
789
+ */
790
+ const DECLARATION = `(?:(?:${[
791
+ "height",
792
+ "min-height",
793
+ "max-height",
794
+ "width",
795
+ "min-width",
796
+ "max-width",
797
+ "top",
798
+ "bottom",
799
+ "left",
800
+ "right",
801
+ "margin",
802
+ "margin-top",
803
+ "margin-right",
804
+ "margin-bottom",
805
+ "margin-left",
806
+ "padding",
807
+ "padding-top",
808
+ "padding-right",
809
+ "padding-bottom",
810
+ "padding-left",
811
+ "border",
812
+ "border-style",
813
+ "border-color",
814
+ "border-width",
815
+ "border-top-width",
816
+ "border-right-width",
817
+ "border-bottom-width",
818
+ "border-left-width",
819
+ "border-top-style",
820
+ "border-right-style",
821
+ "border-bottom-style",
822
+ "border-left-style",
823
+ "border-top-color",
824
+ "border-right-color",
825
+ "border-bottom-color",
826
+ "border-left-color",
827
+ "border-radius",
828
+ "color",
829
+ "background-color",
830
+ "font",
831
+ "font-size",
832
+ "font-style",
833
+ "font-weight",
834
+ "font-family",
835
+ "font-variant",
836
+ "line-height",
837
+ "letter-spacing",
838
+ "word-spacing",
839
+ "text-align",
840
+ "text-decoration",
841
+ "text-indent",
842
+ "white-space",
843
+ "vertical-align",
844
+ "list-style-type",
845
+ "display",
846
+ "float",
847
+ "clear",
848
+ "opacity",
849
+ "overflow"
850
+ ].join("|")})\\s*:[^;:()"'\\\\]*)`;
851
+ const SAFE_STYLE = new RegExp(`^\\s*(?:${DECLARATION};\\s*)*${DECLARATION}?$`, "i");
852
+ /**
853
+ * A collapse group id: one or more digits, anchored.
854
+ *
855
+ * The plugin mints these as a per-document counter, so there is no vocabulary to
856
+ * list. Keeping the shape narrow matters anyway — the toggle JS builds a
857
+ * `[data-vantage-collapse-group="…"]` selector out of the value, and a document
858
+ * that hand-wrote raw HTML is the only way a non-numeric one could ever appear.
859
+ */
860
+ const COLLAPSE_GROUP_ID = /^[0-9]+$/;
861
+ /**
862
+ * Never set `allowComments` here.
863
+ *
864
+ * `hast-util-sanitize` drops comment nodes because that boolean defaults to
865
+ * `false` — comments are not elements, so `tagNames` has nothing to do with it.
866
+ * `rehypeVantageDirectives` relies on that deletion: it consumes a
867
+ * `<!-- vantage: … -->` comment into attributes and deliberately leaves the node
868
+ * for the sanitiser. Turning the switch on readmits every directive comment —
869
+ * valid and malformed alike — into the rendered HTML, which breaks the carrier's
870
+ * whole premise. `vantageDirectives.test.ts` ("leaves no comment in the rendered
871
+ * markup") is the guard.
872
+ */
873
+ const sanitizeSchema = {
874
+ ...defaultSchema,
875
+ tagNames: [
876
+ ...defaultSchema.tagNames || [],
877
+ "math",
878
+ "semantics",
879
+ "mrow",
880
+ "mi",
881
+ "mo",
882
+ "mn",
883
+ "msup",
884
+ "msub",
885
+ "mfrac",
886
+ "mover",
887
+ "munder",
888
+ "msqrt",
889
+ "mroot",
890
+ "mtable",
891
+ "mtr",
892
+ "mtd",
893
+ "mtext",
894
+ "mspace",
895
+ "annotation",
896
+ "figure",
897
+ "figcaption",
898
+ "summary",
899
+ "details"
900
+ ],
901
+ attributes: {
902
+ ...defaultSchema.attributes,
903
+ "*": [
904
+ ...defaultSchema.attributes?.["*"] || [],
905
+ "className",
906
+ ["style", SAFE_STYLE],
907
+ "dataSourceLine",
908
+ ["dataVantageTone", ...VANTAGE_TONES],
909
+ ["dataVantageEmphasis", ...VANTAGE_EMPHASIS],
910
+ ["dataVantageBadge", ...VANTAGE_BADGES],
911
+ ["dataVantageCollapsed", ...VANTAGE_COLLAPSED],
912
+ ["dataVantageCollapseGroup", COLLAPSE_GROUP_ID],
913
+ ["dataVantageCollapseToggle", COLLAPSE_GROUP_ID],
914
+ ["dataVantageRun", ...VANTAGE_RUNS],
915
+ ["dataVantageOq", "true"],
916
+ ["dataVantageAlert", ...VANTAGE_ALERTS],
917
+ "dataVantageLeaning"
918
+ ],
919
+ code: [...defaultSchema.attributes?.code || [], "className"],
920
+ span: [
921
+ ...defaultSchema.attributes?.span || [],
922
+ "className",
923
+ ["style", SAFE_STYLE]
924
+ ],
925
+ div: [
926
+ ...defaultSchema.attributes?.div || [],
927
+ "className",
928
+ ["style", SAFE_STYLE]
929
+ ],
930
+ a: [
931
+ ...defaultSchema.attributes?.a || [],
932
+ "id",
933
+ "className"
934
+ ],
935
+ math: ["xmlns"],
936
+ annotation: ["encoding"],
937
+ img: [...defaultSchema.attributes?.img || [], "loading"],
938
+ td: [...defaultSchema.attributes?.td || [], ["style", SAFE_STYLE]],
939
+ th: [...defaultSchema.attributes?.th || [], ["style", SAFE_STYLE]]
940
+ }
622
941
  };
623
-
624
- // src/pipeline.ts
942
+ //#endregion
943
+ //#region src/pipeline.ts
944
+ /**
945
+ * The mdast half of the chain. Exported on its own because there is a real
946
+ * mdast-only consumer: the CLI checker parses documents without ever running
947
+ * rehype (`packages/vantage-check/src/core/document.ts`), and it has to parse
948
+ * them exactly the way the viewer does.
949
+ */
625
950
  function buildRemarkPlugins(options = {}) {
626
- const { gfm = true, math = true } = options;
627
- const plugins = [];
628
- if (gfm) plugins.push([remarkGfm, { singleTilde: false }]);
629
- if (math) plugins.push([remarkMath, { singleDollarTextMath: false }]);
630
- return plugins;
951
+ const { gfm = true, math = true } = options;
952
+ const plugins = [];
953
+ if (gfm) plugins.push([remarkGfm, { singleTilde: false }]);
954
+ if (math) plugins.push([remarkMath, { singleDollarTextMath: false }]);
955
+ return plugins;
631
956
  }
957
+ /** The hast half. Deliberately not exported: see `buildPipeline`. */
632
958
  function buildRehypePlugins(options = {}) {
633
- const {
634
- math = true,
635
- highlight = true,
636
- sourceLines = true,
637
- sanitize = true,
638
- bodyLineOffset = 0
639
- } = options;
640
- const plugins = [rehypeRaw];
641
- if (sourceLines) {
642
- plugins.push([rehypeSourceLines_default, { offset: bodyLineOffset }]);
643
- }
644
- plugins.push(rehypeVantageDirectives_default);
645
- if (sanitize) plugins.push([rehypeSanitize, sanitizeSchema]);
646
- plugins.push(rehypeSlug);
647
- if (highlight) plugins.push(rehypeHighlight);
648
- if (math) {
649
- plugins.push(rehypeCaptureMathStamps, rehypeKatex, rehypeRestoreMathStamps);
650
- }
651
- return plugins;
959
+ const { math = true, highlight = true, sourceLines = true, sanitize = true, bodyLineOffset = 0 } = options;
960
+ const plugins = [rehypeRaw];
961
+ if (sourceLines) plugins.push([rehypeSourceLines, { offset: bodyLineOffset }]);
962
+ plugins.push(rehypeVantageAlerts);
963
+ plugins.push(rehypeVantageDirectives);
964
+ if (sanitize) plugins.push([rehypeSanitize, sanitizeSchema]);
965
+ plugins.push(rehypeSlug);
966
+ if (highlight) plugins.push(rehypeHighlight);
967
+ if (math) plugins.push(rehypeCaptureMathStamps, rehypeKatex, rehypeRestoreMathStamps);
968
+ return plugins;
652
969
  }
970
+ /**
971
+ * Both halves from one options object.
972
+ *
973
+ * This is what every renderer calls. It takes one object rather than exposing
974
+ * the two builders because `math` spans both halves — `remark-math` parses the
975
+ * delimiters, `rehype-katex` renders the result — and two calls are two places
976
+ * to forget the second one.
977
+ *
978
+ * Returns fresh arrays on every call and reads no module-level state; keep it
979
+ * that way, so a plugin in the chain cannot become a function of how many times
980
+ * the chain has been built.
981
+ */
653
982
  function buildPipeline(options = {}) {
654
- return {
655
- remarkPlugins: buildRemarkPlugins(options),
656
- rehypePlugins: buildRehypePlugins(options)
657
- };
983
+ return {
984
+ remarkPlugins: buildRemarkPlugins(options),
985
+ rehypePlugins: buildRehypePlugins(options)
986
+ };
658
987
  }
988
+ //#endregion
989
+ //#region src/frontmatter.ts
990
+ /**
991
+ * Frontmatter parser for YAML (---) and TOML (+++) delimited content.
992
+ * Works in both browser and server environments.
993
+ */
994
+ /**
995
+ * Parse frontmatter from markdown content.
996
+ * Supports YAML (delimited by ---) and TOML (delimited by +++).
997
+ */
659
998
  function parseFrontmatter(content) {
660
- if (content.startsWith("+++")) {
661
- return parseFrontmatterWithDelimiter(content, "+++", "toml");
662
- }
663
- if (content.startsWith("---")) {
664
- return parseFrontmatterWithDelimiter(content, "---", "yaml");
665
- }
666
- return withOffset(content, {
667
- frontmatter: {},
668
- body: content,
669
- format: "none"
670
- });
999
+ if (content.startsWith("+++")) return parseFrontmatterWithDelimiter(content, "+++", "toml");
1000
+ if (content.startsWith("---")) return parseFrontmatterWithDelimiter(content, "---", "yaml");
1001
+ return withOffset(content, {
1002
+ frontmatter: {},
1003
+ body: content,
1004
+ format: "none"
1005
+ });
671
1006
  }
1007
+ /**
1008
+ * Fill in `bodyLineOffset`. `body` is always a suffix of `content`, so the
1009
+ * newlines in the prefix that was stripped are exactly the shift — which also
1010
+ * accounts for the blank line consumed after the closing delimiter.
1011
+ */
672
1012
  function withOffset(content, parsed) {
673
- const stripped = content.slice(0, content.length - parsed.body.length);
674
- let bodyLineOffset = 0;
675
- for (const ch of stripped) {
676
- if (ch === "\n") bodyLineOffset++;
677
- }
678
- return { ...parsed, bodyLineOffset };
1013
+ const stripped = content.slice(0, content.length - parsed.body.length);
1014
+ let bodyLineOffset = 0;
1015
+ for (const ch of stripped) if (ch === "\n") bodyLineOffset++;
1016
+ return {
1017
+ ...parsed,
1018
+ bodyLineOffset
1019
+ };
679
1020
  }
680
1021
  function parseFrontmatterWithDelimiter(content, delimiter, format) {
681
- const searchStart = delimiter.length;
682
- const endIndex = content.indexOf(`
683
- ${delimiter}`, searchStart);
684
- if (endIndex === -1) {
685
- return withOffset(content, {
686
- frontmatter: {},
687
- body: content,
688
- format: "none",
689
- problem: { kind: "unterminated", delimiter }
690
- });
691
- }
692
- const raw = content.slice(searchStart + 1, endIndex).trim();
693
- const bodyStart = endIndex + 1 + delimiter.length;
694
- const body = content.slice(bodyStart).replace(/^\n/, "");
695
- try {
696
- const parsed = format === "toml" ? parse(raw) : YAML.parse(raw);
697
- return withOffset(content, {
698
- frontmatter: parsed || {},
699
- body,
700
- format,
701
- ...isMapping(parsed) ? {} : { problem: { kind: "not-a-mapping", delimiter } }
702
- });
703
- } catch (error) {
704
- return withOffset(content, {
705
- frontmatter: {},
706
- body: content,
707
- format: "none",
708
- problem: { kind: "invalid", delimiter, ...errorPosition(error) }
709
- });
710
- }
1022
+ const searchStart = delimiter.length;
1023
+ const endIndex = content.indexOf(`\n${delimiter}`, searchStart);
1024
+ if (endIndex === -1) return withOffset(content, {
1025
+ frontmatter: {},
1026
+ body: content,
1027
+ format: "none",
1028
+ problem: {
1029
+ kind: "unterminated",
1030
+ delimiter
1031
+ }
1032
+ });
1033
+ const raw = content.slice(searchStart + 1, endIndex).trim();
1034
+ const bodyStart = endIndex + 1 + delimiter.length;
1035
+ const body = content.slice(bodyStart).replace(/^\n/, "");
1036
+ try {
1037
+ const parsed = format === "toml" ? parse(raw) : YAML.parse(raw);
1038
+ return withOffset(content, {
1039
+ frontmatter: parsed || {},
1040
+ body,
1041
+ format,
1042
+ ...isMapping(parsed) ? {} : { problem: {
1043
+ kind: "not-a-mapping",
1044
+ delimiter
1045
+ } }
1046
+ });
1047
+ } catch (error) {
1048
+ return withOffset(content, {
1049
+ frontmatter: {},
1050
+ body: content,
1051
+ format: "none",
1052
+ problem: {
1053
+ kind: "invalid",
1054
+ delimiter,
1055
+ ...errorPosition(error)
1056
+ }
1057
+ });
1058
+ }
711
1059
  }
1060
+ /** Empty frontmatter is fine; a scalar or a list where a table belongs is not. */
712
1061
  function isMapping(value) {
713
- return value === null || value === void 0 || typeof value === "object" && !Array.isArray(value);
1062
+ return value === null || value === void 0 || typeof value === "object" && !Array.isArray(value);
714
1063
  }
1064
+ /**
1065
+ * Pull the parser's message and, where it gave one, the position inside the
1066
+ * frontmatter block. `yaml` reports `linePos`; `smol-toml` reports `line` and
1067
+ * `column`. Both are optional and both are read defensively — a missing
1068
+ * position costs a less precise report, a wrong assumption costs a crash.
1069
+ */
715
1070
  function errorPosition(error) {
716
- const message = error instanceof Error ? error.message : String(error);
717
- const source = error;
718
- const yamlPosition = source?.linePos?.[0];
719
- if (typeof yamlPosition?.line === "number") {
720
- return {
721
- message,
722
- line: yamlPosition.line,
723
- ...typeof yamlPosition.col === "number" ? { column: yamlPosition.col } : {}
724
- };
725
- }
726
- if (typeof source?.line === "number") {
727
- return {
728
- message,
729
- line: source.line,
730
- ...typeof source.column === "number" ? { column: source.column } : {}
731
- };
732
- }
733
- return { message };
1071
+ const message = error instanceof Error ? error.message : String(error);
1072
+ const source = error;
1073
+ const yamlPosition = source?.linePos?.[0];
1074
+ if (typeof yamlPosition?.line === "number") return {
1075
+ message,
1076
+ line: yamlPosition.line,
1077
+ ...typeof yamlPosition.col === "number" ? { column: yamlPosition.col } : {}
1078
+ };
1079
+ if (typeof source?.line === "number") return {
1080
+ message,
1081
+ line: source.line,
1082
+ ...typeof source.column === "number" ? { column: source.column } : {}
1083
+ };
1084
+ return { message };
734
1085
  }
735
-
736
- // src/mermaidCache.ts
737
- var svgCache = /* @__PURE__ */ new Map();
738
-
739
- // src/mermaidLoader.ts
740
- var mermaidInstance = null;
741
- var mermaidLoading = null;
742
- var isDark = () => typeof document !== "undefined" && document.documentElement.classList.contains("dark");
1086
+ //#endregion
1087
+ //#region src/mermaidCache.ts
1088
+ const svgCache = /* @__PURE__ */ new Map();
1089
+ //#endregion
1090
+ //#region src/mermaidLoader.ts
1091
+ let mermaidInstance = null;
1092
+ let mermaidLoading = null;
1093
+ const isDark = () => typeof document !== "undefined" && document.documentElement.classList.contains("dark");
743
1094
  async function getMermaid() {
744
- if (mermaidInstance) return mermaidInstance;
745
- if (!mermaidLoading) {
746
- mermaidLoading = import('mermaid').then((mod) => {
747
- const m = mod.default;
748
- m.initialize({
749
- startOnLoad: false,
750
- theme: isDark() ? "dark" : "default",
751
- securityLevel: "strict",
752
- suppressErrorRendering: true
753
- });
754
- mermaidInstance = m;
755
- return m;
756
- });
757
- }
758
- return mermaidLoading;
1095
+ if (mermaidInstance) return mermaidInstance;
1096
+ if (!mermaidLoading) mermaidLoading = import("mermaid").then((mod) => {
1097
+ const m = mod.default;
1098
+ m.initialize({
1099
+ startOnLoad: false,
1100
+ theme: isDark() ? "dark" : "default",
1101
+ securityLevel: "strict",
1102
+ suppressErrorRendering: true
1103
+ });
1104
+ mermaidInstance = m;
1105
+ return m;
1106
+ });
1107
+ return mermaidLoading;
759
1108
  }
760
- var AlertTriangleIcon = () => /* @__PURE__ */ jsxs(
761
- "svg",
762
- {
763
- width: "16",
764
- height: "16",
765
- viewBox: "0 0 24 24",
766
- fill: "none",
767
- stroke: "currentColor",
768
- strokeWidth: "2",
769
- strokeLinecap: "round",
770
- strokeLinejoin: "round",
771
- className: "w-4 h-4 shrink-0",
772
- children: [
773
- /* @__PURE__ */ jsx("path", { d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" }),
774
- /* @__PURE__ */ jsx("path", { d: "M12 9v4" }),
775
- /* @__PURE__ */ jsx("path", { d: "M12 17h.01" })
776
- ]
777
- }
778
- );
779
- var ChevronDownIcon = () => /* @__PURE__ */ jsx(
780
- "svg",
781
- {
782
- width: "12",
783
- height: "12",
784
- viewBox: "0 0 24 24",
785
- fill: "none",
786
- stroke: "currentColor",
787
- strokeWidth: "2",
788
- strokeLinecap: "round",
789
- strokeLinejoin: "round",
790
- className: "w-3 h-3",
791
- children: /* @__PURE__ */ jsx("path", { d: "m6 9 6 6 6-6" })
792
- }
793
- );
794
- var ChevronUpIcon = () => /* @__PURE__ */ jsx(
795
- "svg",
796
- {
797
- width: "12",
798
- height: "12",
799
- viewBox: "0 0 24 24",
800
- fill: "none",
801
- stroke: "currentColor",
802
- strokeWidth: "2",
803
- strokeLinecap: "round",
804
- strokeLinejoin: "round",
805
- className: "w-3 h-3",
806
- children: /* @__PURE__ */ jsx("path", { d: "m18 15-6-6-6 6" })
807
- }
808
- );
809
- var MaximizeIcon = () => /* @__PURE__ */ jsxs(
810
- "svg",
811
- {
812
- width: "16",
813
- height: "16",
814
- viewBox: "0 0 24 24",
815
- fill: "none",
816
- stroke: "currentColor",
817
- strokeWidth: "2",
818
- strokeLinecap: "round",
819
- strokeLinejoin: "round",
820
- className: "w-4 h-4 text-gray-600",
821
- children: [
822
- /* @__PURE__ */ jsx("polyline", { points: "15 3 21 3 21 9" }),
823
- /* @__PURE__ */ jsx("polyline", { points: "9 21 3 21 3 15" }),
824
- /* @__PURE__ */ jsx("line", { x1: "21", x2: "14", y1: "3", y2: "10" }),
825
- /* @__PURE__ */ jsx("line", { x1: "3", x2: "10", y1: "21", y2: "14" })
826
- ]
827
- }
828
- );
829
- var CloseIcon = () => /* @__PURE__ */ jsxs(
830
- "svg",
831
- {
832
- width: "20",
833
- height: "20",
834
- viewBox: "0 0 24 24",
835
- fill: "none",
836
- stroke: "currentColor",
837
- strokeWidth: "2",
838
- strokeLinecap: "round",
839
- strokeLinejoin: "round",
840
- className: "w-5 h-5",
841
- children: [
842
- /* @__PURE__ */ jsx("path", { d: "M18 6 6 18" }),
843
- /* @__PURE__ */ jsx("path", { d: "m6 6 12 12" })
844
- ]
845
- }
846
- );
847
- var PlusIcon = () => /* @__PURE__ */ jsxs(
848
- "svg",
849
- {
850
- width: "16",
851
- height: "16",
852
- viewBox: "0 0 24 24",
853
- fill: "none",
854
- stroke: "currentColor",
855
- strokeWidth: "2",
856
- strokeLinecap: "round",
857
- strokeLinejoin: "round",
858
- className: "w-4 h-4",
859
- children: [
860
- /* @__PURE__ */ jsx("path", { d: "M5 12h14" }),
861
- /* @__PURE__ */ jsx("path", { d: "M12 5v14" })
862
- ]
863
- }
864
- );
865
- var MinusIcon = () => /* @__PURE__ */ jsx(
866
- "svg",
867
- {
868
- width: "16",
869
- height: "16",
870
- viewBox: "0 0 24 24",
871
- fill: "none",
872
- stroke: "currentColor",
873
- strokeWidth: "2",
874
- strokeLinecap: "round",
875
- strokeLinejoin: "round",
876
- className: "w-4 h-4",
877
- children: /* @__PURE__ */ jsx("path", { d: "M5 12h14" })
878
- }
879
- );
880
- var ResetIcon = () => /* @__PURE__ */ jsxs(
881
- "svg",
882
- {
883
- width: "16",
884
- height: "16",
885
- viewBox: "0 0 24 24",
886
- fill: "none",
887
- stroke: "currentColor",
888
- strokeWidth: "2",
889
- strokeLinecap: "round",
890
- strokeLinejoin: "round",
891
- className: "w-4 h-4",
892
- children: [
893
- /* @__PURE__ */ jsx("path", { d: "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" }),
894
- /* @__PURE__ */ jsx("path", { d: "M3 3v5h5" })
895
- ]
896
- }
897
- );
898
- var MIN_SCALE = 0.2;
899
- var MAX_SCALE = 8;
1109
+ //#endregion
1110
+ //#region src/MermaidDiagram.tsx
1111
+ const AlertTriangleIcon = () => /* @__PURE__ */ jsxs("svg", {
1112
+ width: "16",
1113
+ height: "16",
1114
+ viewBox: "0 0 24 24",
1115
+ fill: "none",
1116
+ stroke: "currentColor",
1117
+ strokeWidth: "2",
1118
+ strokeLinecap: "round",
1119
+ strokeLinejoin: "round",
1120
+ className: "w-4 h-4 shrink-0",
1121
+ children: [
1122
+ /* @__PURE__ */ jsx("path", { d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" }),
1123
+ /* @__PURE__ */ jsx("path", { d: "M12 9v4" }),
1124
+ /* @__PURE__ */ jsx("path", { d: "M12 17h.01" })
1125
+ ]
1126
+ });
1127
+ const ChevronDownIcon = () => /* @__PURE__ */ jsx("svg", {
1128
+ width: "12",
1129
+ height: "12",
1130
+ viewBox: "0 0 24 24",
1131
+ fill: "none",
1132
+ stroke: "currentColor",
1133
+ strokeWidth: "2",
1134
+ strokeLinecap: "round",
1135
+ strokeLinejoin: "round",
1136
+ className: "w-3 h-3",
1137
+ children: /* @__PURE__ */ jsx("path", { d: "m6 9 6 6 6-6" })
1138
+ });
1139
+ const ChevronUpIcon = () => /* @__PURE__ */ jsx("svg", {
1140
+ width: "12",
1141
+ height: "12",
1142
+ viewBox: "0 0 24 24",
1143
+ fill: "none",
1144
+ stroke: "currentColor",
1145
+ strokeWidth: "2",
1146
+ strokeLinecap: "round",
1147
+ strokeLinejoin: "round",
1148
+ className: "w-3 h-3",
1149
+ children: /* @__PURE__ */ jsx("path", { d: "m18 15-6-6-6 6" })
1150
+ });
1151
+ const MaximizeIcon = () => /* @__PURE__ */ jsxs("svg", {
1152
+ width: "16",
1153
+ height: "16",
1154
+ viewBox: "0 0 24 24",
1155
+ fill: "none",
1156
+ stroke: "currentColor",
1157
+ strokeWidth: "2",
1158
+ strokeLinecap: "round",
1159
+ strokeLinejoin: "round",
1160
+ className: "w-4 h-4 text-gray-600",
1161
+ children: [
1162
+ /* @__PURE__ */ jsx("polyline", { points: "15 3 21 3 21 9" }),
1163
+ /* @__PURE__ */ jsx("polyline", { points: "9 21 3 21 3 15" }),
1164
+ /* @__PURE__ */ jsx("line", {
1165
+ x1: "21",
1166
+ x2: "14",
1167
+ y1: "3",
1168
+ y2: "10"
1169
+ }),
1170
+ /* @__PURE__ */ jsx("line", {
1171
+ x1: "3",
1172
+ x2: "10",
1173
+ y1: "21",
1174
+ y2: "14"
1175
+ })
1176
+ ]
1177
+ });
1178
+ const CloseIcon = () => /* @__PURE__ */ jsxs("svg", {
1179
+ width: "20",
1180
+ height: "20",
1181
+ viewBox: "0 0 24 24",
1182
+ fill: "none",
1183
+ stroke: "currentColor",
1184
+ strokeWidth: "2",
1185
+ strokeLinecap: "round",
1186
+ strokeLinejoin: "round",
1187
+ className: "w-5 h-5",
1188
+ children: [/* @__PURE__ */ jsx("path", { d: "M18 6 6 18" }), /* @__PURE__ */ jsx("path", { d: "m6 6 12 12" })]
1189
+ });
1190
+ const PlusIcon = () => /* @__PURE__ */ jsxs("svg", {
1191
+ width: "16",
1192
+ height: "16",
1193
+ viewBox: "0 0 24 24",
1194
+ fill: "none",
1195
+ stroke: "currentColor",
1196
+ strokeWidth: "2",
1197
+ strokeLinecap: "round",
1198
+ strokeLinejoin: "round",
1199
+ className: "w-4 h-4",
1200
+ children: [/* @__PURE__ */ jsx("path", { d: "M5 12h14" }), /* @__PURE__ */ jsx("path", { d: "M12 5v14" })]
1201
+ });
1202
+ const MinusIcon = () => /* @__PURE__ */ jsx("svg", {
1203
+ width: "16",
1204
+ height: "16",
1205
+ viewBox: "0 0 24 24",
1206
+ fill: "none",
1207
+ stroke: "currentColor",
1208
+ strokeWidth: "2",
1209
+ strokeLinecap: "round",
1210
+ strokeLinejoin: "round",
1211
+ className: "w-4 h-4",
1212
+ children: /* @__PURE__ */ jsx("path", { d: "M5 12h14" })
1213
+ });
1214
+ const ResetIcon = () => /* @__PURE__ */ jsxs("svg", {
1215
+ width: "16",
1216
+ height: "16",
1217
+ viewBox: "0 0 24 24",
1218
+ fill: "none",
1219
+ stroke: "currentColor",
1220
+ strokeWidth: "2",
1221
+ strokeLinecap: "round",
1222
+ strokeLinejoin: "round",
1223
+ className: "w-4 h-4",
1224
+ children: [/* @__PURE__ */ jsx("path", { d: "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" }), /* @__PURE__ */ jsx("path", { d: "M3 3v5h5" })]
1225
+ });
1226
+ const MIN_SCALE = .2;
1227
+ const MAX_SCALE = 8;
1228
+ /**
1229
+ * Zoom + pan viewport for the maximized diagram. Wheel/buttons zoom (anchored
1230
+ * on the cursor), drag pans, double-click resets, and it fills whatever space
1231
+ * the modal gives it.
1232
+ */
900
1233
  function ZoomableSvg({ svg }) {
901
- const [scale, setScale] = useState(1);
902
- const [offset, setOffset] = useState({ x: 0, y: 0 });
903
- const dragRef = useRef(null);
904
- const [isDragging, setIsDragging] = useState(false);
905
- const viewportRef = useRef(null);
906
- const reset = useCallback(() => {
907
- setScale(1);
908
- setOffset({ x: 0, y: 0 });
909
- }, []);
910
- const zoomBy = useCallback(
911
- (factor, anchor) => {
912
- setScale((prev) => {
913
- const next = Math.min(MAX_SCALE, Math.max(MIN_SCALE, prev * factor));
914
- if (next === prev) return prev;
915
- const rect = viewportRef.current?.getBoundingClientRect();
916
- if (rect) {
917
- const ax = (anchor?.x ?? rect.width / 2) - rect.width / 2;
918
- const ay = (anchor?.y ?? rect.height / 2) - rect.height / 2;
919
- setOffset((o) => ({
920
- x: ax - (ax - o.x) * next / prev,
921
- y: ay - (ay - o.y) * next / prev
922
- }));
923
- }
924
- return next;
925
- });
926
- },
927
- []
928
- );
929
- const handleWheel = useCallback(
930
- (e) => {
931
- e.preventDefault();
932
- const rect = viewportRef.current?.getBoundingClientRect();
933
- const anchor = rect ? { x: e.clientX - rect.left, y: e.clientY - rect.top } : void 0;
934
- zoomBy(e.deltaY < 0 ? 1.15 : 1 / 1.15, anchor);
935
- },
936
- [zoomBy]
937
- );
938
- const handlePointerDown = (e) => {
939
- e.currentTarget.setPointerCapture(e.pointerId);
940
- dragRef.current = {
941
- startX: e.clientX,
942
- startY: e.clientY,
943
- originX: offset.x,
944
- originY: offset.y
945
- };
946
- setIsDragging(true);
947
- };
948
- const handlePointerMove = (e) => {
949
- const d = dragRef.current;
950
- if (!d) return;
951
- setOffset({
952
- x: d.originX + (e.clientX - d.startX),
953
- y: d.originY + (e.clientY - d.startY)
954
- });
955
- };
956
- const endDrag = (e) => {
957
- if (dragRef.current) {
958
- try {
959
- e.currentTarget.releasePointerCapture(e.pointerId);
960
- } catch {
961
- }
962
- }
963
- dragRef.current = null;
964
- setIsDragging(false);
965
- };
966
- return /* @__PURE__ */ jsxs("div", { className: "relative w-full h-full", children: [
967
- /* @__PURE__ */ jsx(
968
- "div",
969
- {
970
- ref: viewportRef,
971
- onWheel: handleWheel,
972
- onPointerDown: handlePointerDown,
973
- onPointerMove: handlePointerMove,
974
- onPointerUp: endDrag,
975
- onPointerLeave: endDrag,
976
- onDoubleClick: reset,
977
- className: "w-full h-full overflow-hidden touch-none select-none",
978
- style: { cursor: isDragging ? "grabbing" : "grab" },
979
- children: /* @__PURE__ */ jsx(
980
- "div",
981
- {
982
- className: "mermaid-zoom flex items-center justify-center w-full h-full",
983
- style: {
984
- transform: `translate(${offset.x}px, ${offset.y}px) scale(${scale})`,
985
- transformOrigin: "center center",
986
- transition: isDragging ? "none" : "transform 0.08s ease-out"
987
- },
988
- dangerouslySetInnerHTML: { __html: svg }
989
- }
990
- )
991
- }
992
- ),
993
- /* @__PURE__ */ jsxs("div", { className: "absolute bottom-4 right-4 flex items-center gap-1 rounded-lg bg-white/95 shadow-md border border-gray-200 px-1.5 py-1", children: [
994
- /* @__PURE__ */ jsx(
995
- "button",
996
- {
997
- onClick: () => zoomBy(1 / 1.3),
998
- className: "p-1.5 rounded hover:bg-gray-100 text-gray-600",
999
- "aria-label": "Zoom out",
1000
- title: "Zoom out",
1001
- children: /* @__PURE__ */ jsx(MinusIcon, {})
1002
- }
1003
- ),
1004
- /* @__PURE__ */ jsxs(
1005
- "button",
1006
- {
1007
- onClick: reset,
1008
- className: "px-2 py-1 text-xs font-medium rounded hover:bg-gray-100 text-gray-600 min-w-[3rem]",
1009
- title: "Reset zoom (or double-click)",
1010
- children: [
1011
- Math.round(scale * 100),
1012
- "%"
1013
- ]
1014
- }
1015
- ),
1016
- /* @__PURE__ */ jsx(
1017
- "button",
1018
- {
1019
- onClick: () => zoomBy(1.3),
1020
- className: "p-1.5 rounded hover:bg-gray-100 text-gray-600",
1021
- "aria-label": "Zoom in",
1022
- title: "Zoom in",
1023
- children: /* @__PURE__ */ jsx(PlusIcon, {})
1024
- }
1025
- ),
1026
- /* @__PURE__ */ jsx("div", { className: "w-px h-5 bg-gray-200 mx-0.5" }),
1027
- /* @__PURE__ */ jsx(
1028
- "button",
1029
- {
1030
- onClick: reset,
1031
- className: "p-1.5 rounded hover:bg-gray-100 text-gray-600",
1032
- "aria-label": "Reset view",
1033
- title: "Reset view",
1034
- children: /* @__PURE__ */ jsx(ResetIcon, {})
1035
- }
1036
- )
1037
- ] })
1038
- ] });
1234
+ const [scale, setScale] = useState(1);
1235
+ const [offset, setOffset] = useState({
1236
+ x: 0,
1237
+ y: 0
1238
+ });
1239
+ const dragRef = useRef(null);
1240
+ const [isDragging, setIsDragging] = useState(false);
1241
+ const viewportRef = useRef(null);
1242
+ const reset = useCallback(() => {
1243
+ setScale(1);
1244
+ setOffset({
1245
+ x: 0,
1246
+ y: 0
1247
+ });
1248
+ }, []);
1249
+ const zoomBy = useCallback((factor, anchor) => {
1250
+ setScale((prev) => {
1251
+ const next = Math.min(MAX_SCALE, Math.max(MIN_SCALE, prev * factor));
1252
+ if (next === prev) return prev;
1253
+ const rect = viewportRef.current?.getBoundingClientRect();
1254
+ if (rect) {
1255
+ const ax = (anchor?.x ?? rect.width / 2) - rect.width / 2;
1256
+ const ay = (anchor?.y ?? rect.height / 2) - rect.height / 2;
1257
+ setOffset((o) => ({
1258
+ x: ax - (ax - o.x) * next / prev,
1259
+ y: ay - (ay - o.y) * next / prev
1260
+ }));
1261
+ }
1262
+ return next;
1263
+ });
1264
+ }, []);
1265
+ const handleWheel = useCallback((e) => {
1266
+ e.preventDefault();
1267
+ const rect = viewportRef.current?.getBoundingClientRect();
1268
+ const anchor = rect ? {
1269
+ x: e.clientX - rect.left,
1270
+ y: e.clientY - rect.top
1271
+ } : void 0;
1272
+ zoomBy(e.deltaY < 0 ? 1.15 : 1 / 1.15, anchor);
1273
+ }, [zoomBy]);
1274
+ const handlePointerDown = (e) => {
1275
+ e.currentTarget.setPointerCapture(e.pointerId);
1276
+ dragRef.current = {
1277
+ startX: e.clientX,
1278
+ startY: e.clientY,
1279
+ originX: offset.x,
1280
+ originY: offset.y
1281
+ };
1282
+ setIsDragging(true);
1283
+ };
1284
+ const handlePointerMove = (e) => {
1285
+ const d = dragRef.current;
1286
+ if (!d) return;
1287
+ setOffset({
1288
+ x: d.originX + (e.clientX - d.startX),
1289
+ y: d.originY + (e.clientY - d.startY)
1290
+ });
1291
+ };
1292
+ const endDrag = (e) => {
1293
+ if (dragRef.current) try {
1294
+ e.currentTarget.releasePointerCapture(e.pointerId);
1295
+ } catch {}
1296
+ dragRef.current = null;
1297
+ setIsDragging(false);
1298
+ };
1299
+ return /* @__PURE__ */ jsxs("div", {
1300
+ className: "relative w-full h-full",
1301
+ children: [/* @__PURE__ */ jsx("div", {
1302
+ ref: viewportRef,
1303
+ onWheel: handleWheel,
1304
+ onPointerDown: handlePointerDown,
1305
+ onPointerMove: handlePointerMove,
1306
+ onPointerUp: endDrag,
1307
+ onPointerLeave: endDrag,
1308
+ onDoubleClick: reset,
1309
+ className: "w-full h-full overflow-hidden touch-none select-none",
1310
+ style: { cursor: isDragging ? "grabbing" : "grab" },
1311
+ children: /* @__PURE__ */ jsx("div", {
1312
+ className: "mermaid-zoom flex items-center justify-center w-full h-full",
1313
+ style: {
1314
+ transform: `translate(${offset.x}px, ${offset.y}px) scale(${scale})`,
1315
+ transformOrigin: "center center",
1316
+ transition: isDragging ? "none" : "transform 0.08s ease-out"
1317
+ },
1318
+ dangerouslySetInnerHTML: { __html: svg }
1319
+ })
1320
+ }), /* @__PURE__ */ jsxs("div", {
1321
+ className: "absolute bottom-4 right-4 flex items-center gap-1 rounded-lg bg-white/95 shadow-md border border-gray-200 px-1.5 py-1",
1322
+ children: [
1323
+ /* @__PURE__ */ jsx("button", {
1324
+ onClick: () => zoomBy(1 / 1.3),
1325
+ className: "p-1.5 rounded hover:bg-gray-100 text-gray-600",
1326
+ "aria-label": "Zoom out",
1327
+ title: "Zoom out",
1328
+ children: /* @__PURE__ */ jsx(MinusIcon, {})
1329
+ }),
1330
+ /* @__PURE__ */ jsxs("button", {
1331
+ onClick: reset,
1332
+ className: "px-2 py-1 text-xs font-medium rounded hover:bg-gray-100 text-gray-600 min-w-[3rem]",
1333
+ title: "Reset zoom (or double-click)",
1334
+ children: [Math.round(scale * 100), "%"]
1335
+ }),
1336
+ /* @__PURE__ */ jsx("button", {
1337
+ onClick: () => zoomBy(1.3),
1338
+ className: "p-1.5 rounded hover:bg-gray-100 text-gray-600",
1339
+ "aria-label": "Zoom in",
1340
+ title: "Zoom in",
1341
+ children: /* @__PURE__ */ jsx(PlusIcon, {})
1342
+ }),
1343
+ /* @__PURE__ */ jsx("div", { className: "w-px h-5 bg-gray-200 mx-0.5" }),
1344
+ /* @__PURE__ */ jsx("button", {
1345
+ onClick: reset,
1346
+ className: "p-1.5 rounded hover:bg-gray-100 text-gray-600",
1347
+ "aria-label": "Reset view",
1348
+ title: "Reset view",
1349
+ children: /* @__PURE__ */ jsx(ResetIcon, {})
1350
+ })
1351
+ ]
1352
+ })]
1353
+ });
1039
1354
  }
1040
1355
  function extractErrorMessage(err) {
1041
- if (err instanceof Error) {
1042
- const msg = err.message;
1043
- const parseMatch = msg.match(
1044
- /(?:Parse error|Syntax error|Error).*?(?:line \d+.*)/i
1045
- );
1046
- if (parseMatch) return parseMatch[0];
1047
- return msg.split("\n")[0].slice(0, 200);
1048
- }
1049
- if (typeof err === "string") return err.split("\n")[0].slice(0, 200);
1050
- return "Unknown error";
1356
+ if (err instanceof Error) {
1357
+ const msg = err.message;
1358
+ const parseMatch = msg.match(/(?:Parse error|Syntax error|Error).*?(?:line \d+.*)/i);
1359
+ if (parseMatch) return parseMatch[0];
1360
+ return msg.split("\n")[0].slice(0, 200);
1361
+ }
1362
+ if (typeof err === "string") return err.split("\n")[0].slice(0, 200);
1363
+ return "Unknown error";
1051
1364
  }
1052
- function DiagramModal({
1053
- isOpen,
1054
- onClose,
1055
- children
1056
- }) {
1057
- useEffect(() => {
1058
- if (!isOpen) return;
1059
- const handler = (e) => {
1060
- if (e.key === "Escape") onClose();
1061
- };
1062
- document.addEventListener("keydown", handler);
1063
- document.body.style.overflow = "hidden";
1064
- return () => {
1065
- document.removeEventListener("keydown", handler);
1066
- document.body.style.overflow = "unset";
1067
- };
1068
- }, [isOpen, onClose]);
1069
- if (!isOpen) return null;
1070
- return /* @__PURE__ */ jsx(
1071
- "div",
1072
- {
1073
- className: "fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4",
1074
- onClick: onClose,
1075
- children: /* @__PURE__ */ jsxs(
1076
- "div",
1077
- {
1078
- className: "bg-white rounded-lg shadow-xl w-[96vw] h-[94vh] flex flex-col overflow-hidden",
1079
- role: "dialog",
1080
- "aria-modal": "true",
1081
- onClick: (e) => e.stopPropagation(),
1082
- children: [
1083
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between p-4 border-b shrink-0", children: [
1084
- /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: "Mermaid Diagram" }),
1085
- /* @__PURE__ */ jsx(
1086
- "button",
1087
- {
1088
- onClick: onClose,
1089
- className: "p-1 hover:bg-gray-100 rounded-full transition-colors",
1090
- "aria-label": "Close modal",
1091
- children: /* @__PURE__ */ jsx(CloseIcon, {})
1092
- }
1093
- )
1094
- ] }),
1095
- /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-hidden bg-gray-50", children })
1096
- ]
1097
- }
1098
- )
1099
- }
1100
- );
1365
+ /** Simple modal for expanding diagrams */
1366
+ function DiagramModal({ isOpen, onClose, children }) {
1367
+ useEffect(() => {
1368
+ if (!isOpen) return;
1369
+ const handler = (e) => {
1370
+ if (e.key === "Escape") onClose();
1371
+ };
1372
+ document.addEventListener("keydown", handler);
1373
+ document.body.style.overflow = "hidden";
1374
+ return () => {
1375
+ document.removeEventListener("keydown", handler);
1376
+ document.body.style.overflow = "unset";
1377
+ };
1378
+ }, [isOpen, onClose]);
1379
+ if (!isOpen) return null;
1380
+ return /* @__PURE__ */ jsx("div", {
1381
+ className: "fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4",
1382
+ onClick: onClose,
1383
+ children: /* @__PURE__ */ jsxs("div", {
1384
+ className: "bg-white rounded-lg shadow-xl w-[96vw] h-[94vh] flex flex-col overflow-hidden",
1385
+ role: "dialog",
1386
+ "aria-modal": "true",
1387
+ onClick: (e) => e.stopPropagation(),
1388
+ children: [/* @__PURE__ */ jsxs("div", {
1389
+ className: "flex items-center justify-between p-4 border-b shrink-0",
1390
+ children: [/* @__PURE__ */ jsx("h2", {
1391
+ className: "text-lg font-semibold",
1392
+ children: "Mermaid Diagram"
1393
+ }), /* @__PURE__ */ jsx("button", {
1394
+ onClick: onClose,
1395
+ className: "p-1 hover:bg-gray-100 rounded-full transition-colors",
1396
+ "aria-label": "Close modal",
1397
+ children: /* @__PURE__ */ jsx(CloseIcon, {})
1398
+ })]
1399
+ }), /* @__PURE__ */ jsx("div", {
1400
+ className: "flex-1 overflow-hidden bg-gray-50",
1401
+ children
1402
+ })]
1403
+ })
1404
+ });
1101
1405
  }
1102
- var MermaidDiagramInner = ({ code }) => {
1103
- const hasCached = svgCache.has(code);
1104
- const [svg, setSvg] = useState(() => svgCache.get(code) || "");
1105
- const [errorMessage, setErrorMessage] = useState(null);
1106
- const [showSource, setShowSource] = useState(false);
1107
- const [isModalOpen, setIsModalOpen] = useState(false);
1108
- const [isLoading, setIsLoading] = useState(!hasCached);
1109
- const [minHeight, setMinHeight] = useState("auto");
1110
- const containerRef = useRef(null);
1111
- const lastHeightRef = useRef(null);
1112
- const stableId = useMemo(() => {
1113
- let hash = 0;
1114
- for (let i = 0; i < code.length; i++) {
1115
- const char = code.charCodeAt(i);
1116
- hash = (hash << 5) - hash + char;
1117
- hash = hash & hash;
1118
- }
1119
- return `mermaid-${Math.abs(hash).toString(36)}`;
1120
- }, [code]);
1121
- useEffect(() => {
1122
- if (hasCached) return;
1123
- let mounted = true;
1124
- const renderDiagram = async () => {
1125
- try {
1126
- if (containerRef.current) {
1127
- const height = containerRef.current.offsetHeight;
1128
- lastHeightRef.current = height;
1129
- setMinHeight(`${height}px`);
1130
- }
1131
- const m = await getMermaid();
1132
- const id = `${stableId}-${Date.now()}`;
1133
- const { svg: renderedSvg } = await m.render(id, code);
1134
- if (mounted) {
1135
- svgCache.set(code, renderedSvg);
1136
- setSvg(renderedSvg);
1137
- setErrorMessage(null);
1138
- setIsLoading(false);
1139
- }
1140
- } catch (err) {
1141
- console.error("Mermaid render error:", err);
1142
- if (mounted) {
1143
- setErrorMessage(extractErrorMessage(err));
1144
- setIsLoading(false);
1145
- }
1146
- }
1147
- };
1148
- renderDiagram();
1149
- return () => {
1150
- mounted = false;
1151
- };
1152
- }, [code, stableId, hasCached]);
1153
- if (errorMessage) {
1154
- return /* @__PURE__ */ jsxs(
1155
- "div",
1156
- {
1157
- "data-testid": "mermaid-container",
1158
- className: "my-4 rounded-md border border-yellow-300/40 bg-yellow-50/50 dark:border-yellow-700/40 dark:bg-yellow-950/20 overflow-hidden",
1159
- children: [
1160
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 px-4 py-2.5 text-sm text-yellow-800 dark:text-yellow-200", children: [
1161
- /* @__PURE__ */ jsx(AlertTriangleIcon, {}),
1162
- /* @__PURE__ */ jsx("span", { className: "font-medium", children: "Diagram syntax error" }),
1163
- /* @__PURE__ */ jsxs("span", { className: "text-yellow-700/70 dark:text-yellow-300/60", children: [
1164
- "\u2014 ",
1165
- errorMessage
1166
- ] })
1167
- ] }),
1168
- /* @__PURE__ */ jsxs("div", { className: "border-t border-yellow-300/30 dark:border-yellow-700/30", children: [
1169
- /* @__PURE__ */ jsxs(
1170
- "button",
1171
- {
1172
- onClick: () => setShowSource(!showSource),
1173
- className: "flex items-center gap-1.5 px-4 py-1.5 text-xs text-yellow-700/60 dark:text-yellow-400/50 hover:text-yellow-800 dark:hover:text-yellow-300 transition-colors w-full",
1174
- children: [
1175
- showSource ? /* @__PURE__ */ jsx(ChevronUpIcon, {}) : /* @__PURE__ */ jsx(ChevronDownIcon, {}),
1176
- showSource ? "Hide source" : "Show source"
1177
- ]
1178
- }
1179
- ),
1180
- showSource && /* @__PURE__ */ jsx("pre", { className: "px-4 pb-3 text-xs font-mono text-yellow-800/70 dark:text-yellow-200/60 overflow-auto whitespace-pre-wrap", children: code })
1181
- ] })
1182
- ]
1183
- }
1184
- );
1185
- }
1186
- return /* @__PURE__ */ jsxs(Fragment, { children: [
1187
- /* @__PURE__ */ jsxs(
1188
- "div",
1189
- {
1190
- ref: containerRef,
1191
- "data-testid": "mermaid-container",
1192
- className: "relative group inline-block max-w-full",
1193
- style: { minHeight: isLoading ? minHeight : "auto" },
1194
- children: [
1195
- /* @__PURE__ */ jsx(
1196
- "div",
1197
- {
1198
- className: `mermaid flex justify-center my-4 overflow-x-auto transition-opacity duration-150 ${isLoading ? "opacity-50" : "opacity-100"}`,
1199
- dangerouslySetInnerHTML: { __html: svg }
1200
- }
1201
- ),
1202
- svg && /* @__PURE__ */ jsx(
1203
- "button",
1204
- {
1205
- onClick: () => setIsModalOpen(true),
1206
- className: "absolute top-2 right-2 p-2 bg-white/90 shadow-sm border rounded-md opacity-0 group-hover:opacity-100 transition-opacity hover:bg-gray-50",
1207
- "aria-label": "Maximize diagram",
1208
- children: /* @__PURE__ */ jsx(MaximizeIcon, {})
1209
- }
1210
- )
1211
- ]
1212
- }
1213
- ),
1214
- /* @__PURE__ */ jsx(DiagramModal, { isOpen: isModalOpen, onClose: () => setIsModalOpen(false), children: /* @__PURE__ */ jsx(ZoomableSvg, { svg }) })
1215
- ] });
1406
+ const MermaidDiagramInner = ({ code }) => {
1407
+ const hasCached = svgCache.has(code);
1408
+ const [svg, setSvg] = useState(() => svgCache.get(code) || "");
1409
+ const [errorMessage, setErrorMessage] = useState(null);
1410
+ const [showSource, setShowSource] = useState(false);
1411
+ const [isModalOpen, setIsModalOpen] = useState(false);
1412
+ const [isLoading, setIsLoading] = useState(!hasCached);
1413
+ const [minHeight, setMinHeight] = useState("auto");
1414
+ const containerRef = useRef(null);
1415
+ const lastHeightRef = useRef(null);
1416
+ const stableId = useMemo(() => {
1417
+ let hash = 0;
1418
+ for (let i = 0; i < code.length; i++) {
1419
+ const char = code.charCodeAt(i);
1420
+ hash = (hash << 5) - hash + char;
1421
+ hash = hash & hash;
1422
+ }
1423
+ return `mermaid-${Math.abs(hash).toString(36)}`;
1424
+ }, [code]);
1425
+ useEffect(() => {
1426
+ if (hasCached) return;
1427
+ let mounted = true;
1428
+ const renderDiagram = async () => {
1429
+ try {
1430
+ if (containerRef.current) {
1431
+ const height = containerRef.current.offsetHeight;
1432
+ lastHeightRef.current = height;
1433
+ setMinHeight(`${height}px`);
1434
+ }
1435
+ const m = await getMermaid();
1436
+ const id = `${stableId}-${Date.now()}`;
1437
+ const { svg: renderedSvg } = await m.render(id, code);
1438
+ if (mounted) {
1439
+ svgCache.set(code, renderedSvg);
1440
+ setSvg(renderedSvg);
1441
+ setErrorMessage(null);
1442
+ setIsLoading(false);
1443
+ }
1444
+ } catch (err) {
1445
+ console.error("Mermaid render error:", err);
1446
+ if (mounted) {
1447
+ setErrorMessage(extractErrorMessage(err));
1448
+ setIsLoading(false);
1449
+ }
1450
+ }
1451
+ };
1452
+ renderDiagram();
1453
+ return () => {
1454
+ mounted = false;
1455
+ };
1456
+ }, [
1457
+ code,
1458
+ stableId,
1459
+ hasCached
1460
+ ]);
1461
+ if (errorMessage) return /* @__PURE__ */ jsxs("div", {
1462
+ "data-testid": "mermaid-container",
1463
+ className: "my-4 rounded-md border border-yellow-300/40 bg-yellow-50/50 dark:border-yellow-700/40 dark:bg-yellow-950/20 overflow-hidden",
1464
+ children: [/* @__PURE__ */ jsxs("div", {
1465
+ className: "flex items-center gap-2 px-4 py-2.5 text-sm text-yellow-800 dark:text-yellow-200",
1466
+ children: [
1467
+ /* @__PURE__ */ jsx(AlertTriangleIcon, {}),
1468
+ /* @__PURE__ */ jsx("span", {
1469
+ className: "font-medium",
1470
+ children: "Diagram syntax error"
1471
+ }),
1472
+ /* @__PURE__ */ jsxs("span", {
1473
+ className: "text-yellow-700/70 dark:text-yellow-300/60",
1474
+ children: ["— ", errorMessage]
1475
+ })
1476
+ ]
1477
+ }), /* @__PURE__ */ jsxs("div", {
1478
+ className: "border-t border-yellow-300/30 dark:border-yellow-700/30",
1479
+ children: [/* @__PURE__ */ jsxs("button", {
1480
+ onClick: () => setShowSource(!showSource),
1481
+ className: "flex items-center gap-1.5 px-4 py-1.5 text-xs text-yellow-700/60 dark:text-yellow-400/50 hover:text-yellow-800 dark:hover:text-yellow-300 transition-colors w-full",
1482
+ children: [showSource ? /* @__PURE__ */ jsx(ChevronUpIcon, {}) : /* @__PURE__ */ jsx(ChevronDownIcon, {}), showSource ? "Hide source" : "Show source"]
1483
+ }), showSource && /* @__PURE__ */ jsx("pre", {
1484
+ className: "px-4 pb-3 text-xs font-mono text-yellow-800/70 dark:text-yellow-200/60 overflow-auto whitespace-pre-wrap",
1485
+ children: code
1486
+ })]
1487
+ })]
1488
+ });
1489
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("div", {
1490
+ ref: containerRef,
1491
+ "data-testid": "mermaid-container",
1492
+ className: "relative group inline-block max-w-full",
1493
+ style: { minHeight: isLoading ? minHeight : "auto" },
1494
+ children: [/* @__PURE__ */ jsx("div", {
1495
+ className: `mermaid flex justify-center my-4 overflow-x-auto transition-opacity duration-150 ${isLoading ? "opacity-50" : "opacity-100"}`,
1496
+ dangerouslySetInnerHTML: { __html: svg }
1497
+ }), svg && /* @__PURE__ */ jsx("button", {
1498
+ onClick: () => setIsModalOpen(true),
1499
+ className: "absolute top-2 right-2 p-2 bg-white/90 shadow-sm border rounded-md opacity-0 group-hover:opacity-100 transition-opacity hover:bg-gray-50",
1500
+ "aria-label": "Maximize diagram",
1501
+ children: /* @__PURE__ */ jsx(MaximizeIcon, {})
1502
+ })]
1503
+ }), /* @__PURE__ */ jsx(DiagramModal, {
1504
+ isOpen: isModalOpen,
1505
+ onClose: () => setIsModalOpen(false),
1506
+ children: /* @__PURE__ */ jsx(ZoomableSvg, { svg })
1507
+ })] });
1216
1508
  };
1217
- var MermaidDiagram = memo(
1218
- MermaidDiagramInner,
1219
- (prevProps, nextProps) => prevProps.code === nextProps.code
1220
- );
1221
-
1222
- // src/vantageFrontmatter.ts
1223
- var DOC_STATUSES = [
1224
- "draft",
1225
- "in-review",
1226
- "accepted",
1227
- "deprecated"
1509
+ const MermaidDiagram = memo(MermaidDiagramInner, (prevProps, nextProps) => prevProps.code === nextProps.code);
1510
+ //#endregion
1511
+ //#region src/vantageFrontmatter.ts
1512
+ /**
1513
+ * The document lifecycle vocabulary. Closed; extending it is a code change.
1514
+ *
1515
+ * This is the repo's own existing set, not a new one — `styleGuide.ts` tells
1516
+ * every agent to write `status: in-review # draft | in-review | accepted |
1517
+ * deprecated`, and every document under `docs/` follows it. It is deliberately
1518
+ * *not* the `badge` set (`draft stale blocked done wip`): `badge` is
1519
+ * section-scoped workflow state, `status` is document lifecycle state, and
1520
+ * `in-review` — the value the design doc's own only example renders — is not a
1521
+ * badge word at all. Only `draft` is a member of both, and a token set is per key.
1522
+ */
1523
+ const DOC_STATUSES = [
1524
+ "draft",
1525
+ "in-review",
1526
+ "accepted",
1527
+ "deprecated"
1228
1528
  ];
1229
- var VANTAGE_FRONTMATTER_KEYS = ["status-chip"];
1230
- var DOC_STATUS_TONES = {
1231
- draft: "muted",
1232
- "in-review": "warning",
1233
- accepted: "tip",
1234
- deprecated: "caution"
1529
+ /** Every key this build knows under `vantage:`. Closed. */
1530
+ const VANTAGE_FRONTMATTER_KEYS = ["status-chip"];
1531
+ /**
1532
+ * Which tone each status borrows its colours from.
1533
+ *
1534
+ * The chip has no palette of its own: it reuses the tone chips
1535
+ * (`.vantage-chip--<tone>` in `styles/directives.css`), which is also what makes
1536
+ * a `draft` chip and a `badge=draft` chip the same visual object. A map rather
1537
+ * than a computed class name, so the whole status→tone relation is one readable
1538
+ * table and a test can assert it covers the vocabulary.
1539
+ */
1540
+ const DOC_STATUS_TONES = {
1541
+ draft: "muted",
1542
+ "in-review": "warning",
1543
+ accepted: "tip",
1544
+ deprecated: "caution"
1235
1545
  };
1236
- var STATUS_CHIP_VALUES = [
1237
- ...DOC_STATUSES,
1238
- "true",
1239
- "false"
1546
+ /** The legal `status-chip` values, in the order a message should list them. */
1547
+ const STATUS_CHIP_VALUES = [
1548
+ ...DOC_STATUSES,
1549
+ "true",
1550
+ "false"
1240
1551
  ];
1552
+ /** Narrowing helper the chip and the checker both use. */
1241
1553
  function isDocStatus(value) {
1242
- return typeof value === "string" && DOC_STATUSES.includes(value);
1554
+ return typeof value === "string" && DOC_STATUSES.includes(value);
1243
1555
  }
1244
1556
  function isTable(value) {
1245
- return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
1557
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
1246
1558
  }
1559
+ /**
1560
+ * Read the `vantage:` key out of parsed frontmatter.
1561
+ *
1562
+ * Pure: no module state, no mutation of the input, no logging. The same object
1563
+ * in twice gives equal results out.
1564
+ */
1247
1565
  function readVantageFrontmatter(frontmatter) {
1248
- const issues = [];
1249
- if (!Object.hasOwn(frontmatter, "vantage")) return { issues };
1250
- const value = frontmatter["vantage"];
1251
- if (!isTable(value)) {
1252
- issues.push({ kind: "not-a-table", value });
1253
- return { issues };
1254
- }
1255
- let statusChip;
1256
- for (const key of Object.keys(value)) {
1257
- if (!VANTAGE_FRONTMATTER_KEYS.includes(key)) {
1258
- issues.push({ kind: "unknown-key", key });
1259
- continue;
1260
- }
1261
- if (key === "status-chip") {
1262
- statusChip = readStatusChip(frontmatter, value[key], issues);
1263
- }
1264
- }
1265
- return { ...statusChip === void 0 ? {} : { statusChip }, issues };
1566
+ const issues = [];
1567
+ if (!Object.hasOwn(frontmatter, "vantage")) return { issues };
1568
+ const value = frontmatter["vantage"];
1569
+ if (!isTable(value)) {
1570
+ issues.push({
1571
+ kind: "not-a-table",
1572
+ value
1573
+ });
1574
+ return { issues };
1575
+ }
1576
+ let statusChip;
1577
+ for (const key of Object.keys(value)) {
1578
+ if (!VANTAGE_FRONTMATTER_KEYS.includes(key)) {
1579
+ issues.push({
1580
+ kind: "unknown-key",
1581
+ key
1582
+ });
1583
+ continue;
1584
+ }
1585
+ if (key === "status-chip") statusChip = readStatusChip(frontmatter, value[key], issues);
1586
+ }
1587
+ return {
1588
+ ...statusChip === void 0 ? {} : { statusChip },
1589
+ issues
1590
+ };
1266
1591
  }
1592
+ /**
1593
+ * `status-chip` takes two shapes, and the boolean one is the recommended shape.
1594
+ *
1595
+ * `true` **inherits** the document's own top-level `status:`, so the chip cannot
1596
+ * disagree with it — which is the entire point of §5.3 ("makes `status: draft`
1597
+ * visible rather than only buried in a metadata card"; the row stays, the chip
1598
+ * promotes the value rather than moving it). A literal token is kept
1599
+ * because the design doc's first draft of that example used one, and the
1600
+ * disagreement it makes possible is turned into a checker finding rather than
1601
+ * banned.
1602
+ *
1603
+ * Discrimination is on `typeof`, never truthiness: `true` is a YAML boolean and
1604
+ * `2026-08-31` is a `Date`, and both would sail through a truthy test.
1605
+ */
1267
1606
  function readStatusChip(frontmatter, raw, issues) {
1268
- const status = frontmatter["status"];
1269
- if (raw === false) return void 0;
1270
- if (raw === true) {
1271
- if (isDocStatus(status)) return status;
1272
- issues.push({ kind: "status-chip-orphan", status });
1273
- return void 0;
1274
- }
1275
- if (isDocStatus(raw)) {
1276
- if (isDocStatus(status) && status !== raw) {
1277
- issues.push({ kind: "status-chip-disagrees", chip: raw, status });
1278
- }
1279
- return raw;
1280
- }
1281
- issues.push({
1282
- kind: "bad-value",
1283
- key: "status-chip",
1284
- value: raw,
1285
- legal: STATUS_CHIP_VALUES
1286
- });
1287
- return void 0;
1607
+ const status = frontmatter["status"];
1608
+ if (raw === false) return void 0;
1609
+ if (raw === true) {
1610
+ if (isDocStatus(status)) return status;
1611
+ issues.push({
1612
+ kind: "status-chip-orphan",
1613
+ status
1614
+ });
1615
+ return;
1616
+ }
1617
+ if (isDocStatus(raw)) {
1618
+ if (isDocStatus(status) && status !== raw) issues.push({
1619
+ kind: "status-chip-disagrees",
1620
+ chip: raw,
1621
+ status
1622
+ });
1623
+ return raw;
1624
+ }
1625
+ issues.push({
1626
+ kind: "bad-value",
1627
+ key: "status-chip",
1628
+ value: raw,
1629
+ legal: STATUS_CHIP_VALUES
1630
+ });
1288
1631
  }
1289
- var DocumentStatusChipInner = ({
1290
- status
1291
- }) => /* @__PURE__ */ jsx(
1292
- "span",
1293
- {
1294
- className: `vantage-chip vantage-chip--${DOC_STATUS_TONES[status]}`,
1295
- "data-vantage-status": status,
1296
- title: `Document status: ${status}`,
1297
- children: status
1298
- }
1299
- );
1300
- var DocumentStatusChip = memo(DocumentStatusChipInner);
1301
- var FileTextIcon = () => /* @__PURE__ */ jsxs(
1302
- "svg",
1303
- {
1304
- width: "14",
1305
- height: "14",
1306
- viewBox: "0 0 24 24",
1307
- fill: "none",
1308
- stroke: "currentColor",
1309
- strokeWidth: "2",
1310
- strokeLinecap: "round",
1311
- strokeLinejoin: "round",
1312
- className: "text-slate-400",
1313
- children: [
1314
- /* @__PURE__ */ jsx("path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" }),
1315
- /* @__PURE__ */ jsx("path", { d: "M14 2v4a2 2 0 0 0 2 2h4" }),
1316
- /* @__PURE__ */ jsx("path", { d: "M10 9H8" }),
1317
- /* @__PURE__ */ jsx("path", { d: "M16 13H8" }),
1318
- /* @__PURE__ */ jsx("path", { d: "M16 17H8" })
1319
- ]
1320
- }
1321
- );
1632
+ //#endregion
1633
+ //#region src/DocumentStatusChip.tsx
1634
+ /**
1635
+ * The document's lifecycle status, as a chip.
1636
+ *
1637
+ * Non-interactive on purpose. D4 says a control that cannot work must not
1638
+ * render, and the cheapest way to satisfy that in *every* rendering — the app,
1639
+ * the package's exported viewer, an exported static site — is not to be a
1640
+ * control at all. So there is no `onClick`, no `<button>` and no
1641
+ * `isStaticMode()` gate: gating it would delete the chip from every exported
1642
+ * site, which is the one place D5 costs nothing.
1643
+ *
1644
+ * The text is the token verbatim, lowercase. No display map (`"In review"`) —
1645
+ * that is a second vocabulary that drifts from the first, and the visual
1646
+ * flourish belongs in CSS, where `text-transform` cannot change what the
1647
+ * document's text content is.
1648
+ *
1649
+ * Styling comes entirely from `styles/directives.css` — `.vantage-chip` for the
1650
+ * geometry, shared by selector list with the `badge=` pseudo-element, and
1651
+ * `.vantage-chip--<tone>` for the colours. No Tailwind utility appears here, so
1652
+ * the chip survives in a consumer that does not run Tailwind and no class name
1653
+ * has to be discovered by a content scan.
1654
+ */
1655
+ const DocumentStatusChipInner = ({ status }) => /* @__PURE__ */ jsx("span", {
1656
+ className: `vantage-chip vantage-chip--${DOC_STATUS_TONES[status]}`,
1657
+ "data-vantage-status": status,
1658
+ title: `Document status: ${status}`,
1659
+ children: status
1660
+ });
1661
+ const DocumentStatusChip = memo(DocumentStatusChipInner);
1662
+ //#endregion
1663
+ //#region src/FrontmatterDisplay.tsx
1664
+ const FileTextIcon = () => /* @__PURE__ */ jsxs("svg", {
1665
+ width: "14",
1666
+ height: "14",
1667
+ viewBox: "0 0 24 24",
1668
+ fill: "none",
1669
+ stroke: "currentColor",
1670
+ strokeWidth: "2",
1671
+ strokeLinecap: "round",
1672
+ strokeLinejoin: "round",
1673
+ className: "text-slate-400",
1674
+ children: [
1675
+ /* @__PURE__ */ jsx("path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" }),
1676
+ /* @__PURE__ */ jsx("path", { d: "M14 2v4a2 2 0 0 0 2 2h4" }),
1677
+ /* @__PURE__ */ jsx("path", { d: "M10 9H8" }),
1678
+ /* @__PURE__ */ jsx("path", { d: "M16 13H8" }),
1679
+ /* @__PURE__ */ jsx("path", { d: "M16 17H8" })
1680
+ ]
1681
+ });
1322
1682
  function isStringArray(value) {
1323
- return Array.isArray(value) && value.every((item) => typeof item === "string");
1683
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
1324
1684
  }
1325
1685
  function isPlainObject(value) {
1326
- return typeof value === "object" && value !== null && !Array.isArray(value);
1686
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1327
1687
  }
1328
1688
  function formatValue(value) {
1329
- if (value instanceof Date) {
1330
- return value.toISOString().split("T")[0];
1331
- }
1332
- if (Array.isArray(value)) {
1333
- return value.map(String).join(", ");
1334
- }
1335
- if (typeof value === "boolean") {
1336
- return value ? "true" : "false";
1337
- }
1338
- if (isPlainObject(value)) {
1339
- return JSON.stringify(value, null, 2);
1340
- }
1341
- return String(value);
1689
+ if (value instanceof Date) return value.toISOString().split("T")[0];
1690
+ if (Array.isArray(value)) return value.map(String).join(", ");
1691
+ if (typeof value === "boolean") return value ? "true" : "false";
1692
+ if (isPlainObject(value)) return JSON.stringify(value, null, 2);
1693
+ return String(value);
1342
1694
  }
1343
1695
  function TagList({ items }) {
1344
- return /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: items.map((item) => /* @__PURE__ */ jsx(
1345
- "span",
1346
- {
1347
- className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
1348
- children: item
1349
- },
1350
- item
1351
- )) });
1696
+ return /* @__PURE__ */ jsx("div", {
1697
+ className: "flex flex-wrap gap-1.5",
1698
+ children: items.map((item) => /* @__PURE__ */ jsx("span", {
1699
+ className: "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
1700
+ children: item
1701
+ }, item))
1702
+ });
1352
1703
  }
1353
1704
  function ValueCell({ value }) {
1354
- if (isStringArray(value) && value.length > 0) {
1355
- return /* @__PURE__ */ jsx(TagList, { items: value });
1356
- }
1357
- if (isPlainObject(value)) {
1358
- return /* @__PURE__ */ jsx("pre", { className: "bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-md px-3 py-2 text-xs font-mono overflow-x-auto text-slate-600 dark:text-slate-300", children: formatValue(value) });
1359
- }
1360
- return /* @__PURE__ */ jsx("span", { className: "font-medium", children: formatValue(value) });
1705
+ if (isStringArray(value) && value.length > 0) return /* @__PURE__ */ jsx(TagList, { items: value });
1706
+ if (isPlainObject(value)) return /* @__PURE__ */ jsx("pre", {
1707
+ className: "bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-md px-3 py-2 text-xs font-mono overflow-x-auto text-slate-600 dark:text-slate-300",
1708
+ children: formatValue(value)
1709
+ });
1710
+ return /* @__PURE__ */ jsx("span", {
1711
+ className: "font-medium",
1712
+ children: formatValue(value)
1713
+ });
1361
1714
  }
1362
1715
  function flattenEntries(entries) {
1363
- const result = [];
1364
- for (const [key, value] of entries) {
1365
- if (key === "vantage") continue;
1366
- if (key === "taxonomies" && isPlainObject(value)) {
1367
- for (const [taxKey, taxVal] of Object.entries(value)) {
1368
- result.push([taxKey, taxVal]);
1369
- }
1370
- } else if (key === "extra" && isPlainObject(value)) {
1371
- for (const [extraKey, extraVal] of Object.entries(value)) {
1372
- result.push([extraKey, extraVal]);
1373
- }
1374
- } else {
1375
- result.push([key, value]);
1376
- }
1377
- }
1378
- return result;
1716
+ const result = [];
1717
+ for (const [key, value] of entries) {
1718
+ if (key === "vantage") continue;
1719
+ if (key === "taxonomies" && isPlainObject(value)) for (const [taxKey, taxVal] of Object.entries(value)) result.push([taxKey, taxVal]);
1720
+ else if (key === "extra" && isPlainObject(value)) for (const [extraKey, extraVal] of Object.entries(value)) result.push([extraKey, extraVal]);
1721
+ else result.push([key, value]);
1722
+ }
1723
+ return result;
1379
1724
  }
1380
- var FrontmatterDisplayInner = ({
1381
- frontmatter
1382
- }) => {
1383
- const entries = flattenEntries(Object.entries(frontmatter));
1384
- const { statusChip } = readVantageFrontmatter(frontmatter);
1385
- if (entries.length === 0 && statusChip === void 0) return null;
1386
- return /* @__PURE__ */ jsxs(Fragment, { children: [
1387
- statusChip !== void 0 && /* @__PURE__ */ jsx("div", { className: "vantage-chrome", children: /* @__PURE__ */ jsx(DocumentStatusChip, { status: statusChip }) }),
1388
- entries.length > 0 && /* @__PURE__ */ jsxs("div", { className: "mb-8 rounded-lg overflow-hidden bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-800 dark:to-slate-800/80 border border-slate-200 dark:border-slate-700 shadow-sm", children: [
1389
- /* @__PURE__ */ jsxs("div", { className: "px-4 py-2.5 bg-white/60 dark:bg-slate-900/40 border-b border-slate-200 dark:border-slate-700 flex items-center gap-2", children: [
1390
- /* @__PURE__ */ jsx(FileTextIcon, {}),
1391
- /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider", children: "Metadata" })
1392
- ] }),
1393
- /* @__PURE__ */ jsx("div", { className: "p-4", children: /* @__PURE__ */ jsx("table", { className: "w-full text-sm", children: /* @__PURE__ */ jsx("tbody", { children: entries.map(([key, value]) => /* @__PURE__ */ jsxs(
1394
- "tr",
1395
- {
1396
- className: "border-b border-slate-200/60 dark:border-slate-700/60 last:border-0",
1397
- children: [
1398
- /* @__PURE__ */ jsx("td", { className: "py-2 pr-4 font-medium text-slate-500 dark:text-slate-400 whitespace-nowrap align-top w-1/4 min-w-[100px]", children: key }),
1399
- /* @__PURE__ */ jsx("td", { className: "py-2 text-slate-800 dark:text-slate-200 align-top", children: /* @__PURE__ */ jsx(ValueCell, { value }) })
1400
- ]
1401
- },
1402
- key
1403
- )) }) }) })
1404
- ] })
1405
- ] });
1725
+ const FrontmatterDisplayInner = ({ frontmatter }) => {
1726
+ const entries = flattenEntries(Object.entries(frontmatter));
1727
+ const { statusChip } = readVantageFrontmatter(frontmatter);
1728
+ if (entries.length === 0 && statusChip === void 0) return null;
1729
+ return /* @__PURE__ */ jsxs(Fragment, { children: [statusChip !== void 0 && /* @__PURE__ */ jsx("div", {
1730
+ className: "vantage-chrome",
1731
+ children: /* @__PURE__ */ jsx(DocumentStatusChip, { status: statusChip })
1732
+ }), entries.length > 0 && /* @__PURE__ */ jsxs("div", {
1733
+ className: "mb-8 rounded-lg overflow-hidden bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-800 dark:to-slate-800/80 border border-slate-200 dark:border-slate-700 shadow-sm",
1734
+ children: [/* @__PURE__ */ jsxs("div", {
1735
+ className: "px-4 py-2.5 bg-white/60 dark:bg-slate-900/40 border-b border-slate-200 dark:border-slate-700 flex items-center gap-2",
1736
+ children: [/* @__PURE__ */ jsx(FileTextIcon, {}), /* @__PURE__ */ jsx("span", {
1737
+ className: "text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider",
1738
+ children: "Metadata"
1739
+ })]
1740
+ }), /* @__PURE__ */ jsx("div", {
1741
+ className: "p-4",
1742
+ children: /* @__PURE__ */ jsx("table", {
1743
+ className: "w-full text-sm",
1744
+ children: /* @__PURE__ */ jsx("tbody", { children: entries.map(([key, value]) => /* @__PURE__ */ jsxs("tr", {
1745
+ className: "border-b border-slate-200/60 dark:border-slate-700/60 last:border-0",
1746
+ children: [/* @__PURE__ */ jsx("td", {
1747
+ className: "py-2 pr-4 font-medium text-slate-500 dark:text-slate-400 whitespace-nowrap align-top w-1/4 min-w-[100px]",
1748
+ children: key
1749
+ }), /* @__PURE__ */ jsx("td", {
1750
+ className: "py-2 text-slate-800 dark:text-slate-200 align-top",
1751
+ children: /* @__PURE__ */ jsx(ValueCell, { value })
1752
+ })]
1753
+ }, key)) })
1754
+ })
1755
+ })]
1756
+ })] });
1406
1757
  };
1407
- var FrontmatterDisplay = memo(FrontmatterDisplayInner);
1408
-
1409
- // src/lineAnchor.ts
1758
+ const FrontmatterDisplay = memo(FrontmatterDisplayInner);
1759
+ //#endregion
1760
+ //#region src/lineAnchor.ts
1761
+ /**
1762
+ * Parsing for GitHub-style line anchors, with no DOM in sight.
1763
+ *
1764
+ * Split out from scrollToLineAnchor.ts so that non-browser consumers — the
1765
+ * `vantage-check` CLI, which validates `#L42` links against the file on disk —
1766
+ * can share the *same* syntax the viewer honours instead of reimplementing it
1767
+ * and drifting.
1768
+ */
1769
+ /**
1770
+ * Parse a GitHub-style line anchor hash.
1771
+ * Supports: #L42, #L42-L50, #L42-50
1772
+ * Returns null if the hash is not a line anchor.
1773
+ */
1410
1774
  function parseLineAnchor(hash) {
1411
- if (!hash) return null;
1412
- const frag = hash.startsWith("#") ? hash.slice(1) : hash;
1413
- const match = frag.match(/^L(\d+)(?:-L?(\d+))?$/);
1414
- if (!match) return null;
1415
- const start = parseInt(match[1], 10);
1416
- const end = match[2] ? parseInt(match[2], 10) : start;
1417
- return { start: Math.min(start, end), end: Math.max(start, end) };
1775
+ if (!hash) return null;
1776
+ const match = (hash.startsWith("#") ? hash.slice(1) : hash).match(/^L(\d+)(?:-L?(\d+))?$/);
1777
+ if (!match) return null;
1778
+ const start = parseInt(match[1], 10);
1779
+ const end = match[2] ? parseInt(match[2], 10) : start;
1780
+ return {
1781
+ start: Math.min(start, end),
1782
+ end: Math.max(start, end)
1783
+ };
1418
1784
  }
1419
-
1420
- // src/scrollToLineAnchor.ts
1421
- var HIGHLIGHT_CLASS = "line-anchor-highlight";
1785
+ //#endregion
1786
+ //#region src/scrollToLineAnchor.ts
1787
+ /**
1788
+ * Framework-agnostic line anchor utilities.
1789
+ * Scroll to and highlight the elements a GitHub-style line anchor
1790
+ * (#L42, #L42-L50) names. The parsing half lives in lineAnchor.ts, which has
1791
+ * no DOM dependency.
1792
+ */
1793
+ const HIGHLIGHT_CLASS$1 = "line-anchor-highlight";
1794
+ /**
1795
+ * Clear all line anchor highlights from a container.
1796
+ */
1422
1797
  function clearLineAnchorHighlights(container) {
1423
- container.querySelectorAll(`.${HIGHLIGHT_CLASS}`).forEach((node) => {
1424
- node.classList.remove(HIGHLIGHT_CLASS);
1425
- });
1798
+ container.querySelectorAll(`.${HIGHLIGHT_CLASS$1}`).forEach((node) => {
1799
+ node.classList.remove(HIGHLIGHT_CLASS$1);
1800
+ });
1426
1801
  }
1802
+ /**
1803
+ * Scroll to and highlight line-anchored elements in a container.
1804
+ *
1805
+ * @param container - The DOM element containing rendered markdown
1806
+ * @param hash - The URL hash (e.g. "#L42" or "#L42-L50")
1807
+ * @returns A cleanup function that removes the highlights
1808
+ */
1427
1809
  function scrollToLineAnchor(container, hash) {
1428
- clearLineAnchorHighlights(container);
1429
- const range = parseLineAnchor(hash);
1430
- if (!range) return null;
1431
- const blocks = container.querySelectorAll("[data-source-line]");
1432
- let firstMatch = null;
1433
- for (const block of blocks) {
1434
- const line = parseInt(block.dataset.sourceLine || "0", 10);
1435
- if (line >= range.start && line <= range.end) {
1436
- block.classList.add(HIGHLIGHT_CLASS);
1437
- if (!firstMatch) firstMatch = block;
1438
- }
1439
- }
1440
- if (!firstMatch) {
1441
- let closest = null;
1442
- let closestLine = 0;
1443
- for (const block of blocks) {
1444
- const line = parseInt(
1445
- block.dataset.sourceLine || "0",
1446
- 10
1447
- );
1448
- if (line <= range.start && line > closestLine) {
1449
- closestLine = line;
1450
- closest = block;
1451
- }
1452
- }
1453
- if (closest) {
1454
- closest.classList.add(HIGHLIGHT_CLASS);
1455
- firstMatch = closest;
1456
- }
1457
- }
1458
- if (firstMatch) {
1459
- requestAnimationFrame(() => {
1460
- const scrollParent = findScrollParent(container);
1461
- if (scrollParent) {
1462
- const offset = firstMatch.getBoundingClientRect().top - scrollParent.getBoundingClientRect().top + scrollParent.scrollTop;
1463
- scrollParent.scrollTo({ top: offset - 32, behavior: "smooth" });
1464
- } else {
1465
- firstMatch.scrollIntoView({ behavior: "smooth", block: "start" });
1466
- }
1467
- });
1468
- }
1469
- return () => clearLineAnchorHighlights(container);
1810
+ clearLineAnchorHighlights(container);
1811
+ const range = parseLineAnchor(hash);
1812
+ if (!range) return null;
1813
+ const blocks = container.querySelectorAll("[data-source-line]");
1814
+ let firstMatch = null;
1815
+ for (const block of blocks) {
1816
+ const line = parseInt(block.dataset.sourceLine || "0", 10);
1817
+ if (line >= range.start && line <= range.end) {
1818
+ block.classList.add(HIGHLIGHT_CLASS$1);
1819
+ if (!firstMatch) firstMatch = block;
1820
+ }
1821
+ }
1822
+ if (!firstMatch) {
1823
+ let closest = null;
1824
+ let closestLine = 0;
1825
+ for (const block of blocks) {
1826
+ const line = parseInt(block.dataset.sourceLine || "0", 10);
1827
+ if (line <= range.start && line > closestLine) {
1828
+ closestLine = line;
1829
+ closest = block;
1830
+ }
1831
+ }
1832
+ if (closest) {
1833
+ closest.classList.add(HIGHLIGHT_CLASS$1);
1834
+ firstMatch = closest;
1835
+ }
1836
+ }
1837
+ if (firstMatch) requestAnimationFrame(() => {
1838
+ const scrollParent = findScrollParent(container);
1839
+ if (scrollParent) {
1840
+ const offset = firstMatch.getBoundingClientRect().top - scrollParent.getBoundingClientRect().top + scrollParent.scrollTop;
1841
+ scrollParent.scrollTo({
1842
+ top: offset - 32,
1843
+ behavior: "smooth"
1844
+ });
1845
+ } else firstMatch.scrollIntoView({
1846
+ behavior: "smooth",
1847
+ block: "start"
1848
+ });
1849
+ });
1850
+ return () => clearLineAnchorHighlights(container);
1470
1851
  }
1471
1852
  function findScrollParent(el) {
1472
- let node = el;
1473
- while (node) {
1474
- const overflow = getComputedStyle(node).overflowY;
1475
- if (overflow === "auto" || overflow === "scroll") return node;
1476
- node = node.parentElement;
1477
- }
1478
- return null;
1853
+ let node = el;
1854
+ while (node) {
1855
+ const overflow = getComputedStyle(node).overflowY;
1856
+ if (overflow === "auto" || overflow === "scroll") return node;
1857
+ node = node.parentElement;
1858
+ }
1859
+ return null;
1479
1860
  }
1480
-
1481
- // src/useLineAnchor.ts
1482
- var HIGHLIGHT_CLASS2 = "line-anchor-highlight";
1861
+ //#endregion
1862
+ //#region src/useLineAnchor.ts
1863
+ const HIGHLIGHT_CLASS = "line-anchor-highlight";
1864
+ /**
1865
+ * React hook that handles GitHub-style line anchors (#L42, #L42-L50).
1866
+ *
1867
+ * - Parses the URL hash for line references
1868
+ * - Finds block elements with matching `data-source-line` attributes
1869
+ * - Scrolls to and highlights them
1870
+ * - Dismisses on Escape or click on the highlight
1871
+ *
1872
+ * @param containerRef - Ref to the DOM element containing rendered markdown
1873
+ * @param hash - The current URL hash (e.g. "#L42", from location.hash or window.location.hash)
1874
+ */
1483
1875
  function useLineAnchor(containerRef, hash) {
1484
- const clearHighlights = useCallback(() => {
1485
- const el = containerRef.current;
1486
- if (!el) return;
1487
- clearLineAnchorHighlights(el);
1488
- }, [containerRef]);
1489
- useEffect(() => {
1490
- const el = containerRef.current;
1491
- if (!el) return;
1492
- clearHighlights();
1493
- const range = parseLineAnchor(hash);
1494
- if (!range) return;
1495
- const blocks = el.querySelectorAll("[data-source-line]");
1496
- let firstMatch = null;
1497
- for (const block of blocks) {
1498
- const line = parseInt(
1499
- block.dataset.sourceLine || "0",
1500
- 10
1501
- );
1502
- if (line >= range.start && line <= range.end) {
1503
- block.classList.add(HIGHLIGHT_CLASS2);
1504
- if (!firstMatch) firstMatch = block;
1505
- }
1506
- }
1507
- if (!firstMatch) {
1508
- let closest = null;
1509
- let closestLine = 0;
1510
- for (const block of blocks) {
1511
- const line = parseInt(
1512
- block.dataset.sourceLine || "0",
1513
- 10
1514
- );
1515
- if (line <= range.start && line > closestLine) {
1516
- closestLine = line;
1517
- closest = block;
1518
- }
1519
- }
1520
- if (closest) {
1521
- closest.classList.add(HIGHLIGHT_CLASS2);
1522
- firstMatch = closest;
1523
- }
1524
- }
1525
- if (firstMatch) {
1526
- let scrollParent = el;
1527
- while (scrollParent) {
1528
- const overflow = getComputedStyle(scrollParent).overflowY;
1529
- if (overflow === "auto" || overflow === "scroll") break;
1530
- scrollParent = scrollParent.parentElement;
1531
- }
1532
- if (scrollParent) {
1533
- const target = firstMatch;
1534
- requestAnimationFrame(() => {
1535
- const offset = target.getBoundingClientRect().top - scrollParent.getBoundingClientRect().top + scrollParent.scrollTop;
1536
- scrollParent.scrollTo({ top: offset - 32, behavior: "smooth" });
1537
- });
1538
- }
1539
- }
1540
- }, [hash, containerRef, clearHighlights]);
1541
- useEffect(() => {
1542
- const handler = (e) => {
1543
- if (e.key === "Escape") {
1544
- clearHighlights();
1545
- if (window.location.hash) {
1546
- history.replaceState(null, "", window.location.pathname);
1547
- }
1548
- }
1549
- };
1550
- document.addEventListener("keydown", handler);
1551
- return () => document.removeEventListener("keydown", handler);
1552
- }, [clearHighlights]);
1553
- useEffect(() => {
1554
- const el = containerRef.current;
1555
- if (!el) return;
1556
- const handler = (e) => {
1557
- const target = e.target;
1558
- if (target.closest(`.${HIGHLIGHT_CLASS2}`)) {
1559
- clearHighlights();
1560
- if (window.location.hash) {
1561
- history.replaceState(null, "", window.location.pathname);
1562
- }
1563
- }
1564
- };
1565
- el.addEventListener("click", handler);
1566
- return () => el.removeEventListener("click", handler);
1567
- }, [containerRef, clearHighlights]);
1568
- return { clearHighlights };
1876
+ const clearHighlights = useCallback(() => {
1877
+ const el = containerRef.current;
1878
+ if (!el) return;
1879
+ clearLineAnchorHighlights(el);
1880
+ }, [containerRef]);
1881
+ useEffect(() => {
1882
+ const el = containerRef.current;
1883
+ if (!el) return;
1884
+ clearHighlights();
1885
+ const range = parseLineAnchor(hash);
1886
+ if (!range) return;
1887
+ const blocks = el.querySelectorAll("[data-source-line]");
1888
+ let firstMatch = null;
1889
+ for (const block of blocks) {
1890
+ const line = parseInt(block.dataset.sourceLine || "0", 10);
1891
+ if (line >= range.start && line <= range.end) {
1892
+ block.classList.add(HIGHLIGHT_CLASS);
1893
+ if (!firstMatch) firstMatch = block;
1894
+ }
1895
+ }
1896
+ if (!firstMatch) {
1897
+ let closest = null;
1898
+ let closestLine = 0;
1899
+ for (const block of blocks) {
1900
+ const line = parseInt(block.dataset.sourceLine || "0", 10);
1901
+ if (line <= range.start && line > closestLine) {
1902
+ closestLine = line;
1903
+ closest = block;
1904
+ }
1905
+ }
1906
+ if (closest) {
1907
+ closest.classList.add(HIGHLIGHT_CLASS);
1908
+ firstMatch = closest;
1909
+ }
1910
+ }
1911
+ if (firstMatch) {
1912
+ let scrollParent = el;
1913
+ while (scrollParent) {
1914
+ const overflow = getComputedStyle(scrollParent).overflowY;
1915
+ if (overflow === "auto" || overflow === "scroll") break;
1916
+ scrollParent = scrollParent.parentElement;
1917
+ }
1918
+ if (scrollParent) {
1919
+ const target = firstMatch;
1920
+ requestAnimationFrame(() => {
1921
+ const offset = target.getBoundingClientRect().top - scrollParent.getBoundingClientRect().top + scrollParent.scrollTop;
1922
+ scrollParent.scrollTo({
1923
+ top: offset - 32,
1924
+ behavior: "smooth"
1925
+ });
1926
+ });
1927
+ }
1928
+ }
1929
+ }, [
1930
+ hash,
1931
+ containerRef,
1932
+ clearHighlights
1933
+ ]);
1934
+ useEffect(() => {
1935
+ const handler = (e) => {
1936
+ if (e.key === "Escape") {
1937
+ clearHighlights();
1938
+ if (window.location.hash) history.replaceState(null, "", window.location.pathname);
1939
+ }
1940
+ };
1941
+ document.addEventListener("keydown", handler);
1942
+ return () => document.removeEventListener("keydown", handler);
1943
+ }, [clearHighlights]);
1944
+ useEffect(() => {
1945
+ const el = containerRef.current;
1946
+ if (!el) return;
1947
+ const handler = (e) => {
1948
+ if (e.target.closest(`.${HIGHLIGHT_CLASS}`)) {
1949
+ clearHighlights();
1950
+ if (window.location.hash) history.replaceState(null, "", window.location.pathname);
1951
+ }
1952
+ };
1953
+ el.addEventListener("click", handler);
1954
+ return () => el.removeEventListener("click", handler);
1955
+ }, [containerRef, clearHighlights]);
1956
+ return { clearHighlights };
1569
1957
  }
1570
- var MarkdownViewerInner = ({
1571
- content,
1572
- currentPath = "",
1573
- hash = "",
1574
- baseUrl = "/",
1575
- imageApiBase,
1576
- className,
1577
- onNavigate
1578
- }) => {
1579
- const containerRef = useRef(null);
1580
- useLineAnchor(containerRef, hash);
1581
- const { frontmatter, body, bodyLineOffset } = useMemo(() => {
1582
- return parseFrontmatter(content);
1583
- }, [content]);
1584
- const { remarkPlugins, rehypePlugins } = useMemo(
1585
- () => buildPipeline({ bodyLineOffset }),
1586
- [bodyLineOffset]
1587
- );
1588
- const handleLinkClick = useCallback(
1589
- (e, href) => {
1590
- if (href.startsWith("#")) {
1591
- e.preventDefault();
1592
- const id = href.slice(1);
1593
- const el = document.getElementById(id);
1594
- if (el) {
1595
- const scrollContainer = el.closest("[data-content-scroll]") || el.closest(".overflow-y-auto");
1596
- if (scrollContainer) {
1597
- const offset = el.getBoundingClientRect().top - scrollContainer.getBoundingClientRect().top + scrollContainer.scrollTop;
1598
- scrollContainer.scrollTo({ top: offset - 16 });
1599
- } else {
1600
- el.scrollIntoView();
1601
- }
1602
- }
1603
- return;
1604
- }
1605
- if (href.startsWith("http") || href.startsWith("mailto:")) return;
1606
- if (onNavigate) {
1607
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
1608
- e.preventDefault();
1609
- const [pathPart, hashPart] = href.split("#");
1610
- const parts = currentPath.split("/");
1611
- parts.pop();
1612
- const dir = parts.join("/");
1613
- const cleanHref = pathPart.replace(/^\.\//, "");
1614
- const resolvedPath = dir ? `${dir}/${cleanHref}` : cleanHref;
1615
- onNavigate(resolvedPath + (hashPart ? `#${hashPart}` : ""));
1616
- }
1617
- },
1618
- [currentPath, onNavigate]
1619
- );
1620
- const resolveHref = useCallback(
1621
- (href) => {
1622
- if (!href) return "";
1623
- if (href.startsWith("http") || href.startsWith("mailto:") || href.startsWith("#") || href.startsWith("/")) {
1624
- return href;
1625
- }
1626
- const [pathPart, hashPart] = href.split("#");
1627
- const parts = currentPath.split("/");
1628
- parts.pop();
1629
- const dir = parts.join("/");
1630
- const cleanHref = pathPart.replace(/^\.\//, "");
1631
- const resolvedPath = dir ? `${dir}/${cleanHref}` : cleanHref;
1632
- return `${baseUrl}${resolvedPath}${hashPart ? `#${hashPart}` : ""}`;
1633
- },
1634
- [currentPath, baseUrl]
1635
- );
1636
- const transformImageUri = useCallback(
1637
- (uri, key) => {
1638
- if (key === "href") return uri;
1639
- if (uri.startsWith("http") || uri.startsWith("data:")) return uri;
1640
- const parts = currentPath.split("/");
1641
- parts.pop();
1642
- const dir = parts.join("/");
1643
- const resolvedPath = dir ? `${dir}/${uri}` : uri;
1644
- if (imageApiBase) {
1645
- return `${imageApiBase}/content?path=${encodeURIComponent(resolvedPath)}`;
1646
- }
1647
- return `${baseUrl}${resolvedPath}`;
1648
- },
1649
- [currentPath, baseUrl, imageApiBase]
1650
- );
1651
- const markdownComponents = useMemo(
1652
- () => ({
1653
- a({
1654
- href,
1655
- children,
1656
- ...props
1657
- }) {
1658
- const resolvedHref = resolveHref(href);
1659
- return /* @__PURE__ */ jsx(
1660
- "a",
1661
- {
1662
- href: resolvedHref,
1663
- onClick: (e) => href && handleLinkClick(e, href),
1664
- ...props,
1665
- children
1666
- }
1667
- );
1668
- },
1669
- code(props) {
1670
- const { children, className: codeClassName, ...rest } = props;
1671
- const match = /language-(\w+)/.exec(codeClassName || "");
1672
- if (match && match[1] === "mermaid") {
1673
- return /* @__PURE__ */ jsx(MermaidDiagram, { code: String(children).replace(/\n$/, "") });
1674
- }
1675
- return /* @__PURE__ */ jsx("code", { className: codeClassName, ...rest, children });
1676
- }
1677
- }),
1678
- [handleLinkClick, resolveHref]
1679
- );
1680
- const proseClasses = [
1681
- "prose prose-slate dark:prose-invert max-w-none",
1682
- "prose-headings:font-semibold prose-headings:tracking-tight prose-headings:text-slate-900 dark:prose-headings:text-slate-100",
1683
- "prose-h1:text-[2em] prose-h1:mb-3 prose-h1:pb-[0.3em] prose-h1:border-b prose-h1:border-slate-200 dark:prose-h1:border-slate-700",
1684
- "prose-h2:text-[1.5em] prose-h2:mt-6 prose-h2:mb-3 prose-h2:pb-[0.3em] prose-h2:border-b prose-h2:border-slate-200 dark:prose-h2:border-slate-700",
1685
- "prose-h3:text-[1.25em] prose-h3:mt-6 prose-h3:mb-2",
1686
- "prose-h4:text-[1em] prose-h4:mt-6 prose-h4:mb-2",
1687
- "prose-p:text-slate-700 dark:prose-p:text-slate-300 prose-p:leading-[1.5] prose-p:my-[16px]",
1688
- "prose-ul:my-[16px] prose-ul:list-disc prose-li:my-0.5 prose-li:marker:text-slate-900 dark:prose-li:marker:text-slate-300",
1689
- "prose-ol:my-[16px] prose-li:marker:text-slate-900 dark:prose-li:marker:text-slate-300",
1690
- "prose-pre:bg-slate-50 dark:prose-pre:bg-slate-800 prose-pre:border prose-pre:border-slate-200 dark:prose-pre:border-slate-700 prose-pre:p-4 prose-pre:rounded-md prose-pre:text-[85%] prose-pre:leading-[1.45]",
1691
- "prose-a:text-blue-600 dark:prose-a:text-blue-400 prose-a:no-underline hover:prose-a:underline",
1692
- "prose-img:rounded-lg prose-img:my-4",
1693
- "prose-blockquote:border-l-[0.25em] prose-blockquote:border-slate-300 dark:prose-blockquote:border-slate-600 prose-blockquote:pl-4 prose-blockquote:text-slate-600 dark:prose-blockquote:text-slate-400 prose-blockquote:italic",
1694
- "prose-code:before:content-none prose-code:after:content-none",
1695
- "prose-code:bg-slate-100 dark:prose-code:bg-slate-800 prose-code:px-[0.4em] prose-code:py-[0.2em] prose-code:rounded-md prose-code:text-slate-800 dark:prose-code:text-slate-200 prose-code:font-mono prose-code:text-[85%] prose-code:font-normal prose-code:border prose-code:border-slate-200/50 dark:prose-code:border-slate-700/50",
1696
- "prose-table:text-sm",
1697
- "prose-th:px-3 prose-th:py-1.5 prose-th:border prose-th:border-slate-200 dark:prose-th:border-slate-700",
1698
- "prose-td:px-3 prose-td:py-1.5 prose-td:border prose-td:border-slate-200 dark:prose-td:border-slate-700"
1699
- ].join(" ");
1700
- return /* @__PURE__ */ jsxs(
1701
- "div",
1702
- {
1703
- ref: containerRef,
1704
- className: className ? `${proseClasses} ${className}` : proseClasses,
1705
- children: [
1706
- /* @__PURE__ */ jsx(FrontmatterDisplay, { frontmatter }),
1707
- /* @__PURE__ */ jsx(
1708
- ReactMarkdown,
1709
- {
1710
- remarkPlugins,
1711
- rehypePlugins,
1712
- urlTransform: transformImageUri,
1713
- components: markdownComponents,
1714
- children: body
1715
- }
1716
- )
1717
- ]
1718
- }
1719
- );
1958
+ //#endregion
1959
+ //#region src/MarkdownViewer.tsx
1960
+ /**
1961
+ * React markdown viewer component.
1962
+ *
1963
+ * Renders markdown with the full Vantage pipeline: GFM, math, syntax
1964
+ * highlighting, mermaid diagrams, line anchors, and frontmatter display.
1965
+ *
1966
+ * This is a standalone component with no dependency on Vantage's stores,
1967
+ * router, or review system.
1968
+ */
1969
+ const MarkdownViewerInner = ({ content, currentPath = "", hash = "", baseUrl = "/", imageApiBase, className, onNavigate }) => {
1970
+ const containerRef = useRef(null);
1971
+ useLineAnchor(containerRef, hash);
1972
+ const { frontmatter, body, bodyLineOffset } = useMemo(() => {
1973
+ return parseFrontmatter(content);
1974
+ }, [content]);
1975
+ const { remarkPlugins, rehypePlugins } = useMemo(() => buildPipeline({ bodyLineOffset }), [bodyLineOffset]);
1976
+ const handleLinkClick = useCallback((e, href) => {
1977
+ if (href.startsWith("#")) {
1978
+ e.preventDefault();
1979
+ const id = href.slice(1);
1980
+ const el = document.getElementById(id);
1981
+ if (el) {
1982
+ const scrollContainer = el.closest("[data-content-scroll]") || el.closest(".overflow-y-auto");
1983
+ if (scrollContainer) {
1984
+ const offset = el.getBoundingClientRect().top - scrollContainer.getBoundingClientRect().top + scrollContainer.scrollTop;
1985
+ scrollContainer.scrollTo({ top: offset - 16 });
1986
+ } else el.scrollIntoView();
1987
+ }
1988
+ return;
1989
+ }
1990
+ if (href.startsWith("http") || href.startsWith("mailto:")) return;
1991
+ if (onNavigate) {
1992
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
1993
+ e.preventDefault();
1994
+ const [pathPart, hashPart] = href.split("#");
1995
+ const parts = currentPath.split("/");
1996
+ parts.pop();
1997
+ const dir = parts.join("/");
1998
+ const cleanHref = pathPart.replace(/^\.\//, "");
1999
+ onNavigate((dir ? `${dir}/${cleanHref}` : cleanHref) + (hashPart ? `#${hashPart}` : ""));
2000
+ }
2001
+ }, [currentPath, onNavigate]);
2002
+ const resolveHref = useCallback((href) => {
2003
+ if (!href) return "";
2004
+ if (href.startsWith("http") || href.startsWith("mailto:") || href.startsWith("#") || href.startsWith("/")) return href;
2005
+ const [pathPart, hashPart] = href.split("#");
2006
+ const parts = currentPath.split("/");
2007
+ parts.pop();
2008
+ const dir = parts.join("/");
2009
+ const cleanHref = pathPart.replace(/^\.\//, "");
2010
+ return `${baseUrl}${dir ? `${dir}/${cleanHref}` : cleanHref}${hashPart ? `#${hashPart}` : ""}`;
2011
+ }, [currentPath, baseUrl]);
2012
+ const transformImageUri = useCallback((uri, key) => {
2013
+ if (key === "href") return uri;
2014
+ if (uri.startsWith("http") || uri.startsWith("data:")) return uri;
2015
+ const parts = currentPath.split("/");
2016
+ parts.pop();
2017
+ const dir = parts.join("/");
2018
+ const resolvedPath = dir ? `${dir}/${uri}` : uri;
2019
+ if (imageApiBase) return `${imageApiBase}/content?path=${encodeURIComponent(resolvedPath)}`;
2020
+ return `${baseUrl}${resolvedPath}`;
2021
+ }, [
2022
+ currentPath,
2023
+ baseUrl,
2024
+ imageApiBase
2025
+ ]);
2026
+ const markdownComponents = useMemo(() => ({
2027
+ a({ href, children, ...props }) {
2028
+ const resolvedHref = resolveHref(href);
2029
+ return /* @__PURE__ */ jsx("a", {
2030
+ href: resolvedHref,
2031
+ onClick: (e) => href && handleLinkClick(e, href),
2032
+ ...props,
2033
+ children
2034
+ });
2035
+ },
2036
+ code(props) {
2037
+ const { children, className: codeClassName, ...rest } = props;
2038
+ const match = /language-(\w+)/.exec(codeClassName || "");
2039
+ if (match && match[1] === "mermaid") return /* @__PURE__ */ jsx(MermaidDiagram, { code: String(children).replace(/\n$/, "") });
2040
+ return /* @__PURE__ */ jsx("code", {
2041
+ className: codeClassName,
2042
+ ...rest,
2043
+ children
2044
+ });
2045
+ }
2046
+ }), [handleLinkClick, resolveHref]);
2047
+ const proseClasses = [
2048
+ "prose prose-slate dark:prose-invert max-w-none",
2049
+ "prose-headings:font-semibold prose-headings:tracking-tight prose-headings:text-slate-900 dark:prose-headings:text-slate-100",
2050
+ "prose-h1:text-[2em] prose-h1:mb-3 prose-h1:pb-[0.3em] prose-h1:border-b prose-h1:border-slate-200 dark:prose-h1:border-slate-700",
2051
+ "prose-h2:text-[1.5em] prose-h2:mt-6 prose-h2:mb-3 prose-h2:pb-[0.3em] prose-h2:border-b prose-h2:border-slate-200 dark:prose-h2:border-slate-700",
2052
+ "prose-h3:text-[1.25em] prose-h3:mt-6 prose-h3:mb-2",
2053
+ "prose-h4:text-[1em] prose-h4:mt-6 prose-h4:mb-2",
2054
+ "prose-p:text-slate-700 dark:prose-p:text-slate-300 prose-p:leading-[1.5] prose-p:my-[16px]",
2055
+ "prose-ul:my-[16px] prose-ul:list-disc prose-li:my-0.5 prose-li:marker:text-slate-900 dark:prose-li:marker:text-slate-300",
2056
+ "prose-ol:my-[16px] prose-li:marker:text-slate-900 dark:prose-li:marker:text-slate-300",
2057
+ "prose-pre:bg-slate-50 dark:prose-pre:bg-slate-800 prose-pre:border prose-pre:border-slate-200 dark:prose-pre:border-slate-700 prose-pre:p-4 prose-pre:rounded-md prose-pre:text-[85%] prose-pre:leading-[1.45]",
2058
+ "prose-a:text-blue-600 dark:prose-a:text-blue-400 prose-a:no-underline hover:prose-a:underline",
2059
+ "prose-img:rounded-lg prose-img:my-4",
2060
+ "prose-blockquote:border-l-[0.25em] prose-blockquote:border-slate-300 dark:prose-blockquote:border-slate-600 prose-blockquote:pl-4 prose-blockquote:text-slate-600 dark:prose-blockquote:text-slate-400 prose-blockquote:italic",
2061
+ "prose-code:before:content-none prose-code:after:content-none",
2062
+ "prose-code:bg-slate-100 dark:prose-code:bg-slate-800 prose-code:px-[0.4em] prose-code:py-[0.2em] prose-code:rounded-md prose-code:text-slate-800 dark:prose-code:text-slate-200 prose-code:font-mono prose-code:text-[85%] prose-code:font-normal prose-code:border prose-code:border-slate-200/50 dark:prose-code:border-slate-700/50",
2063
+ "prose-table:text-sm",
2064
+ "prose-th:px-3 prose-th:py-1.5 prose-th:border prose-th:border-slate-200 dark:prose-th:border-slate-700",
2065
+ "prose-td:px-3 prose-td:py-1.5 prose-td:border prose-td:border-slate-200 dark:prose-td:border-slate-700"
2066
+ ].join(" ");
2067
+ return /* @__PURE__ */ jsxs("div", {
2068
+ ref: containerRef,
2069
+ className: className ? `${proseClasses} ${className}` : proseClasses,
2070
+ children: [/* @__PURE__ */ jsx(FrontmatterDisplay, { frontmatter }), /* @__PURE__ */ jsx(ReactMarkdown, {
2071
+ remarkPlugins,
2072
+ rehypePlugins,
2073
+ urlTransform: transformImageUri,
2074
+ components: markdownComponents,
2075
+ children: body
2076
+ })]
2077
+ });
1720
2078
  };
1721
- var MarkdownViewer = memo(
1722
- MarkdownViewerInner,
1723
- (prevProps, nextProps) => prevProps.content === nextProps.content && prevProps.currentPath === nextProps.currentPath && prevProps.hash === nextProps.hash && prevProps.className === nextProps.className
1724
- );
2079
+ const MarkdownViewer = memo(MarkdownViewerInner, (prevProps, nextProps) => prevProps.content === nextProps.content && prevProps.currentPath === nextProps.currentPath && prevProps.hash === nextProps.hash && prevProps.className === nextProps.className);
2080
+ //#endregion
2081
+ //#region src/renderMarkdown.ts
2082
+ /**
2083
+ * Framework-agnostic markdown -> HTML rendering pipeline.
2084
+ * Uses the same remark/rehype chain as the Vantage viewer.
2085
+ */
2086
+ /**
2087
+ * Render a markdown string to HTML using the full Vantage pipeline.
2088
+ *
2089
+ * Features (all enabled by default):
2090
+ * - GitHub Flavored Markdown (tables, strikethrough, task lists)
2091
+ * - KaTeX math rendering, inline and block ($$...$$ only; single $ is not a delimiter)
2092
+ * - Syntax highlighting via highlight.js
2093
+ * - `data-source-line` attributes for line anchors
2094
+ * - XSS sanitization
2095
+ * - Heading slugs/anchors
2096
+ * - YAML/TOML frontmatter parsing
2097
+ *
2098
+ * Mermaid diagrams are NOT rendered server-side (they require a browser).
2099
+ * Mermaid code blocks are preserved as `<pre><code class="language-mermaid">`.
2100
+ * Use the React `<MarkdownViewer>` component for client-side mermaid rendering.
2101
+ */
1725
2102
  async function renderMarkdown(content, options = {}) {
1726
- const {
1727
- gfm = true,
1728
- math = true,
1729
- highlight = true,
1730
- sourceLines = true,
1731
- sanitize = true,
1732
- frontmatter: parseFm = true
1733
- } = options;
1734
- let parsed;
1735
- if (parseFm) {
1736
- parsed = parseFrontmatter(content);
1737
- } else {
1738
- parsed = {
1739
- frontmatter: {},
1740
- body: content,
1741
- format: "none",
1742
- bodyLineOffset: 0
1743
- };
1744
- }
1745
- const { remarkPlugins, rehypePlugins } = buildPipeline({
1746
- gfm,
1747
- math,
1748
- highlight,
1749
- sourceLines,
1750
- sanitize,
1751
- bodyLineOffset: parsed.bodyLineOffset
1752
- });
1753
- const processor = unified().use(remarkParse).use(remarkPlugins).use(remarkRehype, { allowDangerousHtml: true }).use(rehypePlugins).use(rehypeStringify);
1754
- const result = await processor.process(parsed.body);
1755
- return {
1756
- html: String(result),
1757
- frontmatter: parsed.frontmatter,
1758
- body: parsed.body
1759
- };
2103
+ const { gfm = true, math = true, highlight = true, sourceLines = true, sanitize = true, frontmatter: parseFm = true } = options;
2104
+ let parsed;
2105
+ if (parseFm) parsed = parseFrontmatter(content);
2106
+ else parsed = {
2107
+ frontmatter: {},
2108
+ body: content,
2109
+ format: "none",
2110
+ bodyLineOffset: 0
2111
+ };
2112
+ const { remarkPlugins, rehypePlugins } = buildPipeline({
2113
+ gfm,
2114
+ math,
2115
+ highlight,
2116
+ sourceLines,
2117
+ sanitize,
2118
+ bodyLineOffset: parsed.bodyLineOffset
2119
+ });
2120
+ const result = await unified().use(remarkParse).use(remarkPlugins).use(remarkRehype, { allowDangerousHtml: true }).use(rehypePlugins).use(rehypeStringify).process(parsed.body);
2121
+ return {
2122
+ html: String(result),
2123
+ frontmatter: parsed.frontmatter,
2124
+ body: parsed.body
2125
+ };
1760
2126
  }
1761
-
1762
- // src/renderMermaidBlocks.ts
2127
+ //#endregion
2128
+ //#region src/renderMermaidBlocks.ts
2129
+ /**
2130
+ * Client-side utility to find and render mermaid code blocks in a container.
2131
+ *
2132
+ * After calling `renderMarkdown()`, mermaid blocks come through as
2133
+ * `<pre><code class="language-mermaid">...</code></pre>`. This function
2134
+ * finds those blocks and replaces them with rendered SVG diagrams.
2135
+ *
2136
+ * Framework-agnostic — works in any browser environment.
2137
+ */
2138
+ /**
2139
+ * Find all `<pre><code class="language-mermaid">` blocks in a container
2140
+ * and replace them with rendered SVG diagrams.
2141
+ *
2142
+ * @param container - DOM element containing rendered markdown HTML
2143
+ * @param options - Optional configuration
2144
+ * @returns Promise that resolves when all diagrams are rendered
2145
+ *
2146
+ * @example
2147
+ * ```ts
2148
+ * import { renderMarkdown, renderMermaidBlocks } from "vantage-md";
2149
+ *
2150
+ * const { html } = await renderMarkdown(content);
2151
+ * container.innerHTML = html;
2152
+ * await renderMermaidBlocks(container);
2153
+ * ```
2154
+ */
1763
2155
  async function renderMermaidBlocks(container, options = {}) {
1764
- const { className = "mermaid", onError } = options;
1765
- const codeBlocks = container.querySelectorAll(
1766
- 'pre > code.language-mermaid, pre > code[class*="language-mermaid"]'
1767
- );
1768
- if (codeBlocks.length === 0) return;
1769
- const mermaid = await getMermaid();
1770
- const renderPromises = Array.from(codeBlocks).map(async (codeEl) => {
1771
- const preEl = codeEl.parentElement;
1772
- if (!preEl) return;
1773
- const code = codeEl.textContent || "";
1774
- if (!code.trim()) return;
1775
- const cached = svgCache.get(code);
1776
- if (cached) {
1777
- replaceWithSvg(preEl, cached, className);
1778
- return;
1779
- }
1780
- try {
1781
- let hash = 0;
1782
- for (let i = 0; i < code.length; i++) {
1783
- hash = (hash << 5) - hash + code.charCodeAt(i);
1784
- hash = hash & hash;
1785
- }
1786
- const id = `mermaid-${Math.abs(hash).toString(36)}-${Date.now()}`;
1787
- const { svg } = await mermaid.render(id, code);
1788
- svgCache.set(code, svg);
1789
- replaceWithSvg(preEl, svg, className);
1790
- } catch (err) {
1791
- if (onError) {
1792
- onError(code, err instanceof Error ? err : new Error(String(err)));
1793
- }
1794
- }
1795
- });
1796
- await Promise.all(renderPromises);
2156
+ const { className = "mermaid", onError } = options;
2157
+ const codeBlocks = container.querySelectorAll("pre > code.language-mermaid, pre > code[class*=\"language-mermaid\"]");
2158
+ if (codeBlocks.length === 0) return;
2159
+ const mermaid = await getMermaid();
2160
+ const renderPromises = Array.from(codeBlocks).map(async (codeEl) => {
2161
+ const preEl = codeEl.parentElement;
2162
+ if (!preEl) return;
2163
+ const code = codeEl.textContent || "";
2164
+ if (!code.trim()) return;
2165
+ const cached = svgCache.get(code);
2166
+ if (cached) {
2167
+ replaceWithSvg(preEl, cached, className);
2168
+ return;
2169
+ }
2170
+ try {
2171
+ let hash = 0;
2172
+ for (let i = 0; i < code.length; i++) {
2173
+ hash = (hash << 5) - hash + code.charCodeAt(i);
2174
+ hash = hash & hash;
2175
+ }
2176
+ const id = `mermaid-${Math.abs(hash).toString(36)}-${Date.now()}`;
2177
+ const { svg } = await mermaid.render(id, code);
2178
+ svgCache.set(code, svg);
2179
+ replaceWithSvg(preEl, svg, className);
2180
+ } catch (err) {
2181
+ if (onError) onError(code, err instanceof Error ? err : new Error(String(err)));
2182
+ }
2183
+ });
2184
+ await Promise.all(renderPromises);
1797
2185
  }
1798
2186
  function replaceWithSvg(preEl, svg, className) {
1799
- const wrapper = document.createElement("div");
1800
- wrapper.className = className;
1801
- wrapper.innerHTML = svg;
1802
- preEl.replaceWith(wrapper);
2187
+ const wrapper = document.createElement("div");
2188
+ wrapper.className = className;
2189
+ wrapper.innerHTML = svg;
2190
+ preEl.replaceWith(wrapper);
1803
2191
  }
1804
-
1805
- // src/resolveLinks.ts
2192
+ //#endregion
2193
+ //#region src/resolveLinks.ts
2194
+ /**
2195
+ * Rewrite relative links in rendered HTML.
2196
+ *
2197
+ * Processes all `href="..."` attributes, skipping:
2198
+ * - Absolute URLs (http://, https://, mailto:, etc.)
2199
+ * - Anchor-only links (#section)
2200
+ * - Already-absolute paths (/path/to/file)
2201
+ *
2202
+ * @example
2203
+ * ```ts
2204
+ * import { renderMarkdown, resolveLinks } from "vantage-md";
2205
+ *
2206
+ * const { html } = await renderMarkdown(content);
2207
+ *
2208
+ * // Simple: prepend a base path
2209
+ * const resolved = resolveLinks(html, { basePath: "/docs/", currentPath: "guides/setup.md" });
2210
+ *
2211
+ * // Custom: full control over link rewriting
2212
+ * const resolved = resolveLinks(html, {
2213
+ * currentPath: "guides/setup.md",
2214
+ * rewriter: (href, currentPath) => `/kb/${currentPath}/../${href}`,
2215
+ * });
2216
+ * ```
2217
+ */
1806
2218
  function resolveLinks(html, options = {}) {
1807
- const { basePath = "/", rewriter, currentPath = "" } = options;
1808
- const parts = currentPath.split("/");
1809
- parts.pop();
1810
- const currentDir = parts.join("/");
1811
- return html.replace(
1812
- /href="([^"]*?)"/g,
1813
- (_match, href) => {
1814
- if (href.startsWith("http://") || href.startsWith("https://") || href.startsWith("mailto:") || href.startsWith("data:") || href.startsWith("#") || href.startsWith("/")) {
1815
- return `href="${href}"`;
1816
- }
1817
- if (rewriter) {
1818
- const result = rewriter(href, currentPath);
1819
- if (result !== null) {
1820
- return `href="${result}"`;
1821
- }
1822
- return `href="${href}"`;
1823
- }
1824
- const [pathPart, hashPart] = href.split("#");
1825
- const cleanHref = pathPart.replace(/^\.\//, "");
1826
- const resolvedPath = currentDir ? `${currentDir}/${cleanHref}` : cleanHref;
1827
- const base = basePath.endsWith("/") ? basePath : `${basePath}/`;
1828
- const finalHref = `${base}${resolvedPath}${hashPart ? `#${hashPart}` : ""}`;
1829
- return `href="${finalHref}"`;
1830
- }
1831
- );
2219
+ const { basePath = "/", rewriter, currentPath = "" } = options;
2220
+ const parts = currentPath.split("/");
2221
+ parts.pop();
2222
+ const currentDir = parts.join("/");
2223
+ return html.replace(/href="([^"]*?)"/g, (_match, href) => {
2224
+ if (href.startsWith("http://") || href.startsWith("https://") || href.startsWith("mailto:") || href.startsWith("data:") || href.startsWith("#") || href.startsWith("/")) return `href="${href}"`;
2225
+ if (rewriter) {
2226
+ const result = rewriter(href, currentPath);
2227
+ if (result !== null) return `href="${result}"`;
2228
+ return `href="${href}"`;
2229
+ }
2230
+ const [pathPart, hashPart] = href.split("#");
2231
+ const cleanHref = pathPart.replace(/^\.\//, "");
2232
+ const resolvedPath = currentDir ? `${currentDir}/${cleanHref}` : cleanHref;
2233
+ return `href="${`${basePath.endsWith("/") ? basePath : `${basePath}/`}${resolvedPath}${hashPart ? `#${hashPart}` : ""}`}"`;
2234
+ });
1832
2235
  }
2236
+ //#endregion
2237
+ export { DOC_STATUSES, DOC_STATUS_TONES, DocumentStatusChip, FrontmatterDisplay, MarkdownViewer, MermaidDiagram, VANTAGE_FRONTMATTER_KEYS, buildPipeline, buildRemarkPlugins, clearLineAnchorHighlights, isDocStatus, parseFrontmatter, parseLineAnchor, readVantageFrontmatter, rehypeSourceLines, renderMarkdown, renderMermaidBlocks, resolveLinks, sanitizeSchema, scrollToLineAnchor, useLineAnchor };
1833
2238
 
1834
- export { DOC_STATUSES, DOC_STATUS_TONES, DocumentStatusChip, FrontmatterDisplay, MarkdownViewer, MermaidDiagram, VANTAGE_FRONTMATTER_KEYS, buildPipeline, buildRemarkPlugins, clearLineAnchorHighlights, isDocStatus, parseFrontmatter, parseLineAnchor, readVantageFrontmatter, rehypeSourceLines_default as rehypeSourceLines, renderMarkdown, renderMermaidBlocks, resolveLinks, sanitizeSchema, scrollToLineAnchor, useLineAnchor };
1835
- //# sourceMappingURL=react.js.map
1836
2239
  //# sourceMappingURL=react.js.map