markemental 0.2.0 → 0.3.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,4 +1,464 @@
1
- // src/renderers/util/inline.ts
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
+ };
28
+ }
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
+
48
+ // 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*/;
57
+ function isBlankLine(line) {
58
+ return line.trim() === "";
59
+ }
60
+ 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
+ };
69
+ }
70
+ function fenceCloses(open, line) {
71
+ const match = matchFence(line);
72
+ return match !== null && match.marker === open.marker && match.length >= open.length;
73
+ }
74
+ 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
+ };
81
+ }
82
+ function isRuleLine(line) {
83
+ return RULE_RE.test(line.trim());
84
+ }
85
+ function matchQuote(line) {
86
+ const match = QUOTE_RE.exec(line);
87
+ if (!match) return null;
88
+ return { text: match[1] ?? "" };
89
+ }
90
+ 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
+ };
99
+ }
100
+ 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()));
104
+ }
105
+ 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;
115
+ }
116
+ function makeBlock(block, sourceLineCount) {
117
+ return { ...block, sourceLineCount };
118
+ }
119
+ 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;
180
+ }
181
+ function splitTableRow(line) {
182
+ return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
183
+ }
184
+ 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;
191
+ }
192
+
193
+ // src/renderers/renderer-state.ts
194
+ 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
+ }
380
+ };
381
+ 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
+ }
459
+ };
460
+
461
+ // src/renderers/parser/inline.ts
2
462
  var ESCAPABLE_RE = /^[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]$/;
3
463
  var AUTOLINK_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:[^<>\s]*$/;
4
464
  var ALNUM_RE = /[A-Za-z0-9]/;
@@ -129,20 +589,102 @@ function appendInline(parent, text, doc, gfm) {
129
589
  }
130
590
  flushLiteral();
131
591
  }
592
+ function splitHardBreak(line) {
593
+ const hardBreak = / {2,}$/.test(line);
594
+ return { text: hardBreak ? line.replace(/ {2,}$/, "") : line, hardBreak };
595
+ }
132
596
 
133
597
  // src/renderers/commonmark.ts
134
598
  var CommonMarkRenderer = class {
135
599
  /** Rendering options. */
136
600
  options;
601
+ _target;
602
+ _doc;
603
+ _state;
604
+ _open = [];
137
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.
138
610
  * @param opts - CommonMark rendering options.
139
611
  */
140
- constructor(opts) {
612
+ constructor(target, doc, opts) {
613
+ this._target = target;
614
+ this._doc = doc;
141
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);
142
684
  }
143
685
  /**
144
686
  * Whether GFM-only inlines are enabled. Always false here; overridden by
145
- * {@link GFMRenderer}.
687
+ * `GFMRenderer`.
146
688
  *
147
689
  * @returns False.
148
690
  */
@@ -175,15 +717,6 @@ var CommonMarkRenderer = class {
175
717
  pre.appendChild(code);
176
718
  return pre;
177
719
  }
178
- case "list": {
179
- const list = doc.createElement(block.ordered ? "ol" : "ul");
180
- for (const item of block.lines) {
181
- const li = doc.createElement("li");
182
- appendInline(li, item, doc, this.inlineGfm());
183
- list.appendChild(li);
184
- }
185
- return list;
186
- }
187
720
  case "quote": {
188
721
  const quote = doc.createElement("blockquote");
189
722
  const body = doc.createElement("p");
@@ -193,8 +726,6 @@ var CommonMarkRenderer = class {
193
726
  }
194
727
  case "rule":
195
728
  return doc.createElement("hr");
196
- case "table":
197
- return this.renderParagraph(block.lines.filter((_, at) => at !== 1), doc);
198
729
  }
199
730
  }
