@supersolutions/super-chat-ui-core 0.5.0 → 0.6.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/README.md CHANGED
@@ -9,7 +9,7 @@ binding does not have to reimplement them:
9
9
  - `export.ts` — `threadToMarkdown`, `downloadThread`.
10
10
 
11
11
  No React, no DOM framework. Part of the [superchat](../../README.md) monorepo. The React
12
- components live in [`@supersolutions/super-chat-ui`](../ui/README.md); the shared stylesheet still
12
+ components live in [`@supersolutions/super-chat-ui`](../bindings/react-ui/README.md); the shared stylesheet still
13
13
  ships with that package for now.
14
14
 
15
15
  ## Install
package/dist/index.d.ts CHANGED
@@ -68,6 +68,11 @@ type AnchoredMarkdown = {
68
68
  /** Index-aligned with the `data-sc-block` attribute on the rendered HTML. */
69
69
  blocks: MarkdownBlock[];
70
70
  };
71
+ /** A heading's hashes and text, by one linear pass; null when the line is not a heading. */
72
+ declare function atxHeading(line: string): {
73
+ hashes: number;
74
+ text: string;
75
+ } | null;
71
76
  /** Render for the transcript: no anchors, because chat prose is not addressed. */
72
77
  declare function renderMarkdown(src: string, options?: MarkdownOptions): string;
73
78
  /** What renderMarkdownStream keeps between calls. Start from newMarkdownStream(). */
