vantage-md 0.5.4 → 0.5.6

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