markemental 0.2.0 → 0.4.0

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/index.cjs CHANGED
@@ -1,775 +1,1596 @@
1
- 'use strict';
2
-
3
- // src/renderers/util/inline.ts
4
- var ESCAPABLE_RE = /^[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]$/;
5
- var AUTOLINK_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:[^<>\s]*$/;
6
- var ALNUM_RE = /[A-Za-z0-9]/;
7
- function tryParseLink(text, start) {
8
- const labelEnd = text.indexOf("]", start + 1);
9
- if (labelEnd === -1 || text[labelEnd + 1] !== "(") return null;
10
- const label = text.slice(start + 1, labelEnd);
11
- if (label.includes("[") || label.includes("\n")) return null;
12
- const hrefEnd = text.indexOf(")", labelEnd + 2);
13
- if (hrefEnd === -1) return null;
14
- const inside = text.slice(labelEnd + 2, hrefEnd).trim();
15
- if (inside === "") return null;
16
- if (/\s/.test(inside) && !/^<?\S+>?\s+"[^"]*"$/.test(inside)) return null;
17
- const href = inside.replace(/^<(.*)>$/, "$1").split(/\s+/)[0];
18
- return { label, href, end: hrefEnd + 1 };
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/streams/markdown-stream.ts
3
+ /**
4
+ * Create a streaming pipeline around any renderer and target.
5
+ *
6
+ * @remarks
7
+ * The pipeline chunks whatever strings are written into lines and feeds
8
+ * them to the renderer one at a time; the renderer owns its parse state
9
+ * and commits finished output to the target. Closing the stream renders
10
+ * the trailing remainder. Pass a built-in renderer (`GFMRenderer`,
11
+ * `CommonMarkRenderer`) or your own `MarkdownRenderer` implementation,
12
+ * and a DOM target from `createDOMTarget` or your own `HTMLTarget`.
13
+ *
14
+ * @param renderer - Line-consuming renderer holding its own parse state.
15
+ * @param target - Destination the renderer commits to.
16
+ * @returns A working pipeline.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const target = createDOMTarget(document, document.getElementById("out")!);
21
+ * const stream = createMarkdownStream(new GFMRenderer(target, {}), target);
22
+ * const writer = stream.getWriter();
23
+ * await writer.write("# Hello\n");
24
+ * await writer.close();
25
+ * writer.releaseLock();
26
+ * ```
27
+ *
28
+ * @public
29
+ */
30
+ function createMarkdownStream(renderer, target) {
31
+ renderer.setTarget(target);
32
+ let buffer = "";
33
+ const pipeline = new WritableStream({
34
+ write(chunk) {
35
+ if (typeof chunk !== "string") throw new TypeError(`MarkdownPipeline chunks must be strings, received ${typeof chunk}`);
36
+ buffer += chunk;
37
+ let at = buffer.indexOf("\n");
38
+ while (at !== -1) {
39
+ renderer.writeLine(buffer.slice(0, at).replace(/\r$/, ""));
40
+ buffer = buffer.slice(at + 1);
41
+ at = buffer.indexOf("\n");
42
+ }
43
+ },
44
+ close() {
45
+ if (buffer !== "") {
46
+ const rest = buffer.replace(/\r$/, "");
47
+ buffer = "";
48
+ renderer.writeLine(rest);
49
+ }
50
+ return renderer.flush();
51
+ }
52
+ });
53
+ pipeline.setTarget = (next) => {
54
+ renderer.setTarget(next);
55
+ };
56
+ pipeline.setConfig = (next) => {
57
+ renderer.setConfig(next);
58
+ };
59
+ return pipeline;
19
60
  }
20
- function matchEmphasis(text, i, gfm) {
21
- if (gfm && text.startsWith("~~", i)) return { marker: "~~", tag: "del", underscore: false };
22
- if (text.startsWith("**", i)) return { marker: "**", tag: "strong", underscore: false };
23
- if (text.startsWith("__", i)) return { marker: "__", tag: "strong", underscore: true };
24
- if (text[i] === "*") return { marker: "*", tag: "em", underscore: false };
25
- if (text[i] === "_") {
26
- if (i > 0 && ALNUM_RE.test(text[i - 1])) return null;
27
- return { marker: "_", tag: "em", underscore: true };
28
- }
29
- return null;
61
+ // src/core/contracts/html-target.ts
62
+ /**
63
+ * A target call referenced an id the target never minted or already
64
+ * retired. Carries the offending id.
65
+ *
66
+ * @public
67
+ */
68
+ var UnknownNodeError = class extends Error {
69
+ /** The unknown id. */
70
+ nodeId;
71
+ /**
72
+ * @param nodeId - The unknown id.
73
+ */
74
+ constructor(nodeId) {
75
+ super(`Unknown node id: ${nodeId}`);
76
+ this.name = "UnknownNodeError";
77
+ this.nodeId = nodeId;
78
+ }
79
+ };
80
+ /**
81
+ * A replace targeted a node that was never attached. Carries the
82
+ * detached id.
83
+ *
84
+ * @public
85
+ */
86
+ var DetachedNodeError = class extends Error {
87
+ /** The detached id. */
88
+ nodeId;
89
+ /**
90
+ * @param nodeId - The detached id.
91
+ */
92
+ constructor(nodeId) {
93
+ super(`Cannot replace detached node: ${nodeId}`);
94
+ this.name = "DetachedNodeError";
95
+ this.nodeId = nodeId;
96
+ }
97
+ };
98
+ /**
99
+ * An attach would have built a cycle: the node is an ancestor of the
100
+ * parent. Carries both ids.
101
+ *
102
+ * @public
103
+ */
104
+ var HierarchyError = class extends Error {
105
+ /** The node being attached. */
106
+ nodeId;
107
+ /** The parent it was attached to. */
108
+ parentId;
109
+ /**
110
+ * @param nodeId - The node being attached.
111
+ * @param parentId - The parent it was attached to.
112
+ */
113
+ constructor(nodeId, parentId) {
114
+ super(`Cannot attach node ${nodeId} inside its own descendant ${parentId}`);
115
+ this.name = "HierarchyError";
116
+ this.nodeId = nodeId;
117
+ this.parentId = parentId;
118
+ }
119
+ };
120
+ // src/renderers/parser/blocks.ts
121
+ const HEADING_RE = /^(#{1,6})(?:\s+(.*))?\s*$/;
122
+ const RULE_RE = /^(?:\*\s*){3,}$|^(?:-\s*){3,}$|^(?:_\s*){3,}$/;
123
+ const FENCE_RE = /^(`{3,}|~{3,})\s*([^`]*)$/;
124
+ const QUOTE_RE = /^>\s?(.*)$/;
125
+ const BULLET_RE = /^\s*[-*+]\s+(.*)$/;
126
+ const ORDERED_RE = /^\s*\d+[.)]\s+(.*)$/;
127
+ const TABLE_DELIM_CELL_RE = /^:?-{1,}:?$/;
128
+ const LEADING_WS_RE = /^\s*/;
129
+ /**
130
+ * Whether a line is blank (a pure block separator carrying no content).
131
+ *
132
+ * @param line - Source line to test.
133
+ * @returns True for empty or whitespace-only lines.
134
+ */
135
+ function isBlankLine(line) {
136
+ return line.trim() === "";
30
137
  }
31
- function findEmphasisClose(text, from, token) {
32
- let at = text.indexOf(token.marker, from);
33
- while (at !== -1 && token.underscore) {
34
- const next = text[at + token.marker.length];
35
- if (next === void 0 || !ALNUM_RE.test(next)) return at;
36
- at = text.indexOf(token.marker, at + 1);
37
- }
38
- return at;
138
+ /**
139
+ * Match a fence marker line.
140
+ *
141
+ * @param line - Source line to test.
142
+ * @returns The marker, or null when the line is not a fence marker.
143
+ */
144
+ function matchFence(line) {
145
+ const match = FENCE_RE.exec(line.trim());
146
+ if (!match || !match[1]) return null;
147
+ const run = match[1];
148
+ return {
149
+ marker: run[0],
150
+ length: run.length,
151
+ language: (match[2] ?? "").trim() || void 0
152
+ };
39
153
  }
40
- function appendInline(parent, text, doc, gfm) {
41
- let i = 0;
42
- let literal = "";
43
- const flushLiteral = () => {
44
- if (literal !== "") {
45
- parent.appendChild(doc.createTextNode(literal));
46
- literal = "";
47
- }
48
- };
49
- while (i < text.length) {
50
- const ch = text[i];
51
- if (ch === "\\" && i + 1 < text.length && ESCAPABLE_RE.test(text[i + 1])) {
52
- literal += text[i + 1];
53
- i += 2;
54
- continue;
55
- }
56
- if (ch === "`") {
57
- const run = /^`+/.exec(text.slice(i));
58
- const close = text.indexOf(run[0], i + run[0].length);
59
- if (close !== -1) {
60
- flushLiteral();
61
- const code = doc.createElement("code");
62
- code.appendChild(doc.createTextNode(text.slice(i + run[0].length, close)));
63
- parent.appendChild(code);
64
- i = close + run[0].length;
65
- continue;
66
- }
67
- literal += ch;
68
- i++;
69
- continue;
70
- }
71
- if (ch === "!" && text[i + 1] === "[") {
72
- const link = tryParseLink(text, i + 1);
73
- if (link && link.href !== "") {
74
- flushLiteral();
75
- const img = doc.createElement("img");
76
- img.setAttribute?.("src", link.href);
77
- img.setAttribute?.("alt", link.label);
78
- parent.appendChild(img);
79
- i = link.end;
80
- continue;
81
- }
82
- }
83
- if (ch === "[") {
84
- const link = tryParseLink(text, i);
85
- if (link) {
86
- flushLiteral();
87
- const anchor = doc.createElement("a");
88
- anchor.setAttribute?.("href", link.href);
89
- appendInline(anchor, link.label, doc, gfm);
90
- parent.appendChild(anchor);
91
- i = link.end;
92
- continue;
93
- }
94
- literal += ch;
95
- i++;
96
- continue;
97
- }
98
- if (ch === "<") {
99
- const end = text.indexOf(">", i + 1);
100
- if (end !== -1 && AUTOLINK_RE.test(text.slice(i + 1, end))) {
101
- flushLiteral();
102
- const href = text.slice(i + 1, end);
103
- const anchor = doc.createElement("a");
104
- anchor.setAttribute?.("href", href);
105
- anchor.appendChild(doc.createTextNode(href));
106
- parent.appendChild(anchor);
107
- i = end + 1;
108
- continue;
109
- }
110
- literal += ch;
111
- i++;
112
- continue;
113
- }
114
- const token = matchEmphasis(text, i, gfm);
115
- if (token) {
116
- const close = findEmphasisClose(text, i + token.marker.length, token);
117
- if (close !== -1 && close > i + token.marker.length) {
118
- flushLiteral();
119
- const el = doc.createElement(token.tag);
120
- appendInline(el, text.slice(i + token.marker.length, close), doc, gfm);
121
- parent.appendChild(el);
122
- i = close + token.marker.length;
123
- continue;
124
- }
125
- literal += token.marker;
126
- i += token.marker.length;
127
- continue;
128
- }
129
- literal += ch;
130
- i++;
131
- }
132
- flushLiteral();
154
+ /**
155
+ * Whether a line closes an open fence.
156
+ *
157
+ * @param open - Marker that opened the fence.
158
+ * @param line - Source line to test.
159
+ * @returns True for a same-character run at least as long.
160
+ */
161
+ function fenceCloses(open, line) {
162
+ const match = matchFence(line);
163
+ return match !== null && match.marker === open.marker && match.length >= open.length;
133
164
  }
134
-
135
- // src/renderers/commonmark.ts
136
- var CommonMarkRenderer = class {
137
- /** Rendering options. */
138
- options;
139
- /**
140
- * @param opts - CommonMark rendering options.
141
- */
142
- constructor(opts) {
143
- this.options = opts;
144
- }
145
- /**
146
- * Whether GFM-only inlines are enabled. Always false here; overridden by
147
- * {@link GFMRenderer}.
148
- *
149
- * @returns False.
150
- */
151
- inlineGfm() {
152
- return false;
153
- }
154
- /**
155
- * Render one block to a DOM-like node.
156
- *
157
- * @param block - Parsed block to render.
158
- * @param doc - Document used to create nodes.
159
- * @returns The rendered node, or `null` to emit nothing.
160
- */
161
- renderBlock(block, doc) {
162
- switch (block.kind) {
163
- case "heading": {
164
- const heading = doc.createElement(`h${block.level ?? 1}`);
165
- this.appendLinesInline(heading, block.lines, doc, " ");
166
- return heading;
167
- }
168
- case "paragraph":
169
- return this.renderParagraph(block.lines, doc);
170
- case "fence": {
171
- const pre = doc.createElement("pre");
172
- const code = doc.createElement("code");
173
- if (block.language !== void 0) code.setAttribute?.("class", `language-${block.language}`);
174
- const text = block.lines.join("\n");
175
- code.appendChild(doc.createTextNode(text === "" ? "" : `${text}
176
- `));
177
- pre.appendChild(code);
178
- return pre;
179
- }
180
- case "list": {
181
- const list = doc.createElement(block.ordered ? "ol" : "ul");
182
- for (const item of block.lines) {
183
- const li = doc.createElement("li");
184
- appendInline(li, item, doc, this.inlineGfm());
185
- list.appendChild(li);
186
- }
187
- return list;
188
- }
189
- case "quote": {
190
- const quote = doc.createElement("blockquote");
191
- const body = doc.createElement("p");
192
- this.appendLinesInline(body, block.lines, doc, " ");
193
- quote.appendChild(body);
194
- return quote;
195
- }
196
- case "rule":
197
- return doc.createElement("hr");
198
- case "table":
199
- return this.renderParagraph(block.lines.filter((_, at) => at !== 1), doc);
200
- }
201
- }
202
- /**
203
- * Render paragraph lines, honoring two-space hard breaks.
204
- *
205
- * @param lines - Raw paragraph lines.
206
- * @param doc - Document used to create nodes.
207
- * @returns The paragraph element.
208
- */
209
- renderParagraph(lines, doc) {
210
- const paragraph = doc.createElement("p");
211
- lines.forEach((line, at) => {
212
- const hardBreak = / {2,}$/.test(line);
213
- appendInline(paragraph, hardBreak ? line.replace(/ {2,}$/, "") : line, doc, this.inlineGfm());
214
- if (at < lines.length - 1) {
215
- if (hardBreak) paragraph.appendChild(doc.createElement("br"));
216
- else paragraph.appendChild(doc.createTextNode(" "));
217
- }
218
- });
219
- return paragraph;
220
- }
221
- appendLinesInline(parent, lines, doc, join) {
222
- lines.forEach((line, at) => {
223
- if (at > 0) parent.appendChild(doc.createTextNode(join));
224
- appendInline(parent, line, doc, this.inlineGfm());
225
- });
226
- }
227
- };
228
-
229
- // src/renderers/gfm.ts
230
- function splitRow(line) {
231
- return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
165
+ /**
166
+ * Match an ATX heading line.
167
+ *
168
+ * @param line - Source line to test.
169
+ * @returns The heading, or null for non-heading lines.
170
+ */
171
+ function matchHeading(line) {
172
+ const match = HEADING_RE.exec(line);
173
+ if (!match || !match[1]) return null;
174
+ return {
175
+ level: Math.min(6, match[1].length),
176
+ text: (match[2] ?? "").replace(/\s+#+\s*$/, "").trim()
177
+ };
232
178
  }
233
- function parseAlignment(cell) {
234
- const left = cell.startsWith(":");
235
- const right = cell.endsWith(":");
236
- if (left && right) return "center";
237
- if (right) return "right";
238
- if (left) return "left";
239
- return null;
179
+ /**
180
+ * Whether a line is a thematic break.
181
+ *
182
+ * @param line - Source line to test.
183
+ * @returns True for `***`, `---`, `___` style lines.
184
+ */
185
+ function isRuleLine(line) {
186
+ return RULE_RE.test(line.trim());
240
187
  }
241
- var GFMRenderer = class extends CommonMarkRenderer {
242
- /** Rendering options. */
243
- options;
244
- /**
245
- * @param opts - GFM rendering options.
246
- */
247
- constructor(opts) {
248
- super({});
249
- this.options = opts;
250
- }
251
- /**
252
- * GFM-only inlines are enabled.
253
- *
254
- * @returns True.
255
- */
256
- inlineGfm() {
257
- return true;
258
- }
259
- /**
260
- * Render one block to a DOM-like node, handling GFM tables.
261
- *
262
- * @param block - Parsed block to render.
263
- * @param doc - Document used to create nodes.
264
- * @returns The rendered node, or `null` to emit nothing.
265
- */
266
- renderBlock(block, doc) {
267
- if (block.kind !== "table") return super.renderBlock(block, doc);
268
- const rows = block.lines.map(splitRow);
269
- const header = rows[0] ?? [];
270
- const alignments = (rows[1] ?? []).map(parseAlignment);
271
- const width = Math.max(header.length, ...rows.map((row) => row.length));
272
- const table = doc.createElement("table");
273
- const head = doc.createElement("thead");
274
- const headRow = doc.createElement("tr");
275
- for (let col = 0; col < width; col++) {
276
- const cell = doc.createElement("th");
277
- const align = alignments[col] ?? null;
278
- if (align !== null) cell.setAttribute?.("align", align);
279
- appendInline(cell, header[col] ?? "", doc, true);
280
- headRow.appendChild(cell);
281
- }
282
- head.appendChild(headRow);
283
- table.appendChild(head);
284
- const body = doc.createElement("tbody");
285
- for (const row of rows.slice(2)) {
286
- const bodyRow = doc.createElement("tr");
287
- for (let col = 0; col < width; col++) {
288
- const cell = doc.createElement("td");
289
- const align = alignments[col] ?? null;
290
- if (align !== null) cell.setAttribute?.("align", align);
291
- appendInline(cell, row[col] ?? "", doc, true);
292
- bodyRow.appendChild(cell);
293
- }
294
- body.appendChild(bodyRow);
295
- }
296
- table.appendChild(body);
297
- return table;
298
- }
299
- };
300
-
301
- // src/targets/animated-dom-target.ts
302
- var AnimatedDOMTarget = class {
303
- _targetNode;
304
- _raf;
305
- _queue = [];
306
- _scheduled = false;
307
- _flushResolvers = [];
308
- /**
309
- * @param targetNode - Container node receiving rendered output.
310
- * @param raf - Frame scheduler used to batch writes.
311
- */
312
- constructor(targetNode, raf) {
313
- this._targetNode = targetNode;
314
- this._raf = raf;
315
- }
316
- /**
317
- * Queue a rendered node for the next frame.
318
- *
319
- * @param node - Node to attach.
320
- */
321
- append(node) {
322
- this._queue.push(node);
323
- if (!this._scheduled) {
324
- this._scheduled = true;
325
- this._raf(() => {
326
- this._scheduled = false;
327
- const batch = this._queue;
328
- this._queue = [];
329
- for (const queued of batch) this._targetNode.appendChild(queued);
330
- const resolvers = this._flushResolvers;
331
- this._flushResolvers = [];
332
- for (const resolve of resolvers) resolve();
333
- });
334
- }
335
- }
336
- /**
337
- * Wait until every queued node has been attached.
338
- *
339
- * @returns A promise that resolves after the next frame carrying nodes.
340
- */
341
- flush() {
342
- if (!this._scheduled && this._queue.length === 0) return Promise.resolve();
343
- return new Promise((resolve) => {
344
- this._flushResolvers.push(resolve);
345
- });
346
- }
347
- };
348
-
349
- // src/targets/dom-target.ts
350
- var DOMTarget = class {
351
- _targetNode;
352
- /**
353
- * @param targetNode - Container node receiving rendered output.
354
- */
355
- constructor(targetNode) {
356
- this._targetNode = targetNode;
357
- }
358
- /**
359
- * Append a rendered node immediately.
360
- *
361
- * @param node - Node to attach.
362
- */
363
- append(node) {
364
- this._targetNode.appendChild(node);
365
- }
366
- /**
367
- * Resolve immediately: synchronous targets hold every node already.
368
- *
369
- * @returns A resolved promise.
370
- */
371
- flush() {
372
- return Promise.resolve();
373
- }
374
- };
375
-
376
- // src/core/util/blocks.ts
377
- var HEADING_RE = /^(#{1,6})(?:\s+(.*))?\s*$/;
378
- var RULE_RE = /^(?:\*\s*){3,}$|^(?:-\s*){3,}$|^(?:_\s*){3,}$/;
379
- var FENCE_RE = /^(`{3,}|~{3,})\s*([^`]*)$/;
380
- var QUOTE_RE = /^>\s?(.*)$/;
381
- var BULLET_RE = /^\s*[-*+]\s+(.*)$/;
382
- var ORDERED_RE = /^\s*\d+[.)]\s+(.*)$/;
383
- var TABLE_DELIM_CELL_RE = /^:?-{1,}:?$/;
384
- function isBlankLine(line) {
385
- return line.trim() === "";
188
+ /**
189
+ * Match a quote line.
190
+ *
191
+ * @param line - Source line to test.
192
+ * @returns The content, or null for non-quote lines.
193
+ */
194
+ function matchQuote(line) {
195
+ const match = QUOTE_RE.exec(line);
196
+ if (!match) return null;
197
+ return { text: match[1] ?? "" };
386
198
  }
387
- function isBlank(line) {
388
- return isBlankLine(line);
199
+ /**
200
+ * Match a bullet or ordered list item line.
201
+ *
202
+ * @param line - Source line to test.
203
+ * @returns The item, or null for non-item lines.
204
+ */
205
+ function matchListItem(line) {
206
+ const bullet = BULLET_RE.exec(line);
207
+ const ordered = ORDERED_RE.exec(line);
208
+ if (!bullet && !ordered) return null;
209
+ return {
210
+ ordered: !bullet,
211
+ indent: LEADING_WS_RE.exec(line)?.[0].length ?? 0,
212
+ text: bullet?.[1] ?? ordered?.[1] ?? ""
213
+ };
389
214
  }
215
+ /**
216
+ * Whether a line is a table delimiter row.
217
+ *
218
+ * @param line - Source line to test.
219
+ * @returns True for `|---|...` style rows.
220
+ */
390
221
  function isTableDelimiter(line) {
391
- if (!line.includes("|") && !line.includes("-")) return false;
392
- const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|");
393
- return cells.length > 0 && cells.every((cell) => TABLE_DELIM_CELL_RE.test(cell.trim()));
222
+ if (!line.includes("|") && !line.includes("-")) return false;
223
+ const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|");
224
+ return cells.length > 0 && cells.every((cell) => TABLE_DELIM_CELL_RE.test(cell.trim()));
394
225
  }
226
+ /**
227
+ * Whether `lines` ends inside an unclosed fenced code block.
228
+ *
229
+ * @param lines - Source lines to scan.
230
+ * @returns True when a fence opens without a matching close.
231
+ */
395
232
  function hasOpenFence(lines) {
396
- let openChar = "";
397
- let openLen = 0;
398
- for (const line of lines) {
399
- const match = FENCE_RE.exec(line.trim());
400
- if (!match || !match[1]) continue;
401
- const run = match[1];
402
- if (openChar === "") {
403
- openChar = run[0];
404
- openLen = run.length;
405
- } else if (run[0] === openChar && run.length >= openLen) {
406
- openChar = "";
407
- openLen = 0;
408
- }
409
- }
410
- return openChar !== "";
233
+ let open = null;
234
+ for (const line of lines) if (open === null) open = matchFence(line);
235
+ else if (fenceCloses(open, line)) open = null;
236
+ return open !== null;
411
237
  }
412
238
  function makeBlock(block, sourceLineCount) {
413
- return { ...block, sourceLineCount };
239
+ return {
240
+ ...block,
241
+ sourceLineCount
242
+ };
414
243
  }
244
+ /**
245
+ * Split leaf-block lines into blocks.
246
+ *
247
+ * @remarks
248
+ * Tables and lists never reach this function: the render state diverts them
249
+ * into streaming fragments, so only headings, paragraphs, fences, quotes,
250
+ * and rules are split here.
251
+ *
252
+ * @param lines - Source lines without line breaks.
253
+ * @returns Parsed blocks in document order.
254
+ */
415
255
  function splitBlocks(lines) {
416
- const blocks = [];
417
- let i = 0;
418
- while (i < lines.length) {
419
- const line = lines[i];
420
- if (isBlank(line)) {
421
- i++;
422
- continue;
423
- }
424
- const fence = FENCE_RE.exec(line.trim());
425
- if (fence && fence[1]) {
426
- const run = fence[1];
427
- const language = (fence[2] ?? "").trim() || void 0;
428
- const content = [];
429
- let j2 = i + 1;
430
- while (j2 < lines.length) {
431
- const inner = lines[j2];
432
- const close = FENCE_RE.exec(inner.trim());
433
- if (close && close[1] && close[1][0] === run[0] && close[1].length >= run.length) break;
434
- content.push(inner);
435
- j2++;
436
- }
437
- const closed = j2 < lines.length;
438
- blocks.push(makeBlock({ kind: "fence", lines: content, language }, j2 - i + (closed ? 1 : 0)));
439
- i = j2 + (closed ? 1 : 0);
440
- continue;
441
- }
442
- const heading = HEADING_RE.exec(line);
443
- if (heading && heading[1]) {
444
- const text = (heading[2] ?? "").replace(/\s+#+\s*$/, "").trim();
445
- blocks.push(makeBlock({ kind: "heading", lines: [text], level: Math.min(6, heading[1].length) }, 1));
446
- i++;
447
- continue;
448
- }
449
- if (RULE_RE.test(line.trim())) {
450
- blocks.push(makeBlock({ kind: "rule", lines: [] }, 1));
451
- i++;
452
- continue;
453
- }
454
- if (line.includes("|") && i + 1 < lines.length && isTableDelimiter(lines[i + 1])) {
455
- const rows = [line, lines[i + 1]];
456
- let j2 = i + 2;
457
- while (j2 < lines.length && !isBlank(lines[j2]) && lines[j2].includes("|")) {
458
- rows.push(lines[j2]);
459
- j2++;
460
- }
461
- blocks.push(makeBlock({ kind: "table", lines: rows }, j2 - i));
462
- i = j2;
463
- continue;
464
- }
465
- const quote = QUOTE_RE.exec(line);
466
- if (quote) {
467
- const quoted = [quote[1] ?? ""];
468
- let j2 = i + 1;
469
- while (j2 < lines.length) {
470
- const next = QUOTE_RE.exec(lines[j2]);
471
- if (!next) break;
472
- quoted.push(next[1] ?? "");
473
- j2++;
474
- }
475
- blocks.push(makeBlock({ kind: "quote", lines: quoted }, j2 - i));
476
- i = j2;
477
- continue;
478
- }
479
- const bullet = BULLET_RE.exec(line);
480
- const ordered = ORDERED_RE.exec(line);
481
- if (bullet || ordered) {
482
- const isOrdered = !bullet;
483
- const items = [bullet?.[1] ?? ordered?.[1] ?? ""];
484
- let j2 = i + 1;
485
- while (j2 < lines.length) {
486
- const nextBullet = BULLET_RE.exec(lines[j2]);
487
- const nextOrdered = ORDERED_RE.exec(lines[j2]);
488
- if (isOrdered && nextOrdered) items.push(nextOrdered[1] ?? "");
489
- else if (!isOrdered && nextBullet && !ORDERED_RE.test(lines[j2])) items.push(nextBullet[1] ?? "");
490
- else break;
491
- j2++;
492
- }
493
- blocks.push(makeBlock({ kind: "list", lines: items, ordered: isOrdered }, j2 - i));
494
- i = j2;
495
- continue;
496
- }
497
- const paragraph = [line];
498
- let j = i + 1;
499
- while (j < lines.length) {
500
- const next = lines[j];
501
- if (isBlank(next) || FENCE_RE.test(next.trim()) || HEADING_RE.test(next) || RULE_RE.test(next.trim()) || QUOTE_RE.test(next) || BULLET_RE.test(next) || ORDERED_RE.test(next) || next.includes("|") && j + 1 < lines.length && isTableDelimiter(lines[j + 1])) {
502
- break;
503
- }
504
- paragraph.push(next);
505
- j++;
506
- }
507
- blocks.push(makeBlock({ kind: "paragraph", lines: paragraph }, j - i));
508
- i = j;
509
- }
510
- return blocks;
256
+ const blocks = [];
257
+ let i = 0;
258
+ while (i < lines.length) {
259
+ const line = lines[i];
260
+ if (isBlankLine(line)) {
261
+ i++;
262
+ continue;
263
+ }
264
+ const fence = matchFence(line);
265
+ if (fence) {
266
+ const content = [];
267
+ let j = i + 1;
268
+ while (j < lines.length && !fenceCloses(fence, lines[j])) {
269
+ content.push(lines[j]);
270
+ j++;
271
+ }
272
+ const closed = j < lines.length;
273
+ blocks.push(makeBlock({
274
+ kind: "fence",
275
+ lines: content,
276
+ language: fence.language
277
+ }, j - i + (closed ? 1 : 0)));
278
+ i = j + (closed ? 1 : 0);
279
+ continue;
280
+ }
281
+ const heading = matchHeading(line);
282
+ if (heading) {
283
+ blocks.push(makeBlock({
284
+ kind: "heading",
285
+ lines: [heading.text],
286
+ level: heading.level
287
+ }, 1));
288
+ i++;
289
+ continue;
290
+ }
291
+ if (isRuleLine(line)) {
292
+ blocks.push(makeBlock({
293
+ kind: "rule",
294
+ lines: []
295
+ }, 1));
296
+ i++;
297
+ continue;
298
+ }
299
+ const quote = matchQuote(line);
300
+ if (quote) {
301
+ const quoted = [quote.text];
302
+ let j = i + 1;
303
+ while (j < lines.length) {
304
+ const next = matchQuote(lines[j]);
305
+ if (!next) break;
306
+ quoted.push(next.text);
307
+ j++;
308
+ }
309
+ blocks.push(makeBlock({
310
+ kind: "quote",
311
+ lines: quoted
312
+ }, j - i));
313
+ i = j;
314
+ continue;
315
+ }
316
+ const paragraph = [line];
317
+ let j = i + 1;
318
+ while (j < lines.length) {
319
+ const next = lines[j];
320
+ if (isBlankLine(next) || matchFence(next) !== null || matchHeading(next) !== null || isRuleLine(next) || matchQuote(next) !== null) break;
321
+ paragraph.push(next);
322
+ j++;
323
+ }
324
+ blocks.push(makeBlock({
325
+ kind: "paragraph",
326
+ lines: paragraph
327
+ }, j - i));
328
+ i = j;
329
+ }
330
+ return blocks;
331
+ }
332
+ /**
333
+ * Split a table row line into trimmed cells.
334
+ *
335
+ * @param line - Raw row line, with or without outer pipes.
336
+ * @returns Cells in order.
337
+ */
338
+ function splitTableRow(line) {
339
+ return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
340
+ }
341
+ /**
342
+ * Parse column alignment from a delimiter cell.
343
+ *
344
+ * @param cell - Raw delimiter cell (dashes with optional edge colons).
345
+ * @returns The alignment, or null for none.
346
+ */
347
+ function parseTableAlignment(cell) {
348
+ const left = cell.startsWith(":");
349
+ const right = cell.endsWith(":");
350
+ if (left && right) return "center";
351
+ if (right) return "right";
352
+ if (left) return "left";
353
+ return null;
511
354
  }
512
-
513
355
  // src/renderers/renderer-state.ts
514
- var RendererState = class {
515
- _pending = [];
516
- /**
517
- * Buffer newly arrived lines.
518
- *
519
- * @param lines - Complete source lines to buffer.
520
- */
521
- addLines(lines) {
522
- for (const line of lines) this._pending.push(line);
523
- }
524
- /**
525
- * Parse buffered lines, returning every block except a trailing partial one.
526
- *
527
- * @remarks
528
- * The last block is held back because more input may still extend it.
529
- * Nothing is returned while the buffer ends inside an unclosed fence.
530
- *
531
- * @returns Complete blocks ready to render.
532
- */
533
- takeCompleteBlocks() {
534
- let start = 0;
535
- let end = this._pending.length;
536
- while (start < end && isBlankLine(this._pending[start])) start++;
537
- while (end > start && isBlankLine(this._pending[end - 1])) end--;
538
- const trimmed = this._pending.slice(start, end);
539
- if (trimmed.length === 0) {
540
- this._pending = [];
541
- return [];
542
- }
543
- if (hasOpenFence(trimmed)) return [];
544
- const blocks = splitBlocks(trimmed);
545
- const last = blocks[blocks.length - 1];
546
- if (last === void 0) {
547
- this._pending = [];
548
- return [];
549
- }
550
- this._pending = trimmed.slice(trimmed.length - last.sourceLineCount);
551
- return blocks.slice(0, -1);
552
- }
553
- /**
554
- * Parse and drain all buffered lines, including a trailing partial block.
555
- *
556
- * @returns Every remaining block.
557
- */
558
- takeAllBlocks() {
559
- const blocks = splitBlocks(this._pending);
560
- this._pending = [];
561
- return blocks;
562
- }
356
+ /**
357
+ * Incremental line-driven parser for CommonMark structure.
358
+ *
359
+ * @remarks
360
+ * Internal helper owned by a renderer. Lines arrive one at a time: leaf
361
+ * blocks buffer until a new block starts or the stream flushes (preserving
362
+ * trailing holdback), and lists commit one fragment per item with an indent
363
+ * stack for nesting. Tables are not recognized here, so table-looking lines
364
+ * stay plain paragraph text; {@link GFMState} extends this class with table
365
+ * support and nothing else.
366
+ *
367
+ * @internal
368
+ */
369
+ var CommonMarkState = class {
370
+ _emit;
371
+ _pending = [];
372
+ _fence = null;
373
+ _quote = null;
374
+ _lists = [];
375
+ /**
376
+ * @param emit - Receives parse fragments in document order.
377
+ */
378
+ constructor(_emit) {
379
+ this._emit = _emit;
380
+ }
381
+ /**
382
+ * Feed one source line; completed fragments emit to the handler.
383
+ *
384
+ * @param line - Next source line, without its line break.
385
+ */
386
+ addLine(line) {
387
+ if (this._consumeFence(line)) return;
388
+ if (this._consumeLists(line)) return;
389
+ if (this._consumeQuote(line)) return;
390
+ this._classify(line);
391
+ }
392
+ /**
393
+ * Close every open context and emit the trailing remainder.
394
+ */
395
+ flush() {
396
+ this._closeLists();
397
+ if (this._quote !== null) {
398
+ this._pending.push(...this._quote);
399
+ this._quote = null;
400
+ }
401
+ if (this._fence !== null) {
402
+ this._pending.push(this._fence.openLine, ...this._fence.content);
403
+ this._fence = null;
404
+ }
405
+ this._takeAll();
406
+ }
407
+ /**
408
+ * Feed a line to the open fence, if any.
409
+ *
410
+ * @param line - Next source line.
411
+ * @returns True when the line was consumed.
412
+ */
413
+ _consumeFence(line) {
414
+ if (this._fence === null) return false;
415
+ if (fenceCloses(this._fence, line)) {
416
+ this._pending.push(this._fence.openLine, ...this._fence.content, line);
417
+ this._fence = null;
418
+ this._takeComplete();
419
+ } else this._fence.content.push(line);
420
+ return true;
421
+ }
422
+ /**
423
+ * Feed a line to the open lists, if any, closing and reprocessing when
424
+ * the line is not an item.
425
+ *
426
+ * @param line - Next source line.
427
+ * @returns True when the line was consumed or reprocessed.
428
+ */
429
+ _consumeLists(line) {
430
+ if (this._lists.length === 0) return false;
431
+ const item = matchListItem(line);
432
+ if (item !== null) {
433
+ this._listItem(item);
434
+ return true;
435
+ }
436
+ this._closeLists();
437
+ this.addLine(line);
438
+ return true;
439
+ }
440
+ /**
441
+ * Feed a line to the open quote, if any, dumping it back to pending when
442
+ * the line does not continue the quote.
443
+ *
444
+ * @param line - Next source line.
445
+ * @returns True when the line was consumed.
446
+ */
447
+ _consumeQuote(line) {
448
+ if (this._quote === null) return false;
449
+ if (matchQuote(line) !== null) {
450
+ this._quote.push(line);
451
+ return true;
452
+ }
453
+ this._pending.push(...this._quote);
454
+ this._quote = null;
455
+ return false;
456
+ }
457
+ /**
458
+ * Classify a line that continues no open context.
459
+ *
460
+ * @param line - Next source line.
461
+ */
462
+ _classify(line) {
463
+ if (isBlankLine(line)) {
464
+ this._pending.push(line);
465
+ return;
466
+ }
467
+ const fence = matchFence(line);
468
+ if (fence !== null) {
469
+ this._takeAll();
470
+ this._fence = {
471
+ marker: fence.marker,
472
+ length: fence.length,
473
+ openLine: line,
474
+ content: []
475
+ };
476
+ return;
477
+ }
478
+ if (matchHeading(line) !== null || isRuleLine(line)) {
479
+ this._takeAll();
480
+ this._pending.push(line);
481
+ return;
482
+ }
483
+ if (matchQuote(line) !== null) {
484
+ this._takeAll();
485
+ this._quote = [line];
486
+ return;
487
+ }
488
+ const item = matchListItem(line);
489
+ if (item !== null) {
490
+ this._takeAll();
491
+ this._listItem(item);
492
+ return;
493
+ }
494
+ if (this._classifyPipe(line)) return;
495
+ this._pending.push(line);
496
+ this._takeComplete();
497
+ }
498
+ /**
499
+ * Classify a line that matches no CommonMark opener. The base parser has
500
+ * no pipe syntax, so this never consumes; {@link GFMState} overrides it
501
+ * to start table candidates.
502
+ *
503
+ * @param _line - Next source line.
504
+ * @returns Always false here.
505
+ */
506
+ _classifyPipe(_line) {
507
+ return false;
508
+ }
509
+ _listItem(item) {
510
+ while (this._lists.length > 0 && item.indent < this._lists[this._lists.length - 1].indent) {
511
+ this._lists.pop();
512
+ this._emit({ kind: "listEnd" });
513
+ }
514
+ const top = this._lists[this._lists.length - 1];
515
+ if (top && top.indent === item.indent && top.ordered === item.ordered) {
516
+ this._emit({
517
+ kind: "listItem",
518
+ text: item.text
519
+ });
520
+ return;
521
+ }
522
+ if (top && top.indent === item.indent) {
523
+ this._lists.pop();
524
+ this._emit({ kind: "listEnd" });
525
+ }
526
+ this._emit({
527
+ kind: "listStart",
528
+ ordered: item.ordered
529
+ });
530
+ this._lists.push({
531
+ ordered: item.ordered,
532
+ indent: item.indent
533
+ });
534
+ this._emit({
535
+ kind: "listItem",
536
+ text: item.text
537
+ });
538
+ }
539
+ _closeLists() {
540
+ while (this._lists.length > 0) {
541
+ this._lists.pop();
542
+ this._emit({ kind: "listEnd" });
543
+ }
544
+ }
545
+ _takeComplete() {
546
+ let start = 0;
547
+ let end = this._pending.length;
548
+ while (start < end && isBlankLine(this._pending[start])) start++;
549
+ while (end > start && isBlankLine(this._pending[end - 1])) end--;
550
+ const trimmed = this._pending.slice(start, end);
551
+ if (trimmed.length === 0) {
552
+ this._pending = [];
553
+ return;
554
+ }
555
+ if (hasOpenFence(trimmed)) return;
556
+ const blocks = splitBlocks(trimmed);
557
+ const last = blocks[blocks.length - 1];
558
+ if (last === void 0) {
559
+ this._pending = [];
560
+ return;
561
+ }
562
+ this._pending = trimmed.slice(trimmed.length - last.sourceLineCount);
563
+ for (const block of blocks.slice(0, -1)) this._emit({
564
+ kind: "block",
565
+ block
566
+ });
567
+ }
568
+ _takeAll() {
569
+ const blocks = splitBlocks(this._pending);
570
+ this._pending = [];
571
+ for (const block of blocks) this._emit({
572
+ kind: "block",
573
+ block
574
+ });
575
+ }
563
576
  };
564
-
565
- // src/sources/line-source.ts
566
- function createLineSource() {
567
- let buffer = "";
568
- let closed = false;
569
- return {
570
- push(chunk) {
571
- if (closed) throw new Error("push after close");
572
- buffer += chunk;
573
- },
574
- readLines() {
575
- const lines = [];
576
- let at = buffer.indexOf("\n");
577
- while (at !== -1) {
578
- lines.push(buffer.slice(0, at).replace(/\r$/, ""));
579
- buffer = buffer.slice(at + 1);
580
- at = buffer.indexOf("\n");
581
- }
582
- return lines;
583
- },
584
- close() {
585
- closed = true;
586
- if (buffer === "") return [];
587
- const rest = buffer.replace(/\r$/, "");
588
- buffer = "";
589
- return [rest];
590
- }
591
- };
577
+ /**
578
+ * Incremental line-driven parser for GFM structure.
579
+ *
580
+ * @remarks
581
+ * Extends {@link CommonMarkState} with tables and nothing else: a table
582
+ * commits at the delimiter row and streams one fragment per row. All leaf
583
+ * and list parsing is inherited unchanged.
584
+ *
585
+ * @internal
586
+ */
587
+ var GFMState = class extends CommonMarkState {
588
+ _tableOpen = false;
589
+ _candidate = null;
590
+ /**
591
+ * Feed one source line; completed fragments emit to the handler.
592
+ *
593
+ * @param line - Next source line, without its line break.
594
+ */
595
+ addLine(line) {
596
+ if (this._consumeFence(line)) return;
597
+ if (this._consumeTable(line)) return;
598
+ if (this._consumeLists(line)) return;
599
+ if (this._consumeQuote(line)) return;
600
+ if (this._consumeCandidate(line)) return;
601
+ this._classify(line);
602
+ }
603
+ /**
604
+ * Close every open context and emit the trailing remainder.
605
+ */
606
+ flush() {
607
+ if (this._candidate !== null) {
608
+ this._pending.push(this._candidate);
609
+ this._candidate = null;
610
+ }
611
+ if (this._tableOpen) {
612
+ this._emit({ kind: "tableEnd" });
613
+ this._tableOpen = false;
614
+ }
615
+ super.flush();
616
+ }
617
+ /**
618
+ * Feed a line to the open table, if any, closing and reprocessing when
619
+ * the line is not a row.
620
+ *
621
+ * @param line - Next source line.
622
+ * @returns True when the line was consumed or reprocessed.
623
+ */
624
+ _consumeTable(line) {
625
+ if (!this._tableOpen) return false;
626
+ if (!isBlankLine(line) && line.includes("|")) {
627
+ this._emit({
628
+ kind: "tableRow",
629
+ line
630
+ });
631
+ return true;
632
+ }
633
+ this._emit({ kind: "tableEnd" });
634
+ this._tableOpen = false;
635
+ this.addLine(line);
636
+ return true;
637
+ }
638
+ /**
639
+ * Resolve a pending table header candidate against the next line.
640
+ *
641
+ * @param line - Next source line.
642
+ * @returns True when a table opened.
643
+ */
644
+ _consumeCandidate(line) {
645
+ if (this._candidate === null) return false;
646
+ if (isTableDelimiter(line)) {
647
+ this._emit({
648
+ kind: "tableHead",
649
+ headLine: this._candidate,
650
+ delimLine: line
651
+ });
652
+ this._candidate = null;
653
+ this._tableOpen = true;
654
+ return true;
655
+ }
656
+ this._pending.push(this._candidate);
657
+ this._candidate = null;
658
+ return false;
659
+ }
660
+ /**
661
+ * Start a table header candidate on pipe lines.
662
+ *
663
+ * @param line - Next source line.
664
+ * @returns True when the line starts a candidate.
665
+ */
666
+ _classifyPipe(line) {
667
+ if (!line.includes("|")) return false;
668
+ this._takeAll();
669
+ this._candidate = line;
670
+ return true;
671
+ }
672
+ };
673
+ // src/renderers/parser/inline.ts
674
+ const ESCAPABLE_RE = /^[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]$/;
675
+ const AUTOLINK_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:[^<>\s]*$/;
676
+ const ALNUM_RE = /[A-Za-z0-9]/;
677
+ /** Parse `[label](href)` at `text[start]` (which must be `[`). */
678
+ function tryParseLink(text, start) {
679
+ const labelEnd = text.indexOf("]", start + 1);
680
+ if (labelEnd === -1 || text[labelEnd + 1] !== "(") return null;
681
+ const label = text.slice(start + 1, labelEnd);
682
+ if (label.includes("[") || label.includes("\n")) return null;
683
+ const hrefEnd = text.indexOf(")", labelEnd + 2);
684
+ if (hrefEnd === -1) return null;
685
+ const inside = text.slice(labelEnd + 2, hrefEnd).trim();
686
+ if (inside === "") return null;
687
+ if (/\s/.test(inside) && !/^<?\S+>?\s+"[^"]*"$/.test(inside)) return null;
688
+ return {
689
+ label,
690
+ href: inside.replace(/^<(.*)>$/, "$1").split(/\s+/)[0],
691
+ end: hrefEnd + 1
692
+ };
592
693
  }
593
-
594
- // src/core/pipelines/pipeline-engine.ts
595
- function createPipelineEngine(renderer, target, dom) {
596
- const source = createLineSource();
597
- const state = new RendererState();
598
- function render(blocks) {
599
- for (const block of blocks) {
600
- const node = renderer.renderBlock(block, dom);
601
- if (node !== null) target.append(node);
602
- }
603
- }
604
- return {
605
- async push(chunk) {
606
- source.push(await chunk);
607
- state.addLines(source.readLines());
608
- render(state.takeCompleteBlocks());
609
- },
610
- async flush() {
611
- state.addLines(source.close());
612
- render(state.takeAllBlocks());
613
- await target.flush();
614
- }
615
- };
694
+ /** Match an emphasis opener at position `i`, if any. */
695
+ function matchEmphasis(text, i, gfm) {
696
+ if (gfm && text.startsWith("~~", i)) return {
697
+ marker: "~~",
698
+ tag: "del",
699
+ underscore: false
700
+ };
701
+ if (text.startsWith("**", i)) return {
702
+ marker: "**",
703
+ tag: "strong",
704
+ underscore: false
705
+ };
706
+ if (text.startsWith("__", i)) return {
707
+ marker: "__",
708
+ tag: "strong",
709
+ underscore: true
710
+ };
711
+ if (text[i] === "*") return {
712
+ marker: "*",
713
+ tag: "em",
714
+ underscore: false
715
+ };
716
+ if (text[i] === "_") {
717
+ if (i > 0 && ALNUM_RE.test(text[i - 1])) return null;
718
+ return {
719
+ marker: "_",
720
+ tag: "em",
721
+ underscore: true
722
+ };
723
+ }
724
+ return null;
616
725
  }
617
-
618
- // src/core/pipelines/frontend-gfm-pipeline.ts
619
- function createFrontendGFMPipeline(target, dom, opts, raf) {
620
- return new FrontendGFMPipeline(target, dom, opts, raf);
726
+ /** Find the closing marker, skipping `_` closers inside words. */
727
+ function findEmphasisClose(text, from, token) {
728
+ let at = text.indexOf(token.marker, from);
729
+ while (at !== -1 && token.underscore) {
730
+ const next = text[at + token.marker.length];
731
+ if (next === void 0 || !ALNUM_RE.test(next)) return at;
732
+ at = text.indexOf(token.marker, at + 1);
733
+ }
734
+ return at;
621
735
  }
622
- var FrontendGFMPipeline = class {
623
- _engine;
624
- /**
625
- * @param target - Container node receiving rendered blocks.
626
- * @param dom - Document used to create nodes.
627
- * @param opts - GFM rendering options.
628
- * @param raf - Optional frame scheduler for batched DOM writes.
629
- */
630
- constructor(target, dom, opts, raf) {
631
- this._engine = createPipelineEngine(
632
- new GFMRenderer(opts),
633
- raf === void 0 ? new DOMTarget(target) : new AnimatedDOMTarget(target, raf),
634
- dom
635
- );
636
- }
637
- /**
638
- * Push a chunk of markdown into the pipeline.
639
- *
640
- * @param chunk - Markdown text, or a promise resolving to markdown text.
641
- * @returns A promise that resolves once the chunk has been consumed.
642
- */
643
- push(chunk) {
644
- return this._engine.push(chunk);
645
- }
646
- /**
647
- * Render any buffered remainder.
648
- *
649
- * @returns A promise that resolves once all output has been flushed.
650
- */
651
- flush() {
652
- return this._engine.flush();
653
- }
654
- };
655
-
656
- // src/core/pipelines/frontend-commonmark-pipeline.ts
657
- function createFrontendCommonMarkPipeline(target, dom, opts, raf) {
658
- return new FrontendCommonMarkPipeline(target, dom, opts, raf);
736
+ /** Append a text node to the parent unless the run is empty. */
737
+ function appendText(target, parentId, text) {
738
+ if (text !== "") target.appendChild(parentId, target.createTextNode(text));
739
+ }
740
+ /**
741
+ * Parse one line of inline markdown (code spans, emphasis, links, images,
742
+ * autolinks, and GFM strikethrough when `gfm` is set) into the target.
743
+ *
744
+ * @param target - Target receiving the parsed nodes.
745
+ * @param parentId - Node the inlines append to.
746
+ * @param text - Source text for one line.
747
+ * @param gfm - Enable GFM-only inlines (strikethrough).
748
+ */
749
+ function appendInline(target, parentId, text, gfm) {
750
+ let i = 0;
751
+ let literal = "";
752
+ const flushLiteral = () => {
753
+ appendText(target, parentId, literal);
754
+ literal = "";
755
+ };
756
+ while (i < text.length) {
757
+ const ch = text[i];
758
+ if (ch === "\\" && i + 1 < text.length && ESCAPABLE_RE.test(text[i + 1])) {
759
+ literal += text[i + 1];
760
+ i += 2;
761
+ continue;
762
+ }
763
+ if (ch === "`") {
764
+ const run = /^`+/.exec(text.slice(i));
765
+ const close = text.indexOf(run[0], i + run[0].length);
766
+ if (close !== -1) {
767
+ flushLiteral();
768
+ const code = target.createElement("code");
769
+ appendText(target, code, text.slice(i + run[0].length, close));
770
+ target.appendChild(parentId, code);
771
+ i = close + run[0].length;
772
+ continue;
773
+ }
774
+ literal += ch;
775
+ i++;
776
+ continue;
777
+ }
778
+ if (ch === "!" && text[i + 1] === "[") {
779
+ const link = tryParseLink(text, i + 1);
780
+ if (link && link.href !== "") {
781
+ flushLiteral();
782
+ const img = target.createElement("img", {
783
+ src: link.href,
784
+ alt: link.label
785
+ });
786
+ target.appendChild(parentId, img);
787
+ i = link.end;
788
+ continue;
789
+ }
790
+ }
791
+ if (ch === "[") {
792
+ const link = tryParseLink(text, i);
793
+ if (link) {
794
+ flushLiteral();
795
+ const anchor = target.createElement("a", { href: link.href });
796
+ appendInline(target, anchor, link.label, gfm);
797
+ target.appendChild(parentId, anchor);
798
+ i = link.end;
799
+ continue;
800
+ }
801
+ literal += ch;
802
+ i++;
803
+ continue;
804
+ }
805
+ if (ch === "<") {
806
+ const end = text.indexOf(">", i + 1);
807
+ if (end !== -1 && AUTOLINK_RE.test(text.slice(i + 1, end))) {
808
+ flushLiteral();
809
+ const href = text.slice(i + 1, end);
810
+ const anchor = target.createElement("a", { href });
811
+ appendText(target, anchor, href);
812
+ target.appendChild(parentId, anchor);
813
+ i = end + 1;
814
+ continue;
815
+ }
816
+ literal += ch;
817
+ i++;
818
+ continue;
819
+ }
820
+ const token = matchEmphasis(text, i, gfm);
821
+ if (token) {
822
+ const close = findEmphasisClose(text, i + token.marker.length, token);
823
+ if (close !== -1 && close > i + token.marker.length) {
824
+ flushLiteral();
825
+ const el = target.createElement(token.tag);
826
+ appendInline(target, el, text.slice(i + token.marker.length, close), gfm);
827
+ target.appendChild(parentId, el);
828
+ i = close + token.marker.length;
829
+ continue;
830
+ }
831
+ literal += token.marker;
832
+ i += token.marker.length;
833
+ continue;
834
+ }
835
+ literal += ch;
836
+ i++;
837
+ }
838
+ flushLiteral();
659
839
  }
660
- var FrontendCommonMarkPipeline = class {
661
- _engine;
662
- /**
663
- * @param target - Container node receiving rendered blocks.
664
- * @param dom - Document used to create nodes.
665
- * @param opts - CommonMark rendering options.
666
- * @param raf - Optional frame scheduler for batched DOM writes.
667
- */
668
- constructor(target, dom, opts, raf) {
669
- this._engine = createPipelineEngine(
670
- new CommonMarkRenderer(opts),
671
- raf === void 0 ? new DOMTarget(target) : new AnimatedDOMTarget(target, raf),
672
- dom
673
- );
674
- }
675
- /**
676
- * Push a chunk of markdown into the pipeline.
677
- *
678
- * @param chunk - Markdown text, or a promise resolving to markdown text.
679
- * @returns A promise that resolves once the chunk has been consumed.
680
- */
681
- push(chunk) {
682
- return this._engine.push(chunk);
683
- }
684
- /**
685
- * Render any buffered remainder.
686
- *
687
- * @returns A promise that resolves once all output has been flushed.
688
- */
689
- flush() {
690
- return this._engine.flush();
691
- }
840
+ /**
841
+ * Split a paragraph line into text plus a trailing hard break marker.
842
+ *
843
+ * @param line - Raw paragraph line.
844
+ * @returns Text without the break marker, and whether one was present.
845
+ */
846
+ function splitHardBreak(line) {
847
+ const hardBreak = / {2,}$/.test(line);
848
+ return {
849
+ text: hardBreak ? line.replace(/ {2,}$/, "") : line,
850
+ hardBreak
851
+ };
852
+ }
853
+ // src/renderers/commonmark.ts
854
+ /**
855
+ * Renderer for CommonMark.
856
+ *
857
+ * @remarks
858
+ * Constructed with its target and config. Feed it lines with
859
+ * {@link CommonMarkRenderer.writeLine}; it holds its own parse state and
860
+ * writes finished blocks to the target as they complete. Open lists are
861
+ * tracked on a stack so items — including nested ones — append to the
862
+ * right container as they arrive.
863
+ *
864
+ * The renderer never touches the DOM: it builds everything through the
865
+ * write-only target, so the same renderer drives live pages, simulated
866
+ * DOMs, and fully custom targets.
867
+ *
868
+ * @public
869
+ */
870
+ var CommonMarkRenderer = class {
871
+ _target;
872
+ _config;
873
+ _state;
874
+ _open = [];
875
+ /**
876
+ * @param target - Destination for rendered output, from `createDOMTarget`
877
+ * or a custom `HTMLTarget` implementation.
878
+ * @param config - CommonMark rendering config.
879
+ */
880
+ constructor(target, config) {
881
+ this._target = target;
882
+ this._config = config;
883
+ this._state = this._createState((fragment) => this._applyFragment(fragment));
884
+ }
885
+ /**
886
+ * Feed one source line; completed output is written to the target.
887
+ *
888
+ * @param line - Next source line, without its line break.
889
+ */
890
+ writeLine(line) {
891
+ this._state.addLine(line);
892
+ }
893
+ /**
894
+ * Write the buffered remainder and settle the target.
895
+ *
896
+ * @returns A promise that resolves once all output has landed in the target.
897
+ */
898
+ async flush() {
899
+ this._state.flush();
900
+ await this._target.flush();
901
+ }
902
+ /**
903
+ * Point the renderer at another target; subsequent writes go there.
904
+ *
905
+ * @param target - Target receiving future output.
906
+ */
907
+ setTarget(target) {
908
+ this._target = target;
909
+ }
910
+ /**
911
+ * Replace the renderer config; applies to subsequent writes.
912
+ *
913
+ * @param config - Next config.
914
+ */
915
+ setConfig(config) {
916
+ this._config = config;
917
+ }
918
+ /**
919
+ * Create the parser state. Overridden by `GFMRenderer` to parse
920
+ * tables.
921
+ *
922
+ * @param emit - Receives parse fragments in document order.
923
+ * @returns The state for this renderer.
924
+ */
925
+ _createState(emit) {
926
+ return new CommonMarkState(emit);
927
+ }
928
+ _applyFragment(fragment) {
929
+ switch (fragment.kind) {
930
+ case "block":
931
+ this.renderBlock(fragment.block);
932
+ break;
933
+ case "listStart": {
934
+ const parent = this._open[this._open.length - 1]?.currentItem ?? null;
935
+ const list = this._target.createElement(fragment.ordered ? "ol" : "ul");
936
+ this._target.appendChild(parent, list);
937
+ this._open.push({
938
+ id: list,
939
+ currentItem: null
940
+ });
941
+ break;
942
+ }
943
+ case "listItem": {
944
+ const top = this._open[this._open.length - 1];
945
+ const item = this._target.createElement("li");
946
+ appendInline(this._target, item, fragment.text, this.inlineGfm());
947
+ this._target.appendChild(top.id, item);
948
+ top.currentItem = item;
949
+ break;
950
+ }
951
+ case "listEnd": this._open.pop();
952
+ }
953
+ }
954
+ /**
955
+ * Whether GFM-only inlines are enabled. Always false here; overridden by
956
+ * `GFMRenderer`.
957
+ *
958
+ * @returns False.
959
+ */
960
+ inlineGfm() {
961
+ return false;
962
+ }
963
+ /**
964
+ * Write one parsed block to the target.
965
+ *
966
+ * @param block - Parsed block to write.
967
+ */
968
+ renderBlock(block) {
969
+ switch (block.kind) {
970
+ case "heading": {
971
+ const heading = this._target.createElement(`h${block.level ?? 1}`);
972
+ this.appendJoinedLines(heading, block.lines);
973
+ this._target.appendChild(null, heading);
974
+ break;
975
+ }
976
+ case "paragraph": {
977
+ const paragraph = this._target.createElement("p");
978
+ this.appendParagraphLines(paragraph, block.lines);
979
+ this._target.appendChild(null, paragraph);
980
+ break;
981
+ }
982
+ case "fence": {
983
+ const pre = this._target.createElement("pre");
984
+ const code = this._target.createElement("code", block.language === void 0 ? {} : { class: `language-${block.language}` });
985
+ const text = block.lines.join("\n");
986
+ this._target.appendChild(code, this._target.createTextNode(text === "" ? "" : `${text}\n`));
987
+ this._target.appendChild(pre, code);
988
+ this._target.appendChild(null, pre);
989
+ break;
990
+ }
991
+ case "quote": {
992
+ const quote = this._target.createElement("blockquote");
993
+ const body = this._target.createElement("p");
994
+ this.appendJoinedLines(body, block.lines);
995
+ this._target.appendChild(quote, body);
996
+ this._target.appendChild(null, quote);
997
+ break;
998
+ }
999
+ case "rule": this._target.appendChild(null, this._target.createElement("hr"));
1000
+ }
1001
+ }
1002
+ /**
1003
+ * Write paragraph lines into a parent, honoring two-space hard breaks.
1004
+ *
1005
+ * @param parentId - Node the lines append to.
1006
+ * @param lines - Raw paragraph lines.
1007
+ */
1008
+ appendParagraphLines(parentId, lines) {
1009
+ lines.forEach((line, at) => {
1010
+ const { text, hardBreak } = splitHardBreak(line);
1011
+ appendInline(this._target, parentId, text, this.inlineGfm());
1012
+ if (at < lines.length - 1) {
1013
+ if (hardBreak) this._target.appendChild(parentId, this._target.createElement("br"));
1014
+ else this._target.appendChild(parentId, this._target.createTextNode(" "));
1015
+ }
1016
+ });
1017
+ }
1018
+ appendJoinedLines(parentId, lines) {
1019
+ lines.forEach((line, at) => {
1020
+ if (at > 0) this._target.appendChild(parentId, this._target.createTextNode(" "));
1021
+ appendInline(this._target, parentId, line, this.inlineGfm());
1022
+ });
1023
+ }
692
1024
  };
693
-
694
- // src/core/pipelines/backend-gfm-pipeline.ts
695
- function createBackendGFMPipeline(target, dom, opts) {
696
- return new BackendGFMPipeline(target, dom, opts);
1025
+ // src/renderers/gfm.ts
1026
+ /**
1027
+ * Renderer for GitHub Flavored Markdown.
1028
+ *
1029
+ * @remarks
1030
+ * Supports CommonMark blocks and inlines plus GFM tables and strikethrough.
1031
+ * Tables commit at the delimiter row and stream one row at a time; column
1032
+ * widths come from the header row, short rows are padded, and extra cells
1033
+ * on wide rows are kept as unaligned cells.
1034
+ *
1035
+ * @public
1036
+ */
1037
+ var GFMRenderer = class extends CommonMarkRenderer {
1038
+ _table = null;
1039
+ /**
1040
+ * @param target - Destination for rendered output, from `createDOMTarget`
1041
+ * or a custom `HTMLTarget` implementation.
1042
+ * @param config - GFM rendering config.
1043
+ */
1044
+ constructor(target, config) {
1045
+ super(target, config);
1046
+ }
1047
+ /**
1048
+ * GFM-only inlines are enabled.
1049
+ *
1050
+ * @returns True.
1051
+ */
1052
+ inlineGfm() {
1053
+ return true;
1054
+ }
1055
+ /**
1056
+ * Create the GFM parser state.
1057
+ *
1058
+ * @param emit - Receives parse fragments in document order.
1059
+ * @returns The state for this renderer.
1060
+ */
1061
+ _createState(emit) {
1062
+ return new GFMState(emit);
1063
+ }
1064
+ /**
1065
+ * Apply a fragment, handling tables here and delegating the rest.
1066
+ *
1067
+ * @param fragment - Fragment to apply.
1068
+ */
1069
+ _applyFragment(fragment) {
1070
+ switch (fragment.kind) {
1071
+ case "tableHead":
1072
+ this._applyTableHead(fragment.headLine, fragment.delimLine);
1073
+ break;
1074
+ case "tableRow":
1075
+ this._applyTableRow(fragment.line);
1076
+ break;
1077
+ case "tableEnd":
1078
+ this._applyTableEnd();
1079
+ break;
1080
+ default: super._applyFragment(fragment);
1081
+ }
1082
+ }
1083
+ /**
1084
+ * Commit the table with its header; body rows stream in afterwards.
1085
+ *
1086
+ * @param headLine - Raw header row line.
1087
+ * @param delimLine - Delimiter row line carrying column alignment.
1088
+ */
1089
+ _applyTableHead(headLine, delimLine) {
1090
+ const header = splitTableRow(headLine);
1091
+ const aligns = splitTableRow(delimLine).map(parseTableAlignment);
1092
+ const width = header.length;
1093
+ const table = this._target.createElement("table");
1094
+ const head = this._target.createElement("thead");
1095
+ const headRow = this._target.createElement("tr");
1096
+ for (let col = 0; col < width; col++) {
1097
+ const align = aligns[col] ?? null;
1098
+ const cell = this._target.createElement("th", align === null ? {} : { align });
1099
+ appendInline(this._target, cell, header[col] ?? "", true);
1100
+ this._target.appendChild(headRow, cell);
1101
+ }
1102
+ this._target.appendChild(head, headRow);
1103
+ this._target.appendChild(table, head);
1104
+ const body = this._target.createElement("tbody");
1105
+ this._target.appendChild(table, body);
1106
+ this._target.appendChild(null, table);
1107
+ this._table = {
1108
+ body,
1109
+ aligns,
1110
+ width
1111
+ };
1112
+ }
1113
+ /**
1114
+ * Append one body row to the open table.
1115
+ *
1116
+ * @param line - Raw body row line.
1117
+ */
1118
+ _applyTableRow(line) {
1119
+ const table = this._table;
1120
+ if (table === null) return;
1121
+ const cells = splitTableRow(line);
1122
+ const row = this._target.createElement("tr");
1123
+ for (let col = 0; col < table.width; col++) {
1124
+ const align = table.aligns[col] ?? null;
1125
+ const cell = this._target.createElement("td", align === null ? {} : { align });
1126
+ appendInline(this._target, cell, cells[col] ?? "", true);
1127
+ this._target.appendChild(row, cell);
1128
+ }
1129
+ for (let col = table.width; col < cells.length; col++) {
1130
+ const cell = this._target.createElement("td");
1131
+ appendInline(this._target, cell, cells[col], true);
1132
+ this._target.appendChild(row, cell);
1133
+ }
1134
+ this._target.appendChild(table.body, row);
1135
+ }
1136
+ /**
1137
+ * Close the open table.
1138
+ */
1139
+ _applyTableEnd() {
1140
+ this._table = null;
1141
+ }
1142
+ };
1143
+ // src/targets/animated-dom-target.ts
1144
+ /**
1145
+ * Throw when attributes were requested but the DOM cannot set them.
1146
+ *
1147
+ * @param node - Freshly created node.
1148
+ * @param attrs - Requested attributes.
1149
+ */
1150
+ function assertAttributesSupported$1(node, attrs) {
1151
+ if (Object.keys(attrs).length > 0 && typeof node.setAttribute !== "function") throw new Error("Cannot set attributes: this DOM does not implement setAttribute");
697
1152
  }
698
- var BackendGFMPipeline = class {
699
- _engine;
700
- /**
701
- * @param target - Container node receiving rendered blocks.
702
- * @param dom - Document used to create nodes.
703
- * @param opts - GFM rendering options.
704
- */
705
- constructor(target, dom, opts) {
706
- this._engine = createPipelineEngine(new GFMRenderer(opts), new DOMTarget(target), dom);
707
- }
708
- /**
709
- * Push a chunk of markdown into the pipeline.
710
- *
711
- * @param chunk - Markdown text, or a promise resolving to markdown text.
712
- * @returns A promise that resolves once the chunk has been consumed.
713
- */
714
- push(chunk) {
715
- return this._engine.push(chunk);
716
- }
717
- /**
718
- * Render any buffered remainder.
719
- *
720
- * @returns A promise that resolves once all output has been flushed.
721
- */
722
- flush() {
723
- return this._engine.flush();
724
- }
1153
+ /**
1154
+ * Target that batches node updates on animation frames.
1155
+ *
1156
+ * @remarks
1157
+ * Wraps an externally provided container node from a real DOM. Uses the
1158
+ * injected frame scheduler so streamed output lands once per frame instead
1159
+ * of once per write. Ids are minted synchronously and unknown ids throw
1160
+ * synchronously; updates apply in call order when the frame runs.
1161
+ *
1162
+ * Internal implementation behind `createDOMTarget`.
1163
+ *
1164
+ * @internal
1165
+ */
1166
+ var AnimatedDOMTarget = class {
1167
+ _container;
1168
+ _doc;
1169
+ _raf;
1170
+ _graph = /* @__PURE__ */ new Map();
1171
+ _nodes = /* @__PURE__ */ new Map();
1172
+ _nextId = 0;
1173
+ _queue = [];
1174
+ _scheduled = false;
1175
+ _flushResolvers = [];
1176
+ /**
1177
+ * @param targetNode - Container node receiving rendered output.
1178
+ * @param document - Document used to create nodes.
1179
+ * @param raf - Frame scheduler used to batch writes.
1180
+ */
1181
+ constructor(targetNode, document, raf) {
1182
+ this._container = targetNode;
1183
+ this._doc = document;
1184
+ this._raf = raf;
1185
+ }
1186
+ /**
1187
+ * Queue an element creation for the next frame.
1188
+ *
1189
+ * @param tag - Lowercase tag name.
1190
+ * @param attrs - Attributes to set.
1191
+ * @returns Id addressing the new node.
1192
+ */
1193
+ createElement(tag, attrs = {}) {
1194
+ const id = this._mint();
1195
+ const snap = { ...attrs };
1196
+ this._enqueue(() => {
1197
+ const node = this._doc.createElement(tag);
1198
+ assertAttributesSupported$1(node, snap);
1199
+ for (const [name, value] of Object.entries(snap)) node.setAttribute?.(name, value);
1200
+ this._nodes.set(id, node);
1201
+ });
1202
+ return id;
1203
+ }
1204
+ /**
1205
+ * Queue a text node creation for the next frame.
1206
+ *
1207
+ * @param text - Text content.
1208
+ * @returns Id addressing the new node.
1209
+ */
1210
+ createTextNode(text) {
1211
+ const id = this._mint();
1212
+ this._enqueue(() => {
1213
+ this._nodes.set(id, this._doc.createTextNode(text));
1214
+ });
1215
+ return id;
1216
+ }
1217
+ /**
1218
+ * Queue an append for the next frame.
1219
+ *
1220
+ * @param parent - Receiving node, or `null` for the top level.
1221
+ * @param child - Node to append.
1222
+ */
1223
+ appendChild(parent, child) {
1224
+ if (parent !== null) this._mustGraph(parent);
1225
+ this._mustGraph(child);
1226
+ this._assertAcyclic(child, parent);
1227
+ this._reparentGraph(child, parent);
1228
+ this._enqueue(() => {
1229
+ (parent === null ? this._container : this._mustNode(parent)).appendChild(this._mustNode(child));
1230
+ });
1231
+ }
1232
+ /**
1233
+ * Queue a replacement for the next frame, retiring the old id.
1234
+ *
1235
+ * @param oldId - Attached node to replace.
1236
+ * @param newId - Replacement node.
1237
+ */
1238
+ replaceNode(oldId, newId) {
1239
+ const old = this._mustGraph(oldId);
1240
+ this._mustGraph(newId);
1241
+ if (old.parent === void 0) throw new DetachedNodeError(oldId);
1242
+ if (oldId === newId) return;
1243
+ this._assertAcyclic(newId, old.parent);
1244
+ const parent = old.parent;
1245
+ this._reparentGraph(newId, parent);
1246
+ const doomed = this._retireGraph(oldId);
1247
+ this._enqueue(() => {
1248
+ (parent === null ? this._container : this._mustNode(parent)).replaceChild(this._mustNode(newId), this._mustNode(oldId));
1249
+ for (const id of doomed) this._nodes.delete(id);
1250
+ });
1251
+ }
1252
+ /**
1253
+ * Queue a removal for the next frame, retiring the id.
1254
+ *
1255
+ * @param id - Node to remove.
1256
+ */
1257
+ remove(id) {
1258
+ const parent = this._mustGraph(id).parent;
1259
+ const doomed = this._retireGraph(id);
1260
+ this._enqueue(() => {
1261
+ if (parent !== void 0) (parent === null ? this._container : this._mustNode(parent)).removeChild(this._mustNode(id));
1262
+ for (const stale of doomed) this._nodes.delete(stale);
1263
+ });
1264
+ }
1265
+ /**
1266
+ * Queue a text replacement for the next frame.
1267
+ *
1268
+ * @param node - Node to update.
1269
+ * @param text - Replacement text.
1270
+ */
1271
+ setTextContent(node, text) {
1272
+ const entry = this._mustGraph(node);
1273
+ const doomed = [];
1274
+ for (const child of [...entry.children]) doomed.push(...this._retireGraph(child));
1275
+ this._enqueue(() => {
1276
+ this._mustNode(node).textContent = text;
1277
+ for (const stale of doomed) this._nodes.delete(stale);
1278
+ });
1279
+ }
1280
+ /**
1281
+ * Wait until every queued update has been applied.
1282
+ *
1283
+ * @returns A promise that resolves after the next frame carrying updates.
1284
+ */
1285
+ flush() {
1286
+ if (!this._scheduled && this._queue.length === 0) return Promise.resolve();
1287
+ return new Promise((resolve) => {
1288
+ this._flushResolvers.push(resolve);
1289
+ });
1290
+ }
1291
+ _enqueue(apply) {
1292
+ this._queue.push(apply);
1293
+ if (!this._scheduled) {
1294
+ this._scheduled = true;
1295
+ this._raf(() => {
1296
+ this._scheduled = false;
1297
+ const batch = this._queue;
1298
+ this._queue = [];
1299
+ for (const queued of batch) queued();
1300
+ const resolvers = this._flushResolvers;
1301
+ this._flushResolvers = [];
1302
+ for (const resolve of resolvers) resolve();
1303
+ });
1304
+ }
1305
+ }
1306
+ _mint() {
1307
+ this._nextId += 1;
1308
+ const id = `n${this._nextId}`;
1309
+ this._graph.set(id, {
1310
+ parent: void 0,
1311
+ children: /* @__PURE__ */ new Set()
1312
+ });
1313
+ return id;
1314
+ }
1315
+ _mustGraph(id) {
1316
+ const entry = this._graph.get(id);
1317
+ if (entry === void 0) throw new UnknownNodeError(id);
1318
+ return entry;
1319
+ }
1320
+ _assertAcyclic(child, parent) {
1321
+ if (parent === null) return;
1322
+ let at = parent;
1323
+ while (at !== null && at !== void 0) {
1324
+ if (at === child) throw new HierarchyError(child, parent);
1325
+ at = this._graph.get(at)?.parent;
1326
+ }
1327
+ }
1328
+ _mustNode(id) {
1329
+ const node = this._nodes.get(id);
1330
+ if (node === void 0) throw new UnknownNodeError(id);
1331
+ return node;
1332
+ }
1333
+ _reparentGraph(child, parent) {
1334
+ const entry = this._graph.get(child);
1335
+ if (entry.parent !== void 0 && entry.parent !== null) this._graph.get(entry.parent)?.children.delete(child);
1336
+ entry.parent = parent;
1337
+ if (parent !== null) this._graph.get(parent)?.children.add(child);
1338
+ }
1339
+ _retireGraph(id) {
1340
+ const entry = this._graph.get(id);
1341
+ if (entry !== void 0 && entry.parent !== void 0 && entry.parent !== null) this._graph.get(entry.parent)?.children.delete(id);
1342
+ const doomed = [];
1343
+ const visit = (at) => {
1344
+ const next = this._graph.get(at);
1345
+ if (next === void 0) return;
1346
+ doomed.push(at);
1347
+ for (const child of [...next.children]) visit(child);
1348
+ this._graph.delete(at);
1349
+ };
1350
+ visit(id);
1351
+ return doomed;
1352
+ }
725
1353
  };
726
-
727
- // src/core/pipelines/backend-commonmark-pipeline.ts
728
- function createBackendCommonMarkPipeline(target, dom, opts) {
729
- return new BackendCommonMarkPipeline(target, dom, opts);
1354
+ // src/targets/dom-target.ts
1355
+ /**
1356
+ * Throw when attributes were requested but the DOM cannot set them.
1357
+ *
1358
+ * @param node - Freshly created node.
1359
+ * @param attrs - Requested attributes.
1360
+ */
1361
+ function assertAttributesSupported(node, attrs) {
1362
+ if (Object.keys(attrs).length > 0 && typeof node.setAttribute !== "function") throw new Error("Cannot set attributes: this DOM does not implement setAttribute");
730
1363
  }
731
- var BackendCommonMarkPipeline = class {
732
- _engine;
733
- /**
734
- * @param target - Container node receiving rendered blocks.
735
- * @param dom - Document used to create nodes.
736
- * @param opts - CommonMark rendering options.
737
- */
738
- constructor(target, dom, opts) {
739
- this._engine = createPipelineEngine(new CommonMarkRenderer(opts), new DOMTarget(target), dom);
740
- }
741
- /**
742
- * Push a chunk of markdown into the pipeline.
743
- *
744
- * @param chunk - Markdown text, or a promise resolving to markdown text.
745
- * @returns A promise that resolves once the chunk has been consumed.
746
- */
747
- push(chunk) {
748
- return this._engine.push(chunk);
749
- }
750
- /**
751
- * Render any buffered remainder.
752
- *
753
- * @returns A promise that resolves once all output has been flushed.
754
- */
755
- flush() {
756
- return this._engine.flush();
757
- }
1364
+ /**
1365
+ * Target that applies node updates to a DOM container synchronously.
1366
+ *
1367
+ * @remarks
1368
+ * Internal implementation behind `createDOMTarget`. Wraps an externally
1369
+ * provided container node from a real or simulated DOM, and tracks ids
1370
+ * to nodes in memory.
1371
+ *
1372
+ * @internal
1373
+ */
1374
+ var DOMTarget = class {
1375
+ _container;
1376
+ _doc;
1377
+ _entries = /* @__PURE__ */ new Map();
1378
+ _nextId = 0;
1379
+ /**
1380
+ * @param targetNode - Container node receiving rendered output.
1381
+ * @param document - Document used to create nodes.
1382
+ */
1383
+ constructor(targetNode, document) {
1384
+ this._container = targetNode;
1385
+ this._doc = document;
1386
+ }
1387
+ /**
1388
+ * Create a detached element node with attributes.
1389
+ *
1390
+ * @param tag - Lowercase tag name.
1391
+ * @param attrs - Attributes to set.
1392
+ * @returns Id addressing the new node.
1393
+ */
1394
+ createElement(tag, attrs = {}) {
1395
+ const node = this._doc.createElement(tag);
1396
+ assertAttributesSupported(node, attrs);
1397
+ for (const [name, value] of Object.entries(attrs)) node.setAttribute?.(name, value);
1398
+ return this._store(node, void 0);
1399
+ }
1400
+ /**
1401
+ * Create a detached text node.
1402
+ *
1403
+ * @param text - Text content.
1404
+ * @returns Id addressing the new node.
1405
+ */
1406
+ createTextNode(text) {
1407
+ return this._store(this._doc.createTextNode(text), void 0);
1408
+ }
1409
+ /**
1410
+ * Append a child to a parent, or to the top level for a `null` parent.
1411
+ *
1412
+ * @param parent - Receiving node, or `null` for the top level.
1413
+ * @param child - Node to append.
1414
+ */
1415
+ appendChild(parent, child) {
1416
+ const entry = this._must(child);
1417
+ const attachTo = parent === null ? this._container : this._must(parent).node;
1418
+ this._assertAcyclic(child, parent);
1419
+ attachTo.appendChild(entry.node);
1420
+ this._reparent(child, parent);
1421
+ }
1422
+ /**
1423
+ * Replace an attached node with another node, retiring the old id.
1424
+ *
1425
+ * @param oldId - Attached node to replace.
1426
+ * @param newId - Replacement node.
1427
+ */
1428
+ replaceNode(oldId, newId) {
1429
+ const old = this._must(oldId);
1430
+ const fresh = this._must(newId);
1431
+ if (old.parent === void 0) throw new DetachedNodeError(oldId);
1432
+ if (oldId === newId) return;
1433
+ this._assertAcyclic(newId, old.parent);
1434
+ (old.parent === null ? this._container : this._must(old.parent).node).replaceChild(fresh.node, old.node);
1435
+ this._reparent(newId, old.parent);
1436
+ this._retire(oldId);
1437
+ }
1438
+ /**
1439
+ * Detach a node and retire its id.
1440
+ *
1441
+ * @param id - Node to remove.
1442
+ */
1443
+ remove(id) {
1444
+ const entry = this._must(id);
1445
+ if (entry.parent !== void 0) (entry.parent === null ? this._container : this._must(entry.parent).node).removeChild(entry.node);
1446
+ this._retire(id);
1447
+ }
1448
+ /**
1449
+ * Replace a node's children with a single text run.
1450
+ *
1451
+ * @param node - Node to update.
1452
+ * @param text - Replacement text.
1453
+ */
1454
+ setTextContent(node, text) {
1455
+ const entry = this._must(node);
1456
+ entry.node.textContent = text;
1457
+ for (const child of [...entry.children]) this._retire(child);
1458
+ entry.children.clear();
1459
+ }
1460
+ /**
1461
+ * Nothing to wait for: synchronous targets hold every update already.
1462
+ */
1463
+ flush() {}
1464
+ _must(id) {
1465
+ const entry = this._entries.get(id);
1466
+ if (entry === void 0) throw new UnknownNodeError(id);
1467
+ return entry;
1468
+ }
1469
+ _assertAcyclic(child, parent) {
1470
+ if (parent === null) return;
1471
+ let at = parent;
1472
+ while (at !== null && at !== void 0) {
1473
+ if (at === child) throw new HierarchyError(child, parent);
1474
+ at = this._entries.get(at)?.parent;
1475
+ }
1476
+ }
1477
+ _store(node, parent) {
1478
+ this._nextId += 1;
1479
+ const id = `n${this._nextId}`;
1480
+ this._entries.set(id, {
1481
+ node,
1482
+ parent,
1483
+ children: /* @__PURE__ */ new Set()
1484
+ });
1485
+ return id;
1486
+ }
1487
+ _reparent(child, parent) {
1488
+ const entry = this._entries.get(child);
1489
+ if (entry.parent !== void 0 && entry.parent !== null) this._entries.get(entry.parent)?.children.delete(child);
1490
+ entry.parent = parent;
1491
+ if (parent !== null) this._entries.get(parent)?.children.add(child);
1492
+ }
1493
+ _retire(id) {
1494
+ const entry = this._entries.get(id);
1495
+ if (entry === void 0) return;
1496
+ for (const child of [...entry.children]) this._retire(child);
1497
+ if (entry.parent !== void 0 && entry.parent !== null) this._entries.get(entry.parent)?.children.delete(id);
1498
+ this._entries.delete(id);
1499
+ }
758
1500
  };
759
-
760
- exports.AnimatedDOMTarget = AnimatedDOMTarget;
761
- exports.BackendCommonMarkPipeline = BackendCommonMarkPipeline;
762
- exports.BackendGFMPipeline = BackendGFMPipeline;
1501
+ // src/targets/create-dom-target.ts
1502
+ /**
1503
+ * Create a target rendering into a DOM container.
1504
+ *
1505
+ * @param document - Document used to create nodes: a real browser document
1506
+ * for live pages, or a simulated one such as linkedom for server-side
1507
+ * rendering.
1508
+ * @param targetNode - Container node receiving rendered output.
1509
+ * @param options - Frame scheduler.
1510
+ * @returns The target to hand to a renderer.
1511
+ *
1512
+ * @public
1513
+ */
1514
+ function createDOMTarget(document, targetNode, options = {}) {
1515
+ const { raf } = options;
1516
+ return raf === void 0 ? new DOMTarget(targetNode, document) : new AnimatedDOMTarget(targetNode, document, raf);
1517
+ }
1518
+ // src/streams/gfm-stream.ts
1519
+ /**
1520
+ * Create a GFM stream rendering into the given container.
1521
+ *
1522
+ * @remarks
1523
+ * The environment is implicit: pass a real browser document for live pages
1524
+ * or a simulated one such as linkedom for server-side rendering. Pass
1525
+ * target options to batch DOM writes on animation frames.
1526
+ *
1527
+ * @param target - Container node receiving rendered output.
1528
+ * @param dom - Document used to create nodes.
1529
+ * @param config - GFM rendering config.
1530
+ * @param targetOptions - Frame scheduler for the DOM target.
1531
+ * @returns The configured pipeline.
1532
+ *
1533
+ * @example
1534
+ * ```ts
1535
+ * const stream = createGFMStream(
1536
+ * document.getElementById("out")!,
1537
+ * document,
1538
+ * {},
1539
+ * { raf: requestAnimationFrame },
1540
+ * );
1541
+ * const writer = stream.getWriter();
1542
+ * await writer.write("# Hello\n");
1543
+ * await writer.close();
1544
+ * ```
1545
+ *
1546
+ * @public
1547
+ */
1548
+ function createGFMStream(target, dom, config, targetOptions) {
1549
+ const domTarget = createDOMTarget(dom, target, targetOptions);
1550
+ return createMarkdownStream(new GFMRenderer(domTarget, config), domTarget);
1551
+ }
1552
+ // src/streams/commonmark-stream.ts
1553
+ /**
1554
+ * Create a CommonMark stream rendering into the given container.
1555
+ *
1556
+ * @remarks
1557
+ * The environment is implicit: pass a real browser document for live pages
1558
+ * or a simulated one such as linkedom for server-side rendering. Pass
1559
+ * target options to batch DOM writes on animation frames.
1560
+ *
1561
+ * @param target - Container node receiving rendered output.
1562
+ * @param dom - Document used to create nodes.
1563
+ * @param config - CommonMark rendering config.
1564
+ * @param targetOptions - Frame scheduler for the DOM target.
1565
+ * @returns The configured pipeline.
1566
+ *
1567
+ * @example
1568
+ * ```ts
1569
+ * const stream = createCommonMarkStream(
1570
+ * document.getElementById("out")!,
1571
+ * document,
1572
+ * {},
1573
+ * { raf: requestAnimationFrame },
1574
+ * );
1575
+ * const writer = stream.getWriter();
1576
+ * await writer.write("# Hello\n");
1577
+ * await writer.close();
1578
+ * ```
1579
+ *
1580
+ * @public
1581
+ */
1582
+ function createCommonMarkStream(target, dom, config, targetOptions) {
1583
+ const domTarget = createDOMTarget(dom, target, targetOptions);
1584
+ return createMarkdownStream(new CommonMarkRenderer(domTarget, config), domTarget);
1585
+ }
763
1586
  exports.CommonMarkRenderer = CommonMarkRenderer;
764
- exports.DOMTarget = DOMTarget;
765
- exports.FrontendCommonMarkPipeline = FrontendCommonMarkPipeline;
766
- exports.FrontendGFMPipeline = FrontendGFMPipeline;
1587
+ exports.DetachedNodeError = DetachedNodeError;
767
1588
  exports.GFMRenderer = GFMRenderer;
768
- exports.RendererState = RendererState;
769
- exports.createBackendCommonMarkPipeline = createBackendCommonMarkPipeline;
770
- exports.createBackendGFMPipeline = createBackendGFMPipeline;
771
- exports.createFrontendCommonMarkPipeline = createFrontendCommonMarkPipeline;
772
- exports.createFrontendGFMPipeline = createFrontendGFMPipeline;
773
- exports.createLineSource = createLineSource;
774
- //# sourceMappingURL=index.cjs.map
1589
+ exports.HierarchyError = HierarchyError;
1590
+ exports.UnknownNodeError = UnknownNodeError;
1591
+ exports.createCommonMarkStream = createCommonMarkStream;
1592
+ exports.createDOMTarget = createDOMTarget;
1593
+ exports.createGFMStream = createGFMStream;
1594
+ exports.createMarkdownStream = createMarkdownStream;
1595
+
775
1596
  //# sourceMappingURL=index.cjs.map