200
731
  /**
@@ -207,8 +738,8 @@ var CommonMarkRenderer = class {
207
738
  renderParagraph(lines, doc) {
208
739
  const paragraph = doc.createElement("p");
209
740
  lines.forEach((line, at) => {
210
- const hardBreak = / {2,}$/.test(line);
211
- appendInline(paragraph, hardBreak ? line.replace(/ {2,}$/, "") : line, doc, this.inlineGfm());
741
+ const { text, hardBreak } = splitHardBreak(line);
742
+ appendInline(paragraph, text, doc, this.inlineGfm());
212
743
  if (at < lines.length - 1) {
213
744
  if (hardBreak) paragraph.appendChild(doc.createElement("br"));
214
745
  else paragraph.appendChild(doc.createTextNode(" "));
@@ -225,25 +756,19 @@ var CommonMarkRenderer = class {
225
756
  };
226
757
 
227
758
  // src/renderers/gfm.ts
228
- function splitRow(line) {
229
- return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
230
- }
231
- function parseAlignment(cell) {
232
- const left = cell.startsWith(":");
233
- const right = cell.endsWith(":");
234
- if (left && right) return "center";
235
- if (right) return "right";
236
- if (left) return "left";
237
- return null;
238
- }
239
759
  var GFMRenderer = class extends CommonMarkRenderer {
240
760
  /** Rendering options. */
241
761
  options;
762
+ _table = null;
242
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.
243
768
  * @param opts - GFM rendering options.
244
769
  */
245
- constructor(opts) {
246
- super({});
770
+ constructor(target, doc, opts) {
771
+ super(target, doc, opts);
247
772
  this.options = opts;
248
773
  }
249
774
  /**
@@ -255,44 +780,91 @@ var GFMRenderer = class extends CommonMarkRenderer {
255
780
  return true;
256
781
  }
257
782
  /**
258
- * Render one block to a DOM-like node, handling GFM tables.
783
+ * Create the GFM parser state.
259
784
  *
260
- * @param block - Parsed block to render.
261
- * @param doc - Document used to create nodes.
262
- * @returns The rendered node, or `null` to emit nothing.
785
+ * @param emit - Receives parse fragments in document order.
786
+ * @returns The state for this renderer.
263
787
  */
264
- renderBlock(block, doc) {
265
- if (block.kind !== "table") return super.renderBlock(block, doc);
266
- const rows = block.lines.map(splitRow);
267
- const header = rows[0] ?? [];
268
- const alignments = (rows[1] ?? []).map(parseAlignment);
269
- const width = Math.max(header.length, ...rows.map((row) => row.length));
270
- const table = doc.createElement("table");
271
- const head = doc.createElement("thead");
272
- const headRow = doc.createElement("tr");
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");
273
825
  for (let col = 0; col < width; col++) {
274
- const cell = doc.createElement("th");
275
- const align = alignments[col] ?? null;
826
+ const cell = this._doc.createElement("th");
827
+ const align = aligns[col] ?? null;
276
828
  if (align !== null) cell.setAttribute?.("align", align);
277
- appendInline(cell, header[col] ?? "", doc, true);
829
+ appendInline(cell, header[col] ?? "", this._doc, true);
278
830
  headRow.appendChild(cell);
279
831
  }
280
832
  head.appendChild(headRow);
281
833
  table.appendChild(head);
282
- const body = doc.createElement("tbody");
283
- for (const row of rows.slice(2)) {
284
- const bodyRow = doc.createElement("tr");
285
- for (let col = 0; col < width; col++) {
286
- const cell = doc.createElement("td");
287
- const align = alignments[col] ?? null;
288
- if (align !== null) cell.setAttribute?.("align", align);
289
- appendInline(cell, row[col] ?? "", doc, true);
290
- bodyRow.appendChild(cell);
291
- }
292
- body.appendChild(bodyRow);
293
- }
834
+ const body = this._doc.createElement("tbody");
294
835
  table.appendChild(body);
295
- return table;
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;
296
868
  }
297
869
  };
298
870
 
@@ -371,265 +943,26 @@ var DOMTarget = class {
371
943
  }
