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