@hraness/wordcell 0.22.1 → 0.22.3

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.
@@ -41,9 +41,15 @@ function anchorId(text: string, used: Map<string, number>): string {
41
41
  .toLocaleLowerCase("en-US")
42
42
  .replace(VOID_SLUG, "-")
43
43
  .replace(/^[-._~]+|[-._~]+$/gu, "") || "section";
44
- const seen = used.get(base) ?? 0;
44
+ let seen = used.get(base) ?? 0;
45
+ let id = seen === 0 ? base : `${base}-${seen + 1}`;
46
+ while (used.has(id)) {
47
+ seen += 1;
48
+ id = `${base}-${seen + 1}`;
49
+ }
45
50
  used.set(base, seen + 1);
46
- return seen === 0 ? base : `${base}-${seen + 1}`;
51
+ used.set(id, 1);
52
+ return id;
47
53
  }
48
54
 
49
55
  function isExternalUrl(value: string): boolean {
@@ -80,7 +86,60 @@ function wikiDisplay(raw: string): { target: string; fragment: string; label: st
80
86
  };
81
87
  }
82
88
 
83
- function renderInline(text: string, ctx: PublishRenderContext): string {
89
+ const FOOTNOTE_LIMITS = {
90
+ labelBytes: 128,
91
+ definitions: 256,
92
+ bodyBytes: 8_192,
93
+ bodyLines: 32,
94
+ references: 2_048,
95
+ } as const;
96
+
97
+ type Footnote = {
98
+ readonly body: string;
99
+ readonly authored: string;
100
+ invalid: boolean;
101
+ number?: number;
102
+ readonly references: string[];
103
+ };
104
+
105
+ type Footnotes = {
106
+ readonly byLabel: Map<string, Footnote | null>;
107
+ readonly numbered: Footnote[];
108
+ definitions: number;
109
+ references: number;
110
+ disabled: boolean;
111
+ };
112
+
113
+ function footnoteLabel(raw: string): string | undefined {
114
+ const label = raw.normalize("NFC");
115
+ if (label.length > FOOTNOTE_LIMITS.labelBytes || !/^[\p{L}\p{M}\p{N}._:-]+$/u.test(label)) return undefined;
116
+ return new TextEncoder().encode(label).byteLength <= FOOTNOTE_LIMITS.labelBytes ? label : undefined;
117
+ }
118
+
119
+ function footnoteNumber(note: Footnote, footnotes: Footnotes): number {
120
+ if (note.number === undefined) {
121
+ note.number = footnotes.numbered.length + 1;
122
+ footnotes.numbered.push(note);
123
+ }
124
+ return note.number;
125
+ }
126
+
127
+ function renderFootnoteReference(raw: string, label: string, footnotes: Footnotes): string {
128
+ const key = footnoteLabel(label);
129
+ const note = key === undefined ? undefined : footnotes.byLabel.get(key);
130
+ if (footnotes.disabled || note === undefined || note === null || note.invalid || footnotes.references >= FOOTNOTE_LIMITS.references) {
131
+ return `<span class="unresolved footnote-reference" aria-label="Unresolved footnote">${escapeHtml(raw)}</span>`;
132
+ }
133
+ const number = footnoteNumber(note, footnotes);
134
+ // Colons cannot occur in heading slugs, so authored headings cannot capture
135
+ // these targets. Raw labels never enter an HTML id or fragment.
136
+ const id = `wordcell:footnote-ref:${number}:${note.references.length + 1}`;
137
+ note.references.push(id);
138
+ footnotes.references += 1;
139
+ return `<sup><a id="${id}" href="#wordcell:footnote:${number}" role="doc-noteref" aria-label="Footnote ${number}">${number}</a></sup>`;
140
+ }
141
+
142
+ function renderInline(text: string, ctx: PublishRenderContext, footnotes?: Footnotes): string {
84
143
  let output = "";
85
144
  let cursor = 0;
86
145
  const length = text.length;
@@ -99,7 +158,7 @@ function renderInline(text: string, ctx: PublishRenderContext): string {
99
158
  if (closing !== -1) {
100
159
  const code = rest.slice(ticks.length, closing).replace(/\s+/gu, " ");
101
160
  output += `<code>${escapeHtml(code)}</code>`;
102
- cursor += ticks.length + closing + ticks.length;
161
+ cursor += closing + ticks.length;
103
162
  continue;
104
163
  }
105
164
  pushText("`");
@@ -198,6 +257,7 @@ function renderInline(text: string, ctx: PublishRenderContext): string {
198
257
  if (closing !== -1 && rest[closing + 1] === "(") {
199
258
  const destination = readDestination(rest, closing + 2);
200
259
  if (destination !== null) {
260
+ // Supported explicit links take precedence over footnote markers.
201
261
  const label = renderInline(rest.slice(1, closing), ctx);
202
262
  const target = destination.target;
203
263
  const asset = ctx.resolveAsset(target, ctx.source);
@@ -219,6 +279,14 @@ function renderInline(text: string, ctx: PublishRenderContext): string {
219
279
  continue;
220
280
  }
221
281
  }
282
+ if (footnotes !== undefined && rest.startsWith("[^")) {
283
+ const end = rest.indexOf("]", 2);
284
+ if (end !== -1) {
285
+ output += renderFootnoteReference(rest.slice(0, end + 1), rest.slice(2, end), footnotes);
286
+ cursor += end + 1;
287
+ continue;
288
+ }
289
+ }
222
290
  pushText("[");
223
291
  cursor += 1;
224
292
  continue;
@@ -249,7 +317,7 @@ function renderInline(text: string, ctx: PublishRenderContext): string {
249
317
  if (emphasis !== undefined && emphasis !== "_") {
250
318
  const closing = rest.indexOf(emphasis, emphasis.length);
251
319
  if (closing > emphasis.length) {
252
- const inner = renderInline(rest.slice(emphasis.length, closing), ctx);
320
+ const inner = renderInline(rest.slice(emphasis.length, closing), ctx, footnotes);
253
321
  const tag = emphasis === "**" || emphasis === "__"
254
322
  ? "strong"
255
323
  : emphasis === "~~"
@@ -265,7 +333,7 @@ function renderInline(text: string, ctx: PublishRenderContext): string {
265
333
  if (emphasis === "_") {
266
334
  const closing = rest.indexOf("_", 1);
267
335
  if (closing > 1) {
268
- output += `<em>${renderInline(rest.slice(1, closing), ctx)}</em>`;
336
+ output += `<em>${renderInline(rest.slice(1, closing), ctx, footnotes)}</em>`;
269
337
  cursor += closing + 1;
270
338
  continue;
271
339
  }
@@ -398,49 +466,145 @@ function tableCells(line: string): string[] {
398
466
  return cells.map((cell) => cell.trim());
399
467
  }
400
468
 
401
- /** Render authored Markdown to a sanitized HTML fragment. */
402
- export function renderMarkdownToHtml(content: string, ctx: PublishRenderContext): string {
403
- const lines = content.split("\n");
404
- // Strip frontmatter.
405
- let start = 0;
406
- if (lines[0]?.trim() === "---") {
407
- for (let index = 1; index < lines.length; index += 1) {
408
- if (lines[index]?.trim() === "---" || lines[index]?.trim() === "...") {
409
- start = index + 1;
410
- break;
469
+ type ListPart =
470
+ | { readonly type: "open" | "close"; readonly ordered: boolean }
471
+ | { readonly type: "item"; readonly text: string; readonly checked?: boolean }
472
+ | { readonly type: "continuation"; readonly text: string };
473
+
474
+ type MarkdownBlock =
475
+ | { readonly type: "paragraph"; readonly text: string }
476
+ | { readonly type: "heading"; readonly level: number; readonly text: string }
477
+ | { readonly type: "code"; readonly language: string; readonly text: string }
478
+ | { readonly type: "break" }
479
+ | { readonly type: "quote"; readonly blocks: readonly MarkdownBlock[] }
480
+ | { readonly type: "table"; readonly header: readonly string[]; readonly rows: readonly string[][] }
481
+ | { readonly type: "list"; readonly ordered: boolean; readonly parts: readonly ListPart[] }
482
+ | { readonly type: "literal"; readonly text: string }
483
+ | { readonly type: "footnote"; readonly note: Footnote };
484
+
485
+ type Comments = { closing?: "-->" | "%%"; code?: string };
486
+
487
+ /** Strip comments only in prose; code blocks never pass through this scanner. */
488
+ function withoutComments(line: string, comments: Comments, continuesCode?: (ticks: string) => boolean): string {
489
+ let text = "";
490
+ let cursor = 0;
491
+ while (cursor < line.length) {
492
+ if (comments.code !== undefined) {
493
+ const end = line.indexOf(comments.code, cursor);
494
+ if (end === -1) return text + line.slice(cursor);
495
+ const next = end + comments.code.length;
496
+ text += line.slice(cursor, next);
497
+ cursor = next;
498
+ delete comments.code;
499
+ continue;
500
+ }
501
+ if (comments.closing !== undefined) {
502
+ const end = line.indexOf(comments.closing, cursor);
503
+ if (end === -1) return text;
504
+ cursor = end + comments.closing.length;
505
+ delete comments.closing;
506
+ continue;
507
+ }
508
+ const rest = line.slice(cursor);
509
+ if (rest[0] === "\\" && rest.length > 1) {
510
+ text += rest.slice(0, 2);
511
+ cursor += 2;
512
+ continue;
513
+ }
514
+ if (rest[0] === "`") {
515
+ const ticks = /^`+/u.exec(rest)?.[0] ?? "`";
516
+ const closing = rest.indexOf(ticks, ticks.length);
517
+ if (closing !== -1) {
518
+ const end = closing + ticks.length;
519
+ text += rest.slice(0, end);
520
+ cursor += end;
521
+ continue;
522
+ }
523
+ if (continuesCode?.(ticks) === true) {
524
+ comments.code = ticks;
525
+ return text + rest;
411
526
  }
412
527
  }
528
+ if (rest.startsWith("<!--") || rest.startsWith("%%")) {
529
+ comments.closing = rest.startsWith("<!--") ? "-->" : "%%";
530
+ cursor += comments.closing === "-->" ? 4 : 2;
531
+ continue;
532
+ }
533
+ text += rest[0] ?? "";
534
+ cursor += 1;
535
+ }
536
+ return text;
537
+ }
538
+
539
+ function paragraphBoundary(line: string, next: string): boolean {
540
+ return line.trim() === "" || /^(?: {4}|\t|#{1,6}\s|\s{0,3}>|\s{0,3}(?:`{3,}|~{3,}))/u.test(line)
541
+ || listMarker(line) !== undefined || (line.includes("|") && isTableDivider(next))
542
+ || /^\s{0,3}(?:(?:\*\s*){3,}|(?:-\s*){3,}|(?:_\s*){3,})$/u.test(line);
543
+ }
544
+
545
+ function hasContinuedInlineCode(lines: readonly string[], start: number, ticks: string): boolean {
546
+ for (let index = start; index < lines.length; index += 1) {
547
+ const line = lines[index] ?? "";
548
+ if (paragraphBoundary(line, lines[index + 1] ?? "")) return false;
549
+ if (line.includes(ticks)) return true;
413
550
  }
551
+ return false;
552
+ }
414
553
 
415
- const anchors = new Map<string, number>();
416
- const html: string[] = [];
417
- let index = start;
418
- let inComment = false;
554
+ function admitFootnote(rawLabel: string, body: readonly string[], authored: readonly string[], footnotes: Footnotes): Footnote {
555
+ const text = body.join("\n");
556
+ const label = footnoteLabel(rawLabel);
557
+ const note: Footnote = {
558
+ body: text,
559
+ authored: authored.join("\n"),
560
+ invalid: label === undefined || body.length > FOOTNOTE_LIMITS.bodyLines || text.length > FOOTNOTE_LIMITS.bodyBytes
561
+ || new TextEncoder().encode(text).byteLength > FOOTNOTE_LIMITS.bodyBytes || text.trim() === "",
562
+ references: [],
563
+ };
564
+ footnotes.definitions += 1;
565
+ if (footnotes.definitions > FOOTNOTE_LIMITS.definitions) {
566
+ footnotes.disabled = true;
567
+ footnotes.byLabel.clear();
568
+ }
569
+ if (!footnotes.disabled && label !== undefined) {
570
+ if (footnotes.byLabel.has(label)) {
571
+ const prior = footnotes.byLabel.get(label);
572
+ if (prior !== undefined && prior !== null) prior.invalid = true;
573
+ note.invalid = true;
574
+ footnotes.byLabel.set(label, null);
575
+ } else {
576
+ footnotes.byLabel.set(label, note.invalid ? null : note);
577
+ }
578
+ }
579
+ return note;
580
+ }
419
581
 
582
+ /** One block scan owns both rendering precedence and definition admission. */
583
+ function parseMarkdownBlocks(content: string, footnotes: Footnotes, topLevel: boolean): MarkdownBlock[] {
584
+ const lines = content.split("\n");
585
+ let index = 0;
586
+ if (topLevel && lines[0]?.trim() === "---") {
587
+ for (let cursor = 1; cursor < lines.length; cursor += 1) {
588
+ if (lines[cursor]?.trim() === "---" || lines[cursor]?.trim() === "...") {
589
+ index = cursor + 1;
590
+ break;
591
+ }
592
+ }
593
+ }
594
+ const blocks: MarkdownBlock[] = [];
595
+ const comments: Comments = {};
420
596
  const paragraph: string[] = [];
421
597
  const flushParagraph = (): void => {
422
598
  if (paragraph.length === 0) return;
423
- html.push(`<p>${renderInline(paragraph.join("\n").replace(/\n/gu, " "), ctx)}</p>`);
599
+ blocks.push({ type: "paragraph", text: paragraph.join(" ") });
424
600
  paragraph.length = 0;
425
601
  };
426
602
 
427
603
  while (index < lines.length) {
428
- const line = lines[index] ?? "";
429
-
430
- // HTML comments and Obsidian %% comments are stripped entirely.
431
- if (inComment) {
432
- const close = line.indexOf("-->");
433
- index += 1;
434
- if (close !== -1) inComment = false;
435
- continue;
436
- }
437
- if (line.trim().startsWith("%%") && line.trim().endsWith("%%") && line.trim().length > 3) {
438
- index += 1;
439
- continue;
440
- }
441
-
442
- // Fenced code.
443
- const fence = /^\s{0,3}(`{3,}|~{3,})([^`]*)$/u.exec(line);
604
+ const raw = lines[index] ?? "";
605
+ // Code has precedence over prose comments and footnote definitions.
606
+ const inCode = comments.code !== undefined;
607
+ const fence = comments.closing === undefined && !inCode ? /^\s{0,3}(`{3,}|~{3,})([^`]*)$/u.exec(raw) : null;
444
608
  if (fence !== null) {
445
609
  flushParagraph();
446
610
  const marker = fence[1] ?? "```";
@@ -450,151 +614,210 @@ export function renderMarkdownToHtml(content: string, ctx: PublishRenderContext)
450
614
  while (index < lines.length) {
451
615
  const candidate = lines[index] ?? "";
452
616
  const close = /^\s{0,3}(`{3,}|~{3,})\s*$/u.exec(candidate);
453
- if (close !== null && (close[1] ?? "")[0] === marker[0] && (close[1] ?? "").length >= marker.length) {
454
- break;
455
- }
617
+ if (close !== null && (close[1] ?? "")[0] === marker[0] && (close[1] ?? "").length >= marker.length) break;
456
618
  body.push(candidate);
457
619
  index += 1;
458
620
  }
459
621
  index += 1;
460
- const className = language === "" ? "" : ` class="language-${escapeAttribute(language)}"`;
461
- html.push(`<pre><code${className}>${escapeHtml(body.join("\n"))}</code></pre>`);
622
+ blocks.push({ type: "code", language, text: body.join("\n") });
623
+ continue;
624
+ }
625
+ if (comments.closing === undefined && !inCode && /^(?: {4}|\t)/u.test(raw)) {
626
+ flushParagraph();
627
+ const body: string[] = [];
628
+ while (index < lines.length && /^(?: {4}|\t| *$)/u.test(lines[index] ?? "")) {
629
+ body.push((lines[index] ?? "").replace(/^(?: {4}|\t)/u, ""));
630
+ index += 1;
631
+ }
632
+ blocks.push({ type: "code", language: "", text: body.join("\n").replace(/\n+$/u, "") });
633
+ continue;
634
+ }
635
+ const rawDefinition = comments.closing === undefined && !inCode ? /^ {0,3}\[\^([^\]\n]*)\]:/u.exec(raw) : null;
636
+ if (rawDefinition !== null) {
637
+ flushParagraph();
638
+ const authored = [raw];
639
+ index += 1;
640
+ while (index < lines.length) {
641
+ const next = lines[index] ?? "";
642
+ if (/^(?: {4}|\t)/u.test(next) || (next.trim() === "" && /^(?: {4}|\t)/u.test(lines[index + 1] ?? ""))) {
643
+ authored.push(next);
644
+ index += 1;
645
+ } else {
646
+ break;
647
+ }
648
+ }
649
+ // Scan the full inline body together so comments inside a code span
650
+ // crossing continuation lines remain code, rather than disappearing.
651
+ const clean = withoutComments(authored.join("\n"), comments).split("\n");
652
+ const definition = /^ {0,3}\[\^([^\]\n]*)\]:[ \t]*(.*)$/u.exec(clean[0] ?? "");
653
+ if (!topLevel || definition === null) {
654
+ blocks.push({ type: "literal", text: clean.join("\n") });
655
+ } else {
656
+ const body = [definition[2] ?? "", ...clean.slice(1).map((line) => line.replace(/^(?: {4}|\t)/u, ""))];
657
+ blocks.push({ type: "footnote", note: admitFootnote(rawDefinition[1] ?? "", body, clean, footnotes) });
658
+ }
659
+ continue;
660
+ }
661
+ // Quoted blocks own their comment/code scope after removing the marker.
662
+ const line = comments.closing === undefined && !inCode && /^\s{0,3}>/u.test(raw)
663
+ ? raw
664
+ : withoutComments(raw, comments, paragraphBoundary(raw, lines[index + 1] ?? "")
665
+ ? undefined
666
+ : (ticks) => hasContinuedInlineCode(lines, index + 1, ticks));
667
+ if (inCode) {
668
+ paragraph.push(line);
669
+ index += 1;
462
670
  continue;
463
671
  }
464
-
465
- // Blank line.
466
672
  if (line.trim() === "") {
467
673
  flushParagraph();
468
674
  index += 1;
469
675
  continue;
470
676
  }
471
-
472
- // ATX heading.
473
677
  const heading = /^(#{1,6})\s+(.*)$/u.exec(line);
474
678
  if (heading !== null) {
475
679
  flushParagraph();
476
- const level = (heading[1] ?? "#").length;
477
- const body = renderInline((heading[2] ?? "").replace(/\s+#+$/u, ""), ctx);
478
- const id = anchorId(stripMarkup(body), anchors);
479
- html.push(`<h${level} id="${escapeAttribute(id)}">${body}</h${level}>`);
680
+ blocks.push({ type: "heading", level: (heading[1] ?? "#").length, text: (heading[2] ?? "").replace(/\s+#+$/u, "") });
480
681
  index += 1;
481
682
  continue;
482
683
  }
483
-
484
- // Thematic break.
485
684
  if (/^\s{0,3}(?:\*\s*){3,}$/u.test(line) || /^\s{0,3}(?:-\s*){3,}$/u.test(line) || /^\s{0,3}(?:_\s*){3,}$/u.test(line)) {
486
685
  flushParagraph();
487
- html.push("<hr>");
686
+ blocks.push({ type: "break" });
488
687
  index += 1;
489
688
  continue;
490
689
  }
491
-
492
- // Blockquote (one level per pass; nesting via > > accumulation).
493
690
  if (/^\s{0,3}>/u.test(line)) {
494
691
  flushParagraph();
495
- const quote: string[] = [];
692
+ const quote = [line.replace(/^\s{0,3}>\s?/u, "")];
693
+ index += 1;
496
694
  while (index < lines.length && /^\s{0,3}>/u.test(lines[index] ?? "")) {
497
695
  quote.push((lines[index] ?? "").replace(/^\s{0,3}>\s?/u, ""));
498
696
  index += 1;
499
697
  }
500
- html.push(`<blockquote>${renderMarkdownToHtml(quote.join("\n"), ctx)}</blockquote>`);
698
+ blocks.push({ type: "quote", blocks: parseMarkdownBlocks(quote.join("\n"), footnotes, false) });
501
699
  continue;
502
700
  }
503
-
504
- // Tables: header row, divider, body rows.
505
701
  if (line.includes("|") && index + 1 < lines.length && isTableDivider(lines[index + 1] ?? "")) {
506
702
  flushParagraph();
507
703
  const header = tableCells(line);
704
+ const rows: string[][] = [];
508
705
  index += 2;
509
- const rows: string[] = [];
510
706
  while (index < lines.length && (lines[index] ?? "").includes("|") && (lines[index] ?? "").trim() !== "") {
511
- rows.push(lines[index] ?? "");
707
+ const row = withoutComments(lines[index] ?? "", comments);
708
+ if (row.trim() !== "") rows.push(tableCells(row));
512
709
  index += 1;
513
710
  }
514
- const head = header.map((cell) => `<th>${renderInline(cell, ctx)}</th>`).join("");
515
- const bodyRows = rows.map((row) =>
516
- `<tr>${tableCells(row).map((cell) => `<td>${renderInline(cell, ctx)}</td>`).join("")}</tr>`).join("");
517
- html.push(`<table><thead><tr>${head}</tr></thead><tbody>${bodyRows}</tbody></table>`);
711
+ blocks.push({ type: "table", header, rows });
518
712
  continue;
519
713
  }
520
-
521
- // Lists: flat scan with indent-based nesting.
522
714
  const marker = listMarker(line);
523
715
  if (marker !== undefined) {
524
716
  flushParagraph();
525
- const items: string[] = [];
526
- let ordered = marker.ordered;
717
+ const parts: ListPart[] = [];
527
718
  const baseIndent = marker.indent;
528
719
  const stack: { readonly indent: number; readonly ordered: boolean }[] = [];
720
+ let currentLine = line;
529
721
  while (index < lines.length) {
530
- const current = listMarker(lines[index] ?? "");
531
- const raw = lines[index] ?? "";
722
+ const current = listMarker(currentLine);
532
723
  if (current === undefined) {
533
- if (raw.trim() === "") {
724
+ if (currentLine.trim() === "") {
534
725
  index += 1;
535
726
  break;
536
727
  }
537
- const continuationIndent = raw.length - raw.trimStart().length;
538
- if (items.length > 0 && continuationIndent > baseIndent) {
539
- items.push(`\n${renderInline(raw.trim(), ctx)}`);
728
+ const continuationIndent = currentLine.length - currentLine.trimStart().length;
729
+ if (parts.length > 0 && continuationIndent > baseIndent) {
730
+ parts.push({ type: "continuation", text: currentLine.trim() });
540
731
  index += 1;
541
- continue;
732
+ } else {
733
+ break;
542
734
  }
543
- break;
544
- }
545
- const body = raw.slice(raw.search(/\S/u));
546
- const itemBody = body.replace(/^(?:[-+*]|\d{1,9}[.)])\s+/u, "");
547
- const task = /^\[([ xX])\]\s+/u.exec(itemBody);
548
- const content = task === null ? itemBody : itemBody.slice((task[0] ?? "").length);
549
- const checkbox = task === null
550
- ? ""
551
- : `<input type="checkbox" disabled${(task[1] ?? " ").toLowerCase() === "x" ? " checked" : ""}> `;
552
- const top = stack[stack.length - 1];
553
- if (current.indent > (top?.indent ?? baseIndent) && stack.length < 8) {
554
- stack.push({ indent: current.indent, ordered: current.ordered });
555
- items.push(`<${current.ordered ? "ol" : "ul"}>`);
556
- }
557
- while (stack.length > 0 && current.indent < (stack[stack.length - 1]?.indent ?? baseIndent)) {
558
- const popped = stack.pop();
559
- items.push(`</${popped?.ordered === true ? "ol" : "ul"}>`);
735
+ } else {
736
+ const body = currentLine.slice(currentLine.search(/\S/u));
737
+ const itemBody = body.replace(/^(?:[-+*]|\d{1,9}[.)])\s+/u, "");
738
+ const task = /^\[([ xX])\]\s+/u.exec(itemBody);
739
+ const text = task === null ? itemBody : itemBody.slice((task[0] ?? "").length);
740
+ if (current.indent > (stack[stack.length - 1]?.indent ?? baseIndent) && stack.length < 8) {
741
+ stack.push({ indent: current.indent, ordered: current.ordered });
742
+ parts.push({ type: "open", ordered: current.ordered });
743
+ }
744
+ while (stack.length > 0 && current.indent < (stack[stack.length - 1]?.indent ?? baseIndent)) {
745
+ parts.push({ type: "close", ordered: stack.pop()?.ordered === true });
746
+ }
747
+ parts.push({ type: "item", text, ...(task === null ? {} : { checked: (task[1] ?? " ").toLowerCase() === "x" }) });
748
+ index += 1;
560
749
  }
561
- items.push(`<li>${checkbox}${renderInline(content, ctx)}</li>`);
562
- index += 1;
750
+ // Do not consume comments on a line that belongs to the next block.
751
+ const next = lines[index] ?? "";
752
+ if (listMarker(next) === undefined && next.trim() !== "" && next.length - next.trimStart().length <= baseIndent) break;
753
+ currentLine = withoutComments(next, comments);
563
754
  }
564
- while (stack.length > 0) {
565
- const popped = stack.pop();
566
- items.push(`</${popped?.ordered === true ? "ol" : "ul"}>`);
567
- }
568
- html.push(`<${ordered ? "ol" : "ul"}>${items.join("")}</${ordered ? "ol" : "ul"}>`);
569
- continue;
570
- }
571
-
572
- // HTML comment open.
573
- const commentStart = line.indexOf("<!--");
574
- if (commentStart !== -1) {
575
- const close = line.indexOf("-->", commentStart + 4);
576
- if (close === -1) inComment = true;
577
- index += 1;
755
+ while (stack.length > 0) parts.push({ type: "close", ordered: stack.pop()?.ordered === true });
756
+ blocks.push({ type: "list", ordered: marker.ordered, parts });
578
757
  continue;
579
758
  }
759
+ paragraph.push(line);
760
+ index += 1;
761
+ }
762
+ flushParagraph();
763
+ return blocks;
764
+ }
580
765
 
581
- // Indented code.
582
- if (/^(?: {4}|\t)/u.test(line)) {
583
- flushParagraph();
584
- const body: string[] = [];
585
- while (index < lines.length && /^(?: {4}|\t| *$)/u.test(lines[index] ?? "")) {
586
- body.push((lines[index] ?? "").replace(/^(?: {4}|\t)/u, ""));
587
- index += 1;
766
+ function renderBlocks(blocks: readonly MarkdownBlock[], ctx: PublishRenderContext, footnotes: Footnotes, anchors: Map<string, number>): string {
767
+ return blocks.map((block): string => {
768
+ switch (block.type) {
769
+ case "paragraph": return `<p>${renderInline(block.text, ctx, footnotes)}</p>`;
770
+ case "literal": return `<p>${escapeHtml(block.text).replaceAll("\n", "<br>")}</p>`;
771
+ case "heading": {
772
+ const body = renderInline(block.text, ctx, footnotes);
773
+ return `<h${block.level} id="${escapeAttribute(anchorId(stripMarkup(body), anchors))}">${body}</h${block.level}>`;
588
774
  }
589
- html.push(`<pre><code>${escapeHtml(body.join("\n").replace(/\n+$/u, ""))}</code></pre>`);
590
- continue;
775
+ case "code": return `<pre><code${block.language === "" ? "" : ` class="language-${escapeAttribute(block.language)}"`}>${escapeHtml(block.text)}</code></pre>`;
776
+ case "break": return "<hr>";
777
+ case "quote": return `<blockquote>${renderBlocks(block.blocks, ctx, footnotes, anchors)}</blockquote>`;
778
+ case "table": {
779
+ const header = block.header.map((cell) => `<th>${renderInline(cell, ctx, footnotes)}</th>`).join("");
780
+ const rows = block.rows.map((row) => `<tr>${row.map((cell) => `<td>${renderInline(cell, ctx, footnotes)}</td>`).join("")}</tr>`).join("");
781
+ return `<table><thead><tr>${header}</tr></thead><tbody>${rows}</tbody></table>`;
782
+ }
783
+ case "list": {
784
+ const parts = block.parts.map((part) => {
785
+ switch (part.type) {
786
+ case "open": return `<${part.ordered ? "ol" : "ul"}>`;
787
+ case "close": return `</${part.ordered ? "ol" : "ul"}>`;
788
+ case "continuation": return `\n${renderInline(part.text, ctx, footnotes)}`;
789
+ case "item": return `<li>${part.checked === undefined ? "" : `<input type="checkbox" disabled${part.checked ? " checked" : ""}> `}${renderInline(part.text, ctx, footnotes)}</li>`;
790
+ }
791
+ }).join("");
792
+ return `<${block.ordered ? "ol" : "ul"}>${parts}</${block.ordered ? "ol" : "ul"}>`;
793
+ }
794
+ case "footnote": return footnotes.disabled || block.note.invalid
795
+ ? `<p class="unresolved footnote-definition">${escapeHtml(block.note.authored).replaceAll("\n", "<br>")}</p>`
796
+ : "";
591
797
  }
798
+ }).filter((html) => html !== "").join("\n");
799
+ }
592
800
 
593
- paragraph.push(line);
594
- index += 1;
801
+ /** Render authored Markdown to a sanitized HTML fragment. */
802
+ export function renderMarkdownToHtml(content: string, ctx: PublishRenderContext): string {
803
+ const footnotes: Footnotes = { byLabel: new Map(), numbered: [], definitions: 0, references: 0, disabled: false };
804
+ const blocks = parseMarkdownBlocks(content, footnotes, true);
805
+ const body = renderBlocks(blocks, ctx, footnotes, new Map());
806
+ if (footnotes.disabled) return body;
807
+ // Keep unreferenced authored definitions visible after referenced notes.
808
+ for (const note of footnotes.byLabel.values()) {
809
+ if (note !== null && !note.invalid) footnoteNumber(note, footnotes);
595
810
  }
596
- flushParagraph();
597
- return html.join("\n");
811
+ if (footnotes.numbered.length === 0) return body;
812
+ const notes = footnotes.numbered.map((note) => {
813
+ const number = note.number;
814
+ const backlinks = note.references.map((id, index) => `<a href="#${id}" role="doc-backlink" aria-label="Back to reference ${index + 1} for footnote ${number}">↩ ${index + 1}</a>`).join(" ");
815
+ // Definitions are inline prose. Footnote syntax inside them stays literal,
816
+ // so cycles cannot expand and every backlink corresponds to authored prose.
817
+ const text = renderInline(note.body.replaceAll("\n", " "), ctx);
818
+ return `<li id="wordcell:footnote:${number}" tabindex="-1">${text}${backlinks === "" ? "" : ` ${backlinks}`}</li>`;
819
+ }).join("\n");
820
+ return `${body}${body === "" ? "" : "\n"}<section class="footnotes" aria-label="Footnotes"><ol>\n${notes}\n</ol></section>`;
598
821
  }
599
822
 
600
823
  export function stripMarkup(html: string): string {
@@ -2,6 +2,6 @@
2
2
  export const supportProfile = {
3
3
  id: "kb",
4
4
  name: "Wordcell",
5
- valueProposition: "Support ongoing development of inspectable Markdown memory for coding agents.",
5
+ valueProposition: "Support ongoing development of inspectable Markdown memory.",
6
6
  updates: false,
7
7
  } as const;