372
944
  };
373
945
 
374
- // src/core/util/blocks.ts
375
- var HEADING_RE = /^(#{1,6})(?:\s+(.*))?\s*$/;
376
- var RULE_RE = /^(?:\*\s*){3,}$|^(?:-\s*){3,}$|^(?:_\s*){3,}$/;
377
- var FENCE_RE = /^(`{3,}|~{3,})\s*([^`]*)$/;
378
- var QUOTE_RE = /^>\s?(.*)$/;
379
- var BULLET_RE = /^\s*[-*+]\s+(.*)$/;
380
- var ORDERED_RE = /^\s*\d+[.)]\s+(.*)$/;
381
- var TABLE_DELIM_CELL_RE = /^:?-{1,}:?$/;
382
- function isBlankLine(line) {
383
- return line.trim() === "";
384
- }
385
- function isBlank(line) {
386
- return isBlankLine(line);
387
- }
388
- function isTableDelimiter(line) {
389
- if (!line.includes("|") && !line.includes("-")) return false;
390
- const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|");
391
- return cells.length > 0 && cells.every((cell) => TABLE_DELIM_CELL_RE.test(cell.trim()));
392
- }
393
- function hasOpenFence(lines) {
394
- let openChar = "";
395
- let openLen = 0;
396
- for (const line of lines) {
397
- const match = FENCE_RE.exec(line.trim());
398
- if (!match || !match[1]) continue;
399
- const run = match[1];
400
- if (openChar === "") {
401
- openChar = run[0];
402
- openLen = run.length;
403
- } else if (run[0] === openChar && run.length >= openLen) {
404
- openChar = "";
405
- openLen = 0;
406
- }
407
- }
408
- return openChar !== "";
409
- }
410
- function makeBlock(block, sourceLineCount) {
411
- return { ...block, sourceLineCount };
412
- }
413
- function splitBlocks(lines) {
414
- const blocks = [];
415
- let i = 0;
416
- while (i < lines.length) {
417
- const line = lines[i];
418
- if (isBlank(line)) {
419
- i++;
420
- continue;
421
- }
422
- const fence = FENCE_RE.exec(line.trim());
423
- if (fence && fence[1]) {
424
- const run = fence[1];
425
- const language = (fence[2] ?? "").trim() || void 0;
426
- const content = [];
427
- let j2 = i + 1;
428
- while (j2 < lines.length) {
429
- const inner = lines[j2];
430
- const close = FENCE_RE.exec(inner.trim());
431
- if (close && close[1] && close[1][0] === run[0] && close[1].length >= run.length) break;
432
- content.push(inner);
433
- j2++;
434
- }
435
- const closed = j2 < lines.length;
436
- blocks.push(makeBlock({ kind: "fence", lines: content, language }, j2 - i + (closed ? 1 : 0)));
437
- i = j2 + (closed ? 1 : 0);
438
- continue;
439
- }
440
- const heading = HEADING_RE.exec(line);
441
- if (heading && heading[1]) {
442
- const text = (heading[2] ?? "").replace(/\s+#+\s*$/, "").trim();
443
- blocks.push(makeBlock({ kind: "heading", lines: [text], level: Math.min(6, heading[1].length) }, 1));
444
- i++;
445
- continue;
446
- }
447
- if (RULE_RE.test(line.trim())) {
448
- blocks.push(makeBlock({ kind: "rule", lines: [] }, 1));
449
- i++;
450
- continue;
451
- }
452
- if (line.includes("|") && i + 1 < lines.length && isTableDelimiter(lines[i + 1])) {
453
- const rows = [line, lines[i + 1]];
454
- let j2 = i + 2;
455
- while (j2 < lines.length && !isBlank(lines[j2]) && lines[j2].includes("|")) {
456
- rows.push(lines[j2]);
457
- j2++;
458
- }
459
- blocks.push(makeBlock({ kind: "table", lines: rows }, j2 - i));
460
- i = j2;
461
- continue;
462
- }
463
- const quote = QUOTE_RE.exec(line);
464
- if (quote) {
465
- const quoted = [quote[1] ?? ""];
466
- let j2 = i + 1;
467
- while (j2 < lines.length) {
468
- const next = QUOTE_RE.exec(lines[j2]);
469
- if (!next) break;
470
- quoted.push(next[1] ?? "");
471
- j2++;
472
- }
473
- blocks.push(makeBlock({ kind: "quote", lines: quoted }, j2 - i));
474
- i = j2;
475
- continue;
476
- }
477
- const bullet = BULLET_RE.exec(line);
478
- const ordered = ORDERED_RE.exec(line);
479
- if (bullet || ordered) {
480
- const isOrdered = !bullet;
481
- const items = [bullet?.[1] ?? ordered?.[1] ?? ""];
482
- let j2 = i + 1;
483
- while (j2 < lines.length) {
484
- const nextBullet = BULLET_RE.exec(lines[j2]);
485
- const nextOrdered = ORDERED_RE.exec(lines[j2]);
486
- if (isOrdered && nextOrdered) items.push(nextOrdered[1] ?? "");
487
- else if (!isOrdered && nextBullet && !ORDERED_RE.test(lines[j2])) items.push(nextBullet[1] ?? "");
488
- else break;
489
- j2++;
490
- }
491
- blocks.push(makeBlock({ kind: "list", lines: items, ordered: isOrdered }, j2 - i));
492
- i = j2;
493
- continue;
494
- }
495
- const paragraph = [line];
496
- let j = i + 1;
497
- while (j < lines.length) {
498
- const next = lines[j];
499
- 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])) {
500
- break;
501
- }
502
- paragraph.push(next);
503
- j++;
504
- }
505
- blocks.push(makeBlock({ kind: "paragraph", lines: paragraph }, j - i));
506
- i = j;
507
- }
508
- return blocks;
946
+ // src/targets/render-target.ts
947
+ function createRenderTarget(targetNode, raf) {
948
+ return raf === void 0 ? new DOMTarget(targetNode) : new AnimatedDOMTarget(targetNode, raf);
509
949
  }
