@supersolutions/super-chat-ui-core 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -31,29 +31,67 @@ declare function threadToMarkdown(messages: readonly Message[], title?: string):
31
31
  /** Trigger a download of the thread as a `.md` file. */
32
32
  declare function downloadThread(messages: readonly Message[], filename?: string, title?: string): void;
33
33
 
34
+ /**
35
+ * What a host can change about how Markdown becomes HTML. Everything is optional, and the
36
+ * defaults are the safe ones: no image is fetched, no maths is guessed at, code is coloured by
37
+ * a small built-in highlighter.
38
+ */
39
+ type MarkdownOptions = {
40
+ /**
41
+ * Colour fenced code: `(code, lang) => html` for the inside of `<code>`, or `undefined` to
42
+ * leave that block plain. The default knows JS/TS, JSON, Python, shell, SQL, HTML/CSS, YAML
43
+ * and diffs; pass highlight.js or Shiki here for the rest, or `false` for none. The returned
44
+ * HTML is inserted as it is, so it must come from code you trust.
45
+ */
46
+ highlight?: ((code: string, lang: string) => string | undefined) | false;
47
+ /**
48
+ * Typeset `$…$` and `$$…$$`: `(tex, display) => html`, or `undefined` to leave the source as
49
+ * text. Without this, `$` is an ordinary character, so a price is never mistaken for maths.
50
+ * The returned HTML is inserted as it is, so it must come from code you trust (KaTeX, Temml).
51
+ */
52
+ math?: (tex: string, display: boolean) => string | undefined;
53
+ /**
54
+ * What `![alt](https://…)` becomes. `"link"` (the default) is a link to the image: nothing is
55
+ * fetched until the reader follows it, so a model cannot make a page load a URL it chose.
56
+ * `"embed"` draws the picture, with lazy loading and no referrer.
57
+ */
58
+ images?: "link" | "embed";
59
+ /**
60
+ * Draw the buttons for code blocks and tables (copy, wrap, show all) as markup. They carry
61
+ * `data-sc-act` and no words; `ProseHtml` in `super-chat-ui` gives them their labels and
62
+ * answers them. Off by default so a plain `renderMarkdown` string has no dead buttons in it.
63
+ */
64
+ actions?: boolean;
65
+ };
34
66
  type AnchoredMarkdown = {
35
67
  html: string;
36
68
  /** Index-aligned with the `data-sc-block` attribute on the rendered HTML. */
37
69
  blocks: MarkdownBlock[];
38
70
  };
39
71
  /** Render for the transcript: no anchors, because chat prose is not addressed. */
40
- declare function renderMarkdown(src: string): string;
72
+ declare function renderMarkdown(src: string, options?: MarkdownOptions): string;
41
73
  /** What renderMarkdownStream keeps between calls. Start from newMarkdownStream(). */
42
74
  type MarkdownStream = {
43
75
  /** The source the cached blocks were decided on; valid while the text starts with it. */
44
76
  settled: string;
45
- /** Rendered HTML of those blocks. */
46
- html: string;
77
+ /** Rendered HTML of those blocks, one string each, in order. They never change once here. */
78
+ parts: string[];
47
79
  /** Where the block after them starts looking: the line after the last one. */
48
80
  resume: number;
81
+ /** The options the cache was rendered with; a different set starts it over. */
82
+ options: MarkdownOptions | undefined;
49
83
  };
50
84
  declare const newMarkdownStream: () => MarkdownStream;
51
85
  /**
52
86
  * renderMarkdown for text that grows while it is shown — always the same
53
- * string renderMarkdown(src) returns, but blocks that can no longer change are
87
+ * HTML renderMarkdown(src) returns, but blocks that can no longer change are
54
88
  * rendered once and reused, so a streamed answer costs its open tail per
55
89
  * frame instead of its whole length.
56
90
  *
91
+ * Returned block by block: the strings of blocks that cannot change again are the very same
92
+ * strings from one call to the next, which is what lets `ProseHtml` leave their DOM alone
93
+ * (and a selection inside them standing) while the tail grows.
94
+ *
57
95
  * Every block renders from its own source slice alone, so the only question
58
96
  * is which blocks later text can still move. splitBlocks decides a block's
59
97
  * extent from its own lines and, at most, the first line of the block after
@@ -73,7 +111,9 @@ declare const newMarkdownStream: () => MarkdownStream;
73
111
  * Text that does not start with `stream.settled` — a new run, an edit — drops
74
112
  * the cache and renders from scratch.
75
113
  */
76
- declare function renderMarkdownStream(src: string, stream: MarkdownStream): string;
114
+ declare function renderMarkdownBlocks(src: string, stream: MarkdownStream, options?: MarkdownOptions): string[];
115
+ /** `renderMarkdownBlocks`, joined: the string `renderMarkdown(src, options)` would give. */
116
+ declare function renderMarkdownStream(src: string, stream: MarkdownStream, options?: MarkdownOptions): string;
77
117
  /**
78
118
  * Render for a document previewer: every block carries `data-sc-block`, so a
79
119
  * DOM selection resolves to a source span by walking up to the nearest one.
@@ -82,6 +122,19 @@ declare function renderMarkdownStream(src: string, stream: MarkdownStream): stri
82
122
  * assistant prose has nothing to address and the extra attributes would be
83
123
  * noise in every message bubble.
84
124
  */
