Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239import DOMPurify from 'dompurify';import { Marked, Renderer, type TokenizerAndRendererExtension, type Tokens,} from 'marked';
// Transcripts carry text from models and tools, including whatever a tool// fetched, so nothing in them may run in this page: raw HTML is shown as text,// links keep only web and mail schemes, and images become links instead of// loading. DOMPurify then keeps only the tags and attributes listed below, so// a renderer mistake or a new marked token still cannot reach the page.
const escapes: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',};
function escapeHtml(text: string): string { return text.replace(/[&<>"']/g, (char) => escapes[char]);}
/** The URL if it is http, https or mailto, else null. */export function safeHref(href: string): string | null { try { const url = new URL(href, 'https://invalid.example/'); return ['http:', 'https:', 'mailto:'].includes(url.protocol) && url.host !== 'invalid.example' ? url.href : null; } catch { return null; }}
// Math and diagrams are left as placeholders whose text is their source,// shown as is until `enhance` (enhance.ts) draws them; KaTeX and Pele load// only when a message needs them. The source stays text, not an attribute:// DOMPurify drops attribute values holding "-->", which every diagram arrow is.
interface Math extends Tokens.Generic { text: string; display: boolean;}
function mathHtml(text: string, display: boolean) { const tag = display ? 'div' : 'span'; return `<${tag} class="math" data-display="${display ? 1 : 0}">${escapeHtml(text)}</${tag}>`;}
// $$…$$ or \[…\] standing as a block.const mathBlock: TokenizerAndRendererExtension = { name: 'mathBlock', level: 'block', start: (src) => src.match(/\$\$|\\\[/)?.index, tokenizer(src) { const match = /^(?:\$\$([\s\S]+?)\$\$|\\\[([\s\S]+?)\\\])[ \t]*(?:\n|$)/.exec(src); if (match) return { type: 'mathBlock', raw: match[0], text: (match[1] ?? match[2]).trim(), display: true, }; }, renderer: (token) => mathHtml((token as Math).text, true),};
// $…$, \(…\) or $$…$$ inside a line. A dollar amount is not maths: the// opening $ must touch its text, the closing one too, and no digit may// follow it ("$5 and $10" stays prose).const mathInline: TokenizerAndRendererExtension = { name: 'mathInline', level: 'inline', start: (src) => src.match(/\$|\\\(/)?.index, tokenizer(src) { const display = /^\$\$([^\n]+?)\$\$/.exec(src); if (display) return { type: 'mathInline', raw: display[0], text: display[1].trim(), display: true, }; const match = /^\$(?![\s$])((?:\\.|[^\\$\n])+?)(?<!\s)\$(?!\d)/.exec(src) ?? /^\\\(([^\n]+?)\\\)/.exec(src); if (match) return { type: 'mathInline', raw: match[0], text: match[1], display: false, }; }, renderer: (token) => mathHtml((token as Math).text, (token as Math).display),};
const marked = new Marked({ extensions: [mathBlock, mathInline], gfm: true, breaks: false, renderer: { html({ text }: Tokens.HTML | Tokens.Tag) { return escapeHtml(text); }, link({ href, tokens }: Tokens.Link) { const text = this.parser.parseInline(tokens); const safe = safeHref(href); return safe ? `<a href="${escapeHtml(safe)}" target="_blank" rel="noopener noreferrer">${text}</a>` : text; }, code({ text, lang }: Tokens.Code) { if (lang?.trim().toLowerCase() !== 'mermaid') return false; return `<div class="diagram"><pre><code>${escapeHtml(text)}</code></pre></div>`; }, // A cell of prose keeps a reading width (Markdown.svelte), so a narrow // chat scrolls a table sideways instead of wrapping it a few letters a line. tablecell(token: Tokens.TableCell) { const cell = Renderer.prototype.tablecell.call(this, token); return /\s/.test(token.text.trim()) && token.text.length > 24 ? cell.replace(/^<t[dh]/, '$& class="prose"') : cell; }, image({ href, text }: Tokens.Image) { const safe = safeHref(href); return safe ? `<a href="${escapeHtml(safe)}" target="_blank" rel="noopener noreferrer">${escapeHtml(text || safe)}</a>` : escapeHtml(text); }, },});
const allowed = { ALLOWED_TAGS: [ 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'em', 'strong', 'del', 'code', 'pre', 'blockquote', 'ul', 'ol', 'li', 'a', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'div', 'span', 'input', ], // data-display, which tells enhance.ts maths from display maths, passes as data-*. ALLOWED_ATTR: [ 'href', 'target', 'rel', 'class', 'start', 'align', 'type', 'checked', 'disabled', ], ALLOWED_URI_REGEXP: /^(?:https?|mailto):/i,};
/** * Recent renders by source, most recent last: a chat mounting again (another * board, a window reopened) shows the same messages. Bounded by characters, * since a streamed reply passes through as thousands of ever longer texts. */const rendered = new Map<string, string>();let renderedSize = 0;const RENDERED_CHARS = 4_000_000;
export function renderMarkdown(text: string): string { const known = rendered.get(text); if (known !== undefined) { rendered.delete(text); rendered.set(text, known); return known; } const html = DOMPurify.sanitize( marked.parse(text, { async: false }), allowed, ); rendered.set(text, html); renderedSize += text.length + html.length; for (const [oldest, gone] of rendered) { if (renderedSize <= RENDERED_CHARS) break; rendered.delete(oldest); renderedSize -= oldest.length + gone.length; } return html;}
/** * A document opened as a file, as one block per top-level element, each * carrying the lines it came from (`data-from`, `data-to`) and marked * `changed` when one of them is in `changed`. */export function renderDocument( text: string, changed: ReadonlySet<number>,): string { const tokens = marked.lexer(text); let line = 1; let html = ''; for (const token of tokens) { const from = line; line += token.raw.split('\n').length - 1; if (token.type === 'space') continue; const to = Math.max(from, line - (token.raw.endsWith('\n') ? 1 : 0)); let touched = false; for (let n = from; n <= to && !touched; n++) touched = changed.has(n); html += `<div class="block${touched ? ' changed' : ''}" data-from="${from}" data-to="${to}">${marked.parser(Object.assign([token], { links: tokens.links }))}</div>`; } return DOMPurify.sanitize(html, allowed);}