510
950
 
511
- // src/renderers/renderer-state.ts
512
- var RendererState = class {
513
- _pending = [];
514
- /**
515
- * Buffer newly arrived lines.
516
- *
517
- * @param lines - Complete source lines to buffer.
518
- */
519
- addLines(lines) {
520
- for (const line of lines) this._pending.push(line);
521
- }
522
- /**
523
- * Parse buffered lines, returning every block except a trailing partial one.
524
- *
525
- * @remarks
526
- * The last block is held back because more input may still extend it.
527
- * Nothing is returned while the buffer ends inside an unclosed fence.
528
- *
529
- * @returns Complete blocks ready to render.
530
- */
531
- takeCompleteBlocks() {
532
- let start = 0;
533
- let end = this._pending.length;
534
- while (start < end && isBlankLine(this._pending[start])) start++;
535
- while (end > start && isBlankLine(this._pending[end - 1])) end--;
536
- const trimmed = this._pending.slice(start, end);
537
- if (trimmed.length === 0) {
538
- this._pending = [];
539
- return [];
540
- }
541
- if (hasOpenFence(trimmed)) return [];
542
- const blocks = splitBlocks(trimmed);
543
- const last = blocks[blocks.length - 1];
544
- if (last === void 0) {
545
- this._pending = [];
546
- return [];
547
- }
548
- this._pending = trimmed.slice(trimmed.length - last.sourceLineCount);
549
- return blocks.slice(0, -1);
550
- }
551
- /**
552
- * Parse and drain all buffered lines, including a trailing partial block.
553
- *
554
- * @returns Every remaining block.
555
- */
556
- takeAllBlocks() {
557
- const blocks = splitBlocks(this._pending);
558
- this._pending = [];
559
- return blocks;
560
- }
561
- };
562
-
563
- // src/sources/line-source.ts
564
- function createLineSource() {
565
- let buffer = "";
566
- let closed = false;
567
- return {
568
- push(chunk) {
569
- if (closed) throw new Error("push after close");
570
- buffer += chunk;
571
- },
572
- readLines() {
573
- const lines = [];
574
- let at = buffer.indexOf("\n");
575
- while (at !== -1) {
576
- lines.push(buffer.slice(0, at).replace(/\r$/, ""));
577
- buffer = buffer.slice(at + 1);
578
- at = buffer.indexOf("\n");
579
- }
580
- return lines;
581
- },
582
- close() {
583
- closed = true;
584
- if (buffer === "") return [];
585
- const rest = buffer.replace(/\r$/, "");
586
- buffer = "";
587
- return [rest];
588
- }
589
- };
590
- }
591
-
592
- // src/core/pipelines/pipeline-engine.ts
593
- function createPipelineEngine(renderer, target, dom) {
594
- const source = createLineSource();
595
- const state = new RendererState();
596
- function render(blocks) {
597
- for (const block of blocks) {
598
- const node = renderer.renderBlock(block, dom);
599
- if (node !== null) target.append(node);
600
- }
601
- }
602
- return {
603
- async push(chunk) {
604
- source.push(await chunk);
605
- state.addLines(source.readLines());
606
- render(state.takeCompleteBlocks());
607
- },
608
- async flush() {
609
- state.addLines(source.close());
610
- render(state.takeAllBlocks());
611
- await target.flush();
612
- }
613
- };
614
- }
615
-
616
- // src/core/pipelines/frontend-gfm-pipeline.ts
617
- function createFrontendGFMPipeline(target, dom, opts, raf) {
618
- return new FrontendGFMPipeline(target, dom, opts, raf);
951
+ // src/core/pipelines/gfm-pipeline.ts
952
+ function createGFMPipeline(target, dom, opts, raf) {
953
+ return new GFMPipeline(target, dom, opts, raf);
619
954
  }
620
- var FrontendGFMPipeline = class {
955
+ var GFMPipeline = class {
621
956
  _engine;
622
957
  /**
623
- * @param target - Container node receiving rendered blocks.
958
+ * @param target - Container node receiving rendered output.
624
959
  * @param dom - Document used to create nodes.
625
960
  * @param opts - GFM rendering options.
626
961
  * @param raf - Optional frame scheduler for batched DOM writes.
627
962
  */
628
963
  constructor(target, dom, opts, raf) {
629
- this._engine = createPipelineEngine(
630
- new GFMRenderer(opts),
631
- raf === void 0 ? new DOMTarget(target) : new AnimatedDOMTarget(target, raf),
632
- dom
964
+ this._engine = createMarkdownPipeline(
965
+ new GFMRenderer(createRenderTarget(target, raf), dom, opts)
633
966
  );
634
967
  }
635
968
  /**
@@ -651,23 +984,21 @@ var FrontendGFMPipeline = class {
651
984
  }
652
985
  };
653
986
 
654
- // src/core/pipelines/frontend-commonmark-pipeline.ts
655
- function createFrontendCommonMarkPipeline(target, dom, opts, raf) {
656
- return new FrontendCommonMarkPipeline(target, dom, opts, raf);
987
+ // src/core/pipelines/commonmark-pipeline.ts
988
+ function createCommonMarkPipeline(target, dom, opts, raf) {
989
+ return new CommonMarkPipeline(target, dom, opts, raf);
657
990
  }
658
- var FrontendCommonMarkPipeline = class {
991
+ var CommonMarkPipeline = class {
659
992
  _engine;
660
993
  /**
661
- * @param target - Container node receiving rendered blocks.
994
+ * @param target - Container node receiving rendered output.
662
995
  * @param dom - Document used to create nodes.
663
996
  * @param opts - CommonMark rendering options.
664
997
  * @param raf - Optional frame scheduler for batched DOM writes.
665
998
  */
666
999
  constructor(target, dom, opts, raf) {
667
- this._engine = createPipelineEngine(
668
- new CommonMarkRenderer(opts),
669
- raf === void 0 ? new DOMTarget(target) : new AnimatedDOMTarget(target, raf),
670
- dom
1000
+ this._engine = createMarkdownPipeline(
1001
+ new CommonMarkRenderer(createRenderTarget(target, raf), dom, opts)
671
1002
  );
672
1003
  }
673
1004
  /**
@@ -689,72 +1020,6 @@ var FrontendCommonMarkPipeline = class {
689
1020
  }
690
1021
  };
691
1022
 
692
- // src/core/pipelines/backend-gfm-pipeline.ts
693
- function createBackendGFMPipeline(target, dom, opts) {
694
- return new BackendGFMPipeline(target, dom, opts);
695
- }
696
- var BackendGFMPipeline = class {
697
- _engine;
698
- /**
699
- * @param target - Container node receiving rendered blocks.
700
- * @param dom - Document used to create nodes.
701
- * @param opts - GFM rendering options.
702
- */
703
- constructor(target, dom, opts) {
704
- this._engine = createPipelineEngine(new GFMRenderer(opts), new DOMTarget(target), dom);
705
- }
706
- /**
707
- * Push a chunk of markdown into the pipeline.
708
- *
709
- * @param chunk - Markdown text, or a promise resolving to markdown text.
710
- * @returns A promise that resolves once the chunk has been consumed.
711
- */
712
- push(chunk) {
713
- return this._engine.push(chunk);
714
- }
715
- /**
716
- * Render any buffered remainder.
717
- *
718
- * @returns A promise that resolves once all output has been flushed.
719
- */
720
- flush() {
721
- return this._engine.flush();
722
- }
723
- };
724
-
725
- // src/core/pipelines/backend-commonmark-pipeline.ts
726
- function createBackendCommonMarkPipeline(target, dom, opts) {
727
- return new BackendCommonMarkPipeline(target, dom, opts);
728
- }
729
- var BackendCommonMarkPipeline = class {
730
- _engine;
731
- /**
732
- * @param target - Container node receiving rendered blocks.
733
- * @param dom - Document used to create nodes.
734
- * @param opts - CommonMark rendering options.
735
- */
736
- constructor(target, dom, opts) {
737
- this._engine = createPipelineEngine(new CommonMarkRenderer(opts), new DOMTarget(target), dom);
738
- }
739
- /**
740
- * Push a chunk of markdown into the pipeline.
741
- *
742
- * @param chunk - Markdown text, or a promise resolving to markdown text.
743
- * @returns A promise that resolves once the chunk has been consumed.
744
- */
745
- push(chunk) {
746
- return this._engine.push(chunk);
747
- }
748
- /**
749
- * Render any buffered remainder.
750
- *
751
- * @returns A promise that resolves once all output has been flushed.
752
- */
753
- flush() {
754
- return this._engine.flush();
755
- }
756
- };
757
-
758
- export { AnimatedDOMTarget, BackendCommonMarkPipeline, BackendGFMPipeline, CommonMarkRenderer, DOMTarget, FrontendCommonMarkPipeline, FrontendGFMPipeline, GFMRenderer, RendererState, createBackendCommonMarkPipeline, createBackendGFMPipeline, createFrontendCommonMarkPipeline, createFrontendGFMPipeline, createLineSource };
1023
+ export { CommonMarkPipeline, CommonMarkRenderer, GFMPipeline, GFMRenderer, createCommonMarkPipeline, createGFMPipeline, createMarkdownPipeline, createRenderTarget };
759
1024
  //# sourceMappingURL=index.js.map
760
1025
  //# sourceMappingURL=index.js.map