85
- declare function renderMarkdownWithAnchors(src: string): AnchoredMarkdown;
125
+ declare function renderMarkdownWithAnchors(src: string, options?: MarkdownOptions): AnchoredMarkdown;
126
+
127
+ /** The languages the built-in highlighter knows, by every name it answers to. */
128
+ declare const HIGHLIGHT_LANGUAGES: readonly string[];
129
+ /**
130
+ * Highlight `code` written in `lang`, as HTML for the inside of `<code>`.
131
+ * Returns `undefined` for a language it does not know, which leaves the code as plain text.
132
+ */
133
+ declare function highlightCode(code: string, lang: string): string | undefined;
134
+
135
+ /** Header row and data rows, tab-separated — what a spreadsheet pastes into cells. */
136
+ declare function tableToTsv(header: readonly string[], rows: readonly (readonly string[])[]): string;
137
+ /** A GitHub-flavoured Markdown table. A pipe in a cell is escaped; a line break becomes a space. */
138
+ declare function tableToMarkdown(header: readonly string[], rows: readonly (readonly string[])[], align?: readonly ("left" | "center" | "right" | null)[]): string;
86
139
 
87
- export { type AnchoredMarkdown, type FormatOptions, type MarkdownStream, STABLE_FORMAT, deltaTone, downloadThread, formatDelta, formatValue, newMarkdownStream, renderMarkdown, renderMarkdownStream, renderMarkdownWithAnchors, safeHref, threadToMarkdown, toneClass };
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 };
package/dist/index.js CHANGED
@@ -160,15 +160,201 @@ function downloadThread(messages, filename = "conversation.md", title) {
160
160
 
161
161
  // src/markdown.ts
162
162
  import { splitBlocks } from "@supersolutions/super-chat-core";
163
+
164
+ // src/highlight.ts
165
+ var escape = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
166
+ var words = (list) => `\\b(?:${list.trim().split(/\s+/).join("|")})\\b`;
167
+ var STRING = `"(?:[^"\\\\\\n]|\\\\.)*"?|'(?:[^'\\\\\\n]|\\\\.)*'?`;
168
+ var NUMBER = `\\b(?:0x[\\da-fA-F]+|\\d+(?:\\.\\d+)?(?:e[+-]?\\d+)?)\\b`;
169
+ var lexer = (groups, flags = "g") => ({
170
+ re: new RegExp(groups.map(([, source]) => `(${source})`).join("|"), flags),
171
+ classes: groups.map(([cls]) => cls)
172
+ });
173
+ var JS_WORDS = /* @__PURE__ */ words(`
174
+ as async await break case catch class const continue debugger default delete do else enum export
175
+ extends finally for from function if implements import in instanceof interface let new of package
176
+ private protected public readonly return static super switch this throw try type typeof var void
177
+ while with yield satisfies declare namespace abstract keyof
178
+ `);
179
+ var LITERALS = /* @__PURE__ */ words("true false null undefined NaN Infinity None True False nil");
180
+ var SOURCES = {
181
+ js: () => lexer([
182
+ ["c", "\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$)"],
183
+ ["s", `${STRING}|\`(?:[^\`\\\\]|\\\\[\\s\\S])*\`?`],
184
+ ["k", JS_WORDS],
185
+ ["l", LITERALS],
186
+ ["n", NUMBER],
187
+ ["f", "\\b[A-Za-z_$][\\w$]*(?=\\s*\\()"]
188
+ ]),
189
+ py: () => lexer([
190
+ ["c", "#[^\\n]*"],
191
+ ["s", `(?:[rbfRBF]{0,2})(?:"""[\\s\\S]*?(?:"""|$)|'''[\\s\\S]*?(?:'''|$))|(?:[rbfRBF]{0,2})(?:${STRING})`],
192
+ [
193
+ "k",
194
+ words(`
195
+ and as assert async await break class continue def del elif else except finally for from global
196
+ if import in is lambda nonlocal not or pass raise return try while with yield match case
197
+ `)
198
+ ],
199
+ ["l", LITERALS],
200
+ ["n", NUMBER],
201
+ ["f", "\\b[A-Za-z_]\\w*(?=\\s*\\()"]
202
+ ]),
203
+ json: () => lexer([
204
+ ["p", `"(?:[^"\\\\\\n]|\\\\.)*"(?=\\s*:)`],
205
+ ["s", `"(?:[^"\\\\\\n]|\\\\.)*"?`],
206
+ ["l", words("true false null")],
207
+ ["n", "-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?"]
208
+ ]),
209
+ sh: () => lexer([
210
+ ["c", "(?:^|(?<=\\s))#[^\\n]*"],
211
+ ["s", STRING],
212
+ ["v", "\\$(?:\\{[^}\\n]*\\}|[A-Za-z_]\\w*|[0-9?!#@*$])"],
213
+ ["f", "(?:^|(?<=[;|&(]))[ \\t]*(?:sudo\\s+)?[A-Za-z_.\\/-][\\w./-]*"],
214
+ ["a", "(?<=\\s)--?[A-Za-z][\\w-]*"],
215
+ ["k", words("if then else elif fi for while do done case esac function in export return exit")],
216
+ ["n", NUMBER]
217
+ ], "gm"),
218
+ sql: () => lexer(
219
+ [
220
+ ["c", "--[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$)"],
221
+ ["s", "'(?:[^']|'')*'?"],
222
+ [
223
+ "k",
224
+ words(`
225
+ select from where and or not null is in as on join left right inner outer full cross group by
226
+ order having limit offset insert into values update set delete create alter drop table index
227
+ view distinct union all case when then else end exists between like ilike asc desc primary key
228
+ foreign references default returning with
229
+ `)
230
+ ],
231
+ ["n", NUMBER],
232
+ ["f", "\\b[A-Za-z_]\\w*(?=\\s*\\()"]
233
+ ],
234
+ "gi"
235
+ ),
236
+ markup: () => lexer([
237
+ ["c", "<!--[\\s\\S]*?(?:-->|$)|\\/\\*[\\s\\S]*?(?:\\*\\/|$)"],
238
+ ["s", STRING],
239
+ ["k", "<\\/?[A-Za-z][\\w:-]*|\\/?>|@[A-Za-z-]+"],
240
+ ["a", "\\b[A-Za-z-]+(?==)"],
241
+ ["p", "(?<=[{;\\s])[a-z-]+(?=\\s*:)"],
242
+ ["n", "#[\\da-fA-F]{3,8}\\b|\\b\\d+(?:\\.\\d+)?(?:px|em|rem|%|vh|vw|s|ms)?\\b"]
243
+ ]),
244
+ yaml: () => lexer([
245
+ ["c", "(?:^|(?<=\\s))#[^\\n]*"],
246
+ ["p", `^[ \\t-]*[\\w."'/-]+(?=\\s*:(?:\\s|$))`],
247
+ ["s", STRING],
248
+ ["l", words("true false null yes no on off")],
249
+ ["n", NUMBER]
250
+ ], "gm")
251
+ };
252
+ var ALIASES = {
253
+ js: "js",
254
+ jsx: "js",
255
+ mjs: "js",
256
+ cjs: "js",
257
+ javascript: "js",
258
+ ts: "js",
259
+ tsx: "js",
260
+ typescript: "js",
261
+ py: "py",
262
+ python: "py",
263
+ json: "json",
264
+ jsonc: "json",
265
+ json5: "json",
266
+ sh: "sh",
267
+ bash: "sh",
268
+ zsh: "sh",
269
+ shell: "sh",
270
+ console: "sh",
271
+ shellsession: "sh",
272
+ sql: "sql",
273
+ psql: "sql",
274
+ postgres: "sql",
275
+ mysql: "sql",
276
+ sqlite: "sql",
277
+ html: "markup",
278
+ xml: "markup",
279
+ svg: "markup",
280
+ css: "markup",
281
+ scss: "markup",
282
+ vue: "markup",
283
+ yaml: "yaml",
284
+ yml: "yaml",
285
+ toml: "yaml"
286
+ };
287
+ var built = /* @__PURE__ */ new Map();
288
+ function lexerFor(key) {
289
+ if (!built.has(key)) {
290
+ try {
291
+ built.set(key, SOURCES[key]());
292
+ } catch {
293
+ built.set(key, null);
294
+ }
295
+ }
296
+ return built.get(key);
297
+ }
298
+ function run({ re, classes }, code) {
299
+ let out = "";
300
+ let last = 0;
301
+ re.lastIndex = 0;
302
+ for (let m = re.exec(code); m; m = re.exec(code)) {
303
+ if (m[0] === "") {
304
+ re.lastIndex += 1;
305
+ continue;
306
+ }
307
+ let group = 1;
308
+ while (group < m.length && m[group] === void 0) group += 1;
309
+ const cls = classes[group - 1];
310
+ out += escape(code.slice(last, m.index));
311
+ out += cls ? `<span class="sc-tok-${cls}">${escape(m[0])}</span>` : escape(m[0]);
312
+ last = m.index + m[0].length;
313
+ }
314
+ return out + escape(code.slice(last));
315
+ }
316
+ function diff(code) {
317
+ return code.split("\n").map((line) => {
318
+ const cls = /^(?:\+\+\+|---)/.test(line) ? "k" : line.startsWith("+") ? "add" : line.startsWith("-") ? "del" : line.startsWith("@@") ? "k" : "";
319
+ return cls ? `<span class="sc-tok-${cls}">${escape(line)}</span>` : escape(line);
320
+ }).join("\n");
321
+ }
322
+ var HIGHLIGHT_LANGUAGES = /* @__PURE__ */ (() => [...Object.keys(ALIASES), "diff", "patch"])();
323
+ function highlightCode(code, lang) {
324
+ const name = lang.toLowerCase();
325
+ if (name === "diff" || name === "patch") return diff(code);
326
+ const key = ALIASES[name];
327
+ const lex = key ? lexerFor(key) : null;
328
+ return lex ? run(lex, code) : void 0;
329
+ }
330
+
331
+ // src/markdown.ts
332
+ var contextOf = (o) => ({
333
+ highlight: o?.highlight === void 0 ? highlightCode : o.highlight,
334
+ math: o?.math,
335
+ embed: o?.images === "embed",
336
+ actions: o?.actions === true
337
+ });
163
338
  var MARKDOWN_SIGNIFICANT = /[`*_#[\]>~|-]/;
164
339
  var ORDERED_ITEM = /^ {0,3}\d{1,9}[.)]\s/m;
165
340
  var SETEXT_EQUALS = /\n {0,3}=+[ \t]*$/;
166
- var isPlainProse = (raw) => !MARKDOWN_SIGNIFICANT.test(raw) && !ORDERED_ITEM.test(raw) && !SETEXT_EQUALS.test(raw);
341
+ var AUTOLINKABLE = /https?:\/\//;
342
+ var ENTITY = /&(?:[a-z][a-z\d]{1,31}|#\d{1,7}|#x[\da-f]{1,6});/i;
343
+ var isPlainProse = (raw, ctx) => !MARKDOWN_SIGNIFICANT.test(raw) && !ORDERED_ITEM.test(raw) && !SETEXT_EQUALS.test(raw) && !AUTOLINKABLE.test(raw) && !ENTITY.test(raw) && !(ctx.math && raw.includes("$"));
167
344
  var MAX_DEPTH = 4;
168
345
  var escapeHtml = (s) => s.replace(/\0/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
169
- var LINK = /\[([^\]]+)\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+|ref:[A-Za-z0-9._:~%=&;?-]{1,3000})\)/g;
170
- var emphasize = (s) => s.replace(/~~([^~\n]+)~~/g, "<del>$1</del>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/(^|[^*])\*([^*\n]+)\*/g, "$1<em>$2</em>");
171
- function inline(raw) {
346
+ var LINK = /\[((?:[^\[\]]|\[[^\[\]]*\])+)\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+|ref:[A-Za-z0-9._:~%=&;?-]{1,3000})\)/g;
347
+ var IMAGE = /!\[([^\]]*)\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+)\)/g;
348
+ var URL_BODY = String.raw`(?:(?!&(?:quot|lt|gt);)[^\s\0()]|\([^\s\0()]*\))+`;
349
+ var ANGLE_URL = /* @__PURE__ */ new RegExp(String.raw`&lt;(https?:\/\/${URL_BODY})&gt;`, "g");
350
+ var BARE_URL = /* @__PURE__ */ new RegExp(String.raw`(?<![\w/=@])https?:\/\/${URL_BODY}`, "g");
351
+ var URL_TAIL = /[.,;:!?*_~]+$/;
352
+ var ESCAPED_ENTITY = /&amp;([a-z][a-z\d]{1,31}|#\d{1,7}|#x[\da-f]{1,6});/gi;
353
+ var MATH_DISPLAY = /\$\$([^\0]+?)\$\$/g;
354
+ 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>");
356
+ var unescapeHtml = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
357
+ function inline(raw, ctx) {
172
358
  const spans = [];
173
359
  const spanSource = [];
174
360
  let s = escapeHtml(raw);
@@ -177,31 +363,78 @@ function inline(raw) {
177
363
  spanSource.push(all);
178
364
  return `\0${spans.length - 1}\0`;
179
365
  });
366
+ const maths = [];
367
+ const mathSource = [];
368
+ if (ctx.math) {
369
+ const typeset = (tex, display, whole) => {
370
+ const out = ctx.math(unescapeHtml(tex).trim(), display);
371
+ if (out === void 0) return whole;
372
+ maths.push(out);
373
+ mathSource.push(whole);
374
+ return `\0M${maths.length - 1}\0`;
375
+ };
376
+ s = s.replace(MATH_DISPLAY, (all, tex) => typeset(tex, true, all));
377
+ s = s.replace(MATH_INLINE, (all, tex) => typeset(tex, false, all));
378
+ }
180
379
  const links = [];
181
- s = s.replace(LINK, (_all, text, url) => {
182
- const literal = url.replace(/\0(\d+)\0/g, (_m, i) => spanSource[Number(i)]);
183
- links.push({ text, url: literal, ref: literal.startsWith("ref:") });
380
+ const lift = (link) => {
381
+ links.push(link);
184
382
  return `\0L${links.length - 1}\0`;
383
+ };
384
+ const literalUrl = (url) => url.replace(/\0M(\d+)\0/g, (_m, i) => mathSource[Number(i)]).replace(/\0(\d+)\0/g, (_m, i) => spanSource[Number(i)]);
385
+ s = s.replace(
386
+ IMAGE,
387
+ (_all, alt, url) => lift({ text: literalUrl(alt), url: literalUrl(url), ref: false, plain: true, image: true })
388
+ );
389
+ s = s.replace(LINK, (_all, text, url) => {
390
+ const literal = literalUrl(url);
391
+ return lift({ text, url: literal, ref: literal.startsWith("ref:"), plain: false });
392
+ });
393
+ s = s.replace(ANGLE_URL, (_all, url) => lift({ text: url, url, ref: false, plain: true }));
394
+ s = s.replace(BARE_URL, (all) => {
395
+ const url = all.replace(URL_TAIL, "");
396
+ return lift({ text: url, url, ref: false, plain: true }) + all.slice(url.length);
185
397
  });
186
- s = emphasize(s).replace(
187
- /\0L(\d+)\0/g,
188
- (_all, i) => {
189
- const link = links[Number(i)];
190
- if (link.ref) return `<span class="sc-ref" data-ref="${link.url}">${emphasize(link.text)}</span>`;
191
- return `<a href="${link.url}" target="_blank" rel="noopener noreferrer">${emphasize(link.text)}</a>`;
398
+ s = emphasize(s.replace(ESCAPED_ENTITY, "&$1;"));
399
+ const draw = (index, inside) => {
400
+ const link = links[index];
401
+ const nest = (text) => text.replace(/\0L(\d+)\0/g, (_all, j) => draw(Number(j), true));
402
+ if (link.image) {
403
+ const alt = link.text;
404
+ if (ctx.embed) {
405
+ return `<img class="sc-md-img" src="${link.url}" alt="${alt}" loading="lazy" decoding="async" referrerpolicy="no-referrer">`;
406
+ }
407
+ if (inside) return alt || link.url;
408
+ return `<a class="sc-md-image" href="${link.url}" target="_blank" rel="noopener noreferrer">${alt || link.url}</a>`;
192
409
  }
193
- );
194
- return s.replace(/\0(\d+)\0/g, (_all, i) => `<code>${spans[Number(i)]}</code>`);
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>`;
412
+ };
413
+ s = s.replace(/\0L(\d+)\0/g, (_all, i) => draw(Number(i), false));
414
+ return s.replace(/\0M(\d+)\0/g, (_all, i) => maths[Number(i)]).replace(/\0(\d+)\0/g, (_all, i) => `<code>${spans[Number(i)]}</code>`);
195
415
  }