@@ -137,4 +142,4 @@ declare function tableToTsv(header: readonly string[], rows: readonly (readonly
137
142
  /** A GitHub-flavoured Markdown table. A pipe in a cell is escaped; a line break becomes a space. */
138
143
  declare function tableToMarkdown(header: readonly string[], rows: readonly (readonly string[])[], align?: readonly ("left" | "center" | "right" | null)[]): string;
139
144
 
140
- export { type AnchoredMarkdown, type FormatOptions, HIGHLIGHT_LANGUAGES, type MarkdownOptions, type MarkdownStream, STABLE_FORMAT, deltaTone, downloadThread, formatDelta, formatValue, highlightCode, newMarkdownStream, renderMarkdown, renderMarkdownBlocks, renderMarkdownStream, renderMarkdownWithAnchors, safeHref, tableToMarkdown, tableToTsv, threadToMarkdown, toneClass };
145
+ export { type AnchoredMarkdown, type FormatOptions, HIGHLIGHT_LANGUAGES, type MarkdownOptions, type MarkdownStream, STABLE_FORMAT, atxHeading, deltaTone, downloadThread, formatDelta, formatValue, highlightCode, newMarkdownStream, renderMarkdown, renderMarkdownBlocks, renderMarkdownStream, renderMarkdownWithAnchors, safeHref, tableToMarkdown, tableToTsv, threadToMarkdown, toneClass };
package/dist/index.js CHANGED
@@ -18,32 +18,49 @@ function numbersFor(locale) {
18
18
  }
19
19
  return formats;
20
20
  }
21
+ function numeric(value) {
22
+ if (typeof value === "number") return value;
23
+ if (typeof value === "bigint") return Number(value);
24
+ if (typeof value === "string" && value.trim() !== "") return Number(value);
25
+ return Number.NaN;
26
+ }
27
+ function plain(value) {
28
+ if (typeof value === "string" && value.trim() === "") return "\u2014";
29
+ if (typeof value === "object") {
30
+ try {
31
+ return JSON.stringify(value) ?? String(value);
32
+ } catch {
33
+ return String(value);
34
+ }
35
+ }
36
+ return String(value);
37
+ }
21
38
  function formatValue(value, format = "text", options = {}) {
22
39
  if (value == null) return "\u2014";
23
40
  const { locale, timeZone } = options;
24
41
  const numbers = numbersFor(locale);
25
42
  switch (format) {
26
43
  case "number": {
27
- const n = Number(value);
28
- if (!Number.isFinite(n)) return String(value);
44
+ const n = numeric(value);
45
+ if (!Number.isFinite(n)) return plain(value);
29
46
  return Math.abs(n) >= 1e5 ? numbers.compact.format(n) : numbers.plain.format(n);
30
47
  }
31
48
  case "currency": {
32
- const n = Number(value);
33
- if (!Number.isFinite(n)) return String(value);
49
+ const n = numeric(value);
50
+ if (!Number.isFinite(n)) return plain(value);
34
51
  const abs = Math.abs(n);
35
52
  const digits = abs >= 1 ? 2 : abs >= 0.01 ? 4 : 8;
36
53
  const min = abs >= 1e3 && Number.isInteger(n) ? 0 : 2;
37
54
  return `$${n.toLocaleString(locale, { minimumFractionDigits: min, maximumFractionDigits: Math.max(min, digits) })}`;
38
55
  }
39
56
  case "percent": {
40
- const n = Number(value);
41
- if (!Number.isFinite(n)) return String(value);
57
+ const n = numeric(value);
58
+ if (!Number.isFinite(n)) return plain(value);
42
59
  return `${(Math.abs(n) < 1 ? numbers.pctNarrow : numbers.pctWide).format(n)}%`;
43
60
  }
44
61
  case "bytes": {
45
- const n = Number(value);
46
- if (!Number.isFinite(n)) return String(value);
62
+ const n = numeric(value);
63
+ if (!Number.isFinite(n)) return plain(value);
47
64
  const units = ["B", "KB", "MB", "GB", "TB"];
48
65
  let i = 0;
49
66
  let v = n;
@@ -54,22 +71,22 @@ function formatValue(value, format = "text", options = {}) {
54
71
  return `${v.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
55
72
  }
56
73
  case "duration": {
57
- const ms = Number(value);
58
- if (!Number.isFinite(ms)) return String(value);
74
+ const ms = numeric(value);
75
+ if (!Number.isFinite(ms)) return plain(value);
59
76
  if (ms < 1e3) return `${Math.round(ms)}ms`;
60
77
  if (ms < 6e4) return `${(ms / 1e3).toFixed(1)}s`;
61
78
  if (ms < 36e5) return `${Math.floor(ms / 6e4)}m ${Math.round(ms % 6e4 / 1e3)}s`;
62
79
  return `${(ms / 36e5).toFixed(1)}h`;
63
80
  }
64
81
  case "datetime": {
65
- const d = typeof value === "number" ? new Date(value) : new Date(String(value));
66
- if (Number.isNaN(d.getTime())) return String(value);
82
+ const d = typeof value === "number" ? new Date(value) : typeof value === "string" ? new Date(value) : new Date(Number.NaN);
83
+ if (Number.isNaN(d.getTime())) return plain(value);
67
84
  return d.toLocaleString(locale, timeZone ? { timeZone, timeZoneName: "short" } : void 0);
68
85
  }
69
86
  case "code":
70
87
  case "text":
71
88
  default:
72
- return typeof value === "object" ? JSON.stringify(value) : String(value);
89
+ return typeof value === "object" ? plain(value) : String(value);
73
90
  }
74
91
  }
75
92
  function formatDelta(delta, format = "number", options = {}) {
@@ -86,31 +103,56 @@ function safeHref(url) {
86
103
  }
87
104
 
88
105
  // src/export.ts
106
+ function fence(text) {
107
+ let longest = 0;
108
+ for (const run2 of text.match(/`+/g) ?? []) longest = Math.max(longest, run2.length);
109
+ return "`".repeat(Math.max(3, longest + 1));
110
+ }
111
+ function fenced(info, text) {
112
+ const f = fence(text);
113
+ return `${f}${info}
114
+ ${text}
115
+ ${f}`;
116
+ }
117
+ function cell(value) {
118
+ let text;
119
+ if (value === null || value === void 0) text = "";
120
+ else if (typeof value === "object") {
121
+ try {
122
+ text = JSON.stringify(value);
123
+ } catch {
124
+ text = String(value);
125
+ }
126
+ } else text = String(value);
127
+ return text.replace(/\|/g, "\\|").replace(/\r\n|\r|\n/g, "<br>");
128
+ }
89
129
  function cardToMarkdown(spec) {
90
130
  const kind = String(spec.kind ?? "unknown");
91
131
  const title = spec.title ? `**${spec.title}**
92
132
 
93
133
  ` : "";
94
134
  if (kind === "table" && Array.isArray(spec.columns) && Array.isArray(spec.rows)) {
95
- const cols = spec.columns;
96
- const rows = spec.rows;
97
- const head = `| ${cols.map((c) => c.label).join(" | ")} |`;
135
+ const cols = spec.columns.filter((c) => typeof c === "object" && c !== null);
136
+ const rows = spec.rows.filter((r) => typeof r === "object" && r !== null);
137
+ const head = `| ${cols.map((c) => cell(c.label)).join(" | ")} |`;
98
138
  const rule = `| ${cols.map(() => "---").join(" | ")} |`;
99
- const body = rows.map((r) => `| ${cols.map((c) => String(r[c.key] ?? "")).join(" | ")} |`).join("\n");
139
+ const body = rows.map((r) => `| ${cols.map((c) => cell(r[c.key])).join(" | ")} |`).join("\n");
100
140
  return `${title}${head}
101
141
  ${rule}
102
142
  ${body}`;
103
143
  }
104
144
  if (kind === "markdown" && typeof spec.body === "string") return `${title}${spec.body}`;
105
145
  if (kind === "code" && typeof spec.code === "string") {
106
- return `${title}\`\`\`${spec.language ?? ""}
107
- ${spec.code}
108
- \`\`\``;
146
+ return `${title}${fenced(typeof spec.language === "string" ? spec.language : "", spec.code)}`;
109
147
  }
110
148
  if (kind === "callout" && typeof spec.body === "string") return `> ${title}${spec.body}`;
111
- return `${title}\`\`\`json
112
- ${JSON.stringify(spec, null, 2)}
113
- \`\`\``;
149
+ let json;
150
+ try {
151
+ json = JSON.stringify(spec, null, 2) ?? "null";
152
+ } catch {
153
+ json = "(data that cannot be shown as JSON)";
154
+ }
155
+ return `${title}${fenced("json", json)}`;
114
156
  }
115
157
  function partToMarkdown(part) {
116
158
  switch (part.type) {
@@ -122,8 +164,15 @@ function partToMarkdown(part) {
122
164
  ${part.text}
123
165
 
124
166
  </details>`;
125
- case "tool-call":
126
- return `- \`${part.name}(${JSON.stringify(part.input ?? {})})\``;
167
+ case "tool-call": {
168
+ let args;
169
+ try {
170
+ args = JSON.stringify(part.input ?? {}) ?? "{}";
171
+ } catch {
172
+ args = "\u2026";
173
+ }
174
+ return `- \`${part.name}(${args})\``;
175
+ }
127
176
  case "tool-result":
128
177
  return part.failure ? `- \`${part.name}\` failed: ${part.failure}` : null;
129
178
  case "image":
@@ -131,7 +180,12 @@ ${part.text}
131
180
  case "file":
132
181
  return `_(file: ${part.filename ?? "attachment"})_`;
133
182
  case "artifact":
134
- return part.kind.startsWith("card:") ? cardToMarkdown(part.data.spec ?? part.data) : null;
183
+ if (!part.kind.startsWith("card:")) return null;
184
+ {
185
+ const data = part.data;
186
+ const spec = data?.spec ?? data;
187
+ return typeof spec === "object" && spec !== null && !Array.isArray(spec) ? cardToMarkdown(spec) : null;
188
+ }
135
189
  default:
136
190
  return null;
137
191
  }
@@ -143,7 +197,8 @@ function threadToMarkdown(messages, title) {
143
197
  const body = m.parts.map(partToMarkdown).filter(Boolean).join("\n\n");
144
198
  if (!body) continue;
145
199
  const who = m.role === "user" ? "You" : m.role === "tool" ? "Tools" : "Assistant";
146
- const when = m.createdAt ? ` \xB7 ${new Date(m.createdAt).toISOString().slice(0, 16).replace("T", " ")}` : "";
200
+ const at = typeof m.createdAt === "number" ? new Date(m.createdAt) : void 0;
201
+ const when = at && Number.isFinite(at.getTime()) ? ` \xB7 ${at.toISOString().slice(0, 16).replace("T", " ")}` : "";
147
202
  out.push(`## ${who}${when}`, "", body, "");
148
203
  }
149
204
  return out.join("\n").trimEnd() + "\n";
@@ -323,7 +378,7 @@ var HIGHLIGHT_LANGUAGES = /* @__PURE__ */ (() => [...Object.keys(ALIASES), "diff
323
378
  function highlightCode(code, lang) {
324
379
  const name = lang.toLowerCase();
325
380
  if (name === "diff" || name === "patch") return diff(code);
326
- const key = ALIASES[name];
381
+ const key = Object.hasOwn(ALIASES, name) ? ALIASES[name] : void 0;
327
382
  const lex = key ? lexerFor(key) : null;
328
383
  return lex ? run(lex, code) : void 0;
329
384
  }
@@ -348,11 +403,28 @@ var IMAGE = /!\[([^\]]*)\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+)\)/g;
348
403
  var URL_BODY = String.raw`(?:(?!&(?:quot|lt|gt);)[^\s\0()]|\([^\s\0()]*\))+`;
349
404
  var ANGLE_URL = /* @__PURE__ */ new RegExp(String.raw`&lt;(https?:\/\/${URL_BODY})&gt;`, "g");
350
405
  var BARE_URL = /* @__PURE__ */ new RegExp(String.raw`(?<![\w/=@])https?:\/\/${URL_BODY}`, "g");
351
- var URL_TAIL = /[.,;:!?*_~]+$/;
406
+ var URL_TAIL_CHARS = ".,;:!?*_~";
352
407
  var ESCAPED_ENTITY = /&amp;([a-z][a-z\d]{1,31}|#\d{1,7}|#x[\da-f]{1,6});/gi;
353
408
  var MATH_DISPLAY = /\$\$([^\0]+?)\$\$/g;
354
409
  var MATH_INLINE = /(?<![\\$\w])\$(?=[^\s$])((?:[^$\n\\]|\\.)+?)(?<=[^\s\\])\$(?![\d\w$])/g;
355
- var emphasize = (s) => s.replace(/~~([^~\n]+)~~/g, "<del>$1</del>").replace(/\*\*\*(?=[^\s*])([^*\n]+?)\*\*\*/g, "<strong><em>$1</em></strong>").replace(/\*\*(?=\S)((?:[^*]|\*(?!\*))+?)\*\*/g, "<strong>$1</strong>").replace(/(^|[^\w])__(?=\S)((?:[^_]|_(?!_))+?)__(?!\w)/g, "$1<strong>$2</strong>").replace(/(^|[^*])\*(?=[^\s*])([^*\n]*[^\s*])\*(?!\*)/g, "$1<em>$2</em>").replace(/(^|[^\w])_(?=[^\s_])([^_\n]*[^\s_])_(?![\w])/g, "$1<em>$2</em>");
410
+ var INLINE_TAG = /<(\/?)(strong|em|del)>/g;
411
+ function nest(html) {
412
+ const open = [];
413
+ const out = html.replace(INLINE_TAG, (_all, close, tag) => {
414
+ if (!close) {
415
+ open.push(tag);
416
+ return `<${tag}>`;
417
+ }
418
+ const at = open.lastIndexOf(tag);
419
+ if (at < 0) return "";
420
+ const inner = open.splice(at);
421
+ inner.shift();
422
+ open.push(...inner);
423
+ return inner.reverse().map((t) => `</${t}>`).join("") + `</${tag}>` + [...inner].reverse().map((t) => `<${t}>`).join("");
424
+ });
425
+ return out + open.reverse().map((t) => `</${t}>`).join("");
426
+ }
427
+ var emphasize = (s) => nest(s.replace(/~~([^~\n]+)~~/g, "<del>$1</del>").replace(/\*\*\*(?=[^\s*])([^*\n]+?)\*\*\*/g, "<strong><em>$1</em></strong>").replace(/\*\*(?=\S)((?:[^*]|\*(?!\*))+?)\*\*/g, "<strong>$1</strong>").replace(/(^|[^\w])__(?=\S)((?:[^_]|_(?!_))+?)__(?!\w)/g, "$1<strong>$2</strong>").replace(/(^|[^*])\*(?=[^\s*])([^*\n]*[^\s*])\*(?!\*)/g, "$1<em>$2</em>").replace(/(^|[^\w])_(?=[^\s_])([^_\n]*[^\s_])_(?![\w])/g, "$1<em>$2</em>"));
356
428
  var unescapeHtml = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
357
429
  function inline(raw, ctx) {
358
430
  const spans = [];
@@ -392,13 +464,15 @@ function inline(raw, ctx) {
392
464
  });
393
465
  s = s.replace(ANGLE_URL, (_all, url) => lift({ text: url, url, ref: false, plain: true }));
394
466
  s = s.replace(BARE_URL, (all) => {
395
- const url = all.replace(URL_TAIL, "");
467
+ let end = all.length;
468
+ while (end > 0 && URL_TAIL_CHARS.includes(all[end - 1])) end -= 1;
469
+ const url = all.slice(0, end);
396
470
  return lift({ text: url, url, ref: false, plain: true }) + all.slice(url.length);
397
471
  });
398
472
  s = emphasize(s.replace(ESCAPED_ENTITY, "&$1;"));
399
473
  const draw = (index, inside) => {
400
474
  const link = links[index];
401
- const nest = (text) => text.replace(/\0L(\d+)\0/g, (_all, j) => draw(Number(j), true));
475
+ const nest2 = (text) => text.replace(/\0L(\d+)\0/g, (_all, j) => draw(Number(j), true));
402
476
  if (link.image) {
403
477
  const alt = link.text;
404
478
  if (ctx.embed) {
@@ -407,8 +481,8 @@ function inline(raw, ctx) {
407
481
  if (inside) return alt || link.url;
408
482
  return `<a class="sc-md-image" href="${link.url}" target="_blank" rel="noopener noreferrer">${alt || link.url}</a>`;
409
483
  }
410
- if (link.ref) return `<span class="sc-ref" data-ref="${link.url}">${nest(emphasize(link.text))}</span>`;
411
- return `<a href="${link.url}" target="_blank" rel="noopener noreferrer">${nest(link.plain ? link.text : emphasize(link.text))}</a>`;
484
+ if (link.ref) return `<span class="sc-ref" data-ref="${link.url}">${nest2(emphasize(link.text))}</span>`;
485
+ return `<a href="${link.url}" target="_blank" rel="noopener noreferrer">${nest2(link.plain ? link.text : emphasize(link.text))}</a>`;
412
486
  };
413
487
  s = s.replace(/\0L(\d+)\0/g, (_all, i) => draw(Number(i), false));
414
488
  return s.replace(/\0M(\d+)\0/g, (_all, i) => maths[Number(i)]).replace(/\0(\d+)\0/g, (_all, i) => `<code>${spans[Number(i)]}</code>`);
@@ -421,7 +495,7 @@ function codeBox(source, lang, ctx) {
421
495
  const colored = lang && ctx.highlight ? ctx.highlight(code, lang) : void 0;
422
496
  const body = colored ?? escapeHtml(code);
423
497
  const attr = lang ? ` data-lang="${lang}"` : "";
424
- const pre = `<pre${attr}><code${lang ? ` class="language-${lang}"` : ""}>${body}</code></pre>`;
498
+ const pre = `<pre${attr} tabindex="0"><code${lang ? ` class="language-${lang}"` : ""}>${body}</code></pre>`;
425
499
  if (!ctx.actions) return pre;
426
500
  return `<div class="sc-mdcode"${attr}><div class="sc-mdcode__bar"><span class="sc-mdcode__lang">${lang}</span><span class="sc-mdcode__tools"><button type="button" class="sc-mdcode__btn" data-sc-act="wrap">${WRAP_ICON}</button><button type="button" class="sc-mdcode__btn" data-sc-act="copy"></button></span></div>${pre}<button type="button" class="sc-mdcode__more" data-sc-act="more"></button></div>`;
427
501
  }
@@ -441,9 +515,9 @@ function cellsOf(line) {
441
515
  const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
442
516
  return trimmed.split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, "|"));
443
517
  }
444
- var alignOf = (cell) => {
445
- const left = cell.startsWith(":");
446
- const right = cell.endsWith(":");
518
+ var alignOf = (cell2) => {
519
+ const left = cell2.startsWith(":");
520
+ const right = cell2.endsWith(":");
447
521
  return left && right ? "center" : right ? "right" : left ? "left" : null;
448
522
  };
449
523
  function renderTable(lines, ctx) {
@@ -453,16 +527,16 @@ function renderTable(lines, ctx) {
453
527
  const head = cellsOf(lines[0]);
454
528
  if (head.length !== delimiter.length) return null;
455
529
  const align = delimiter.map(alignOf);
456
- const cell = (tag, text, i) => {
530
+ const cell2 = (tag, text, i) => {
457
531
  const a = align[i];
458
532
  return `<${tag}${a ? ` class="sc-md-${a}"` : ""}>${inline(text, ctx)}</${tag}>`;
459
533
  };
460
534
  const body = lines.slice(2).filter((l) => l.trim() !== "").map((l) => {
461
535
  const row = cellsOf(l);
462
- const cells = Array.from({ length: head.length }, (_, i) => cell("td", row[i] ?? "", i));
536
+ const cells = Array.from({ length: head.length }, (_, i) => cell2("td", row[i] ?? "", i));
463
537
  return `<tr>${cells.join("")}</tr>`;
464
538
  }).join("");
465
- const table = `<div class="sc-md-scroll" tabindex="0"><table class="sc-md-table"><thead><tr>${head.map((h, i) => cell("th", h, i)).join("")}</tr></thead><tbody>${body}</tbody></table></div>`;
539
+ const table = `<div class="sc-md-scroll" tabindex="0"><table class="sc-md-table"><thead><tr>${head.map((h, i) => cell2("th", h, i)).join("")}</tr></thead><tbody>${body}</tbody></table></div>`;
466
540
  if (!ctx.actions) return table;
467
541
  return `<div class="sc-md-tablebox"><div class="sc-md-tablebar"><button type="button" class="sc-md-tablebtn" data-sc-act="copy-tsv"></button><button type="button" class="sc-md-tablebtn" data-sc-act="copy-md"></button></div>${table}</div>`;
468
542
  }
@@ -490,7 +564,7 @@ function parseList(lines) {
490
564
  function renderItem(item, depth, ctx) {
491
565
  const mark = TASK_MARK.exec(item);
492
566
  const body = mark ? item.slice(mark[0].length) : item;
493
- const lines = body.replace(/\s+$/, "").split("\n");
567
+ const lines = body.trimEnd().split("\n");
494
568
  const nestedAt = lines.findIndex((l, i) => i > 0 && LIST_ITEM.test(l));
495
569
  const head = (nestedAt === -1 ? lines : lines.slice(0, nestedAt)).filter((l) => l.trim() !== "");
496
570
  const rest = nestedAt === -1 ? [] : lines.slice(nestedAt);
@@ -518,7 +592,29 @@ function renderList(lines, depth, ctx) {
518
592
  var QUOTE_MARK = /^ {0,3}> ?/;
519
593
  var THEMATIC_BREAK = /^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/;
520
594
  var SETEXT = /^ {0,3}(=+|-+)\s*$/;
521
- var ATX = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
595
+ var ATX_HEAD = /^ {0,3}(#{1,6})\s+/;
596
+ var ATX_SLOW = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
597
+ var ATX_SLOW_MAX = 2e3;
598
+ var ODD_TERMINATOR = /[\r\u2028\u2029]/;
599
+ function atxHeading(line) {
600
+ if (ODD_TERMINATOR.test(line)) {
601
+ if (line.length > ATX_SLOW_MAX) return null;
602
+ const m = ATX_SLOW.exec(line);
603
+ return m ? { hashes: m[1].length, text: m[2] } : null;
604
+ }
605
+ const head = ATX_HEAD.exec(line);
606
+ if (!head) return null;
607
+ let end = line.length;
608
+ const floor = head[0].length;
609
+ const skip = (test) => {
610
+ while (end > floor && test(line[end - 1])) end -= 1;
611
+ };
612
+ const space = (c) => /\s/.test(c);
613
+ skip(space);
614
+ skip((c) => c === "#");
615
+ skip(space);
616
+ return { hashes: head[1].length, text: line.slice(floor, end) };
617
+ }
522
618
  var DISPLAY_MATH = /^\s*\$\$([\s\S]+?)\$\$\s*$/;
523
619
  function renderProse(lines, ctx) {
524
620
  const out = [];
@@ -533,11 +629,11 @@ function renderProse(lines, ctx) {
533
629
  para = [];
534
630
  };
535
631
  for (const line of lines) {
536
- const h = ATX.exec(line);
632
+ const h = atxHeading(line);
537
633
  if (h) {
538
634
  flush();
539
- const level = Math.min(h[1].length + 1, 6);
540
- out.push(`<h${level}>${inline(h[2], ctx)}</h${level}>`);
635
+ const level = Math.min(h.hashes + 1, 6);
636
+ out.push(`<h${level}>${inline(h.text, ctx)}</h${level}>`);
541
637
  continue;
542
638
  }
543
639
  para.push(line);
@@ -618,23 +714,24 @@ function renderMarkdownWithAnchors(src, options) {
618
714
  }
619
715
 
620
716
  // src/table.ts
621
- var flatten = (cell) => cell.replace(/[\t\r\n]+/g, " ");
717
+ var flatten = (cell2) => cell2.replace(/[\t\r\n]+/g, " ");
622
718
  function tableToTsv(header, rows) {
623
719
  const line = (cells) => cells.map(flatten).join(" ");
624
720
  return [line(header), ...rows.map(line)].join("\n");
625
721
  }
626
722
  function tableToMarkdown(header, rows, align = []) {
627
- const cell = (c) => flatten(c).replace(/\|/g, "\\|").trim();
723
+ const cell2 = (c) => flatten(c).replace(/\|/g, "\\|").trim();
628
724
  const rule = header.map((_, i) => {
629
725
  const a = align[i];
630
726
  return a === "center" ? ":---:" : a === "right" ? "---:" : a === "left" ? ":---" : "---";
631
727
  });
632
- const line = (cells) => `| ${header.map((_, i) => cell(cells[i] ?? "")).join(" | ")} |`;
728
+ const line = (cells) => `| ${header.map((_, i) => cell2(cells[i] ?? "")).join(" | ")} |`;
633
729
  return [line(header), `| ${rule.join(" | ")} |`, ...rows.map(line)].join("\n");
634
730
  }
635
731
  export {
636
732
  HIGHLIGHT_LANGUAGES,
637
733
  STABLE_FORMAT,
734
+ atxHeading,
638
735
  deltaTone,
639
736
  downloadThread,
640
737
  formatDelta,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/format.ts","../src/export.ts","../src/markdown.ts","../src/highlight.ts","../src/table.ts"],"sourcesContent":["// Value formatting shared by every card renderer.\n//\n// Centralised because a table cell and a stat tile showing the same number in\n// different formats is the fastest way to make an interface look untrustworthy.\n\nimport type { CardValueFormat } from \"@supersolutions/super-chat-core\";\n\nexport type FormatOptions = {\n /** BCP 47 locale. Omitted means the viewer's own. */\n locale?: string;\n /** IANA time zone for `datetime` values. Omitted means the viewer's own. */\n timeZone?: string;\n};\n\n/**\n * Fixed settings for HTML rendered ahead of the browser. A build server and a\n * viewer rarely share a locale or time zone, so server output and the first\n * client render must both use these or hydration fails.\n */\nexport const STABLE_FORMAT: FormatOptions = { locale: \"en-US\", timeZone: \"UTC\" };\n\nfunction createNumberFormats(locale?: string) {\n return {\n compact: new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 2 }),\n plain: new Intl.NumberFormat(locale, { maximumFractionDigits: 6 }),\n pctWide: new Intl.NumberFormat(locale, { maximumFractionDigits: 1, useGrouping: false }),\n pctNarrow: new Intl.NumberFormat(locale, { maximumFractionDigits: 2, useGrouping: false }),\n };\n}\n\nconst numberFormats = new Map<string, ReturnType<typeof createNumberFormats>>();\n\nfunction numbersFor(locale?: string) {\n const key = locale ?? \"\";\n let formats = numberFormats.get(key);\n if (!formats) {\n formats = createNumberFormats(locale);\n numberFormats.set(key, formats);\n }\n return formats;\n}\n\nexport function formatValue(value: unknown, format: CardValueFormat = \"text\", options: FormatOptions = {}): string {\n if (value == null) return \"—\";\n const { locale, timeZone } = options;\n const numbers = numbersFor(locale);\n\n switch (format) {\n case \"number\": {\n const n = Number(value);\n if (!Number.isFinite(n)) return String(value);\n // Compact only above 5 digits: \"12.3K\" is helpful, \"1.2K\" hides precision\n // people expect to see on small counts.\n return Math.abs(n) >= 100_000 ? numbers.compact.format(n) : numbers.plain.format(n);\n }\n case \"currency\": {\n const n = Number(value);\n if (!Number.isFinite(n)) return String(value);\n const abs = Math.abs(n);\n // Sub-cent values are common in crypto; fixed 2dp would render them as $0.00.\n const digits = abs >= 1 ? 2 : abs >= 0.01 ? 4 : 8;\n // A whole amount in the thousands reads as \"$48,200\". Forcing \".00\" onto\n // it is the machine-printed look; amounts with cents keep them.\n const min = abs >= 1000 && Number.isInteger(n) ? 0 : 2;\n return `$${n.toLocaleString(locale, { minimumFractionDigits: min, maximumFractionDigits: Math.max(min, digits) })}`;\n }\n case \"percent\": {\n const n = Number(value);\n if (!Number.isFinite(n)) return String(value);\n // One decimal at most (\"8.2%\", \"12%\"), two only below 1% where the\n // second digit is the signal (\"0.04%\"). A fixed \"8.20%\" is false precision.\n return `${(Math.abs(n) < 1 ? numbers.pctNarrow : numbers.pctWide).format(n)}%`;\n }\n case \"bytes\": {\n const n = Number(value);\n if (!Number.isFinite(n)) return String(value);\n const units = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\"];\n let i = 0;\n let v = n;\n while (v >= 1024 && i < units.length - 1) {\n v /= 1024;\n i += 1;\n }\n return `${v.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;\n }\n case \"duration\": {\n const ms = Number(value);\n if (!Number.isFinite(ms)) return String(value);\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;\n if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;\n return `${(ms / 3_600_000).toFixed(1)}h`;\n }\n case \"datetime\": {\n const d = typeof value === \"number\" ? new Date(value) : new Date(String(value));\n if (Number.isNaN(d.getTime())) return String(value);\n return d.toLocaleString(locale, timeZone ? { timeZone, timeZoneName: \"short\" } : undefined);\n }\n case \"code\":\n case \"text\":\n default:\n return typeof value === \"object\" ? JSON.stringify(value) : String(value);\n }\n}\n\nexport function formatDelta(delta: number, format: CardValueFormat = \"number\", options: FormatOptions = {}): string {\n // A true minus sign: the hyphen-minus is narrower and misaligns a column of\n // signed deltas against the plus signs above it.\n const sign = delta > 0 ? \"+\" : delta < 0 ? \"−\" : \"\";\n return `${sign}${formatValue(Math.abs(delta), format, options)}`;\n}\n\nexport const toneClass = (tone?: string): string => (tone && tone !== \"neutral\" ? ` sc-tone--${tone}` : \"\");\n\n/** Positive is not always good — but for a delta with no stated tone it is the useful default. */\nexport const deltaTone = (delta: number): \"positive\" | \"negative\" | \"neutral\" =>\n delta > 0 ? \"positive\" : delta < 0 ? \"negative\" : \"neutral\";\n\n/**\n * A URL that came from a model or a tool, made safe to put in an `href`: only http(s) links\n * pass, anything else (`javascript:`, `data:`, `vbscript:`, a relative path that could be read\n * as a scheme after whitespace tricks) comes back as `undefined` and the caller renders plain\n * text. React 19 refuses `javascript:` hrefs itself, but this package supports React 18, which\n * only warns and then navigates.\n */\nexport function safeHref(url: string | undefined | null): string | undefined {\n if (typeof url !== \"string\") return undefined;\n const trimmed = url.trim();\n // Browsers strip tab and newline characters inside a URL before parsing it, so\n // `java\\tscript:` is a javascript: URL; reject anything with control characters outright.\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(trimmed)) return undefined;\n return /^https?:\\/\\/[^\\s]+$/i.test(trimmed) ? trimmed : undefined;\n}\n","// Thread export.\n//\n// Markdown rather than JSON: the point of exporting a conversation is to read it\n// somewhere else or paste it into a ticket, and JSON serves neither. Cards are\n// rendered as their data, not as their markup — a table exported as HTML is\n// useless in a text file, but as a markdown table it survives.\n//\n// Sharing (a hosted link) is deliberately NOT here: it needs a backend the kit\n// does not have, and faking it with a data: URL would produce links that break\n// the moment they leave the browser.\n\nimport type { Card, ContentPart, Message } from \"@supersolutions/super-chat-core\";\n\nfunction cardToMarkdown(spec: Record<string, unknown>): string {\n const kind = String(spec.kind ?? \"unknown\");\n const title = spec.title ? `**${spec.title}**\\n\\n` : \"\";\n\n if (kind === \"table\" && Array.isArray(spec.columns) && Array.isArray(spec.rows)) {\n const cols = spec.columns as { key: string; label: string }[];\n const rows = spec.rows as Record<string, unknown>[];\n const head = `| ${cols.map((c) => c.label).join(\" | \")} |`;\n const rule = `| ${cols.map(() => \"---\").join(\" | \")} |`;\n const body = rows.map((r) => `| ${cols.map((c) => String(r[c.key] ?? \"\")).join(\" | \")} |`).join(\"\\n\");\n return `${title}${head}\\n${rule}\\n${body}`;\n }\n\n if (kind === \"markdown\" && typeof spec.body === \"string\") return `${title}${spec.body}`;\n if (kind === \"code\" && typeof spec.code === \"string\") {\n return `${title}\\`\\`\\`${spec.language ?? \"\"}\\n${spec.code}\\n\\`\\`\\``;\n }\n if (kind === \"callout\" && typeof spec.body === \"string\") return `> ${title}${spec.body}`;\n\n // Everything else keeps its data rather than being dropped — an export that\n // silently omits a card is worse than one that is a little verbose.\n return `${title}\\`\\`\\`json\\n${JSON.stringify(spec, null, 2)}\\n\\`\\`\\``;\n}\n\nfunction partToMarkdown(part: ContentPart): string | null {\n switch (part.type) {\n case \"text\":\n return part.text;\n case \"reasoning\":\n return `<details><summary>Reasoning</summary>\\n\\n${part.text}\\n\\n</details>`;\n case \"tool-call\":\n return `- \\`${part.name}(${JSON.stringify(part.input ?? {})})\\``;\n case \"tool-result\":\n return part.failure ? `- \\`${part.name}\\` failed: ${part.failure}` : null;\n case \"image\":\n return \"_(image)_\";\n case \"file\":\n return `_(file: ${part.filename ?? \"attachment\"})_`;\n case \"artifact\":\n return part.kind.startsWith(\"card:\")\n ? cardToMarkdown(((part.data as { spec?: Card[\"spec\"] }).spec ?? part.data) as Record<string, unknown>)\n : null;\n default:\n return null;\n }\n}\n\n/** Render a thread as markdown. `title` becomes the H1 when given. */\nexport function threadToMarkdown(messages: readonly Message[], title?: string): string {\n const out: string[] = title ? [`# ${title}`, \"\"] : [];\n\n for (const m of messages) {\n if (m.role === \"system\") continue;\n const body = m.parts.map(partToMarkdown).filter(Boolean).join(\"\\n\\n\");\n if (!body) continue;\n const who = m.role === \"user\" ? \"You\" : m.role === \"tool\" ? \"Tools\" : \"Assistant\";\n const when = m.createdAt ? ` · ${new Date(m.createdAt).toISOString().slice(0, 16).replace(\"T\", \" \")}` : \"\";\n out.push(`## ${who}${when}`, \"\", body, \"\");\n }\n\n return out.join(\"\\n\").trimEnd() + \"\\n\";\n}\n\n/** Trigger a download of the thread as a `.md` file. */\nexport function downloadThread(messages: readonly Message[], filename = \"conversation.md\", title?: string): void {\n const blob = new Blob([threadToMarkdown(messages, title)], { type: \"text/markdown;charset=utf-8\" });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.click();\n // Revoking immediately can race the download in some browsers; one frame is\n // enough for the click to have been consumed.\n requestAnimationFrame(() => URL.revokeObjectURL(url));\n}\n","// Minimal markdown renderer for assistant text, markdown cards and document\n// artifacts.\n//\n// Deliberately not a full parser — a chat message or card body is short, and\n// pulling in a markdown library plus a sanitizer for this is disproportionate.\n//\n// It does now split into blocks before rendering, and that is not a stylistic\n// change. A document previewer has to answer \"the user selected this on screen;\n// where is it in the source?\", because that span is both what gets quoted into\n// the next request and what an edit has to anchor against. The previous shape —\n// escape the whole string, pull fences out into placeholders, then run a chain\n// of global regexes — destroyed source positions in its first statement.\n//\n// So the order is inverted: split on the RAW source and record offsets, then\n// escape and transform each block independently. Escaping per block rather than\n// up front is load-bearing, not tidiness: `&` → `&amp;` changes the string\n// length, so escaping first would shift every offset recorded afterwards. That\n// failure is invisible on screen — the page renders perfectly and the anchors\n// silently point at the wrong text — which is why markdown.test.ts asserts the\n// offsets round-trip rather than trusting the output to look right.\n//\n// ── Why it grew ──────────────────────────────────────────────────────────────\n//\n// The block set used to be headings, emphasis, code, links and bullet lists,\n// and for a chat bubble that is the right amount of renderer. A document\n// artifact changed the requirement under it: a document is a thing the user\n// KEEPS, reads in a previewer and downloads as `.md`, and a report whose table\n// renders as a column of literal pipes is not a document — it is the source of\n// one. Tables, quotes, ordered lists and indented code are not exotic; they are\n// what anyone writing a report reaches for in the first paragraph.\n//\n// The structure changed with the scope. A chain of global regexes over one\n// escaped string cannot tell a table from a paragraph, so each block is now\n// CLASSIFIED first and rendered by shape, and only the leaves run inline\n// transforms. Nesting (a list inside a quote, a quote inside a list) falls out\n// of rendering a block's interior through the same splitter, with a depth cap\n// so a pathological `> > > > …` cannot recurse without end.\n\nimport { splitBlocks, type MarkdownBlock } from \"@supersolutions/super-chat-core\";\nimport { highlightCode } from \"./highlight.js\";\n\n/**\n * What a host can change about how Markdown becomes HTML. Everything is optional, and the\n * defaults are the safe ones: no image is fetched, no maths is guessed at, code is coloured by\n * a small built-in highlighter.\n */\nexport type MarkdownOptions = {\n /**\n * Colour fenced code: `(code, lang) => html` for the inside of `<code>`, or `undefined` to\n * leave that block plain. The default knows JS/TS, JSON, Python, shell, SQL, HTML/CSS, YAML\n * and diffs; pass highlight.js or Shiki here for the rest, or `false` for none. The returned\n * HTML is inserted as it is, so it must come from code you trust.\n */\n highlight?: ((code: string, lang: string) => string | undefined) | false;\n /**\n * Typeset `$…$` and `$$…$$`: `(tex, display) => html`, or `undefined` to leave the source as\n * text. Without this, `$` is an ordinary character, so a price is never mistaken for maths.\n * The returned HTML is inserted as it is, so it must come from code you trust (KaTeX, Temml).\n */\n math?: (tex: string, display: boolean) => string | undefined;\n /**\n * What `![alt](https://…)` becomes. `\"link\"` (the default) is a link to the image: nothing is\n * fetched until the reader follows it, so a model cannot make a page load a URL it chose.\n * `\"embed\"` draws the picture, with lazy loading and no referrer.\n */\n images?: \"link\" | \"embed\";\n /**\n * Draw the buttons for code blocks and tables (copy, wrap, show all) as markup. They carry\n * `data-sc-act` and no words; `ProseHtml` in `super-chat-ui` gives them their labels and\n * answers them. Off by default so a plain `renderMarkdown` string has no dead buttons in it.\n */\n actions?: boolean;\n};\n\ntype Ctx = {\n highlight: ((code: string, lang: string) => string | undefined) | false;\n math: MarkdownOptions[\"math\"];\n embed: boolean;\n actions: boolean;\n};\n\nconst contextOf = (o: MarkdownOptions | undefined): Ctx => ({\n highlight: o?.highlight === undefined ? highlightCode : o.highlight,\n math: o?.math,\n embed: o?.images === \"embed\",\n actions: o?.actions === true,\n});\n\nexport type AnchoredMarkdown = {\n html: string;\n /** Index-aligned with the `data-sc-block` attribute on the rendered HTML. */\n blocks: MarkdownBlock[];\n};\n\n// Cheap pre-check carried over from main: with none of these characters\n// present, no heading, emphasis, code, link, list, quote or table rule below\n// could match, so the whole chain is skippable. Applied per BLOCK rather than\n// per document — one fenced snippet in an otherwise plain artifact should not\n// cost the other forty paragraphs their shortcut.\nconst MARKDOWN_SIGNIFICANT = /[`*_#[\\]>~|-]/;\n// Two constructs carry no character the test above would catch: an ordered\n// item, and a setext heading underlined with `=`. Adding `=` and the digits to\n// MARKDOWN_SIGNIFICANT would cost the shortcut on most prose, so they get their\n// own (equally cheap) look instead.\nconst ORDERED_ITEM = /^ {0,3}\\d{1,9}[.)]\\s/m;\nconst SETEXT_EQUALS = /\\n {0,3}=+[ \\t]*$/;\n\n// A bare URL and a character reference also have to be seen, and they carry none of the above.\nconst AUTOLINKABLE = /https?:\\/\\//;\nconst ENTITY = /&(?:[a-z][a-z\\d]{1,31}|#\\d{1,7}|#x[\\da-f]{1,6});/i;\n\nconst isPlainProse = (raw: string, ctx: Ctx) =>\n !MARKDOWN_SIGNIFICANT.test(raw) &&\n !ORDERED_ITEM.test(raw) &&\n !SETEXT_EQUALS.test(raw) &&\n !AUTOLINKABLE.test(raw) &&\n !ENTITY.test(raw) &&\n !(ctx.math && raw.includes(\"$\"));\n\n/** How deep a quote or list may nest before its interior is rendered flat. */\nconst MAX_DEPTH = 4;\n\n// Quotes are escaped because link URLs are interpolated into href=\"…\" — an\n// unescaped quote in a URL would close the attribute and open a new one\n// (browsers recover from the missing-whitespace parse error by reading\n// `\"onmouseover=\"…` as a fresh attribute).\n//\n// NUL is dropped here, at the one place every leaf is escaped, rather than only in\n// `inline`: the inline placeholders below are built from it, so it must never come from\n// the source, and code blocks and the plain-prose shortcut would otherwise let a raw\n// U+0000 through into the output. (Block offsets are computed on the raw source, so\n// removing it from the output moves no anchor.)\nconst escapeHtml = (s: string) =>\n s.replace(/\\0/g, \"\").replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\n// ── Inline ───────────────────────────────────────────────────────────────────\n\n/**\n * Escape, then transform. Every leaf goes through here and nothing else does.\n *\n * Code spans are lifted out FIRST and put back last, so `**not bold**` inside\n * backticks stays literal — the same protection fenced blocks get, which the\n * old chain gave only to fences. NUL is stripped from the input because the\n * placeholders are built from it; without that, text could forge one.\n */\n// Only http(s) links — a javascript: URL must never survive. The destination may\n// contain one level of balanced parentheses (`…/wiki/Foo_(bar)`), as CommonMark\n// allows; the two alternatives cannot match the same character, so there is no\n// backtracking blow-up on a hostile string.\n//\n// The other destination is a card reference, `ref:<card>?key=value&…` (super-protocol\n// docs/CARD-REFS.md). It is not a link: it becomes a span the host wires to a card, and it\n// stays plain text where no host does. The character set is the envelope's own, plus the `;`\n// that escaping gives `&`, so nothing in it can close an attribute or open a tag. The limits\n// are the parser's to enforce (a ref that breaks them degrades where it is used), not this\n// regex's; the bound here only keeps a hostile string from costing a long scan.\nconst LINK = /\\[((?:[^\\[\\]]|\\[[^\\[\\]]*\\])+)\\]\\((https?:\\/\\/(?:[^()\\s]|\\([^()\\s]*\\))+|ref:[A-Za-z0-9._:~%=&;?-]{1,3000})\\)/g;\n\n// An image: the destination follows the same rules as a link's, and only http(s) is one.\nconst IMAGE = /!\\[([^\\]]*)\\]\\((https?:\\/\\/(?:[^()\\s]|\\([^()\\s]*\\))+)\\)/g;\n// `<https://…>` (escaped, by now) and a bare URL. A URL stops at whitespace, at an escaped quote\n// or angle bracket, and at a parenthesis that is not part of a balanced pair, so a sentence\n// that ends with \"(see https://example.com)\" does not take the bracket with it.\nconst URL_BODY = String.raw`(?:(?!&(?:quot|lt|gt);)[^\\s\\0()]|\\([^\\s\\0()]*\\))+`;\nconst ANGLE_URL = /* @__PURE__ */ new RegExp(String.raw`&lt;(https?:\\/\\/${URL_BODY})&gt;`, \"g\");\nconst BARE_URL = /* @__PURE__ */ new RegExp(String.raw`(?<![\\w/=@])https?:\\/\\/${URL_BODY}`, \"g\");\n// Punctuation that ends a sentence, or the emphasis around a URL, is not part of it.\nconst URL_TAIL = /[.,;:!?*_~]+$/;\n// A character reference in text stays one (`&amp;` shows `&`), and everything it can name is text.\nconst ESCAPED_ENTITY = /&amp;([a-z][a-z\\d]{1,31}|#\\d{1,7}|#x[\\da-f]{1,6});/gi;\n// `$$…$$`, then `$…$` where the opening `$` is followed and the closing one preceded by\n// something that is not a space, and the closing one is not followed by a digit or letter, so\n// \"costs $5 and $10\" is two prices and not a formula.\nconst MATH_DISPLAY = /\\$\\$([^\\0]+?)\\$\\$/g;\nconst MATH_INLINE = /(?<![\\\\$\\w])\\$(?=[^\\s$])((?:[^$\\n\\\\]|\\\\.)+?)(?<=[^\\s\\\\])\\$(?![\\d\\w$])/g;\n\n/** Strike-through, strong, emphasis. Runs on already-escaped text. */\nconst emphasize = (s: string) =>\n s\n .replace(/~~([^~\\n]+)~~/g, \"<del>$1</del>\")\n .replace(/\\*\\*\\*(?=[^\\s*])([^*\\n]+?)\\*\\*\\*/g, \"<strong><em>$1</em></strong>\")\n .replace(/\\*\\*(?=\\S)((?:[^*]|\\*(?!\\*))+?)\\*\\*/g, \"<strong>$1</strong>\")\n .replace(/(^|[^\\w])__(?=\\S)((?:[^_]|_(?!_))+?)__(?!\\w)/g, \"$1<strong>$2</strong>\")\n .replace(/(^|[^*])\\*(?=[^\\s*])([^*\\n]*[^\\s*])\\*(?!\\*)/g, \"$1<em>$2</em>\")\n .replace(/(^|[^\\w])_(?=[^\\s_])([^_\\n]*[^\\s_])_(?![\\w])/g, \"$1<em>$2</em>\");\n\nconst unescapeHtml = (s: string) =>\n s.replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").replace(/&quot;/g, '\"').replace(/&amp;/g, \"&\");\n\ntype Link = { text: string; url: string; ref: boolean; plain: boolean; image?: boolean };\n\nfunction inline(raw: string, ctx: Ctx): string {\n const spans: string[] = [];\n const spanSource: string[] = []; // what each code span looked like, for where it must stay literal\n let s = escapeHtml(raw);\n\n s = s.replace(/(`+)([\\s\\S]+?)\\1(?!`)/g, (all, _ticks, body: string) => {\n spans.push(body);\n spanSource.push(all);\n return `\\0${spans.length - 1}\\0`;\n });\n\n // Maths is lifted next, so its underscores and asterisks are not read as emphasis, and only\n // when the host supplied the typesetter: otherwise a `$` is a dollar sign.\n const maths: string[] = [];\n const mathSource: string[] = [];\n if (ctx.math) {\n const typeset = (tex: string, display: boolean, whole: string) => {\n const out = ctx.math!(unescapeHtml(tex).trim(), display);\n if (out === undefined) return whole;\n maths.push(out);\n mathSource.push(whole);\n return `\\0M${maths.length - 1}\\0`;\n };\n s = s.replace(MATH_DISPLAY, (all, tex: string) => typeset(tex, true, all));\n s = s.replace(MATH_INLINE, (all, tex: string) => typeset(tex, false, all));\n }\n\n // Links are lifted out the same way, BEFORE emphasis. Otherwise the emphasis rules\n // run over the destination too, and `…/a*b*c` becomes `href=\"…/a<em>b</em>c\"`: the\n // link silently points somewhere else. Only the link's text is emphasised.\n const links: Link[] = [];\n const lift = (link: Link) => {\n links.push(link);\n return `\\0L${links.length - 1}\\0`;\n };\n // A backtick pair inside a URL (or an image's alt text, which lands in an attribute) is part of\n // it, not a code span.\n const literalUrl = (url: string) =>\n url\n .replace(/\\0M(\\d+)\\0/g, (_m, i: string) => mathSource[Number(i)]!)\n .replace(/\\0(\\d+)\\0/g, (_m, i: string) => spanSource[Number(i)]!);\n\n s = s.replace(IMAGE, (_all, alt: string, url: string) =>\n lift({ text: literalUrl(alt), url: literalUrl(url), ref: false, plain: true, image: true }),\n );\n s = s.replace(LINK, (_all, text: string, url: string) => {\n const literal = literalUrl(url);\n return lift({ text, url: literal, ref: literal.startsWith(\"ref:\"), plain: false });\n });\n s = s.replace(ANGLE_URL, (_all, url: string) => lift({ text: url, url, ref: false, plain: true }));\n s = s.replace(BARE_URL, (all: string) => {\n const url = all.replace(URL_TAIL, \"\");\n return lift({ text: url, url, ref: false, plain: true }) + all.slice(url.length);\n });\n\n s = emphasize(s.replace(ESCAPED_ENTITY, \"&$1;\"));\n\n // A link's text may hold another lifted construct (an image inside a link). Drawn from the\n // outside in, so the image can know it is inside one: an anchor never holds an anchor.\n const draw = (index: number, inside: boolean): string => {\n const link = links[index]!;\n const nest = (text: string) => text.replace(/\\0L(\\d+)\\0/g, (_all, j: string) => draw(Number(j), true));\n if (link.image) {\n const alt = link.text;\n if (ctx.embed) {\n return `<img class=\"sc-md-img\" src=\"${link.url}\" alt=\"${alt}\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\">`;\n }\n // A link to the picture, not the picture: the model chose this URL, and fetching it is\n // how a conversation leaks to a third party. The words stay readable and the `!` is gone.\n if (inside) return alt || link.url;\n return `<a class=\"sc-md-image\" href=\"${link.url}\" target=\"_blank\" rel=\"noopener noreferrer\">${alt || link.url}</a>`;\n }\n if (link.ref) return `<span class=\"sc-ref\" data-ref=\"${link.url}\">${nest(emphasize(link.text))}</span>`;\n return `<a href=\"${link.url}\" target=\"_blank\" rel=\"noopener noreferrer\">${nest(link.plain ? link.text : emphasize(link.text))}</a>`;\n };\n s = s.replace(/\\0L(\\d+)\\0/g, (_all, i: string) => draw(Number(i), false));\n\n return s\n .replace(/\\0M(\\d+)\\0/g, (_all, i: string) => maths[Number(i)]!)\n .replace(/\\0(\\d+)\\0/g, (_all, i: string) => `<code>${spans[Number(i)]}</code>`);\n}\n\n// ── Verbatim blocks ──────────────────────────────────────────────────────────\n\nconst CLOSING_FENCE = /^ {0,3}(?:`{3,}|~{3,})\\s*$/;\n// The first word of the info string, if it is a name and not prose: `js`, `c++`, `c#`, `shell-session`.\nconst FENCE_LANG = /^ {0,3}(?:`{3,}|~{3,})[ \\t]*([A-Za-z0-9][A-Za-z0-9_+#.-]{0,31})(?:[ \\t{].*)?$/;\n\n// Lines running on to a second row. Part of the markup, not a mask image or a decoration pass, so\n// it needs no stylesheet request and survives the page's strictest content security policy.\nconst WRAP_ICON =\n '<svg viewBox=\"0 0 16 16\" width=\"14\" height=\"14\" aria-hidden=\"true\"><path d=\"M2 4h12M2 8h8.5a2.5 2.5 0 0 1 0 5H8m0 0 1.6-1.6M8 13l1.6 1.6M2 12h2.5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>';\n\n/** The code, its language, and the buttons a host may wire, in one box. */\nfunction codeBox(source: string, lang: string, ctx: Ctx): string {\n // NUL never reaches a highlighter or the page, whichever of them writes the markup.\n const code = source.replace(/\\0/g, \"\");\n const colored = lang && ctx.highlight ? ctx.highlight(code, lang) : undefined;\n const body = colored ?? escapeHtml(code);\n const attr = lang ? ` data-lang=\"${lang}\"` : \"\";\n const pre = `<pre${attr}><code${lang ? ` class=\"language-${lang}\"` : \"\"}>${body}</code></pre>`;\n if (!ctx.actions) return pre;\n return (\n `<div class=\"sc-mdcode\"${attr}><div class=\"sc-mdcode__bar\"><span class=\"sc-mdcode__lang\">${lang}</span>` +\n `<span class=\"sc-mdcode__tools\"><button type=\"button\" class=\"sc-mdcode__btn\" data-sc-act=\"wrap\">${WRAP_ICON}</button>` +\n `<button type=\"button\" class=\"sc-mdcode__btn\" data-sc-act=\"copy\"></button></span></div>${pre}` +\n `<button type=\"button\" class=\"sc-mdcode__more\" data-sc-act=\"more\"></button></div>`\n );\n}\n\nfunction renderFence(raw: string, ctx: Ctx): string {\n // Drop the opening fence line (which may carry a language) and the closing\n // one if it is there — an unterminated fence has none. Content is escaped but\n // never sees an inline transform.\n const lines = raw.split(\"\\n\");\n const lang = (FENCE_LANG.exec(lines[0]!)?.[1] ?? \"\").toLowerCase();\n lines.shift();\n if (lines.length && CLOSING_FENCE.test(lines[lines.length - 1]!)) lines.pop();\n return codeBox(lines.join(\"\\n\"), lang, ctx);\n}\n\nfunction renderIndentedCode(raw: string, ctx: Ctx): string {\n const body = raw.split(\"\\n\").map((l) => l.replace(/^(?: {4}|\\t)/, \"\")).join(\"\\n\");\n return codeBox(body, \"\", ctx);\n}\n\n// ── Tables ───────────────────────────────────────────────────────────────────\n\ntype Align = \"left\" | \"center\" | \"right\" | null;\n\nconst DELIMITER_CELL = /^:?-+:?$/;\n\n/** Split a pipe row into cells, honouring `\\|` as a literal pipe. */\nfunction cellsOf(line: string): string[] {\n const trimmed = line.trim().replace(/^\\|/, \"\").replace(/\\|$/, \"\");\n return trimmed\n .split(/(?<!\\\\)\\|/)\n .map((c) => c.trim().replace(/\\\\\\|/g, \"|\"));\n}\n\nconst alignOf = (cell: string): Align => {\n const left = cell.startsWith(\":\");\n const right = cell.endsWith(\":\");\n return left && right ? \"center\" : right ? \"right\" : left ? \"left\" : null;\n};\n\nfunction renderTable(lines: string[], ctx: Ctx): string | null {\n if (lines.length < 2 || !lines[0]!.includes(\"|\")) return null;\n const delimiter = cellsOf(lines[1]!);\n if (!delimiter.length || !delimiter.every((c) => DELIMITER_CELL.test(c))) return null;\n\n const head = cellsOf(lines[0]!);\n if (head.length !== delimiter.length) return null;\n const align = delimiter.map(alignOf);\n\n // Alignment rides on a class rather than a style attribute: a host with a\n // strict CSP can ship this without allowing inline styles.\n const cell = (tag: \"th\" | \"td\", text: string, i: number) => {\n const a = align[i];\n return `<${tag}${a ? ` class=\"sc-md-${a}\"` : \"\"}>${inline(text, ctx)}</${tag}>`;\n };\n\n const body = lines\n .slice(2)\n .filter((l) => l.trim() !== \"\")\n .map((l) => {\n const row = cellsOf(l);\n // Short rows are padded and long ones cut, so a ragged table still lines\n // up under its header instead of leaking cells into a new column.\n const cells = Array.from({ length: head.length }, (_, i) => cell(\"td\", row[i] ?? \"\", i));\n return `<tr>${cells.join(\"\")}</tr>`;\n })\n .join(\"\");\n\n // The table scrolls inside a box of its own, and the box takes focus: a wide table is\n // otherwise unreachable by keyboard. (A `display:block` table would scroll without the box,\n // but a block table is no longer a table to some assistive technology.)\n const table =\n `<div class=\"sc-md-scroll\" tabindex=\"0\"><table class=\"sc-md-table\"><thead><tr>${head\n .map((h, i) => cell(\"th\", h, i))\n .join(\"\")}</tr></thead><tbody>${body}</tbody></table></div>`;\n if (!ctx.actions) return table;\n return (\n `<div class=\"sc-md-tablebox\"><div class=\"sc-md-tablebar\">` +\n `<button type=\"button\" class=\"sc-md-tablebtn\" data-sc-act=\"copy-tsv\"></button>` +\n `<button type=\"button\" class=\"sc-md-tablebtn\" data-sc-act=\"copy-md\"></button></div>${table}</div>`\n );\n}\n\n// ── Lists ────────────────────────────────────────────────────────────────────\n\nconst LIST_ITEM = /^(\\s*)([-*+]|\\d{1,9}[.)])[ \\t]+(.*)$/;\nconst TASK_MARK = /^\\[([ xX])\\][ \\t]+/;\n\ntype ParsedList = { ordered: boolean; start: number; items: string[] };\n\nfunction parseList(lines: string[]): ParsedList | null {\n const first = LIST_ITEM.exec(lines[0] ?? \"\");\n if (!first) return null;\n const base = first[1]!.length;\n const marker = first[2]!;\n const ordered = /^\\d/.test(marker);\n // Everything indented at least as far as the first item's text belongs to\n // that item — its wrapped lines, its paragraphs, and any list nested under it.\n const strip = new RegExp(`^ {0,${base + marker.length + 1}}`);\n\n const items: string[][] = [];\n for (const line of lines) {\n const m = LIST_ITEM.exec(line);\n if (m && m[1]!.length <= base) {\n items.push([m[3]!]);\n continue;\n }\n if (!items.length) return null;\n items[items.length - 1]!.push(line.replace(strip, \"\"));\n }\n\n return { ordered, start: ordered ? Number.parseInt(marker, 10) : 1, items: items.map((l) => l.join(\"\\n\")) };\n}\n\n/**\n * One item's interior.\n *\n * A single-paragraph item stays tight — `<li>text</li>`, not\n * `<li><p>text</p></li>` — because the paragraph margin inside a list item is\n * the classic \"why is my list double-spaced\" bug. Anything with a blank line or\n * a nested list goes back through the block pipeline, which is where nesting\n * comes from.\n *\n * A task item (`[ ] todo`, `[x] done`) gets a checkbox that is shown and cannot be changed:\n * the reader is looking at an answer, not filling in a form. In a tight item the checkbox and\n * the text share a `<label>`, which is what names the box for a screen reader.\n */\nfunction renderItem(item: string, depth: number, ctx: Ctx): { html: string; task: boolean } {\n const mark = TASK_MARK.exec(item);\n const body = mark ? item.slice(mark[0].length) : item;\n const lines = body.replace(/\\s+$/, \"\").split(\"\\n\");\n const nestedAt = lines.findIndex((l, i) => i > 0 && LIST_ITEM.test(l));\n const head = (nestedAt === -1 ? lines : lines.slice(0, nestedAt)).filter((l) => l.trim() !== \"\");\n const rest = nestedAt === -1 ? [] : lines.slice(nestedAt);\n const loose = /\\n[ \\t]*\\n/.test(body.trim());\n\n const headHtml = head.length\n ? loose\n ? renderSource(head.join(\"\\n\"), depth + 1, ctx)\n : inline(head.join(\" \").trim(), ctx)\n : \"\";\n const nested = rest.length ? renderSource(rest.join(\"\\n\"), depth + 1, ctx) : \"\";\n if (!mark) return { html: headHtml + nested, task: false };\n\n const checked = mark[1] !== \" \" ? \" checked\" : \"\";\n const box = `<input type=\"checkbox\" disabled${checked}`;\n return {\n html: (loose ? `${box} aria-label=\"[${mark[1]}]\">${headHtml}` : `<label>${box}> ${headHtml}</label>`) + nested,\n task: true,\n };\n}\n\nfunction renderList(lines: string[], depth: number, ctx: Ctx): string | null {\n const parsed = parseList(lines);\n if (!parsed) return null;\n const items = parsed.items\n .map((item) => {\n const { html, task } = renderItem(item, depth, ctx);\n return `<li${task ? ' class=\"sc-md-task\"' : \"\"}>${html}</li>`;\n })\n .join(\"\");\n if (!parsed.ordered) return `<ul>${items}</ul>`;\n return `<ol${parsed.start !== 1 ? ` start=\"${parsed.start}\"` : \"\"}>${items}</ol>`;\n}\n\n// ── Prose ────────────────────────────────────────────────────────────────────\n\nconst QUOTE_MARK = /^ {0,3}> ?/;\nconst THEMATIC_BREAK = /^ {0,3}(?:-{3,}|\\*{3,}|_{3,})\\s*$/;\nconst SETEXT = /^ {0,3}(=+|-+)\\s*$/;\n// Headings shift down one: the card or page owns the h1, so a document's own\n// `#` must not compete with it for the document outline a screen reader builds.\nconst ATX = /^ {0,3}(#{1,6})\\s+(.*?)\\s*#*\\s*$/;\n// A paragraph that is nothing but `$$ … $$`, which may span lines.\nconst DISPLAY_MATH = /^\\s*\\$\\$([\\s\\S]+?)\\$\\$\\s*$/;\n\nfunction renderProse(lines: string[], ctx: Ctx): string {\n const out: string[] = [];\n let para: string[] = [];\n const flush = () => {\n if (!para.length) return;\n const display = ctx.math ? DISPLAY_MATH.exec(para.join(\"\\n\")) : null;\n const typeset = display ? ctx.math!(display[1]!.trim(), true) : undefined;\n out.push(\n typeset !== undefined\n ? `<div class=\"sc-math-block\">${typeset}</div>`\n : `<p>${para.map((l) => inline(l, ctx)).join(\"<br/>\")}</p>`,\n );\n para = [];\n };\n\n for (const line of lines) {\n const h = ATX.exec(line);\n if (h) {\n flush();\n const level = Math.min(h[1]!.length + 1, 6);\n out.push(`<h${level}>${inline(h[2]!, ctx)}</h${level}>`);\n continue;\n }\n para.push(line);\n }\n flush();\n return out.join(\"\");\n}\n\nfunction renderTextBlock(raw: string, depth: number, ctx: Ctx): string {\n if (isPlainProse(raw, ctx)) {\n // Escaping still happens — safety is not what the shortcut skips.\n return `<p>${escapeHtml(raw).replace(/\\n/g, \"<br/>\")}</p>`;\n }\n\n const lines = raw.split(\"\\n\");\n\n const table = renderTable(lines, ctx);\n if (table) return table;\n\n if (depth < MAX_DEPTH && QUOTE_MARK.test(lines[0]!)) {\n const inner = lines.map((l) => l.replace(QUOTE_MARK, \"\")).join(\"\\n\");\n return `<blockquote>${renderSource(inner, depth + 1, ctx)}</blockquote>`;\n }\n\n if (depth < MAX_DEPTH) {\n const list = renderList(lines, depth, ctx);\n if (list) return list;\n }\n\n if (lines.length === 1 && THEMATIC_BREAK.test(lines[0]!)) return \"<hr/>\";\n\n // Setext: the underline belongs to the lines above it, and reading it as a\n // paragraph followed by a rule is the wrong document — the title stops being\n // a heading, which is exactly what the outline is built from.\n const last = lines[lines.length - 1]!;\n if (lines.length >= 2 && SETEXT.test(last)) {\n const level = last.trim().startsWith(\"=\") ? 2 : 3;\n const text = lines.slice(0, -1).join(\" \").trim();\n return `<h${level}>${inline(text, ctx)}</h${level}>`;\n }\n\n return renderProse(lines, ctx);\n}\n\n// ── Assembly ─────────────────────────────────────────────────────────────────\n\nfunction renderBlock(src: string, block: MarkdownBlock, depth: number, ctx: Ctx): string {\n const raw = src.slice(block.start, block.end);\n if (block.kind === \"fence\") return renderFence(raw, ctx);\n if (block.kind === \"code\") return renderIndentedCode(raw, ctx);\n return renderTextBlock(raw, depth, ctx);\n}\n\n/** Split and render a source, with no anchors. Also the recursion step. */\nfunction renderSource(src: string, depth: number, ctx: Ctx): string {\n return splitBlocks(src)\n .map((b) => renderBlock(src, b, depth, ctx))\n .join(\"\");\n}\n\n/** Render for the transcript: no anchors, because chat prose is not addressed. */\nexport function renderMarkdown(src: string, options?: MarkdownOptions): string {\n return renderSource(src, 0, contextOf(options));\n}\n\n/** What renderMarkdownStream keeps between calls. Start from newMarkdownStream(). */\nexport type MarkdownStream = {\n /** The source the cached blocks were decided on; valid while the text starts with it. */\n settled: string;\n /** Rendered HTML of those blocks, one string each, in order. They never change once here. */\n parts: string[];\n /** Where the block after them starts looking: the line after the last one. */\n resume: number;\n /** The options the cache was rendered with; a different set starts it over. */\n options: MarkdownOptions | undefined;\n};\n\nexport const newMarkdownStream = (): MarkdownStream => ({ settled: \"\", parts: [], resume: 0, options: undefined });\n\n/**\n * renderMarkdown for text that grows while it is shown — always the same\n * HTML renderMarkdown(src) returns, but blocks that can no longer change are\n * rendered once and reused, so a streamed answer costs its open tail per\n * frame instead of its whole length.\n *\n * Returned block by block: the strings of blocks that cannot change again are the very same\n * strings from one call to the next, which is what lets `ProseHtml` leave their DOM alone\n * (and a selection inside them standing) while the tail grows.\n *\n * Every block renders from its own source slice alone, so the only question\n * is which blocks later text can still move. splitBlocks decides a block's\n * extent from its own lines and, at most, the first line of the block after\n * it: the blank line or fence opener that ends it, and for a list or quote the\n * next non-blank line, which may continue it. Whether a line is blank, a fence\n * opener or closer, a list item or a quote can change while it is the last,\n * unterminated line — `1` becomes `1.`, a closing ``` becomes ```js, ``` gains\n * a backtick and stops opening a fence, a blank line gets text. Every line\n * before the last is final. So a block is settled once the block after it\n * starts before the last line: a setext underline, a loose list's next item,\n * a table's delimiter row or the rest of an open fence all belong to the\n * block that is still open. (This renderer has no reference definitions,\n * footnotes or raw HTML blocks, the other constructs that reach back.) And\n * splitBlocks never looks behind the line it stands on, so splitting from the\n * line after the settled blocks yields the same blocks the whole text would.\n *\n * Text that does not start with `stream.settled` — a new run, an edit — drops\n * the cache and renders from scratch.\n */\nexport function renderMarkdownBlocks(src: string, stream: MarkdownStream, options?: MarkdownOptions): string[] {\n if (!src.startsWith(stream.settled) || stream.options !== options) {\n Object.assign(stream, newMarkdownStream());\n stream.options = options;\n }\n const ctx = contextOf(options);\n\n const from = stream.resume;\n const tail = src.slice(from);\n const blocks = splitBlocks(tail);\n const lastLine = src.lastIndexOf(\"\\n\") + 1 - from;\n const shown = stream.parts.slice();\n for (let i = 0; i < blocks.length; i += 1) {\n const rendered = renderBlock(tail, blocks[i]!, 0, ctx);\n shown.push(rendered);\n if (i + 1 < blocks.length && blocks[i + 1]!.start < lastLine) {\n stream.parts.push(rendered);\n stream.resume = from + blocks[i]!.end + 1;\n }\n }\n stream.settled = src.slice(0, lastLine + from);\n return shown;\n}\n\n/** `renderMarkdownBlocks`, joined: the string `renderMarkdown(src, options)` would give. */\nexport function renderMarkdownStream(src: string, stream: MarkdownStream, options?: MarkdownOptions): string {\n return renderMarkdownBlocks(src, stream, options).join(\"\");\n}\n\n/**\n * Render for a document previewer: every block carries `data-sc-block`, so a\n * DOM selection resolves to a source span by walking up to the nearest one.\n *\n * Kept separate from renderMarkdown rather than added as an option, because\n * assistant prose has nothing to address and the extra attributes would be\n * noise in every message bubble.\n */\nexport function renderMarkdownWithAnchors(src: string, options?: MarkdownOptions): AnchoredMarkdown {\n const ctx = contextOf(options);\n const blocks = splitBlocks(src);\n const html = blocks\n .map((block, i) => {\n const rendered = renderBlock(src, block, 0, ctx);\n // Every branch of renderBlock returns markup, so the first tag always\n // exists; the anchor rides on it instead of an extra wrapper element,\n // which keeps the DOM (and therefore .sc-prose's spacing rules) unchanged.\n return rendered.replace(/^(\\s*<[a-z][a-z0-9]*)/i, `$1 data-sc-block=\"${i}\"`);\n })\n .join(\"\");\n return { html, blocks };\n}\n","// A small syntax highlighter for the code a chat answer is most likely to contain.\n//\n// This is the default for fenced code, and it is deliberately modest: one lexer per language\n// family, no grammar, no scopes, a couple of kilobytes. A host that wants more (every language,\n// theme-grade accuracy) passes its own `highlight` to the Markdown renderer — highlight.js,\n// Shiki, anything that turns code into HTML — and this is not used at all. Bundling a real\n// highlighter would cost more than the whole Markdown renderer (highlight.js with seven\n// languages is about three times its size), which is why the choice is the host's.\n//\n// Input is code; output is HTML for the inside of `<code>`. Every character of the code is\n// escaped, and a token is a `<span class=\"sc-tok-X\">` around escaped text, so nothing the model\n// wrote can become markup. Each lexer is a single alternation tried left to right, with no\n// nested quantifiers, so a hostile string costs a linear scan.\n\nconst escape = (s: string) =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\n/** One alternation, and the token class each of its groups stands for (undefined = plain). */\ntype Lexer = { re: RegExp; classes: (string | undefined)[] };\n\nconst words = (list: string) => `\\\\b(?:${list.trim().split(/\\s+/).join(\"|\")})\\\\b`;\n\nconst STRING = `\"(?:[^\"\\\\\\\\\\\\n]|\\\\\\\\.)*\"?|'(?:[^'\\\\\\\\\\\\n]|\\\\\\\\.)*'?`;\nconst NUMBER = `\\\\b(?:0x[\\\\da-fA-F]+|\\\\d+(?:\\\\.\\\\d+)?(?:e[+-]?\\\\d+)?)\\\\b`;\n\nconst lexer = (groups: [cls: string | undefined, source: string][], flags = \"g\"): Lexer => ({\n re: new RegExp(groups.map(([, source]) => `(${source})`).join(\"|\"), flags),\n classes: groups.map(([cls]) => cls),\n});\n\nconst JS_WORDS = /* @__PURE__ */ words(`\n as async await break case catch class const continue debugger default delete do else enum export\n extends finally for from function if implements import in instanceof interface let new of package\n private protected public readonly return static super switch this throw try type typeof var void\n while with yield satisfies declare namespace abstract keyof\n`);\nconst LITERALS = /* @__PURE__ */ words(\"true false null undefined NaN Infinity None True False nil\");\n\nconst SOURCES: Record<string, () => Lexer> = {\n js: () => lexer([\n [\"c\", \"\\\\/\\\\/[^\\\\n]*|\\\\/\\\\*[\\\\s\\\\S]*?(?:\\\\*\\\\/|$)\"],\n [\"s\", `${STRING}|\\`(?:[^\\`\\\\\\\\]|\\\\\\\\[\\\\s\\\\S])*\\`?`],\n [\"k\", JS_WORDS],\n [\"l\", LITERALS],\n [\"n\", NUMBER],\n [\"f\", \"\\\\b[A-Za-z_$][\\\\w$]*(?=\\\\s*\\\\()\"],\n ]),\n py: () => lexer([\n [\"c\", \"#[^\\\\n]*\"],\n [\"s\", `(?:[rbfRBF]{0,2})(?:\"\"\"[\\\\s\\\\S]*?(?:\"\"\"|$)|'''[\\\\s\\\\S]*?(?:'''|$))|(?:[rbfRBF]{0,2})(?:${STRING})`],\n [\n \"k\",\n words(`\n and as assert async await break class continue def del elif else except finally for from global\n if import in is lambda nonlocal not or pass raise return try while with yield match case\n `),\n ],\n [\"l\", LITERALS],\n [\"n\", NUMBER],\n [\"f\", \"\\\\b[A-Za-z_]\\\\w*(?=\\\\s*\\\\()\"],\n ]),\n json: () => lexer([\n [\"p\", `\"(?:[^\"\\\\\\\\\\\\n]|\\\\\\\\.)*\"(?=\\\\s*:)`],\n [\"s\", `\"(?:[^\"\\\\\\\\\\\\n]|\\\\\\\\.)*\"?`],\n [\"l\", words(\"true false null\")],\n [\"n\", \"-?\\\\d+(?:\\\\.\\\\d+)?(?:[eE][+-]?\\\\d+)?\"],\n ]),\n sh: () => lexer([\n [\"c\", \"(?:^|(?<=\\\\s))#[^\\\\n]*\"],\n [\"s\", STRING],\n [\"v\", \"\\\\$(?:\\\\{[^}\\\\n]*\\\\}|[A-Za-z_]\\\\w*|[0-9?!#@*$])\"],\n [\"f\", \"(?:^|(?<=[;|&(]))[ \\\\t]*(?:sudo\\\\s+)?[A-Za-z_.\\\\/-][\\\\w./-]*\"],\n [\"a\", \"(?<=\\\\s)--?[A-Za-z][\\\\w-]*\"],\n [\"k\", words(\"if then else elif fi for while do done case esac function in export return exit\")],\n [\"n\", NUMBER],\n ], \"gm\"),\n sql: () => lexer(\n [\n [\"c\", \"--[^\\\\n]*|\\\\/\\\\*[\\\\s\\\\S]*?(?:\\\\*\\\\/|$)\"],\n [\"s\", \"'(?:[^']|'')*'?\"],\n [\n \"k\",\n words(`\n select from where and or not null is in as on join left right inner outer full cross group by\n order having limit offset insert into values update set delete create alter drop table index\n view distinct union all case when then else end exists between like ilike asc desc primary key\n foreign references default returning with\n `),\n ],\n [\"n\", NUMBER],\n [\"f\", \"\\\\b[A-Za-z_]\\\\w*(?=\\\\s*\\\\()\"],\n ],\n \"gi\",\n ),\n markup: () => lexer([\n [\"c\", \"<!--[\\\\s\\\\S]*?(?:-->|$)|\\\\/\\\\*[\\\\s\\\\S]*?(?:\\\\*\\\\/|$)\"],\n [\"s\", STRING],\n [\"k\", \"<\\\\/?[A-Za-z][\\\\w:-]*|\\\\/?>|@[A-Za-z-]+\"],\n [\"a\", \"\\\\b[A-Za-z-]+(?==)\"],\n [\"p\", \"(?<=[{;\\\\s])[a-z-]+(?=\\\\s*:)\"],\n [\"n\", \"#[\\\\da-fA-F]{3,8}\\\\b|\\\\b\\\\d+(?:\\\\.\\\\d+)?(?:px|em|rem|%|vh|vw|s|ms)?\\\\b\"],\n ]),\n yaml: () => lexer([\n [\"c\", \"(?:^|(?<=\\\\s))#[^\\\\n]*\"],\n [\"p\", \"^[ \\\\t-]*[\\\\w.\\\"'/-]+(?=\\\\s*:(?:\\\\s|$))\"],\n [\"s\", STRING],\n [\"l\", words(\"true false null yes no on off\")],\n [\"n\", NUMBER],\n ], \"gm\"),\n};\n\nconst ALIASES: Record<string, string> = {\n js: \"js\", jsx: \"js\", mjs: \"js\", cjs: \"js\", javascript: \"js\", ts: \"js\", tsx: \"js\", typescript: \"js\",\n py: \"py\", python: \"py\",\n json: \"json\", jsonc: \"json\", json5: \"json\",\n sh: \"sh\", bash: \"sh\", zsh: \"sh\", shell: \"sh\", console: \"sh\", shellsession: \"sh\",\n sql: \"sql\", psql: \"sql\", postgres: \"sql\", mysql: \"sql\", sqlite: \"sql\",\n html: \"markup\", xml: \"markup\", svg: \"markup\", css: \"markup\", scss: \"markup\", vue: \"markup\",\n yaml: \"yaml\", yml: \"yaml\", toml: \"yaml\",\n};\n\nconst built = new Map<string, Lexer | null>();\n/** Built on first use: a lexer with a lookbehind must not be able to stop the module loading. */\nfunction lexerFor(key: string): Lexer | null {\n if (!built.has(key)) {\n try {\n built.set(key, SOURCES[key]!());\n } catch {\n built.set(key, null);\n }\n }\n return built.get(key)!;\n}\n\nfunction run({ re, classes }: Lexer, code: string): string {\n let out = \"\";\n let last = 0;\n re.lastIndex = 0;\n for (let m = re.exec(code); m; m = re.exec(code)) {\n if (m[0] === \"\") {\n re.lastIndex += 1;\n continue;\n }\n let group = 1;\n while (group < m.length && m[group] === undefined) group += 1;\n const cls = classes[group - 1];\n out += escape(code.slice(last, m.index));\n out += cls ? `<span class=\"sc-tok-${cls}\">${escape(m[0])}</span>` : escape(m[0]);\n last = m.index + m[0].length;\n }\n return out + escape(code.slice(last));\n}\n\n/** A diff is read line by line: what was added, what was taken out, where the hunk is. */\nfunction diff(code: string): string {\n return code\n .split(\"\\n\")\n .map((line) => {\n const cls = /^(?:\\+\\+\\+|---)/.test(line) ? \"k\" : line.startsWith(\"+\") ? \"add\" : line.startsWith(\"-\") ? \"del\" : line.startsWith(\"@@\") ? \"k\" : \"\";\n return cls ? `<span class=\"sc-tok-${cls}\">${escape(line)}</span>` : escape(line);\n })\n .join(\"\\n\");\n}\n\n/** The languages the built-in highlighter knows, by every name it answers to. */\nexport const HIGHLIGHT_LANGUAGES: readonly string[] = /* @__PURE__ */ (() => [...Object.keys(ALIASES), \"diff\", \"patch\"])();\n\n/**\n * Highlight `code` written in `lang`, as HTML for the inside of `<code>`.\n * Returns `undefined` for a language it does not know, which leaves the code as plain text.\n */\nexport function highlightCode(code: string, lang: string): string | undefined {\n const name = lang.toLowerCase();\n if (name === \"diff\" || name === \"patch\") return diff(code);\n const key = ALIASES[name];\n const lex = key ? lexerFor(key) : null;\n return lex ? run(lex, code) : undefined;\n}\n","// Tables as text, for the clipboard.\n//\n// One implementation for every table the kit shows: the `table` card hands it formatted cells,\n// and a table inside rendered Markdown hands it the text of its cells. Cells arrive already as\n// the strings a reader sees; nothing here formats a value.\n\n/** Tabs and line breaks inside a cell become a space: TSV has no way to escape them. */\nconst flatten = (cell: string) => cell.replace(/[\\t\\r\\n]+/g, \" \");\n\n/** Header row and data rows, tab-separated — what a spreadsheet pastes into cells. */\nexport function tableToTsv(header: readonly string[], rows: readonly (readonly string[])[]): string {\n const line = (cells: readonly string[]) => cells.map(flatten).join(\"\\t\");\n return [line(header), ...rows.map(line)].join(\"\\n\");\n}\n\n/** A GitHub-flavoured Markdown table. A pipe in a cell is escaped; a line break becomes a space. */\nexport function tableToMarkdown(\n header: readonly string[],\n rows: readonly (readonly string[])[],\n align: readonly (\"left\" | \"center\" | \"right\" | null)[] = [],\n): string {\n const cell = (c: string) => flatten(c).replace(/\\|/g, \"\\\\|\").trim();\n const rule = header.map((_, i) => {\n const a = align[i];\n return a === \"center\" ? \":---:\" : a === \"right\" ? \"---:\" : a === \"left\" ? \":---\" : \"---\";\n });\n const line = (cells: readonly string[]) => `| ${header.map((_, i) => cell(cells[i] ?? \"\")).join(\" | \")} |`;\n return [line(header), `| ${rule.join(\" | \")} |`, ...rows.map(line)].join(\"\\n\");\n}\n"],"mappings":";AAmBO,IAAM,gBAA+B,EAAE,QAAQ,SAAS,UAAU,MAAM;AAE/E,SAAS,oBAAoB,QAAiB;AAC5C,SAAO;AAAA,IACL,SAAS,IAAI,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AM,OAAO,CAAC,UAA6B,KAAK,OAAO,IAAI,CAAC,GAAG,MAAM,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC,EAAE,KAAK,KAAK,CAAC;AACtG,SAAO,CAAC,KAAK,MAAM,GAAG,KAAK,KAAK,KAAK,KAAK,CAAC,MAAM,GAAG,KAAK,IAAI,IAAI,CAAC,EAAE,KAAK,IAAI;AAC/E;","names":[]}
1
+ {"version":3,"sources":["../src/format.ts","../src/export.ts","../src/markdown.ts","../src/highlight.ts","../src/table.ts"],"sourcesContent":["// Value formatting shared by every card renderer.\n//\n// Centralised because a table cell and a stat tile showing the same number in\n// different formats is the fastest way to make an interface look untrustworthy.\n\nimport type { CardValueFormat } from \"@supersolutions/super-chat-core\";\n\nexport type FormatOptions = {\n /** BCP 47 locale. Omitted means the viewer's own. */\n locale?: string;\n /** IANA time zone for `datetime` values. Omitted means the viewer's own. */\n timeZone?: string;\n};\n\n/**\n * Fixed settings for HTML rendered ahead of the browser. A build server and a\n * viewer rarely share a locale or time zone, so server output and the first\n * client render must both use these or hydration fails.\n */\nexport const STABLE_FORMAT: FormatOptions = { locale: \"en-US\", timeZone: \"UTC\" };\n\nfunction createNumberFormats(locale?: string) {\n return {\n compact: new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 2 }),\n plain: new Intl.NumberFormat(locale, { maximumFractionDigits: 6 }),\n pctWide: new Intl.NumberFormat(locale, { maximumFractionDigits: 1, useGrouping: false }),\n pctNarrow: new Intl.NumberFormat(locale, { maximumFractionDigits: 2, useGrouping: false }),\n };\n}\n\nconst numberFormats = new Map<string, ReturnType<typeof createNumberFormats>>();\n\nfunction numbersFor(locale?: string) {\n const key = locale ?? \"\";\n let formats = numberFormats.get(key);\n if (!formats) {\n formats = createNumberFormats(locale);\n numberFormats.set(key, formats);\n }\n return formats;\n}\n\n/**\n * A value as a number, or NaN. `Number(\"\")` is 0, `Number(true)` is 1 and `Number([5])` is 5: an empty cell, a flag or a list is\n * not a count, and showing it as \"0\" or \"$0.00\" tells the reader something the data does not.\n */\nfunction numeric(value: unknown): number {\n if (typeof value === \"number\") return value;\n if (typeof value === \"bigint\") return Number(value);\n if (typeof value === \"string\" && value.trim() !== \"\") return Number(value);\n return Number.NaN;\n}\n\n/** What to show for a value that is not the kind the format needs: the text of it, never `[object Object]`. */\nfunction plain(value: unknown): string {\n if (typeof value === \"string\" && value.trim() === \"\") return \"—\";\n if (typeof value === \"object\") {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n }\n return String(value);\n}\n\nexport function formatValue(value: unknown, format: CardValueFormat = \"text\", options: FormatOptions = {}): string {\n if (value == null) return \"—\";\n const { locale, timeZone } = options;\n const numbers = numbersFor(locale);\n\n switch (format) {\n case \"number\": {\n const n = numeric(value);\n if (!Number.isFinite(n)) return plain(value);\n // Compact only above 5 digits: \"12.3K\" is helpful, \"1.2K\" hides precision\n // people expect to see on small counts.\n return Math.abs(n) >= 100_000 ? numbers.compact.format(n) : numbers.plain.format(n);\n }\n case \"currency\": {\n const n = numeric(value);\n if (!Number.isFinite(n)) return plain(value);\n const abs = Math.abs(n);\n // Sub-cent values are common in crypto; fixed 2dp would render them as $0.00.\n const digits = abs >= 1 ? 2 : abs >= 0.01 ? 4 : 8;\n // A whole amount in the thousands reads as \"$48,200\". Forcing \".00\" onto\n // it is the machine-printed look; amounts with cents keep them.\n const min = abs >= 1000 && Number.isInteger(n) ? 0 : 2;\n return `$${n.toLocaleString(locale, { minimumFractionDigits: min, maximumFractionDigits: Math.max(min, digits) })}`;\n }\n case \"percent\": {\n const n = numeric(value);\n if (!Number.isFinite(n)) return plain(value);\n // One decimal at most (\"8.2%\", \"12%\"), two only below 1% where the\n // second digit is the signal (\"0.04%\"). A fixed \"8.20%\" is false precision.\n return `${(Math.abs(n) < 1 ? numbers.pctNarrow : numbers.pctWide).format(n)}%`;\n }\n case \"bytes\": {\n const n = numeric(value);\n if (!Number.isFinite(n)) return plain(value);\n const units = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\"];\n let i = 0;\n let v = n;\n while (v >= 1024 && i < units.length - 1) {\n v /= 1024;\n i += 1;\n }\n return `${v.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;\n }\n case \"duration\": {\n const ms = numeric(value);\n if (!Number.isFinite(ms)) return plain(value);\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;\n if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;\n return `${(ms / 3_600_000).toFixed(1)}h`;\n }\n case \"datetime\": {\n const d = typeof value === \"number\" ? new Date(value) : typeof value === \"string\" ? new Date(value) : new Date(Number.NaN);\n if (Number.isNaN(d.getTime())) return plain(value);\n return d.toLocaleString(locale, timeZone ? { timeZone, timeZoneName: \"short\" } : undefined);\n }\n case \"code\":\n case \"text\":\n default:\n return typeof value === \"object\" ? plain(value) : String(value);\n }\n}\n\nexport function formatDelta(delta: number, format: CardValueFormat = \"number\", options: FormatOptions = {}): string {\n // A true minus sign: the hyphen-minus is narrower and misaligns a column of\n // signed deltas against the plus signs above it.\n const sign = delta > 0 ? \"+\" : delta < 0 ? \"−\" : \"\";\n return `${sign}${formatValue(Math.abs(delta), format, options)}`;\n}\n\nexport const toneClass = (tone?: string): string => (tone && tone !== \"neutral\" ? ` sc-tone--${tone}` : \"\");\n\n/** Positive is not always good — but for a delta with no stated tone it is the useful default. */\nexport const deltaTone = (delta: number): \"positive\" | \"negative\" | \"neutral\" =>\n delta > 0 ? \"positive\" : delta < 0 ? \"negative\" : \"neutral\";\n\n/**\n * A URL that came from a model or a tool, made safe to put in an `href`: only http(s) links\n * pass, anything else (`javascript:`, `data:`, `vbscript:`, a relative path that could be read\n * as a scheme after whitespace tricks) comes back as `undefined` and the caller renders plain\n * text. React 19 refuses `javascript:` hrefs itself, but this package supports React 18, which\n * only warns and then navigates.\n */\nexport function safeHref(url: string | undefined | null): string | undefined {\n if (typeof url !== \"string\") return undefined;\n const trimmed = url.trim();\n // Browsers strip tab and newline characters inside a URL before parsing it, so\n // `java\\tscript:` is a javascript: URL; reject anything with control characters outright.\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(trimmed)) return undefined;\n return /^https?:\\/\\/[^\\s]+$/i.test(trimmed) ? trimmed : undefined;\n}\n","// Thread export.\n//\n// Markdown rather than JSON: the point of exporting a conversation is to read it\n// somewhere else or paste it into a ticket, and JSON serves neither. Cards are\n// rendered as their data, not as their markup — a table exported as HTML is\n// useless in a text file, but as a markdown table it survives.\n//\n// Sharing (a hosted link) is deliberately NOT here: it needs a backend the kit\n// does not have, and faking it with a data: URL would produce links that break\n// the moment they leave the browser.\n\nimport type { Card, ContentPart, Message } from \"@supersolutions/super-chat-core\";\n\n/** A code fence that the text inside cannot close: longer than any run of backticks in it. */\nfunction fence(text: string): string {\n let longest = 0;\n for (const run of text.match(/`+/g) ?? []) longest = Math.max(longest, run.length);\n return \"`\".repeat(Math.max(3, longest + 1));\n}\n\nfunction fenced(info: string, text: string): string {\n const f = fence(text);\n return `${f}${info}\\n${text}\\n${f}`;\n}\n\n/** One table cell: a `|` or a line break inside it would end the cell or the row. */\nfunction cell(value: unknown): string {\n let text: string;\n if (value === null || value === undefined) text = \"\";\n else if (typeof value === \"object\") {\n try {\n text = JSON.stringify(value);\n } catch {\n text = String(value);\n }\n } else text = String(value);\n return text.replace(/\\|/g, \"\\\\|\").replace(/\\r\\n|\\r|\\n/g, \"<br>\");\n}\n\nfunction cardToMarkdown(spec: Record<string, unknown>): string {\n const kind = String(spec.kind ?? \"unknown\");\n const title = spec.title ? `**${spec.title}**\\n\\n` : \"\";\n\n if (kind === \"table\" && Array.isArray(spec.columns) && Array.isArray(spec.rows)) {\n const cols = (spec.columns as unknown[]).filter((c): c is { key: string; label: string } => typeof c === \"object\" && c !== null);\n const rows = (spec.rows as unknown[]).filter((r): r is Record<string, unknown> => typeof r === \"object\" && r !== null);\n const head = `| ${cols.map((c) => cell(c.label)).join(\" | \")} |`;\n const rule = `| ${cols.map(() => \"---\").join(\" | \")} |`;\n const body = rows.map((r) => `| ${cols.map((c) => cell(r[c.key])).join(\" | \")} |`).join(\"\\n\");\n return `${title}${head}\\n${rule}\\n${body}`;\n }\n\n if (kind === \"markdown\" && typeof spec.body === \"string\") return `${title}${spec.body}`;\n if (kind === \"code\" && typeof spec.code === \"string\") {\n return `${title}${fenced(typeof spec.language === \"string\" ? spec.language : \"\", spec.code)}`;\n }\n if (kind === \"callout\" && typeof spec.body === \"string\") return `> ${title}${spec.body}`;\n\n // Everything else keeps its data rather than being dropped — an export that\n // silently omits a card is worse than one that is a little verbose.\n let json: string;\n try {\n json = JSON.stringify(spec, null, 2) ?? \"null\";\n } catch {\n json = \"(data that cannot be shown as JSON)\";\n }\n return `${title}${fenced(\"json\", json)}`;\n}\n\nfunction partToMarkdown(part: ContentPart): string | null {\n switch (part.type) {\n case \"text\":\n return part.text;\n case \"reasoning\":\n return `<details><summary>Reasoning</summary>\\n\\n${part.text}\\n\\n</details>`;\n case \"tool-call\":\n {\n let args: string;\n try {\n args = JSON.stringify(part.input ?? {}) ?? \"{}\";\n } catch {\n args = \"…\";\n }\n return `- \\`${part.name}(${args})\\``;\n }\n case \"tool-result\":\n return part.failure ? `- \\`${part.name}\\` failed: ${part.failure}` : null;\n case \"image\":\n return \"_(image)_\";\n case \"file\":\n return `_(file: ${part.filename ?? \"attachment\"})_`;\n case \"artifact\":\n if (!part.kind.startsWith(\"card:\")) return null;\n {\n const data = part.data as { spec?: Card[\"spec\"] } | null | undefined;\n const spec = (data?.spec ?? data) as unknown;\n return typeof spec === \"object\" && spec !== null && !Array.isArray(spec) ? cardToMarkdown(spec as Record<string, unknown>) : null;\n }\n default:\n return null;\n }\n}\n\n/** Render a thread as markdown. `title` becomes the H1 when given. */\nexport function threadToMarkdown(messages: readonly Message[], title?: string): string {\n const out: string[] = title ? [`# ${title}`, \"\"] : [];\n\n for (const m of messages) {\n if (m.role === \"system\") continue;\n const body = m.parts.map(partToMarkdown).filter(Boolean).join(\"\\n\\n\");\n if (!body) continue;\n const who = m.role === \"user\" ? \"You\" : m.role === \"tool\" ? \"Tools\" : \"Assistant\";\n // A stored `createdAt` that is not a time (a hand edit, a string, 1e21) would make `toISOString` throw a RangeError.\n const at = typeof m.createdAt === \"number\" ? new Date(m.createdAt) : undefined;\n const when = at && Number.isFinite(at.getTime()) ? ` · ${at.toISOString().slice(0, 16).replace(\"T\", \" \")}` : \"\";\n out.push(`## ${who}${when}`, \"\", body, \"\");\n }\n\n return out.join(\"\\n\").trimEnd() + \"\\n\";\n}\n\n/** Trigger a download of the thread as a `.md` file. */\nexport function downloadThread(messages: readonly Message[], filename = \"conversation.md\", title?: string): void {\n const blob = new Blob([threadToMarkdown(messages, title)], { type: \"text/markdown;charset=utf-8\" });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.click();\n // Revoking immediately can race the download in some browsers; one frame is\n // enough for the click to have been consumed.\n requestAnimationFrame(() => URL.revokeObjectURL(url));\n}\n","// Minimal markdown renderer for assistant text, markdown cards and document\n// artifacts.\n//\n// Deliberately not a full parser — a chat message or card body is short, and\n// pulling in a markdown library plus a sanitizer for this is disproportionate.\n//\n// It does now split into blocks before rendering, and that is not a stylistic\n// change. A document previewer has to answer \"the user selected this on screen;\n// where is it in the source?\", because that span is both what gets quoted into\n// the next request and what an edit has to anchor against. The previous shape —\n// escape the whole string, pull fences out into placeholders, then run a chain\n// of global regexes — destroyed source positions in its first statement.\n//\n// So the order is inverted: split on the RAW source and record offsets, then\n// escape and transform each block independently. Escaping per block rather than\n// up front is load-bearing, not tidiness: `&` → `&amp;` changes the string\n// length, so escaping first would shift every offset recorded afterwards. That\n// failure is invisible on screen — the page renders perfectly and the anchors\n// silently point at the wrong text — which is why markdown.test.ts asserts the\n// offsets round-trip rather than trusting the output to look right.\n//\n// ── Why it grew ──────────────────────────────────────────────────────────────\n//\n// The block set used to be headings, emphasis, code, links and bullet lists,\n// and for a chat bubble that is the right amount of renderer. A document\n// artifact changed the requirement under it: a document is a thing the user\n// KEEPS, reads in a previewer and downloads as `.md`, and a report whose table\n// renders as a column of literal pipes is not a document — it is the source of\n// one. Tables, quotes, ordered lists and indented code are not exotic; they are\n// what anyone writing a report reaches for in the first paragraph.\n//\n// The structure changed with the scope. A chain of global regexes over one\n// escaped string cannot tell a table from a paragraph, so each block is now\n// CLASSIFIED first and rendered by shape, and only the leaves run inline\n// transforms. Nesting (a list inside a quote, a quote inside a list) falls out\n// of rendering a block's interior through the same splitter, with a depth cap\n// so a pathological `> > > > …` cannot recurse without end.\n\nimport { splitBlocks, type MarkdownBlock } from \"@supersolutions/super-chat-core\";\nimport { highlightCode } from \"./highlight.js\";\n\n/**\n * What a host can change about how Markdown becomes HTML. Everything is optional, and the\n * defaults are the safe ones: no image is fetched, no maths is guessed at, code is coloured by\n * a small built-in highlighter.\n */\nexport type MarkdownOptions = {\n /**\n * Colour fenced code: `(code, lang) => html` for the inside of `<code>`, or `undefined` to\n * leave that block plain. The default knows JS/TS, JSON, Python, shell, SQL, HTML/CSS, YAML\n * and diffs; pass highlight.js or Shiki here for the rest, or `false` for none. The returned\n * HTML is inserted as it is, so it must come from code you trust.\n */\n highlight?: ((code: string, lang: string) => string | undefined) | false;\n /**\n * Typeset `$…$` and `$$…$$`: `(tex, display) => html`, or `undefined` to leave the source as\n * text. Without this, `$` is an ordinary character, so a price is never mistaken for maths.\n * The returned HTML is inserted as it is, so it must come from code you trust (KaTeX, Temml).\n */\n math?: (tex: string, display: boolean) => string | undefined;\n /**\n * What `![alt](https://…)` becomes. `\"link\"` (the default) is a link to the image: nothing is\n * fetched until the reader follows it, so a model cannot make a page load a URL it chose.\n * `\"embed\"` draws the picture, with lazy loading and no referrer.\n */\n images?: \"link\" | \"embed\";\n /**\n * Draw the buttons for code blocks and tables (copy, wrap, show all) as markup. They carry\n * `data-sc-act` and no words; `ProseHtml` in `super-chat-ui` gives them their labels and\n * answers them. Off by default so a plain `renderMarkdown` string has no dead buttons in it.\n */\n actions?: boolean;\n};\n\ntype Ctx = {\n highlight: ((code: string, lang: string) => string | undefined) | false;\n math: MarkdownOptions[\"math\"];\n embed: boolean;\n actions: boolean;\n};\n\nconst contextOf = (o: MarkdownOptions | undefined): Ctx => ({\n highlight: o?.highlight === undefined ? highlightCode : o.highlight,\n math: o?.math,\n embed: o?.images === \"embed\",\n actions: o?.actions === true,\n});\n\nexport type AnchoredMarkdown = {\n html: string;\n /** Index-aligned with the `data-sc-block` attribute on the rendered HTML. */\n blocks: MarkdownBlock[];\n};\n\n// Cheap pre-check carried over from main: with none of these characters\n// present, no heading, emphasis, code, link, list, quote or table rule below\n// could match, so the whole chain is skippable. Applied per BLOCK rather than\n// per document — one fenced snippet in an otherwise plain artifact should not\n// cost the other forty paragraphs their shortcut.\nconst MARKDOWN_SIGNIFICANT = /[`*_#[\\]>~|-]/;\n// Two constructs carry no character the test above would catch: an ordered\n// item, and a setext heading underlined with `=`. Adding `=` and the digits to\n// MARKDOWN_SIGNIFICANT would cost the shortcut on most prose, so they get their\n// own (equally cheap) look instead.\nconst ORDERED_ITEM = /^ {0,3}\\d{1,9}[.)]\\s/m;\nconst SETEXT_EQUALS = /\\n {0,3}=+[ \\t]*$/;\n\n// A bare URL and a character reference also have to be seen, and they carry none of the above.\nconst AUTOLINKABLE = /https?:\\/\\//;\nconst ENTITY = /&(?:[a-z][a-z\\d]{1,31}|#\\d{1,7}|#x[\\da-f]{1,6});/i;\n\nconst isPlainProse = (raw: string, ctx: Ctx) =>\n !MARKDOWN_SIGNIFICANT.test(raw) &&\n !ORDERED_ITEM.test(raw) &&\n !SETEXT_EQUALS.test(raw) &&\n !AUTOLINKABLE.test(raw) &&\n !ENTITY.test(raw) &&\n !(ctx.math && raw.includes(\"$\"));\n\n/** How deep a quote or list may nest before its interior is rendered flat. */\nconst MAX_DEPTH = 4;\n\n// Quotes are escaped because link URLs are interpolated into href=\"…\" — an\n// unescaped quote in a URL would close the attribute and open a new one\n// (browsers recover from the missing-whitespace parse error by reading\n// `\"onmouseover=\"…` as a fresh attribute).\n//\n// NUL is dropped here, at the one place every leaf is escaped, rather than only in\n// `inline`: the inline placeholders below are built from it, so it must never come from\n// the source, and code blocks and the plain-prose shortcut would otherwise let a raw\n// U+0000 through into the output. (Block offsets are computed on the raw source, so\n// removing it from the output moves no anchor.)\nconst escapeHtml = (s: string) =>\n s.replace(/\\0/g, \"\").replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\n// ── Inline ───────────────────────────────────────────────────────────────────\n\n/**\n * Escape, then transform. Every leaf goes through here and nothing else does.\n *\n * Code spans are lifted out FIRST and put back last, so `**not bold**` inside\n * backticks stays literal — the same protection fenced blocks get, which the\n * old chain gave only to fences. NUL is stripped from the input because the\n * placeholders are built from it; without that, text could forge one.\n */\n// Only http(s) links — a javascript: URL must never survive. The destination may\n// contain one level of balanced parentheses (`…/wiki/Foo_(bar)`), as CommonMark\n// allows; the two alternatives cannot match the same character, so there is no\n// backtracking blow-up on a hostile string.\n//\n// The other destination is a card reference, `ref:<card>?key=value&…` (super-protocol\n// docs/CARD-REFS.md). It is not a link: it becomes a span the host wires to a card, and it\n// stays plain text where no host does. The character set is the envelope's own, plus the `;`\n// that escaping gives `&`, so nothing in it can close an attribute or open a tag. The limits\n// are the parser's to enforce (a ref that breaks them degrades where it is used), not this\n// regex's; the bound here only keeps a hostile string from costing a long scan.\nconst LINK = /\\[((?:[^\\[\\]]|\\[[^\\[\\]]*\\])+)\\]\\((https?:\\/\\/(?:[^()\\s]|\\([^()\\s]*\\))+|ref:[A-Za-z0-9._:~%=&;?-]{1,3000})\\)/g;\n\n// An image: the destination follows the same rules as a link's, and only http(s) is one.\nconst IMAGE = /!\\[([^\\]]*)\\]\\((https?:\\/\\/(?:[^()\\s]|\\([^()\\s]*\\))+)\\)/g;\n// `<https://…>` (escaped, by now) and a bare URL. A URL stops at whitespace, at an escaped quote\n// or angle bracket, and at a parenthesis that is not part of a balanced pair, so a sentence\n// that ends with \"(see https://example.com)\" does not take the bracket with it.\nconst URL_BODY = String.raw`(?:(?!&(?:quot|lt|gt);)[^\\s\\0()]|\\([^\\s\\0()]*\\))+`;\nconst ANGLE_URL = /* @__PURE__ */ new RegExp(String.raw`&lt;(https?:\\/\\/${URL_BODY})&gt;`, \"g\");\nconst BARE_URL = /* @__PURE__ */ new RegExp(String.raw`(?<![\\w/=@])https?:\\/\\/${URL_BODY}`, \"g\");\n// Punctuation that ends a sentence, or the emphasis around a URL, is not part of it.\nconst URL_TAIL_CHARS = \".,;:!?*_~\";\n// A character reference in text stays one (`&amp;` shows `&`), and everything it can name is text.\nconst ESCAPED_ENTITY = /&amp;([a-z][a-z\\d]{1,31}|#\\d{1,7}|#x[\\da-f]{1,6});/gi;\n// `$$…$$`, then `$…$` where the opening `$` is followed and the closing one preceded by\n// something that is not a space, and the closing one is not followed by a digit or letter, so\n// \"costs $5 and $10\" is two prices and not a formula.\nconst MATH_DISPLAY = /\\$\\$([^\\0]+?)\\$\\$/g;\nconst MATH_INLINE = /(?<![\\\\$\\w])\\$(?=[^\\s$])((?:[^$\\n\\\\]|\\\\.)+?)(?<=[^\\s\\\\])\\$(?![\\d\\w$])/g;\n\n/**\n * The replacements below run one after another, so `*a **b* c**` comes out as `<em>a <strong>b</em> c</strong>`: tags that\n * cross. A browser repairs that when it parses the string, but the string itself is what tests, copy-as-HTML and anything\n * that walks it see. Where a closing tag is not the innermost open one, close the ones inside it first and open them again\n * after it, which is also what the browser's repair gives.\n */\nconst INLINE_TAG = /<(\\/?)(strong|em|del)>/g;\nfunction nest(html: string): string {\n const open: string[] = [];\n const out = html.replace(INLINE_TAG, (_all, close: string, tag: string) => {\n if (!close) {\n open.push(tag);\n return `<${tag}>`;\n }\n const at = open.lastIndexOf(tag);\n if (at < 0) return \"\";\n const inner = open.splice(at);\n inner.shift();\n open.push(...inner);\n return inner.reverse().map((t) => `</${t}>`).join(\"\") + `</${tag}>` + [...inner].reverse().map((t) => `<${t}>`).join(\"\");\n });\n return out + open.reverse().map((t) => `</${t}>`).join(\"\");\n}\n\n/** Strike-through, strong, emphasis. Runs on already-escaped text. */\nconst emphasize = (s: string) =>\n nest(s\n .replace(/~~([^~\\n]+)~~/g, \"<del>$1</del>\")\n .replace(/\\*\\*\\*(?=[^\\s*])([^*\\n]+?)\\*\\*\\*/g, \"<strong><em>$1</em></strong>\")\n .replace(/\\*\\*(?=\\S)((?:[^*]|\\*(?!\\*))+?)\\*\\*/g, \"<strong>$1</strong>\")\n .replace(/(^|[^\\w])__(?=\\S)((?:[^_]|_(?!_))+?)__(?!\\w)/g, \"$1<strong>$2</strong>\")\n .replace(/(^|[^*])\\*(?=[^\\s*])([^*\\n]*[^\\s*])\\*(?!\\*)/g, \"$1<em>$2</em>\")\n .replace(/(^|[^\\w])_(?=[^\\s_])([^_\\n]*[^\\s_])_(?![\\w])/g, \"$1<em>$2</em>\"));\n\nconst unescapeHtml = (s: string) =>\n s.replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").replace(/&quot;/g, '\"').replace(/&amp;/g, \"&\");\n\ntype Link = { text: string; url: string; ref: boolean; plain: boolean; image?: boolean };\n\nfunction inline(raw: string, ctx: Ctx): string {\n const spans: string[] = [];\n const spanSource: string[] = []; // what each code span looked like, for where it must stay literal\n let s = escapeHtml(raw);\n\n s = s.replace(/(`+)([\\s\\S]+?)\\1(?!`)/g, (all, _ticks, body: string) => {\n spans.push(body);\n spanSource.push(all);\n return `\\0${spans.length - 1}\\0`;\n });\n\n // Maths is lifted next, so its underscores and asterisks are not read as emphasis, and only\n // when the host supplied the typesetter: otherwise a `$` is a dollar sign.\n const maths: string[] = [];\n const mathSource: string[] = [];\n if (ctx.math) {\n const typeset = (tex: string, display: boolean, whole: string) => {\n const out = ctx.math!(unescapeHtml(tex).trim(), display);\n if (out === undefined) return whole;\n maths.push(out);\n mathSource.push(whole);\n return `\\0M${maths.length - 1}\\0`;\n };\n s = s.replace(MATH_DISPLAY, (all, tex: string) => typeset(tex, true, all));\n s = s.replace(MATH_INLINE, (all, tex: string) => typeset(tex, false, all));\n }\n\n // Links are lifted out the same way, BEFORE emphasis. Otherwise the emphasis rules\n // run over the destination too, and `…/a*b*c` becomes `href=\"…/a<em>b</em>c\"`: the\n // link silently points somewhere else. Only the link's text is emphasised.\n const links: Link[] = [];\n const lift = (link: Link) => {\n links.push(link);\n return `\\0L${links.length - 1}\\0`;\n };\n // A backtick pair inside a URL (or an image's alt text, which lands in an attribute) is part of\n // it, not a code span.\n const literalUrl = (url: string) =>\n url\n .replace(/\\0M(\\d+)\\0/g, (_m, i: string) => mathSource[Number(i)]!)\n .replace(/\\0(\\d+)\\0/g, (_m, i: string) => spanSource[Number(i)]!);\n\n s = s.replace(IMAGE, (_all, alt: string, url: string) =>\n lift({ text: literalUrl(alt), url: literalUrl(url), ref: false, plain: true, image: true }),\n );\n s = s.replace(LINK, (_all, text: string, url: string) => {\n const literal = literalUrl(url);\n return lift({ text, url: literal, ref: literal.startsWith(\"ref:\"), plain: false });\n });\n s = s.replace(ANGLE_URL, (_all, url: string) => lift({ text: url, url, ref: false, plain: true }));\n s = s.replace(BARE_URL, (all: string) => {\n let end = all.length;\n while (end > 0 && URL_TAIL_CHARS.includes(all[end - 1]!)) end -= 1; // a regex `[…]+$` is quadratic on \"a....x\"\n const url = all.slice(0, end);\n return lift({ text: url, url, ref: false, plain: true }) + all.slice(url.length);\n });\n\n s = emphasize(s.replace(ESCAPED_ENTITY, \"&$1;\"));\n\n // A link's text may hold another lifted construct (an image inside a link). Drawn from the\n // outside in, so the image can know it is inside one: an anchor never holds an anchor.\n const draw = (index: number, inside: boolean): string => {\n const link = links[index]!;\n const nest = (text: string) => text.replace(/\\0L(\\d+)\\0/g, (_all, j: string) => draw(Number(j), true));\n if (link.image) {\n const alt = link.text;\n if (ctx.embed) {\n return `<img class=\"sc-md-img\" src=\"${link.url}\" alt=\"${alt}\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\">`;\n }\n // A link to the picture, not the picture: the model chose this URL, and fetching it is\n // how a conversation leaks to a third party. The words stay readable and the `!` is gone.\n if (inside) return alt || link.url;\n return `<a class=\"sc-md-image\" href=\"${link.url}\" target=\"_blank\" rel=\"noopener noreferrer\">${alt || link.url}</a>`;\n }\n if (link.ref) return `<span class=\"sc-ref\" data-ref=\"${link.url}\">${nest(emphasize(link.text))}</span>`;\n return `<a href=\"${link.url}\" target=\"_blank\" rel=\"noopener noreferrer\">${nest(link.plain ? link.text : emphasize(link.text))}</a>`;\n };\n s = s.replace(/\\0L(\\d+)\\0/g, (_all, i: string) => draw(Number(i), false));\n\n return s\n .replace(/\\0M(\\d+)\\0/g, (_all, i: string) => maths[Number(i)]!)\n .replace(/\\0(\\d+)\\0/g, (_all, i: string) => `<code>${spans[Number(i)]}</code>`);\n}\n\n// ── Verbatim blocks ──────────────────────────────────────────────────────────\n\nconst CLOSING_FENCE = /^ {0,3}(?:`{3,}|~{3,})\\s*$/;\n// The first word of the info string, if it is a name and not prose: `js`, `c++`, `c#`, `shell-session`.\nconst FENCE_LANG = /^ {0,3}(?:`{3,}|~{3,})[ \\t]*([A-Za-z0-9][A-Za-z0-9_+#.-]{0,31})(?:[ \\t{].*)?$/;\n\n// Lines running on to a second row. Part of the markup, not a mask image or a decoration pass, so\n// it needs no stylesheet request and survives the page's strictest content security policy.\nconst WRAP_ICON =\n '<svg viewBox=\"0 0 16 16\" width=\"14\" height=\"14\" aria-hidden=\"true\"><path d=\"M2 4h12M2 8h8.5a2.5 2.5 0 0 1 0 5H8m0 0 1.6-1.6M8 13l1.6 1.6M2 12h2.5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>';\n\n/** The code, its language, and the buttons a host may wire, in one box. */\nfunction codeBox(source: string, lang: string, ctx: Ctx): string {\n // NUL never reaches a highlighter or the page, whichever of them writes the markup.\n const code = source.replace(/\\0/g, \"\");\n const colored = lang && ctx.highlight ? ctx.highlight(code, lang) : undefined;\n const body = colored ?? escapeHtml(code);\n const attr = lang ? ` data-lang=\"${lang}\"` : \"\";\n const pre = `<pre${attr} tabindex=\"0\"><code${lang ? ` class=\"language-${lang}\"` : \"\"}>${body}</code></pre>`;\n if (!ctx.actions) return pre;\n return (\n `<div class=\"sc-mdcode\"${attr}><div class=\"sc-mdcode__bar\"><span class=\"sc-mdcode__lang\">${lang}</span>` +\n `<span class=\"sc-mdcode__tools\"><button type=\"button\" class=\"sc-mdcode__btn\" data-sc-act=\"wrap\">${WRAP_ICON}</button>` +\n `<button type=\"button\" class=\"sc-mdcode__btn\" data-sc-act=\"copy\"></button></span></div>${pre}` +\n `<button type=\"button\" class=\"sc-mdcode__more\" data-sc-act=\"more\"></button></div>`\n );\n}\n\nfunction renderFence(raw: string, ctx: Ctx): string {\n // Drop the opening fence line (which may carry a language) and the closing\n // one if it is there — an unterminated fence has none. Content is escaped but\n // never sees an inline transform.\n const lines = raw.split(\"\\n\");\n const lang = (FENCE_LANG.exec(lines[0]!)?.[1] ?? \"\").toLowerCase();\n lines.shift();\n if (lines.length && CLOSING_FENCE.test(lines[lines.length - 1]!)) lines.pop();\n return codeBox(lines.join(\"\\n\"), lang, ctx);\n}\n\nfunction renderIndentedCode(raw: string, ctx: Ctx): string {\n const body = raw.split(\"\\n\").map((l) => l.replace(/^(?: {4}|\\t)/, \"\")).join(\"\\n\");\n return codeBox(body, \"\", ctx);\n}\n\n// ── Tables ───────────────────────────────────────────────────────────────────\n\ntype Align = \"left\" | \"center\" | \"right\" | null;\n\nconst DELIMITER_CELL = /^:?-+:?$/;\n\n/** Split a pipe row into cells, honouring `\\|` as a literal pipe. */\nfunction cellsOf(line: string): string[] {\n const trimmed = line.trim().replace(/^\\|/, \"\").replace(/\\|$/, \"\");\n return trimmed\n .split(/(?<!\\\\)\\|/)\n .map((c) => c.trim().replace(/\\\\\\|/g, \"|\"));\n}\n\nconst alignOf = (cell: string): Align => {\n const left = cell.startsWith(\":\");\n const right = cell.endsWith(\":\");\n return left && right ? \"center\" : right ? \"right\" : left ? \"left\" : null;\n};\n\nfunction renderTable(lines: string[], ctx: Ctx): string | null {\n if (lines.length < 2 || !lines[0]!.includes(\"|\")) return null;\n const delimiter = cellsOf(lines[1]!);\n if (!delimiter.length || !delimiter.every((c) => DELIMITER_CELL.test(c))) return null;\n\n const head = cellsOf(lines[0]!);\n if (head.length !== delimiter.length) return null;\n const align = delimiter.map(alignOf);\n\n // Alignment rides on a class rather than a style attribute: a host with a\n // strict CSP can ship this without allowing inline styles.\n const cell = (tag: \"th\" | \"td\", text: string, i: number) => {\n const a = align[i];\n return `<${tag}${a ? ` class=\"sc-md-${a}\"` : \"\"}>${inline(text, ctx)}</${tag}>`;\n };\n\n const body = lines\n .slice(2)\n .filter((l) => l.trim() !== \"\")\n .map((l) => {\n const row = cellsOf(l);\n // Short rows are padded and long ones cut, so a ragged table still lines\n // up under its header instead of leaking cells into a new column.\n const cells = Array.from({ length: head.length }, (_, i) => cell(\"td\", row[i] ?? \"\", i));\n return `<tr>${cells.join(\"\")}</tr>`;\n })\n .join(\"\");\n\n // The table scrolls inside a box of its own, and the box takes focus: a wide table is\n // otherwise unreachable by keyboard. (A `display:block` table would scroll without the box,\n // but a block table is no longer a table to some assistive technology.)\n const table =\n `<div class=\"sc-md-scroll\" tabindex=\"0\"><table class=\"sc-md-table\"><thead><tr>${head\n .map((h, i) => cell(\"th\", h, i))\n .join(\"\")}</tr></thead><tbody>${body}</tbody></table></div>`;\n if (!ctx.actions) return table;\n return (\n `<div class=\"sc-md-tablebox\"><div class=\"sc-md-tablebar\">` +\n `<button type=\"button\" class=\"sc-md-tablebtn\" data-sc-act=\"copy-tsv\"></button>` +\n `<button type=\"button\" class=\"sc-md-tablebtn\" data-sc-act=\"copy-md\"></button></div>${table}</div>`\n );\n}\n\n// ── Lists ────────────────────────────────────────────────────────────────────\n\nconst LIST_ITEM = /^(\\s*)([-*+]|\\d{1,9}[.)])[ \\t]+(.*)$/;\nconst TASK_MARK = /^\\[([ xX])\\][ \\t]+/;\n\ntype ParsedList = { ordered: boolean; start: number; items: string[] };\n\nfunction parseList(lines: string[]): ParsedList | null {\n const first = LIST_ITEM.exec(lines[0] ?? \"\");\n if (!first) return null;\n const base = first[1]!.length;\n const marker = first[2]!;\n const ordered = /^\\d/.test(marker);\n // Everything indented at least as far as the first item's text belongs to\n // that item — its wrapped lines, its paragraphs, and any list nested under it.\n const strip = new RegExp(`^ {0,${base + marker.length + 1}}`);\n\n const items: string[][] = [];\n for (const line of lines) {\n const m = LIST_ITEM.exec(line);\n if (m && m[1]!.length <= base) {\n items.push([m[3]!]);\n continue;\n }\n if (!items.length) return null;\n items[items.length - 1]!.push(line.replace(strip, \"\"));\n }\n\n return { ordered, start: ordered ? Number.parseInt(marker, 10) : 1, items: items.map((l) => l.join(\"\\n\")) };\n}\n\n/**\n * One item's interior.\n *\n * A single-paragraph item stays tight — `<li>text</li>`, not\n * `<li><p>text</p></li>` — because the paragraph margin inside a list item is\n * the classic \"why is my list double-spaced\" bug. Anything with a blank line or\n * a nested list goes back through the block pipeline, which is where nesting\n * comes from.\n *\n * A task item (`[ ] todo`, `[x] done`) gets a checkbox that is shown and cannot be changed:\n * the reader is looking at an answer, not filling in a form. In a tight item the checkbox and\n * the text share a `<label>`, which is what names the box for a screen reader.\n */\nfunction renderItem(item: string, depth: number, ctx: Ctx): { html: string; task: boolean } {\n const mark = TASK_MARK.exec(item);\n const body = mark ? item.slice(mark[0].length) : item;\n const lines = body.trimEnd().split(\"\\n\");\n const nestedAt = lines.findIndex((l, i) => i > 0 && LIST_ITEM.test(l));\n const head = (nestedAt === -1 ? lines : lines.slice(0, nestedAt)).filter((l) => l.trim() !== \"\");\n const rest = nestedAt === -1 ? [] : lines.slice(nestedAt);\n const loose = /\\n[ \\t]*\\n/.test(body.trim());\n\n const headHtml = head.length\n ? loose\n ? renderSource(head.join(\"\\n\"), depth + 1, ctx)\n : inline(head.join(\" \").trim(), ctx)\n : \"\";\n const nested = rest.length ? renderSource(rest.join(\"\\n\"), depth + 1, ctx) : \"\";\n if (!mark) return { html: headHtml + nested, task: false };\n\n const checked = mark[1] !== \" \" ? \" checked\" : \"\";\n const box = `<input type=\"checkbox\" disabled${checked}`;\n return {\n html: (loose ? `${box} aria-label=\"[${mark[1]}]\">${headHtml}` : `<label>${box}> ${headHtml}</label>`) + nested,\n task: true,\n };\n}\n\nfunction renderList(lines: string[], depth: number, ctx: Ctx): string | null {\n const parsed = parseList(lines);\n if (!parsed) return null;\n const items = parsed.items\n .map((item) => {\n const { html, task } = renderItem(item, depth, ctx);\n return `<li${task ? ' class=\"sc-md-task\"' : \"\"}>${html}</li>`;\n })\n .join(\"\");\n if (!parsed.ordered) return `<ul>${items}</ul>`;\n return `<ol${parsed.start !== 1 ? ` start=\"${parsed.start}\"` : \"\"}>${items}</ol>`;\n}\n\n// ── Prose ────────────────────────────────────────────────────────────────────\n\nconst QUOTE_MARK = /^ {0,3}> ?/;\nconst THEMATIC_BREAK = /^ {0,3}(?:-{3,}|\\*{3,}|_{3,})\\s*$/;\nconst SETEXT = /^ {0,3}(=+|-+)\\s*$/;\n// Headings shift down one: the card or page owns the h1, so a document's own\n// `#` must not compete with it for the document outline a screen reader builds.\nconst ATX_HEAD = /^ {0,3}(#{1,6})\\s+/;\n// The one-regex form of a heading, `^ {0,3}(#{1,6})\\s+(.*?)\\s*#*\\s*$`, backtracks without end on a line with a long run of\n// whitespace (20 000 spaces in a heading froze the page for minutes). It is kept only for the lines whose line terminators\n// make `.` stop early, which are rare, and bounded.\nconst ATX_SLOW = /^ {0,3}(#{1,6})\\s+(.*?)\\s*#*\\s*$/;\nconst ATX_SLOW_MAX = 2000;\nconst ODD_TERMINATOR = /[\\r\\u2028\\u2029]/;\n\n/** A heading's hashes and text, by one linear pass; null when the line is not a heading. */\nexport function atxHeading(line: string): { hashes: number; text: string } | null {\n if (ODD_TERMINATOR.test(line)) {\n if (line.length > ATX_SLOW_MAX) return null;\n const m = ATX_SLOW.exec(line);\n return m ? { hashes: m[1]!.length, text: m[2]! } : null;\n }\n const head = ATX_HEAD.exec(line);\n if (!head) return null;\n // The text ends before any whitespace, then any closing hashes, then any whitespace, at the end of the line.\n let end = line.length;\n const floor = head[0].length;\n const skip = (test: (c: string) => boolean) => {\n while (end > floor && test(line[end - 1]!)) end -= 1;\n };\n const space = (c: string) => /\\s/.test(c);\n skip(space);\n skip((c) => c === \"#\");\n skip(space);\n return { hashes: head[1]!.length, text: line.slice(floor, end) };\n}\n// A paragraph that is nothing but `$$ … $$`, which may span lines.\nconst DISPLAY_MATH = /^\\s*\\$\\$([\\s\\S]+?)\\$\\$\\s*$/;\n\nfunction renderProse(lines: string[], ctx: Ctx): string {\n const out: string[] = [];\n let para: string[] = [];\n const flush = () => {\n if (!para.length) return;\n const display = ctx.math ? DISPLAY_MATH.exec(para.join(\"\\n\")) : null;\n const typeset = display ? ctx.math!(display[1]!.trim(), true) : undefined;\n out.push(\n typeset !== undefined\n ? `<div class=\"sc-math-block\">${typeset}</div>`\n : `<p>${para.map((l) => inline(l, ctx)).join(\"<br/>\")}</p>`,\n );\n para = [];\n };\n\n for (const line of lines) {\n const h = atxHeading(line);\n if (h) {\n flush();\n const level = Math.min(h.hashes + 1, 6);\n out.push(`<h${level}>${inline(h.text, ctx)}</h${level}>`);\n continue;\n }\n para.push(line);\n }\n flush();\n return out.join(\"\");\n}\n\nfunction renderTextBlock(raw: string, depth: number, ctx: Ctx): string {\n if (isPlainProse(raw, ctx)) {\n // Escaping still happens — safety is not what the shortcut skips.\n return `<p>${escapeHtml(raw).replace(/\\n/g, \"<br/>\")}</p>`;\n }\n\n const lines = raw.split(\"\\n\");\n\n const table = renderTable(lines, ctx);\n if (table) return table;\n\n if (depth < MAX_DEPTH && QUOTE_MARK.test(lines[0]!)) {\n const inner = lines.map((l) => l.replace(QUOTE_MARK, \"\")).join(\"\\n\");\n return `<blockquote>${renderSource(inner, depth + 1, ctx)}</blockquote>`;\n }\n\n if (depth < MAX_DEPTH) {\n const list = renderList(lines, depth, ctx);\n if (list) return list;\n }\n\n if (lines.length === 1 && THEMATIC_BREAK.test(lines[0]!)) return \"<hr/>\";\n\n // Setext: the underline belongs to the lines above it, and reading it as a\n // paragraph followed by a rule is the wrong document — the title stops being\n // a heading, which is exactly what the outline is built from.\n const last = lines[lines.length - 1]!;\n if (lines.length >= 2 && SETEXT.test(last)) {\n const level = last.trim().startsWith(\"=\") ? 2 : 3;\n const text = lines.slice(0, -1).join(\" \").trim();\n return `<h${level}>${inline(text, ctx)}</h${level}>`;\n }\n\n return renderProse(lines, ctx);\n}\n\n// ── Assembly ─────────────────────────────────────────────────────────────────\n\nfunction renderBlock(src: string, block: MarkdownBlock, depth: number, ctx: Ctx): string {\n const raw = src.slice(block.start, block.end);\n if (block.kind === \"fence\") return renderFence(raw, ctx);\n if (block.kind === \"code\") return renderIndentedCode(raw, ctx);\n return renderTextBlock(raw, depth, ctx);\n}\n\n/** Split and render a source, with no anchors. Also the recursion step. */\nfunction renderSource(src: string, depth: number, ctx: Ctx): string {\n return splitBlocks(src)\n .map((b) => renderBlock(src, b, depth, ctx))\n .join(\"\");\n}\n\n/** Render for the transcript: no anchors, because chat prose is not addressed. */\nexport function renderMarkdown(src: string, options?: MarkdownOptions): string {\n return renderSource(src, 0, contextOf(options));\n}\n\n/** What renderMarkdownStream keeps between calls. Start from newMarkdownStream(). */\nexport type MarkdownStream = {\n /** The source the cached blocks were decided on; valid while the text starts with it. */\n settled: string;\n /** Rendered HTML of those blocks, one string each, in order. They never change once here. */\n parts: string[];\n /** Where the block after them starts looking: the line after the last one. */\n resume: number;\n /** The options the cache was rendered with; a different set starts it over. */\n options: MarkdownOptions | undefined;\n};\n\nexport const newMarkdownStream = (): MarkdownStream => ({ settled: \"\", parts: [], resume: 0, options: undefined });\n\n/**\n * renderMarkdown for text that grows while it is shown — always the same\n * HTML renderMarkdown(src) returns, but blocks that can no longer change are\n * rendered once and reused, so a streamed answer costs its open tail per\n * frame instead of its whole length.\n *\n * Returned block by block: the strings of blocks that cannot change again are the very same\n * strings from one call to the next, which is what lets `ProseHtml` leave their DOM alone\n * (and a selection inside them standing) while the tail grows.\n *\n * Every block renders from its own source slice alone, so the only question\n * is which blocks later text can still move. splitBlocks decides a block's\n * extent from its own lines and, at most, the first line of the block after\n * it: the blank line or fence opener that ends it, and for a list or quote the\n * next non-blank line, which may continue it. Whether a line is blank, a fence\n * opener or closer, a list item or a quote can change while it is the last,\n * unterminated line — `1` becomes `1.`, a closing ``` becomes ```js, ``` gains\n * a backtick and stops opening a fence, a blank line gets text. Every line\n * before the last is final. So a block is settled once the block after it\n * starts before the last line: a setext underline, a loose list's next item,\n * a table's delimiter row or the rest of an open fence all belong to the\n * block that is still open. (This renderer has no reference definitions,\n * footnotes or raw HTML blocks, the other constructs that reach back.) And\n * splitBlocks never looks behind the line it stands on, so splitting from the\n * line after the settled blocks yields the same blocks the whole text would.\n *\n * Text that does not start with `stream.settled` — a new run, an edit — drops\n * the cache and renders from scratch.\n */\nexport function renderMarkdownBlocks(src: string, stream: MarkdownStream, options?: MarkdownOptions): string[] {\n if (!src.startsWith(stream.settled) || stream.options !== options) {\n Object.assign(stream, newMarkdownStream());\n stream.options = options;\n }\n const ctx = contextOf(options);\n\n const from = stream.resume;\n const tail = src.slice(from);\n const blocks = splitBlocks(tail);\n const lastLine = src.lastIndexOf(\"\\n\") + 1 - from;\n const shown = stream.parts.slice();\n for (let i = 0; i < blocks.length; i += 1) {\n const rendered = renderBlock(tail, blocks[i]!, 0, ctx);\n shown.push(rendered);\n if (i + 1 < blocks.length && blocks[i + 1]!.start < lastLine) {\n stream.parts.push(rendered);\n stream.resume = from + blocks[i]!.end + 1;\n }\n }\n stream.settled = src.slice(0, lastLine + from);\n return shown;\n}\n\n/** `renderMarkdownBlocks`, joined: the string `renderMarkdown(src, options)` would give. */\nexport function renderMarkdownStream(src: string, stream: MarkdownStream, options?: MarkdownOptions): string {\n return renderMarkdownBlocks(src, stream, options).join(\"\");\n}\n\n/**\n * Render for a document previewer: every block carries `data-sc-block`, so a\n * DOM selection resolves to a source span by walking up to the nearest one.\n *\n * Kept separate from renderMarkdown rather than added as an option, because\n * assistant prose has nothing to address and the extra attributes would be\n * noise in every message bubble.\n */\nexport function renderMarkdownWithAnchors(src: string, options?: MarkdownOptions): AnchoredMarkdown {\n const ctx = contextOf(options);\n const blocks = splitBlocks(src);\n const html = blocks\n .map((block, i) => {\n const rendered = renderBlock(src, block, 0, ctx);\n // Every branch of renderBlock returns markup, so the first tag always\n // exists; the anchor rides on it instead of an extra wrapper element,\n // which keeps the DOM (and therefore .sc-prose's spacing rules) unchanged.\n return rendered.replace(/^(\\s*<[a-z][a-z0-9]*)/i, `$1 data-sc-block=\"${i}\"`);\n })\n .join(\"\");\n return { html, blocks };\n}\n","// A small syntax highlighter for the code a chat answer is most likely to contain.\n//\n// This is the default for fenced code, and it is deliberately modest: one lexer per language\n// family, no grammar, no scopes, a couple of kilobytes. A host that wants more (every language,\n// theme-grade accuracy) passes its own `highlight` to the Markdown renderer — highlight.js,\n// Shiki, anything that turns code into HTML — and this is not used at all. Bundling a real\n// highlighter would cost more than the whole Markdown renderer (highlight.js with seven\n// languages is about three times its size), which is why the choice is the host's.\n//\n// Input is code; output is HTML for the inside of `<code>`. Every character of the code is\n// escaped, and a token is a `<span class=\"sc-tok-X\">` around escaped text, so nothing the model\n// wrote can become markup. Each lexer is a single alternation tried left to right, with no\n// nested quantifiers, so a hostile string costs a linear scan.\n\nconst escape = (s: string) =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n\n/** One alternation, and the token class each of its groups stands for (undefined = plain). */\ntype Lexer = { re: RegExp; classes: (string | undefined)[] };\n\nconst words = (list: string) => `\\\\b(?:${list.trim().split(/\\s+/).join(\"|\")})\\\\b`;\n\nconst STRING = `\"(?:[^\"\\\\\\\\\\\\n]|\\\\\\\\.)*\"?|'(?:[^'\\\\\\\\\\\\n]|\\\\\\\\.)*'?`;\nconst NUMBER = `\\\\b(?:0x[\\\\da-fA-F]+|\\\\d+(?:\\\\.\\\\d+)?(?:e[+-]?\\\\d+)?)\\\\b`;\n\nconst lexer = (groups: [cls: string | undefined, source: string][], flags = \"g\"): Lexer => ({\n re: new RegExp(groups.map(([, source]) => `(${source})`).join(\"|\"), flags),\n classes: groups.map(([cls]) => cls),\n});\n\nconst JS_WORDS = /* @__PURE__ */ words(`\n as async await break case catch class const continue debugger default delete do else enum export\n extends finally for from function if implements import in instanceof interface let new of package\n private protected public readonly return static super switch this throw try type typeof var void\n while with yield satisfies declare namespace abstract keyof\n`);\nconst LITERALS = /* @__PURE__ */ words(\"true false null undefined NaN Infinity None True False nil\");\n\nconst SOURCES: Record<string, () => Lexer> = {\n js: () => lexer([\n [\"c\", \"\\\\/\\\\/[^\\\\n]*|\\\\/\\\\*[\\\\s\\\\S]*?(?:\\\\*\\\\/|$)\"],\n [\"s\", `${STRING}|\\`(?:[^\\`\\\\\\\\]|\\\\\\\\[\\\\s\\\\S])*\\`?`],\n [\"k\", JS_WORDS],\n [\"l\", LITERALS],\n [\"n\", NUMBER],\n [\"f\", \"\\\\b[A-Za-z_$][\\\\w$]*(?=\\\\s*\\\\()\"],\n ]),\n py: () => lexer([\n [\"c\", \"#[^\\\\n]*\"],\n [\"s\", `(?:[rbfRBF]{0,2})(?:\"\"\"[\\\\s\\\\S]*?(?:\"\"\"|$)|'''[\\\\s\\\\S]*?(?:'''|$))|(?:[rbfRBF]{0,2})(?:${STRING})`],\n [\n \"k\",\n words(`\n and as assert async await break class continue def del elif else except finally for from global\n if import in is lambda nonlocal not or pass raise return try while with yield match case\n `),\n ],\n [\"l\", LITERALS],\n [\"n\", NUMBER],\n [\"f\", \"\\\\b[A-Za-z_]\\\\w*(?=\\\\s*\\\\()\"],\n ]),\n json: () => lexer([\n [\"p\", `\"(?:[^\"\\\\\\\\\\\\n]|\\\\\\\\.)*\"(?=\\\\s*:)`],\n [\"s\", `\"(?:[^\"\\\\\\\\\\\\n]|\\\\\\\\.)*\"?`],\n [\"l\", words(\"true false null\")],\n [\"n\", \"-?\\\\d+(?:\\\\.\\\\d+)?(?:[eE][+-]?\\\\d+)?\"],\n ]),\n sh: () => lexer([\n [\"c\", \"(?:^|(?<=\\\\s))#[^\\\\n]*\"],\n [\"s\", STRING],\n [\"v\", \"\\\\$(?:\\\\{[^}\\\\n]*\\\\}|[A-Za-z_]\\\\w*|[0-9?!#@*$])\"],\n [\"f\", \"(?:^|(?<=[;|&(]))[ \\\\t]*(?:sudo\\\\s+)?[A-Za-z_.\\\\/-][\\\\w./-]*\"],\n [\"a\", \"(?<=\\\\s)--?[A-Za-z][\\\\w-]*\"],\n [\"k\", words(\"if then else elif fi for while do done case esac function in export return exit\")],\n [\"n\", NUMBER],\n ], \"gm\"),\n sql: () => lexer(\n [\n [\"c\", \"--[^\\\\n]*|\\\\/\\\\*[\\\\s\\\\S]*?(?:\\\\*\\\\/|$)\"],\n [\"s\", \"'(?:[^']|'')*'?\"],\n [\n \"k\",\n words(`\n select from where and or not null is in as on join left right inner outer full cross group by\n order having limit offset insert into values update set delete create alter drop table index\n view distinct union all case when then else end exists between like ilike asc desc primary key\n foreign references default returning with\n `),\n ],\n [\"n\", NUMBER],\n [\"f\", \"\\\\b[A-Za-z_]\\\\w*(?=\\\\s*\\\\()\"],\n ],\n \"gi\",\n ),\n markup: () => lexer([\n [\"c\", \"<!--[\\\\s\\\\S]*?(?:-->|$)|\\\\/\\\\*[\\\\s\\\\S]*?(?:\\\\*\\\\/|$)\"],\n [\"s\", STRING],\n [\"k\", \"<\\\\/?[A-Za-z][\\\\w:-]*|\\\\/?>|@[A-Za-z-]+\"],\n [\"a\", \"\\\\b[A-Za-z-]+(?==)\"],\n [\"p\", \"(?<=[{;\\\\s])[a-z-]+(?=\\\\s*:)\"],\n [\"n\", \"#[\\\\da-fA-F]{3,8}\\\\b|\\\\b\\\\d+(?:\\\\.\\\\d+)?(?:px|em|rem|%|vh|vw|s|ms)?\\\\b\"],\n ]),\n yaml: () => lexer([\n [\"c\", \"(?:^|(?<=\\\\s))#[^\\\\n]*\"],\n [\"p\", \"^[ \\\\t-]*[\\\\w.\\\"'/-]+(?=\\\\s*:(?:\\\\s|$))\"],\n [\"s\", STRING],\n [\"l\", words(\"true false null yes no on off\")],\n [\"n\", NUMBER],\n ], \"gm\"),\n};\n\nconst ALIASES: Record<string, string> = {\n js: \"js\", jsx: \"js\", mjs: \"js\", cjs: \"js\", javascript: \"js\", ts: \"js\", tsx: \"js\", typescript: \"js\",\n py: \"py\", python: \"py\",\n json: \"json\", jsonc: \"json\", json5: \"json\",\n sh: \"sh\", bash: \"sh\", zsh: \"sh\", shell: \"sh\", console: \"sh\", shellsession: \"sh\",\n sql: \"sql\", psql: \"sql\", postgres: \"sql\", mysql: \"sql\", sqlite: \"sql\",\n html: \"markup\", xml: \"markup\", svg: \"markup\", css: \"markup\", scss: \"markup\", vue: \"markup\",\n yaml: \"yaml\", yml: \"yaml\", toml: \"yaml\",\n};\n\nconst built = new Map<string, Lexer | null>();\n/** Built on first use: a lexer with a lookbehind must not be able to stop the module loading. */\nfunction lexerFor(key: string): Lexer | null {\n if (!built.has(key)) {\n try {\n built.set(key, SOURCES[key]!());\n } catch {\n built.set(key, null);\n }\n }\n return built.get(key)!;\n}\n\nfunction run({ re, classes }: Lexer, code: string): string {\n let out = \"\";\n let last = 0;\n re.lastIndex = 0;\n for (let m = re.exec(code); m; m = re.exec(code)) {\n if (m[0] === \"\") {\n re.lastIndex += 1;\n continue;\n }\n let group = 1;\n while (group < m.length && m[group] === undefined) group += 1;\n const cls = classes[group - 1];\n out += escape(code.slice(last, m.index));\n out += cls ? `<span class=\"sc-tok-${cls}\">${escape(m[0])}</span>` : escape(m[0]);\n last = m.index + m[0].length;\n }\n return out + escape(code.slice(last));\n}\n\n/** A diff is read line by line: what was added, what was taken out, where the hunk is. */\nfunction diff(code: string): string {\n return code\n .split(\"\\n\")\n .map((line) => {\n const cls = /^(?:\\+\\+\\+|---)/.test(line) ? \"k\" : line.startsWith(\"+\") ? \"add\" : line.startsWith(\"-\") ? \"del\" : line.startsWith(\"@@\") ? \"k\" : \"\";\n return cls ? `<span class=\"sc-tok-${cls}\">${escape(line)}</span>` : escape(line);\n })\n .join(\"\\n\");\n}\n\n/** The languages the built-in highlighter knows, by every name it answers to. */\nexport const HIGHLIGHT_LANGUAGES: readonly string[] = /* @__PURE__ */ (() => [...Object.keys(ALIASES), \"diff\", \"patch\"])();\n\n/**\n * Highlight `code` written in `lang`, as HTML for the inside of `<code>`.\n * Returns `undefined` for a language it does not know, which leaves the code as plain text.\n */\nexport function highlightCode(code: string, lang: string): string | undefined {\n const name = lang.toLowerCase();\n if (name === \"diff\" || name === \"patch\") return diff(code);\n const key = Object.hasOwn(ALIASES, name) ? ALIASES[name] : undefined;\n const lex = key ? lexerFor(key) : null;\n return lex ? run(lex, code) : undefined;\n}\n","// Tables as text, for the clipboard.\n//\n// One implementation for every table the kit shows: the `table` card hands it formatted cells,\n// and a table inside rendered Markdown hands it the text of its cells. Cells arrive already as\n// the strings a reader sees; nothing here formats a value.\n\n/** Tabs and line breaks inside a cell become a space: TSV has no way to escape them. */\nconst flatten = (cell: string) => cell.replace(/[\\t\\r\\n]+/g, \" \");\n\n/** Header row and data rows, tab-separated — what a spreadsheet pastes into cells. */\nexport function tableToTsv(header: readonly string[], rows: readonly (readonly string[])[]): string {\n const line = (cells: readonly string[]) => cells.map(flatten).join(\"\\t\");\n return [line(header), ...rows.map(line)].join(\"\\n\");\n}\n\n/** A GitHub-flavoured Markdown table. A pipe in a cell is escaped; a line break becomes a space. */\nexport function tableToMarkdown(\n header: readonly string[],\n rows: readonly (readonly string[])[],\n align: readonly (\"left\" | \"center\" | \"right\" | null)[] = [],\n): string {\n const cell = (c: string) => flatten(c).replace(/\\|/g, \"\\\\|\").trim();\n const rule = header.map((_, i) => {\n const a = align[i];\n return a === \"center\" ? \":---:\" : a === \"right\" ? \"---:\" : a === \"left\" ? \":---\" : \"---\";\n });\n const line = (cells: readonly string[]) => `| ${header.map((_, i) => cell(cells[i] ?? \"\")).join(\" | \")} |`;\n return [line(header), `| ${rule.join(\" | \")} |`, ...rows.map(line)].join(\"\\n\");\n}\n"],"mappings":";AAmBO,IAAM,gBAA+B,EAAE,QAAQ,SAAS,UAAU,MAAM;AAE/E,SAAS,oBAAoB,QAAiB;AAC5C,SAAO;AAAA,IACL,SAAS,IAAI,KAAK,aAAa,QAAQ,EAAE,UAAU,WAAW,uBAAuB,EAAE,CAAC;AAAA,IACxF,OAAO,IAAI,KAAK,aAAa,QAAQ,EAAE,uBAAuB,EAAE,CAAC;AAAA,IACjE,SAAS,IAAI,KAAK,aAAa,QAAQ,EAAE,uBAAuB,GAAG,aAAa,MAAM,CAAC;AAAA,IACvF,WAAW,IAAI,KAAK,aAAa,QAAQ,EAAE,uBAAuB,GAAG,aAAa,MAAM,CAAC;AAAA,EAC3F;AACF;AAEA,IAAM,gBAAgB,oBAAI,IAAoD;AAE9E,SAAS,WAAW,QAAiB;AACnC,QAAM,MAAM,UAAU;AACtB,MAAI,UAAU,cAAc,IAAI,GAAG;AACnC,MAAI,CAAC,SAAS;AACZ,cAAU,oBAAoB,MAAM;AACpC,kBAAc,IAAI,KAAK,OAAO;AAAA,EAChC;AACA,SAAO;AACT;AAMA,SAAS,QAAQ,OAAwB;AACvC,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,KAAK;AAClD,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,GAAI,QAAO,OAAO,KAAK;AACzE,SAAO,OAAO;AAChB;AAGA,SAAS,MAAM,OAAwB;AACrC,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,GAAI,QAAO;AAC7D,MAAI,OAAO,UAAU,UAAU;AAC7B,QA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EAAE,CAAC,EAAE,KAAK,KAAK,CAAC;AACtG,SAAO,CAAC,KAAK,MAAM,GAAG,KAAK,KAAK,KAAK,KAAK,CAAC,MAAM,GAAG,KAAK,IAAI,IAAI,CAAC,EAAE,KAAK,IAAI;AAC/E;","names":["run","nest","cell","cell"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supersolutions/super-chat-ui-core",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Framework-free helpers shared by superchat UI bindings: markdown rendering (incl. streaming), value formatting and thread export.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SUPER SOLUTION LABS INC",
@@ -44,7 +44,7 @@
44
44
  "access": "public"
45
45
  },
46
46
  "dependencies": {
47
- "@supersolutions/super-chat-core": "0.5.0"
47
+ "@supersolutions/super-chat-core": "0.6.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "tsup": "^8.3.5",