@mdsvex/render 0.0.0 → 1.0.0-next.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.
@@ -0,0 +1,855 @@
1
+ /**
2
+ * cursor-based pfm html renderer
3
+ *
4
+ * renders html from a cursor over soa NodeBuffer.
5
+ * zero per-node allocations, the cursor walks typed arrays directly,
6
+ * text is lazily sliced from source only when needed.
7
+ *
8
+ * usage:
9
+ *
10
+ * const cursor = new cursor(tree.get_buffer(), source);
11
+ * const html = rendercursor(cursor);
12
+ */
13
+
14
+ import { Cursor } from "@mdsvex/parse/cursor";
15
+ import type { NodeBuffer } from "@mdsvex/parse/utils";
16
+ import { CI_TEXT, CI_CODE, CI_SVELTE, CI_STRUCTURE } from "./mappings";
17
+ import type { Mapping, CodeInformation, MappingData } from "./mappings";
18
+
19
+ export type { Mapping, CodeInformation, MappingData } from "./mappings";
20
+
21
+ // html escaping
22
+
23
+ const ESCAPE_TEST = /[&<>"]/;
24
+ const ESCAPE_MATCH = /[&<>"]/g;
25
+ const ESCAPE_TABLE: Record<string, string> = {
26
+ "&": "&amp;",
27
+ "<": "&lt;",
28
+ ">": "&gt;",
29
+ '"': "&quot;",
30
+ };
31
+ function escape_replace(ch: string): string {
32
+ return ESCAPE_TABLE[ch];
33
+ }
34
+ export function escape(text: string): string {
35
+ if (!ESCAPE_TEST.test(text)) return text;
36
+ return text.replace(ESCAPE_MATCH, escape_replace);
37
+ }
38
+
39
+ // kind constants
40
+
41
+ export const K_ROOT = 0;
42
+ export const K_TEXT = 1;
43
+ export const K_HTML = 2;
44
+ export const K_HEADING = 3;
45
+ export const K_CODE_FENCE = 5;
46
+ export const K_LINE_BREAK = 6;
47
+ export const K_PARAGRAPH = 7;
48
+ export const K_CODE_SPAN = 8;
49
+ export const K_EMPHASIS = 9;
50
+ export const K_STRONG = 10;
51
+ export const K_THEMATIC_BREAK = 11;
52
+ export const K_LINK = 12;
53
+ export const K_IMAGE = 13;
54
+ export const K_BLOCK_QUOTE = 14;
55
+ export const K_LIST = 15;
56
+ export const K_LIST_ITEM = 16;
57
+ export const K_HARD_BREAK = 17;
58
+ export const K_SOFT_BREAK = 18;
59
+ export const K_STRIKETHROUGH = 19;
60
+ export const K_SUPERSCRIPT = 20;
61
+ export const K_SUBSCRIPT = 21;
62
+ export const K_TABLE = 22;
63
+ export const K_TABLE_HEADER = 23;
64
+ export const K_TABLE_ROW = 24;
65
+ export const K_TABLE_CELL = 25;
66
+ export const K_HTML_COMMENT = 26;
67
+ export const K_SVELTE_TAG = 27;
68
+ export const K_SVELTE_BLOCK = 28;
69
+ export const K_SVELTE_BRANCH = 29;
70
+ export const K_MUSTACHE = 4;
71
+ export const K_FRONTMATTER = 33;
72
+ export const K_IMPORT_STATEMENT = 34;
73
+
74
+ export const NONE = 0xffffffff;
75
+
76
+ // pending mapping entry (resolved to Mapping<MappingData> after render)
77
+
78
+ export interface PendingMapping {
79
+ out_idx: number;
80
+ out_count: number;
81
+ source_offset: number;
82
+ source_length: number;
83
+ data: MappingData;
84
+ }
85
+
86
+ /** emit a mapping entry. skips if generated range is empty. */
87
+ export function _emit(
88
+ entries: PendingMapping[],
89
+ out_start: number,
90
+ out_end: number,
91
+ src_start: number,
92
+ src_end: number,
93
+ data: MappingData,
94
+ ): void {
95
+ if (out_end > out_start && src_start !== NONE) {
96
+ entries.push({
97
+ out_idx: out_start,
98
+ out_count: out_end - out_start,
99
+ source_offset: src_start,
100
+ source_length: src_end > src_start ? src_end - src_start : 0,
101
+ data,
102
+ });
103
+ }
104
+ }
105
+
106
+ /** emit node span + open_syntax + close_syntax for a rendered node. */
107
+ function _spans(
108
+ entries: PendingMapping[],
109
+ pre: number,
110
+ after_open: number,
111
+ before_close: number,
112
+ post: number,
113
+ c: Cursor,
114
+ ci: CodeInformation,
115
+ ): void {
116
+ const idx = c.index;
117
+ const s = c.start, e = c.end, vs = c.value_start, ve = c.value_end;
118
+ // value range is meaningful when ve > vs (same check as Cursor.text()).
119
+ // Uint32Array defaults to 0 for unset slots, so ve !== NONE is not enough.
120
+ const has_value = ve > vs;
121
+ _emit(entries, pre, post, s, e, { ...ci, nodeIndex: idx, role: "node" });
122
+ _emit(entries, pre, after_open, s, has_value ? vs : s, { ...CI_STRUCTURE, nodeIndex: idx, role: "open_syntax" });
123
+ _emit(entries, before_close, post, has_value ? ve : e, e, { ...CI_STRUCTURE, nodeIndex: idx, role: "close_syntax" });
124
+ }
125
+
126
+ // precomputed tag strings
127
+
128
+ const H_OPEN = ["", "<h1>", "<h2>", "<h3>", "<h4>", "<h5>", "<h6>"];
129
+ const H_CLOSE = ["", "</h1>", "</h2>", "</h3>", "</h4>", "</h5>", "</h6>"];
130
+
131
+ const HTML_VOID_ELEMENTS = new Set([
132
+ "area",
133
+ "base",
134
+ "br",
135
+ "col",
136
+ "embed",
137
+ "hr",
138
+ "img",
139
+ "input",
140
+ "link",
141
+ "meta",
142
+ "param",
143
+ "source",
144
+ "track",
145
+ "wbr",
146
+ ]);
147
+
148
+ // generic attribute emission
149
+
150
+ /**
151
+ * metadata keys that are structural / internal and should never be
152
+ * emitted as html attributes. everything else is fair game.
153
+ */
154
+ const INTERNAL_KEYS = new Set([
155
+ // list semantics
156
+ "ordered", "tight", "start",
157
+ // code fence info (transformed into class="language-X")
158
+ "info", "info_start", "info_end",
159
+ // raw html node internals
160
+ "tag", "attributes", "self_closing",
161
+ // table internals
162
+ "alignments", "col_count",
163
+ // image src (handled specially with alt ordering)
164
+ "src",
165
+ ]);
166
+
167
+ /**
168
+ * emit all non-internal metadata as html attributes.
169
+ * keys already handled by the caller are passed in `skip`.
170
+ */
171
+ function _attrs(c: Cursor, out: string[], skip?: Set<string>): void {
172
+ const meta = c.meta();
173
+ if (!meta) return;
174
+ for (const key in meta) {
175
+ if (INTERNAL_KEYS.has(key)) continue;
176
+ if (skip !== undefined && skip.has(key)) continue;
177
+ const val = meta[key];
178
+ if (val === true) {
179
+ out.push(" ", key);
180
+ } else if (val !== false && val != null) {
181
+ if (typeof val === "object" && (val as any).type === "expression") {
182
+ out.push(" ", key, "={", (val as any).value, "}");
183
+ } else {
184
+ out.push(' ', key, '="', escape(String(val)), '"');
185
+ }
186
+ }
187
+ }
188
+ }
189
+
190
+ const LINK_HANDLED = new Set(["href", "title"]);
191
+ const IMAGE_HANDLED = new Set(["title"]);
192
+
193
+ // renderer
194
+
195
+ /** render children of the current cursor position, collecting escaped text and recursive node output. */
196
+ export function _children(c: Cursor, out: string[], entries?: PendingMapping[]): void {
197
+ if (!c.goto_first_child()) return;
198
+ do {
199
+ if (c.kind === K_TEXT) {
200
+ const vs = c.value_start, ve = c.value_end;
201
+ if (entries && vs !== NONE && ve > vs) {
202
+ _emit(entries, out.length, out.length + 1, vs, ve,
203
+ { ...CI_TEXT, nodeIndex: c.index, role: "content" });
204
+ }
205
+ out.push(escape(c.text()));
206
+ } else {
207
+ _node(c, out, entries);
208
+ }
209
+ } while (c.goto_next_sibling());
210
+ c.goto_parent();
211
+ }
212
+
213
+ /** collect raw text from child text nodes (for image alt, link text fallback, etc.). */
214
+ function _children_raw(c: Cursor): string {
215
+ if (!c.goto_first_child()) return "";
216
+ let text = "";
217
+ do {
218
+ if (c.kind === K_TEXT) {
219
+ text += c.text();
220
+ } else {
221
+ text += _children_raw(c);
222
+ }
223
+ } while (c.goto_next_sibling());
224
+ c.goto_parent();
225
+ return text;
226
+ }
227
+
228
+ /** render a single node at the current cursor position. */
229
+ export function _node(c: Cursor, out: string[], entries?: PendingMapping[]): void {
230
+ switch (c.kind) {
231
+ case K_ROOT:
232
+ _children(c, out, entries);
233
+ break;
234
+
235
+ case K_HEADING: {
236
+ const pre = out.length;
237
+ out.push("<h", String(c.extra));
238
+ _attrs(c, out);
239
+ out.push(">");
240
+ const ao = out.length;
241
+ _children(c, out, entries);
242
+ const bc = out.length;
243
+ out.push(H_CLOSE[c.extra]);
244
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
245
+ break;
246
+ }
247
+
248
+ case K_PARAGRAPH:
249
+ // pending paragraphs inside list_items are speculative tight-list
250
+ // wrappers, render their children transparently until the list
251
+ // closes (commit keeps the wrapper, revoke drops it).
252
+ if (c.pending && c.parent_kind === K_LIST_ITEM) {
253
+ _children(c, out, entries);
254
+ } else {
255
+ const pre = out.length;
256
+ out.push("<p");
257
+ _attrs(c, out);
258
+ out.push(">");
259
+ const ao = out.length;
260
+ _children(c, out, entries);
261
+ const bc = out.length;
262
+ out.push("</p>");
263
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
264
+ }
265
+ break;
266
+
267
+ case K_EMPHASIS: {
268
+ const pre = out.length;
269
+ out.push("<em");
270
+ _attrs(c, out);
271
+ out.push(">");
272
+ const ao = out.length;
273
+ _children(c, out, entries);
274
+ const bc = out.length;
275
+ out.push("</em>");
276
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
277
+ break;
278
+ }
279
+
280
+ case K_STRONG: {
281
+ const pre = out.length;
282
+ out.push("<strong");
283
+ _attrs(c, out);
284
+ out.push(">");
285
+ const ao = out.length;
286
+ _children(c, out, entries);
287
+ const bc = out.length;
288
+ out.push("</strong>");
289
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
290
+ break;
291
+ }
292
+
293
+ case K_CODE_SPAN: {
294
+ const pre = out.length;
295
+ out.push("<code");
296
+ _attrs(c, out);
297
+ out.push(">");
298
+ const ao = out.length;
299
+ if (entries) {
300
+ _emit(entries, out.length, out.length + 1, c.value_start, c.value_end,
301
+ { ...CI_CODE, nodeIndex: c.index, role: "content" });
302
+ }
303
+ out.push(escape(c.text()).replace(/\n/g, " "));
304
+ const bc = out.length;
305
+ out.push("</code>");
306
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_CODE);
307
+ break;
308
+ }
309
+
310
+ case K_CODE_FENCE: {
311
+ const pre = out.length;
312
+ const meta = c.meta();
313
+ // wire path: resolved 'info' string. treebuilder path: info_start/info_end byte offsets.
314
+ let info = meta?.info as string | undefined;
315
+ if (!info) {
316
+ const info_start = meta?.info_start as number | undefined;
317
+ const info_end = meta?.info_end as number | undefined;
318
+ if (info_start != null && info_end != null)
319
+ info = c.slice(info_start, info_end);
320
+ }
321
+ out.push("<pre><code");
322
+ if (info) out.push(' class="language-', escape(info), '"');
323
+ _attrs(c, out);
324
+ out.push(">");
325
+ const ao = out.length;
326
+ if (entries) {
327
+ _emit(entries, out.length, out.length + 1, c.value_start, c.value_end,
328
+ { ...CI_CODE, nodeIndex: c.index, role: "content" });
329
+ }
330
+ out.push(escape(c.text()));
331
+ const bc = out.length;
332
+ out.push("</code></pre>");
333
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_CODE);
334
+ break;
335
+ }
336
+
337
+ case K_BLOCK_QUOTE: {
338
+ const pre = out.length;
339
+ out.push("<blockquote");
340
+ _attrs(c, out);
341
+ out.push(">\n");
342
+ const ao = out.length;
343
+ _children(c, out, entries);
344
+ const bc = out.length;
345
+ out.push("\n</blockquote>");
346
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
347
+ break;
348
+ }
349
+
350
+ case K_LINK: {
351
+ const pre = out.length;
352
+ const meta = c.meta();
353
+ out.push("<a");
354
+ if (meta?.href) out.push(' href="', escape(meta.href as string), '"');
355
+ if (meta?.title) out.push(' title="', escape(meta.title as string), '"');
356
+ _attrs(c, out, LINK_HANDLED);
357
+ out.push(">");
358
+ const ao = out.length;
359
+ _children(c, out, entries);
360
+ const bc = out.length;
361
+ out.push("</a>");
362
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
363
+ break;
364
+ }
365
+
366
+ case K_IMAGE: {
367
+ const pre = out.length;
368
+ const meta = c.meta();
369
+ out.push("<img");
370
+ if (meta?.src) out.push(' src="', escape(meta.src as string), '"');
371
+ out.push(' alt="', escape(_children_raw(c)), '"');
372
+ if (meta?.title) out.push(' title="', escape(meta.title as string), '"');
373
+ _attrs(c, out, IMAGE_HANDLED);
374
+ out.push(" />");
375
+ if (entries) _spans(entries, pre, pre, out.length, out.length, c, CI_TEXT);
376
+ break;
377
+ }
378
+
379
+ case K_LIST: {
380
+ const pre = out.length;
381
+ const meta = c.meta();
382
+ const ordered = !!meta?.ordered;
383
+ const tag = ordered ? "ol" : "ul";
384
+ const start = meta?.start as number | undefined;
385
+ out.push("<", tag);
386
+ if (ordered && start != null && start !== 1)
387
+ out.push(' start="', String(start), '"');
388
+ _attrs(c, out);
389
+ out.push(">\n");
390
+ const ao = out.length;
391
+ _children(c, out, entries);
392
+ const bc = out.length;
393
+ out.push("\n</", tag, ">");
394
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_STRUCTURE);
395
+ break;
396
+ }
397
+
398
+ case K_LIST_ITEM: {
399
+ const pre = out.length;
400
+ out.push("<li");
401
+ _attrs(c, out);
402
+ out.push(">");
403
+ const ao = out.length;
404
+ _children(c, out, entries);
405
+ const bc = out.length;
406
+ out.push("</li>\n");
407
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
408
+ break;
409
+ }
410
+
411
+ case K_THEMATIC_BREAK: {
412
+ const pre = out.length;
413
+ out.push("<hr />");
414
+ if (entries) _spans(entries, pre, out.length, out.length, out.length, c, CI_STRUCTURE);
415
+ break;
416
+ }
417
+
418
+ case K_HARD_BREAK:
419
+ out.push("<br />\n");
420
+ break;
421
+
422
+ case K_SOFT_BREAK:
423
+ out.push("\n");
424
+ break;
425
+
426
+ case K_STRIKETHROUGH: {
427
+ const pre = out.length;
428
+ out.push("<del");
429
+ _attrs(c, out);
430
+ out.push(">");
431
+ const ao = out.length;
432
+ _children(c, out, entries);
433
+ const bc = out.length;
434
+ out.push("</del>");
435
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
436
+ break;
437
+ }
438
+
439
+ case K_SUPERSCRIPT: {
440
+ const pre = out.length;
441
+ out.push("<sup");
442
+ _attrs(c, out);
443
+ out.push(">");
444
+ const ao = out.length;
445
+ _children(c, out, entries);
446
+ const bc = out.length;
447
+ out.push("</sup>");
448
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
449
+ break;
450
+ }
451
+
452
+ case K_SUBSCRIPT: {
453
+ const pre = out.length;
454
+ out.push("<sub");
455
+ _attrs(c, out);
456
+ out.push(">");
457
+ const ao = out.length;
458
+ _children(c, out, entries);
459
+ const bc = out.length;
460
+ out.push("</sub>");
461
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
462
+ break;
463
+ }
464
+
465
+ case K_HTML: {
466
+ const pre = out.length;
467
+ const meta = c.meta();
468
+ const tag = meta?.tag as string;
469
+ const html_attrs = meta?.attributes as
470
+ | Record<string, string | boolean>
471
+ | undefined;
472
+
473
+ out.push("<", tag);
474
+ if (html_attrs) {
475
+ for (const k in html_attrs) {
476
+ const v = html_attrs[k];
477
+ if (v === true) {
478
+ out.push(" ", k);
479
+ } else if (typeof v === "object" && (v as any).type === "expression") {
480
+ out.push(" ", k, "={", (v as any).value, "}");
481
+ } else {
482
+ out.push(" ", k, '="', escape(v as string), '"');
483
+ }
484
+ }
485
+ }
486
+ if (meta?.self_closing) {
487
+ // source passthrough: use exact source text to guarantee
488
+ // identity mapping. reconstruction can differ from the
489
+ // source (extra space before />, attribute escaping, quote
490
+ // style) which makes the mapping non-identity and breaks
491
+ // per-token precision in the PFM->Svelte->TS composition
492
+ // pipeline.
493
+ // falls back to reconstruction when source is unavailable
494
+ // (e.g. wire/streaming renderer with empty source).
495
+ const passthrough = c.end > c.start ? c.slice(c.start, c.end) : "";
496
+ if (passthrough) {
497
+ out.length = pre;
498
+ out.push(passthrough);
499
+ } else {
500
+ out.push(" />");
501
+ }
502
+ if (entries) {
503
+ _emit(entries, pre, out.length, c.start, c.end,
504
+ { ...CI_SVELTE, nodeIndex: c.index, role: "content" });
505
+ }
506
+ } else {
507
+ out.push(">");
508
+ const ao = out.length;
509
+ // raw-text elements: parser stores content as value range on
510
+ // the html node itself (no child nodes). emit unescaped, the
511
+ // browser does not parse script/style bodies as html.
512
+ if (tag === "script" || tag === "style") {
513
+ if (entries) {
514
+ _emit(entries, out.length, out.length + 1, c.value_start, c.value_end,
515
+ { ...CI_SVELTE, nodeIndex: c.index, role: "content" });
516
+ }
517
+ out.push(c.text());
518
+ } else {
519
+ _children(c, out, entries);
520
+ }
521
+ const bc = out.length;
522
+ out.push("</", tag, ">");
523
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
524
+ }
525
+ break;
526
+ }
527
+
528
+ case K_HTML_COMMENT: {
529
+ const pre = out.length;
530
+ out.push("<!--");
531
+ const ao = out.length;
532
+ if (entries) {
533
+ _emit(entries, out.length, out.length + 1, c.value_start, c.value_end,
534
+ { ...CI_TEXT, nodeIndex: c.index, role: "content" });
535
+ }
536
+ out.push(c.text());
537
+ const bc = out.length;
538
+ out.push("-->");
539
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_TEXT);
540
+ break;
541
+ }
542
+
543
+ case K_MUSTACHE: {
544
+ const pre = out.length;
545
+ out.push("{");
546
+ const ao = out.length;
547
+ if (entries) {
548
+ _emit(entries, out.length, out.length + 1, c.value_start, c.value_end,
549
+ { ...CI_SVELTE, nodeIndex: c.index, role: "content" });
550
+ }
551
+ out.push(c.text());
552
+ const bc = out.length;
553
+ out.push("}");
554
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_SVELTE);
555
+ break;
556
+ }
557
+
558
+ case K_SVELTE_TAG: {
559
+ const pre = out.length;
560
+ const meta = c.meta();
561
+ const tag = meta?.tag as string;
562
+ const text = c.text();
563
+ out.push("{@", tag);
564
+ if (text) out.push(" ");
565
+ const ao = out.length;
566
+ if (text && entries) {
567
+ _emit(entries, out.length, out.length + 1, c.value_start, c.value_end,
568
+ { ...CI_SVELTE, nodeIndex: c.index, role: "content" });
569
+ }
570
+ if (text) out.push(text);
571
+ const bc = out.length;
572
+ out.push("}");
573
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_SVELTE);
574
+ break;
575
+ }
576
+
577
+ case K_SVELTE_BLOCK: {
578
+ const pre = out.length;
579
+ // render branches; each branch handles its own opening tag
580
+ const block_meta = c.meta();
581
+ const block_tag = block_meta?.tag as string;
582
+ if (c.goto_first_child()) {
583
+ let is_first = true;
584
+ do {
585
+ if (c.kind === K_SVELTE_BRANCH) {
586
+ const branch_meta = c.meta();
587
+ const branch_tag = branch_meta?.tag as string;
588
+ const branch_expr = c.text();
589
+ if (is_first) {
590
+ out.push("{#", block_tag);
591
+ if (branch_expr) {
592
+ out.push(" ");
593
+ if (entries) {
594
+ _emit(entries, out.length, out.length + 1, c.value_start, c.value_end,
595
+ { ...CI_SVELTE, nodeIndex: c.index, role: "content" });
596
+ }
597
+ out.push(branch_expr);
598
+ }
599
+ out.push("}\n");
600
+ is_first = false;
601
+ } else {
602
+ out.push("{:", branch_tag);
603
+ if (branch_expr) {
604
+ out.push(" ");
605
+ if (entries) {
606
+ _emit(entries, out.length, out.length + 1, c.value_start, c.value_end,
607
+ { ...CI_SVELTE, nodeIndex: c.index, role: "content" });
608
+ }
609
+ out.push(branch_expr);
610
+ }
611
+ out.push("}\n");
612
+ }
613
+ _children(c, out, entries);
614
+ } else if (c.kind !== K_LINE_BREAK) {
615
+ _node(c, out, entries);
616
+ }
617
+ } while (c.goto_next_sibling());
618
+ c.goto_parent();
619
+ }
620
+ out.push("{/", block_tag, "}");
621
+ // node span for the whole block, use the block node (goto_parent already called)
622
+ if (entries) {
623
+ const idx = c.index;
624
+ const s = c.start, e = c.end;
625
+ _emit(entries, pre, out.length, s, e, { ...CI_SVELTE, nodeIndex: idx, role: "node" });
626
+ }
627
+ break;
628
+ }
629
+
630
+ case K_TABLE: {
631
+ const pre = out.length;
632
+ out.push("<table");
633
+ _attrs(c, out);
634
+ out.push(">\n");
635
+ const ao = out.length;
636
+ _table_content(c, out, entries);
637
+ const bc = out.length;
638
+ out.push("\n</table>");
639
+ if (entries) _spans(entries, pre, ao, bc, out.length, c, CI_STRUCTURE);
640
+ break;
641
+ }
642
+
643
+ case K_LINE_BREAK:
644
+ break;
645
+
646
+ default:
647
+ _children(c, out, entries);
648
+ break;
649
+ }
650
+ }
651
+
652
+ function _table_content(c: Cursor, out: string[], entries?: PendingMapping[]): void {
653
+ const meta = c.meta();
654
+ const alignments = (meta?.alignments as string[]) ?? [];
655
+ let in_body = false;
656
+
657
+ if (!c.goto_first_child()) return;
658
+ do {
659
+ if (c.kind === K_TABLE_HEADER) {
660
+ out.push("<thead>\n<tr>\n");
661
+ _table_cells(c, "th", alignments, out, entries);
662
+ out.push("</tr>\n</thead>\n");
663
+ } else if (c.kind === K_TABLE_ROW) {
664
+ if (!in_body) {
665
+ out.push("<tbody>\n");
666
+ in_body = true;
667
+ }
668
+ out.push("<tr>\n");
669
+ _table_cells(c, "td", alignments, out, entries);
670
+ out.push("</tr>\n");
671
+ }
672
+ } while (c.goto_next_sibling());
673
+ c.goto_parent();
674
+
675
+ if (in_body) out.push("</tbody>");
676
+ }
677
+
678
+ function _table_cells(
679
+ c: Cursor,
680
+ tag: string,
681
+ alignments: string[],
682
+ out: string[],
683
+ entries?: PendingMapping[],
684
+ ): void {
685
+ let col = 0;
686
+ if (!c.goto_first_child()) return;
687
+ do {
688
+ if (c.kind === K_TABLE_CELL) {
689
+ const align = alignments[col];
690
+ if (align && align !== "none") {
691
+ out.push("<", tag, ' align="', align, '">');
692
+ } else {
693
+ out.push("<", tag, ">");
694
+ }
695
+ _children(c, out, entries);
696
+ out.push("</", tag, ">\n");
697
+ col++;
698
+ }
699
+ } while (c.goto_next_sibling());
700
+ c.goto_parent();
701
+ }
702
+
703
+ // mapping resolution
704
+
705
+ /** convert pending mapping entries to volar-compatible Mapping[] using out[] offsets. */
706
+ export function _resolve_mappings(
707
+ out: string[],
708
+ entries: PendingMapping[],
709
+ ): Mapping<MappingData>[] {
710
+ // build cumulative offset table
711
+ const offsets = new Uint32Array(out.length + 1);
712
+ for (let i = 0; i < out.length; i++) {
713
+ offsets[i + 1] = offsets[i] + out[i].length;
714
+ }
715
+
716
+ const mappings: Mapping<MappingData>[] = [];
717
+ for (let i = 0; i < entries.length; i++) {
718
+ const e = entries[i];
719
+ const gen_offset = offsets[e.out_idx];
720
+ const gen_length = offsets[e.out_idx + e.out_count] - gen_offset;
721
+ const m: Mapping<MappingData> = {
722
+ sourceOffsets: [e.source_offset],
723
+ generatedOffsets: [gen_offset],
724
+ lengths: [e.source_length],
725
+ data: e.data,
726
+ };
727
+ if (gen_length !== e.source_length) {
728
+ m.generatedLengths = [gen_length];
729
+ }
730
+ mappings.push(m);
731
+ }
732
+ return mappings;
733
+ }
734
+
735
+ // internal helpers
736
+
737
+ /** render the node at the current cursor position to html string. */
738
+ function _render_block(cursor: Cursor): string {
739
+ const out: string[] = [];
740
+ _node(cursor, out);
741
+ return out.join("");
742
+ }
743
+
744
+ // block entry
745
+
746
+ export interface CursorBlockEntry {
747
+ /** node buffer index, use as keyed each key. */
748
+ idx: number;
749
+ /** rendered html string. */
750
+ html: string;
751
+ }
752
+
753
+ // cursorhtmlrenderer (incremental)
754
+
755
+ /**
756
+ * incremental html renderer using the cursor over soa buffers.
757
+ *
758
+ * same caching strategy as htmlrenderer: walks root's children,
759
+ * skips closed+cached blocks, re-renders only open blocks.
760
+ * but uses cursor traversal, zero per-node allocations per render.
761
+ *
762
+ * usage:
763
+ *
764
+ * const tree = new treebuilder(128);
765
+ * const parser = new pfmparser(tree);
766
+ * const renderer = new cursorhtmlrenderer();
767
+ *
768
+ * parser.init();
769
+ * parser.feed(chunk);
770
+ * renderer.update(tree.get_buffer(), accumulated_source);
771
+ * // renderer.blocks has stable {idx, html} entries
772
+ */
773
+ export class CursorHTMLRenderer {
774
+ blocks: CursorBlockEntry[] = [];
775
+ /** full document html (available after update, whether cached or not). */
776
+ html = "";
777
+ private closed: Set<number> | null = null;
778
+ private cursor: Cursor | null = null;
779
+ private cache: boolean;
780
+
781
+ constructor(opts?: { cache?: boolean }) {
782
+ this.cache = opts?.cache ?? true;
783
+ if (this.cache) this.closed = new Set();
784
+ }
785
+
786
+ update(buf: NodeBuffer, source: string): CursorBlockEntry[] {
787
+ // reuse or create cursor
788
+ if (!this.cursor) {
789
+ this.cursor = new Cursor(buf, source);
790
+ } else {
791
+ this.cursor.reinit(buf, source);
792
+ }
793
+ const c = this.cursor;
794
+ c.reset();
795
+
796
+ // no caching, single-pass full render
797
+ if (!this.cache) {
798
+ const out: string[] = [];
799
+ _node(c, out);
800
+ this.html = out.join("");
801
+ return this.blocks;
802
+ }
803
+
804
+ // cached block-level rendering
805
+ if (!c.goto_first_child()) return this.blocks;
806
+
807
+ let block_idx = 0;
808
+ do {
809
+ if (c.kind === K_LINE_BREAK) continue;
810
+
811
+ const idx = c.index;
812
+
813
+ if (block_idx >= this.blocks.length) {
814
+ this.blocks.push({ idx, html: _render_block(c) });
815
+ if (c.closed) this.closed!.add(idx);
816
+ } else if (!this.closed!.has(idx)) {
817
+ this.blocks[block_idx].html = _render_block(c);
818
+ if (c.closed) this.closed!.add(idx);
819
+ }
820
+
821
+ block_idx++;
822
+ } while (c.goto_next_sibling());
823
+
824
+ c.goto_parent();
825
+ this.html = this.blocks.map((b) => b.html).join("");
826
+ return this.blocks;
827
+ }
828
+
829
+ /** render with source mapping. always full render (no caching). */
830
+ update_mapped(
831
+ buf: NodeBuffer,
832
+ source: string,
833
+ ): { blocks: CursorBlockEntry[]; mappings: Mapping<MappingData>[] } {
834
+ if (!this.cursor) {
835
+ this.cursor = new Cursor(buf, source);
836
+ } else {
837
+ this.cursor.reinit(buf, source);
838
+ }
839
+ const c = this.cursor;
840
+ c.reset();
841
+
842
+ const out: string[] = [];
843
+ const entries: PendingMapping[] = [];
844
+ _node(c, out, entries);
845
+ this.html = out.join("");
846
+ const mappings = _resolve_mappings(out, entries);
847
+ return { blocks: this.blocks, mappings };
848
+ }
849
+
850
+ reset(): void {
851
+ this.blocks.length = 0;
852
+ this.closed?.clear();
853
+ this.html = "";
854
+ }
855
+ }