196
416
  var CLOSING_FENCE = /^ {0,3}(?:`{3,}|~{3,})\s*$/;
197
- function renderFence(raw) {
198
- const lines = raw.split("\n").slice(1);
417
+ var FENCE_LANG = /^ {0,3}(?:`{3,}|~{3,})[ \t]*([A-Za-z0-9][A-Za-z0-9_+#.-]{0,31})(?:[ \t{].*)?$/;
418
+ var WRAP_ICON = '<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>';
419
+ function codeBox(source, lang, ctx) {
420
+ const code = source.replace(/\0/g, "");
421
+ const colored = lang && ctx.highlight ? ctx.highlight(code, lang) : void 0;
422
+ const body = colored ?? escapeHtml(code);
423
+ const attr = lang ? ` data-lang="${lang}"` : "";
424
+ const pre = `<pre${attr}><code${lang ? ` class="language-${lang}"` : ""}>${body}</code></pre>`;
425
+ if (!ctx.actions) return pre;
426
+ 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
+ }
428
+ function renderFence(raw, ctx) {
429
+ const lines = raw.split("\n");
430
+ const lang = (FENCE_LANG.exec(lines[0])?.[1] ?? "").toLowerCase();
431
+ lines.shift();
199
432
  if (lines.length && CLOSING_FENCE.test(lines[lines.length - 1])) lines.pop();
200
- return `<pre><code>${escapeHtml(lines.join("\n"))}</code></pre>`;
433
+ return codeBox(lines.join("\n"), lang, ctx);
201
434
  }
202
- function renderIndentedCode(raw) {
435
+ function renderIndentedCode(raw, ctx) {
203
436
  const body = raw.split("\n").map((l) => l.replace(/^(?: {4}|\t)/, "")).join("\n");
204
- return `<pre><code>${escapeHtml(body)}</code></pre>`;
437
+ return codeBox(body, "", ctx);
205
438
  }
206
439
  var DELIMITER_CELL = /^:?-+:?$/;
207
440
  function cellsOf(line) {
@@ -213,7 +446,7 @@ var alignOf = (cell) => {
213
446
  const right = cell.endsWith(":");
214
447
  return left && right ? "center" : right ? "right" : left ? "left" : null;
215
448
  };
216
- function renderTable(lines) {
449
+ function renderTable(lines, ctx) {
217
450
  if (lines.length < 2 || !lines[0].includes("|")) return null;
218
451
  const delimiter = cellsOf(lines[1]);
219
452
  if (!delimiter.length || !delimiter.every((c) => DELIMITER_CELL.test(c))) return null;
@@ -222,16 +455,19 @@ function renderTable(lines) {
222
455
  const align = delimiter.map(alignOf);
223
456
  const cell = (tag, text, i) => {
224
457
  const a = align[i];
225
- return `<${tag}${a ? ` class="sc-md-${a}"` : ""}>${inline(text)}</${tag}>`;
458
+ return `<${tag}${a ? ` class="sc-md-${a}"` : ""}>${inline(text, ctx)}</${tag}>`;
226
459
  };
227
460
  const body = lines.slice(2).filter((l) => l.trim() !== "").map((l) => {
228
461
  const row = cellsOf(l);
229
462
  const cells = Array.from({ length: head.length }, (_, i) => cell("td", row[i] ?? "", i));
230
463
  return `<tr>${cells.join("")}</tr>`;
231
464
  }).join("");
232
- return `<table class="sc-md-table"><thead><tr>${head.map((h, i) => cell("th", h, i)).join("")}</tr></thead><tbody>${body}</tbody></table>`;
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>`;
466
+ if (!ctx.actions) return table;
467
+ 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>`;
233
468
  }
234
469
  var LIST_ITEM = /^(\s*)([-*+]|\d{1,9}[.)])[ \t]+(.*)$/;
470
+ var TASK_MARK = /^\[([ xX])\][ \t]+/;
235
471
  function parseList(lines) {
236
472
  const first = LIST_ITEM.exec(lines[0] ?? "");
237
473
  if (!first) return null;
@@ -251,19 +487,31 @@ function parseList(lines) {
251
487
  }
252
488
  return { ordered, start: ordered ? Number.parseInt(marker, 10) : 1, items: items.map((l) => l.join("\n")) };
253
489
  }
254
- function renderItem(item, depth) {
255
- const lines = item.replace(/\s+$/, "").split("\n");
490
+ function renderItem(item, depth, ctx) {
491
+ const mark = TASK_MARK.exec(item);
492
+ const body = mark ? item.slice(mark[0].length) : item;
493
+ const lines = body.replace(/\s+$/, "").split("\n");
256
494
  const nestedAt = lines.findIndex((l, i) => i > 0 && LIST_ITEM.test(l));
257
495
  const head = (nestedAt === -1 ? lines : lines.slice(0, nestedAt)).filter((l) => l.trim() !== "");
258
496
  const rest = nestedAt === -1 ? [] : lines.slice(nestedAt);
259
- const loose = /\n[ \t]*\n/.test(item.trim());
260
- const headHtml = head.length ? loose ? renderSource(head.join("\n"), depth + 1) : inline(head.join(" ").trim()) : "";
261
- return headHtml + (rest.length ? renderSource(rest.join("\n"), depth + 1) : "");
497
+ const loose = /\n[ \t]*\n/.test(body.trim());
498
+ const headHtml = head.length ? loose ? renderSource(head.join("\n"), depth + 1, ctx) : inline(head.join(" ").trim(), ctx) : "";
499
+ const nested = rest.length ? renderSource(rest.join("\n"), depth + 1, ctx) : "";
500
+ if (!mark) return { html: headHtml + nested, task: false };
501
+ const checked = mark[1] !== " " ? " checked" : "";
502
+ const box = `<input type="checkbox" disabled${checked}`;
503
+ return {
504
+ html: (loose ? `${box} aria-label="[${mark[1]}]">${headHtml}` : `<label>${box}> ${headHtml}</label>`) + nested,
505
+ task: true
506
+ };
262
507
  }
263
- function renderList(lines, depth) {
508
+ function renderList(lines, depth, ctx) {
264
509
  const parsed = parseList(lines);
265
510
  if (!parsed) return null;
266
- const items = parsed.items.map((item) => `<li>${renderItem(item, depth)}</li>`).join("");
511
+ const items = parsed.items.map((item) => {
512
+ const { html, task } = renderItem(item, depth, ctx);
513
+ return `<li${task ? ' class="sc-md-task"' : ""}>${html}</li>`;
514
+ }).join("");
267
515
  if (!parsed.ordered) return `<ul>${items}</ul>`;
268
516
  return `<ol${parsed.start !== 1 ? ` start="${parsed.start}"` : ""}>${items}</ol>`;
269
517
  }
@@ -271,12 +519,17 @@ var QUOTE_MARK = /^ {0,3}> ?/;
271
519
  var THEMATIC_BREAK = /^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/;
272
520
  var SETEXT = /^ {0,3}(=+|-+)\s*$/;
273
521
  var ATX = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
274
- function renderProse(lines) {
522
+ var DISPLAY_MATH = /^\s*\$\$([\s\S]+?)\$\$\s*$/;
523
+ function renderProse(lines, ctx) {
275
524
  const out = [];
276
525
  let para = [];
277
526
  const flush = () => {
278
527
  if (!para.length) return;
279
- out.push(`<p>${para.map(inline).join("<br/>")}</p>`);
528
+ const display = ctx.math ? DISPLAY_MATH.exec(para.join("\n")) : null;
529
+ const typeset = display ? ctx.math(display[1].trim(), true) : void 0;
530
+ out.push(
531
+ typeset !== void 0 ? `<div class="sc-math-block">${typeset}</div>` : `<p>${para.map((l) => inline(l, ctx)).join("<br/>")}</p>`
532
+ );
280
533
  para = [];
281
534
  };
282
535
  for (const line of lines) {
@@ -284,7 +537,7 @@ function renderProse(lines) {
284
537
  if (h) {
285
538
  flush();
286
539
  const level = Math.min(h[1].length + 1, 6);
287
- out.push(`<h${level}>${inline(h[2])}</h${level}>`);
540
+ out.push(`<h${level}>${inline(h[2], ctx)}</h${level}>`);
288
541
  continue;
289
542
  }
290
543
  para.push(line);
@@ -292,19 +545,19 @@ function renderProse(lines) {
292
545
  flush();
293
546
  return out.join("");
294
547
  }
295
- function renderTextBlock(raw, depth) {
296
- if (isPlainProse(raw)) {
548
+ function renderTextBlock(raw, depth, ctx) {
549
+ if (isPlainProse(raw, ctx)) {
297
550
  return `<p>${escapeHtml(raw).replace(/\n/g, "<br/>")}</p>`;
298
551
  }
299
552
  const lines = raw.split("\n");
300
- const table = renderTable(lines);
553
+ const table = renderTable(lines, ctx);
301
554
  if (table) return table;
302
555
  if (depth < MAX_DEPTH && QUOTE_MARK.test(lines[0])) {
303
556
  const inner = lines.map((l) => l.replace(QUOTE_MARK, "")).join("\n");
304
- return `<blockquote>${renderSource(inner, depth + 1)}</blockquote>`;
557
+ return `<blockquote>${renderSource(inner, depth + 1, ctx)}</blockquote>`;
305
558
  }
306
559
  if (depth < MAX_DEPTH) {
307
- const list = renderList(lines, depth);
560
+ const list = renderList(lines, depth, ctx);
308
561
  if (list) return list;
309
562
  }
310
563
  if (lines.length === 1 && THEMATIC_BREAK.test(lines[0])) return "<hr/>";
@@ -312,60 +565,89 @@ function renderTextBlock(raw, depth) {
312
565
  if (lines.length >= 2 && SETEXT.test(last)) {
313
566
  const level = last.trim().startsWith("=") ? 2 : 3;
314
567
  const text = lines.slice(0, -1).join(" ").trim();
315
- return `<h${level}>${inline(text)}</h${level}>`;
568
+ return `<h${level}>${inline(text, ctx)}</h${level}>`;
316
569
  }
317
- return renderProse(lines);
570
+ return renderProse(lines, ctx);
318
571
  }
319
- function renderBlock(src, block, depth) {
572
+ function renderBlock(src, block, depth, ctx) {
320
573
  const raw = src.slice(block.start, block.end);
321
- if (block.kind === "fence") return renderFence(raw);
322
- if (block.kind === "code") return renderIndentedCode(raw);
323
- return renderTextBlock(raw, depth);
574
+ if (block.kind === "fence") return renderFence(raw, ctx);
575
+ if (block.kind === "code") return renderIndentedCode(raw, ctx);
576
+ return renderTextBlock(raw, depth, ctx);
324
577
  }
325
- function renderSource(src, depth) {
326
- return splitBlocks(src).map((b) => renderBlock(src, b, depth)).join("");
578
+ function renderSource(src, depth, ctx) {
579
+ return splitBlocks(src).map((b) => renderBlock(src, b, depth, ctx)).join("");
327
580
  }
328
- function renderMarkdown(src) {
329
- return renderSource(src, 0);
581
+ function renderMarkdown(src, options) {
582
+ return renderSource(src, 0, contextOf(options));
330
583
  }
331
- var newMarkdownStream = () => ({ settled: "", html: "", resume: 0 });
332
- function renderMarkdownStream(src, stream) {
333
- if (!src.startsWith(stream.settled)) Object.assign(stream, newMarkdownStream());
584
+ var newMarkdownStream = () => ({ settled: "", parts: [], resume: 0, options: void 0 });
585
+ function renderMarkdownBlocks(src, stream, options) {
586
+ if (!src.startsWith(stream.settled) || stream.options !== options) {
587
+ Object.assign(stream, newMarkdownStream());
588
+ stream.options = options;
589
+ }
590
+ const ctx = contextOf(options);
334
591
  const from = stream.resume;
335
592
  const tail = src.slice(from);
336
593
  const blocks = splitBlocks(tail);
337
594
  const lastLine = src.lastIndexOf("\n") + 1 - from;
338
- let html = stream.html;
595
+ const shown = stream.parts.slice();
339
596
  for (let i = 0; i < blocks.length; i += 1) {
340
- const rendered = renderBlock(tail, blocks[i], 0);
341
- html += rendered;
597
+ const rendered = renderBlock(tail, blocks[i], 0, ctx);
598
+ shown.push(rendered);
342
599
  if (i + 1 < blocks.length && blocks[i + 1].start < lastLine) {
343
- stream.html += rendered;
600
+ stream.parts.push(rendered);
344
601
  stream.resume = from + blocks[i].end + 1;
345
602
  }
346
603
  }
347
604
  stream.settled = src.slice(0, lastLine + from);
348
- return html;
605
+ return shown;
349
606
  }
350
- function renderMarkdownWithAnchors(src) {
607
+ function renderMarkdownStream(src, stream, options) {
608
+ return renderMarkdownBlocks(src, stream, options).join("");
609
+ }
610
+ function renderMarkdownWithAnchors(src, options) {
611
+ const ctx = contextOf(options);
351
612
  const blocks = splitBlocks(src);
352
613
  const html = blocks.map((block, i) => {
353
- const rendered = renderBlock(src, block, 0);
614
+ const rendered = renderBlock(src, block, 0, ctx);
354
615
  return rendered.replace(/^(\s*<[a-z][a-z0-9]*)/i, `$1 data-sc-block="${i}"`);
355
616
  }).join("");
356
617
  return { html, blocks };
357
618
  }
619
+
620
+ // src/table.ts
621
+ var flatten = (cell) => cell.replace(/[\t\r\n]+/g, " ");
622
+ function tableToTsv(header, rows) {
623
+ const line = (cells) => cells.map(flatten).join(" ");
624
+ return [line(header), ...rows.map(line)].join("\n");
625
+ }
626
+ function tableToMarkdown(header, rows, align = []) {
627
+ const cell = (c) => flatten(c).replace(/\|/g, "\\|").trim();
628
+ const rule = header.map((_, i) => {
629
+ const a = align[i];
630
+ return a === "center" ? ":---:" : a === "right" ? "---:" : a === "left" ? ":---" : "---";
631
+ });
632
+ const line = (cells) => `| ${header.map((_, i) => cell(cells[i] ?? "")).join(" | ")} |`;
633
+ return [line(header), `| ${rule.join(" | ")} |`, ...rows.map(line)].join("\n");
634
+ }
358
635
  export {
636
+ HIGHLIGHT_LANGUAGES,
359
637
  STABLE_FORMAT,
360
638
  deltaTone,
361
639
  downloadThread,
362
640
  formatDelta,
363
641
  formatValue,
642
+ highlightCode,
364
643
  newMarkdownStream,
365
644
  renderMarkdown,
645
+ renderMarkdownBlocks,
366
646
  renderMarkdownStream,
367
647
  renderMarkdownWithAnchors,
368
648
  safeHref,
649
+ tableToMarkdown,
650
+ tableToTsv,
369
651
  threadToMarkdown,
370
652
  toneClass
371
653
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/format.ts","../src/export.ts","../src/markdown.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\";\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\nconst isPlainProse = (raw: string) =>\n !MARKDOWN_SIGNIFICANT.test(raw) && !ORDERED_ITEM.test(raw) && !SETEXT_EQUALS.test(raw);\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/** Strike-through, strong, emphasis. Runs on already-escaped text. */\nconst emphasize = (s: string) =>\n s\n .replace(/~~([^~\\n]+)~~/g, \"<del>$1</del>\")\n .replace(/\\*\\*([^*]+)\\*\\*/g, \"<strong>$1</strong>\")\n .replace(/(^|[^*])\\*([^*\\n]+)\\*/g, \"$1<em>$2</em>\");\n\nfunction inline(raw: string): 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 // 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: { text: string; url: string; ref: boolean }[] = [];\n s = s.replace(LINK, (_all, text: string, url: string) => {\n // A backtick pair inside a URL is part of the URL, not a code span.\n const literal = url.replace(/\\0(\\d+)\\0/g, (_m, i: string) => spanSource[Number(i)]!);\n links.push({ text, url: literal, ref: literal.startsWith(\"ref:\") });\n return `\\0L${links.length - 1}\\0`;\n });\n\n s = emphasize(s).replace(\n /\\0L(\\d+)\\0/g,\n (_all, i: string) => {\n const link = links[Number(i)]!;\n if (link.ref) return `<span class=\"sc-ref\" data-ref=\"${link.url}\">${emphasize(link.text)}</span>`;\n return `<a href=\"${link.url}\" target=\"_blank\" rel=\"noopener noreferrer\">${emphasize(link.text)}</a>`;\n },\n );\n\n return s.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\nfunction renderFence(raw: string): 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\").slice(1);\n if (lines.length && CLOSING_FENCE.test(lines[lines.length - 1]!)) lines.pop();\n return `<pre><code>${escapeHtml(lines.join(\"\\n\"))}</code></pre>`;\n}\n\nfunction renderIndentedCode(raw: string): string {\n const body = raw.split(\"\\n\").map((l) => l.replace(/^(?: {4}|\\t)/, \"\")).join(\"\\n\");\n return `<pre><code>${escapeHtml(body)}</code></pre>`;\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[]): 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)}</${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 return `<table class=\"sc-md-table\"><thead><tr>${head\n .map((h, i) => cell(\"th\", h, i))\n .join(\"\")}</tr></thead><tbody>${body}</tbody></table>`;\n}\n\n// ── Lists ────────────────────────────────────────────────────────────────────\n\nconst LIST_ITEM = /^(\\s*)([-*+]|\\d{1,9}[.)])[ \\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 */\nfunction renderItem(item: string, depth: number): string {\n const lines = item.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(item.trim());\n\n const headHtml = head.length\n ? loose\n ? renderSource(head.join(\"\\n\"), depth + 1)\n : inline(head.join(\" \").trim())\n : \"\";\n return headHtml + (rest.length ? renderSource(rest.join(\"\\n\"), depth + 1) : \"\");\n}\n\nfunction renderList(lines: string[], depth: number): string | null {\n const parsed = parseList(lines);\n if (!parsed) return null;\n const items = parsed.items.map((item) => `<li>${renderItem(item, depth)}</li>`).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\nfunction renderProse(lines: string[]): string {\n const out: string[] = [];\n let para: string[] = [];\n const flush = () => {\n if (!para.length) return;\n out.push(`<p>${para.map(inline).join(\"<br/>\")}</p>`);\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]!)}</h${level}>`);\n continue;\n }\n para.push(line);\n }\n flush();\n return out.join(\"\");\n}\n\nfunction renderTextBlock(raw: string, depth: number): string {\n if (isPlainProse(raw)) {\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);\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)}</blockquote>`;\n }\n\n if (depth < MAX_DEPTH) {\n const list = renderList(lines, depth);\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)}</h${level}>`;\n }\n\n return renderProse(lines);\n}\n\n// ── Assembly ─────────────────────────────────────────────────────────────────\n\nfunction renderBlock(src: string, block: MarkdownBlock, depth: number): string {\n const raw = src.slice(block.start, block.end);\n if (block.kind === \"fence\") return renderFence(raw);\n if (block.kind === \"code\") return renderIndentedCode(raw);\n return renderTextBlock(raw, depth);\n}\n\n/** Split and render a source, with no anchors. Also the recursion step. */\nfunction renderSource(src: string, depth: number): string {\n return splitBlocks(src)\n .map((b) => renderBlock(src, b, depth))\n .join(\"\");\n}\n\n/** Render for the transcript: no anchors, because chat prose is not addressed. */\nexport function renderMarkdown(src: string): string {\n return renderSource(src, 0);\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. */\n html: string;\n /** Where the block after them starts looking: the line after the last one. */\n resume: number;\n};\n\nexport const newMarkdownStream = (): MarkdownStream => ({ settled: \"\", html: \"\", resume: 0 });\n\n/**\n * renderMarkdown for text that grows while it is shown — always the same\n * string 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 * 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 renderMarkdownStream(src: string, stream: MarkdownStream): string {\n if (!src.startsWith(stream.settled)) Object.assign(stream, newMarkdownStream());\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 let html = stream.html;\n for (let i = 0; i < blocks.length; i += 1) {\n const rendered = renderBlock(tail, blocks[i]!, 0);\n html += rendered;\n if (i + 1 < blocks.length && blocks[i + 1]!.start < lastLine) {\n stream.html += rendered;\n stream.resume = from + blocks[i]!.end + 1;\n }\n }\n stream.settled = src.slice(0, lastLine + from);\n return html;\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): AnchoredMarkdown {\n const blocks = splitBlocks(src);\n const html = blocks\n .map((block, i) => {\n const rendered = renderBlock(src, block, 0);\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}\"`);\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D,YAAQ;AACR,QAAI,IAAI,IAAI,OAAO,UAAU,OAAO,IAAI,CAAC,EAAG,QAAQ,UAAU;AAC5D,aAAO,QAAQ;AACf,aAAO,SAAS,OAAO,OAAO,CAAC,EAAG,MAAM;AAAA,IAC1C;AAAA,EACF;AACA,SAAO,UAAU,IAAI,MAAM,GAAG,WAAW,IAAI;AAC7C,SAAO;AACT;AAUO,SAAS,0BAA0B,KAA+B;AACvE,QAAM,SAAS,YAAY,GAAG;AAC9B,QAAM,OAAO,OACV,IAAI,CAAC,OAAO,MAAM;AACjB,UAAM,WAAW,YAAY,KAAK,OAAO,CAAC;AAI1C,WAAO,SAAS,QAAQ,0BAA0B,qBAAqB,CAAC,GAAG;AAAA,EAC7E,CAAC,EACA,KAAK,EAAE;AACV,SAAO,EAAE,MAAM,OAAO;AACxB;","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\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,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;AAEO,SAAS,YAAY,OAAgB,SAA0B,QAAQ,UAAyB,CAAC,GAAW;AACjH,MAAI,SAAS,KAAM,QAAO;AAC1B,QAAM,EAAE,QAAQ,SAAS,IAAI;AAC7B,QAAM,UAAU,WAAW,MAAM;AAEjC,UAAQ,QAAQ;AAAA,IACd,KAAK,UAAU;AACb,YAAM,IAAI,OAAO,KAAK;AACtB,UAAI,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QAAM,OAAO,CAAC,UAA6B,MAAM,IAAI,OAAO,EAAE,KAAK,GAAI;AACvE,SAAO,CAAC,KAAK,MAAM,GAAG,GAAG,KAAK,IAAI,IAAI,CAAC,EAAE,KAAK,IAAI;AACpD;AAGO,SAAS,gBACd,QACA,MACA,QAAyD,CAAC,GAClD;AACR,QAAM,OAAO,CAAC,MAAc,QAAQ,CAAC,EAAE,QAAQ,OAAO,KAAK,EAAE,KAAK;AAClE,QAAM,OAAO,OAAO,IAAI,CAAC,GAAG,MAAM;AAChC,UAAM,IAAI,MAAM,CAAC;AACjB,WAAO,MAAM,WAAW,UAAU,MAAM,UAAU,SAAS,MAAM,SAAS,SAAS;AAAA,EACrF,CAAC;AACD,QAAM,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":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supersolutions/super-chat-ui-core",
3
- "version": "0.4.4",
3
+ "version": "0.5.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.4.4"
47
+ "@supersolutions/super-chat-core": "0.5.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "tsup": "^8.3.5",