Files
stack/packages/webui/src/public/markdown-preview.js
T
jason.woltjeandClaude Opus 5.5 d4ea7e5a69 webui, bus, project: a Console editor for the project's spec and docs (row 148, #1642)
Row 148 round 3, Researcher's candidate (agents/researcher/work/queue-148/,
row148.patch 1b63164b, manifest 95ae4736, 27 paths, base 18aee8fa1).
Dewey approved round 3 (comment 28832) and Filbert approved it with no
findings (28835). Mos gave the decision 123 go on public diff 8360122b
(mos-0636): no vendored code, no innerHTML or other HTML sinks.

The Docs page #/docs lists each project's spec/north-star.md and the
Markdown files directly under docs/. Save writes the typed text as one
local commit authored by business.human, through a new human-only bus
verb project.file.save that carries the opened commit as base and
refuses stale-base if the file moved. The preview is a textarea plus a
renderer built with createElement and textContent only; raw HTML shows
as source text and images never load. CSP is unchanged.

Round 3 replaced the backreference HR regex, which overflowed the
regexp stack, with an isRule scan. Round 4 added a textContent fallback
when paintDoc throws, and the submit handler resets saving in a finally.
Mos's rule (ceiling 1 s at 1 MiB, growth x3 per doubling over 1 to
4 MiB): 130/130 and 138/138 cells pass, worst 513 ms at 1 MiB, worst
ratio x2.50, control x2.01; the 756-cell grid has 0 timeouts. Mutants
43/44, v21 equivalent.

Follow-ups: Vikunja P19 tasks 318 (Save stays off after a non-render
paint throw), 319 (dead NUL check in bus.js) and 320 (the 1 MiB + 64 KiB
buffer before the human proof, Gitea #1650).

Sage's landing gate ran on a4779d2a5 plus the candidate: 25 steps,
all rc 0 (15 packages, 10 script suites), 22:19:24Z to 22:24:09Z,
network sage-r148g_default removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 17:24:39 -05:00

339 lines
16 KiB
JavaScript

// Row 148 (#1642, ruling sage-0507): the Markdown preview for the spec and docs editor.
// Every node is made with createElement and every string reaches the page as text (textContent or a
// text node), so nothing a file says becomes markup and there is no sanitizer to get wrong. The test
// in tests/markdown-preview.test.mjs reads this file and fails if it names a string-to-markup sink.
//
// Rendered: headings, paragraphs, lists, block quotes, code blocks, inline code, emphasis and links.
// Everything else, raw HTML, tables, thematic breaks and the rest, shows as its source text.
// A link is made only for an http:, https: or relative target and is followed by the target in
// text; any other target leaves the whole `[text](target)` as source text. An image shows its alt
// text and URL and is never loaded. This is not a CommonMark engine: where it differs it keeps text.
(() => {
const MAX_DEPTH = 12; // block nesting and inline nesting beyond this stay source text
const SPAN = 2000; // the farthest one inline opener looks ahead for its closer
// SPAN alone does not bound a render: n unclosed openers each look SPAN ahead, so n x SPAN. Every
// scan that fails charges the characters it looked at to `work`; once `work` reaches `budget` (32 per
// character of the text, at least 1 Mi) each later opener is refused its scan and stays source text.
// A scan that succeeds consumes what it looked at, so the position it moves to pays for it.
const BUDGET_PER_CHAR = 32, BUDGET_FLOOR = 1 << 20;
let work = 0, budget = 0;
const PUNCT = /[!-/:-@[-`{-~]/;
// The `s` flag on FENCE, ATX and ITEM: without it `.` stops at U+2028 and U+2029, which the split on
// "\n" leaves inside a line, `$` then fails, and the engine retries `(.*)` from every offset of a long
// run in front of it, which is quadratic in the run. With `s` the first try matches to the end.
const FENCE = /^( {0,3})(`{3,}|~{3,})(.*)$/s;
const ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*))?$/s;
const SETEXT = /^ {0,3}(=+|-+)[ \t]*$/;
// A thematic break is up to 3 spaces, one of - * _, then only that mark, spaces and tabs, with at least
// 3 marks. A walk, not a regex: `(?:[ \t]*\1){2,}` recurses once per mark, and V8 throws RangeError
// ("Maximum call stack size exceeded") on one line of about 2 MiB of marks.
const isRule = line => {
let i = 0, marks = 0;
while (i < 3 && line[i] === ' ') i++;
const mark = line[i];
if (mark !== '-' && mark !== '*' && mark !== '_') return false;
for (; i < line.length; i++) {
if (line[i] === mark) marks++;
else if (!blank(line[i])) return false;
}
return marks >= 3;
};
const QUOTE = /^ {0,3}> ?/;
const ITEM = /^( {0,3})([-+*]|\d{1,9}[.)])([ \t]+|$)(.*)$/s;
const make = (doc, tag, text) => {
const node = doc.createElement(tag);
if (text !== undefined) node.textContent = text;
return node;
};
const isOrdered = marker => marker >= '0' && marker <= '9';
const blank = c => c === ' ' || c === '\t';
// Trailing blanks, and a closing run of hashes after a blank, cut by a walk from the end. A regex
// for either retries from every blank of a long blank run, which is quadratic in the run.
const trimBlanksEnd = s => { let e = s.length; while (e > 0 && blank(s[e - 1])) e--; return s.slice(0, e); };
const stripClosingHashes = s => {
let e = s.length;
while (e > 0 && s[e - 1] === '#') e--;
if (e === s.length) return s;
return e === 0 || blank(s[e - 1]) ? trimBlanksEnd(s.slice(0, e)) : s;
};
// The one gate for a link: the same function decides the href and whether a link is made at all.
// No whitespace, control, backslash or bidirectional-format character (a browser would read or
// hide it), no scheme other than http or https, and no "//" start that would name another host.
function linkTarget(raw) {
const target = String(raw);
if (!target || target.length > SPAN || /[\u0000-\u0020\u007f-\u009f\\\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/.test(target)) return null;
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(target)) return /^https?:\/\/[^/?#]/i.test(target) ? target : null;
return target.startsWith('//') ? null : target;
}
// ------------------------------------------------------------------ inline
// The first index at or after `from` where a run of exactly `size` copies of `ch` starts, within
// SPAN characters; used for code spans.
function findRun(text, from, ch, size) {
if (work >= budget) return -1;
const end = Math.min(text.length, from + SPAN);
let j = from;
while (j < end) {
if (text[j] !== ch) { j++; continue; }
let run = 1;
while (text[j + run] === ch) run++;
if (run === size) return j;
j += run;
}
work += j - from;
return -1;
}
// The first index of `ch` from `from` to `last` inclusive, or -1. Unlike indexOf on the whole text,
// one search looks at no more than `last - from + 1` characters, not the rest of the text. The
// caller charges a miss; the render's total is capped by `budget`, not by this bound.
const findWithin = (text, ch, from, last) => {
const found = text.slice(from, last + 1).indexOf(ch);
return found < 0 ? -1 : from + found;
};
// `[label](destination "title")` at `at`, or null. Brackets and parentheses balance; an escape
// hides one character; each step looks at most SPAN characters past where the one before ended.
// A miss charges the characters it looked at, up to `reached`.
function linkAt(text, at) {
if (work >= budget) return null;
const miss = reached => { work += reached - at + 1; return null; };
const limit = Math.min(text.length, at + SPAN);
let depth = 0, j = at;
for (; j < limit; j++) {
const c = text[j];
if (c === '\\') { j++; continue; }
if (c === '[') depth++;
else if (c === ']' && --depth === 0) break;
}
if (j >= limit || text[j + 1] !== '(') return miss(j);
const label = text.slice(at + 1, j);
let k = j + 2;
const space = () => { while (k < limit + SPAN && /[ \t\n]/.test(text[k] ?? '')) k++; };
space();
let dest = '';
if (text[k] === '<') {
const close = findWithin(text, '>', k, k + SPAN);
if (close < 0) return miss(k + SPAN);
if (/[\n<]/.test(text.slice(k + 1, close))) return miss(close);
dest = text.slice(k + 1, close); k = close + 1;
} else {
const from = k;
let parens = 0;
for (; k < text.length && k - from <= SPAN; k++) {
const c = text[k];
if (c === '\\' && PUNCT.test(text[k + 1] ?? '')) { k++; continue; }
if (c === '(') parens++;
else if (c === ')') { if (parens === 0) break; parens--; }
else if (/\s/.test(c)) break;
}
dest = text.slice(from, k);
}
space();
const open = text[k];
if (open === '"' || open === "'" || open === '(') {
const close = findWithin(text, open === '(' ? ')' : open, k + 1, k + SPAN);
if (close < 0) return miss(k + SPAN);
k = close + 1; space();
}
if (text[k] !== ')') return miss(k);
return { label, dest: dest.replace(/\\([!-/:-@[-`{-~])/g, '$1'), end: k + 1 };
}
// The closing run of an emphasis opener: its start and length, or null. A closer follows
// a non-space and (for "_") is not inside a word; a run of the opener's own size, or three, closes.
function closerOf(text, from, ch, use) {
if (work >= budget) return null;
const end = Math.min(text.length, from + SPAN);
let j = from;
while (j < end) {
const c = text[j];
if (c === '\\') { j += 2; continue; }
if (c === '`') {
let run = 1;
while (text[j + run] === '`') run++;
const close = findRun(text, j + run, '`', run);
j = close < 0 ? j + run : close + run;
continue;
}
if (c !== ch) { j++; continue; }
let run = 1;
while (text[j + run] === ch) run++;
const prev = text[j - 1] ?? ' ', next = text[j + run] ?? ' ';
if (j > from && !/\s/.test(prev) && (run === use || run === 3) && (ch === '*' || !/[A-Za-z0-9]/.test(next))) return { start: j, run };
j += run;
}
work += j - from;
return null;
}
function inline(text, parent, doc, depth, inLink) {
let pending = '';
const flush = () => { if (pending) { parent.appendChild(doc.createTextNode(pending)); pending = ''; } };
const n = text.length;
let i = 0;
while (i < n) {
const c = text[i];
if (c === '\\' && i + 1 < n && PUNCT.test(text[i + 1])) { pending += text[i + 1]; i += 2; continue; }
if (c === '`') {
let run = 1;
while (text[i + run] === '`') run++;
const close = findRun(text, i + run, '`', run);
if (close < 0) { pending += '`'.repeat(run); i += run; continue; }
let code = text.slice(i + run, close).replace(/\n/g, ' ');
if (code.length > 2 && code.startsWith(' ') && code.endsWith(' ') && code.trim()) code = code.slice(1, -1);
flush(); parent.appendChild(make(doc, 'code', code));
i = close + run; continue;
}
if (c === '!' && text[i + 1] === '[') {
const image = depth < MAX_DEPTH ? linkAt(text, i + 1) : null;
if (image) { flush(); parent.appendChild(make(doc, 'span', `[image: ${image.label}] ${image.dest}`)); parent.lastChild.className = 'md-image'; i = image.end; continue; }
}
if (c === '[' && !inLink && depth < MAX_DEPTH) {
const link = linkAt(text, i), target = link && linkTarget(link.dest);
if (link && target) {
flush();
const a = make(doc, 'a');
a.setAttribute('href', target);
a.setAttribute('rel', 'noopener noreferrer');
a.setAttribute('target', '_blank');
inline(link.label, a, doc, depth + 1, true);
parent.appendChild(a);
parent.appendChild(doc.createTextNode(' '));
const shown = make(doc, 'span', `(${target})`);
shown.className = 'md-target';
parent.appendChild(shown);
i = link.end; continue;
}
if (link) { pending += text.slice(i, link.end); i = link.end; continue; } // any other target: source text
}
if ((c === '*' || c === '_') && depth < MAX_DEPTH) {
let run = 1;
while (text[i + run] === c) run++;
const before = text[i - 1], after = text[i + run];
const opens = after !== undefined && !/\s/.test(after) && (c === '*' || !(before && /[A-Za-z0-9]/.test(before)));
const use = Math.min(run, 2), close = opens ? closerOf(text, i + run, c, use) : null;
if (close) {
flush();
const node = make(doc, use === 2 ? 'strong' : 'em');
inline(text.slice(i + use, close.start + close.run - use), node, doc, depth + 1, inLink);
parent.appendChild(node);
i = close.start + close.run; continue;
}
pending += c.repeat(run); i += run; continue;
}
pending += c; i++;
}
flush();
}
// ------------------------------------------------------------------ blocks
const fenceOf = line => {
const m = FENCE.exec(line);
return m && !(m[2][0] === '`' && m[3].includes('`')) ? { ch: m[2][0], size: m[2].length, indent: m[1].length } : null;
};
const closesFence = (line, fence) => {
const t = line.trimStart(), run = /^(`+|~+)[ \t]*$/.exec(t);
return line.length - t.length <= 3 && run && run[1][0] === fence.ch && run[1].length >= fence.size;
};
// A list marker line. When it would interrupt a paragraph it needs content, and an ordered one must start at 1.
const itemAt = (line, interrupt) => {
const m = ITEM.exec(line);
if (!m) return null;
if (interrupt && (!m[4].trim() || (isOrdered(m[2][0]) && parseInt(m[2], 10) !== 1))) return null;
return m;
};
function parse(lines, depth, out, doc, tight) {
const deep = depth >= MAX_DEPTH, n = lines.length;
// Past the depth limit a quote or list marker is just text.
const starts = line => fenceOf(line) || ATX.test(line) || (!deep && (QUOTE.test(line) || (!isRule(line) && itemAt(line, true))));
let i = 0;
while (i < n) {
const line = lines[i];
if (!line.trim()) { i++; continue; }
const fence = fenceOf(line);
if (fence) {
const body = [];
for (i++; i < n && !closesFence(lines[i], fence); i++) body.push(lines[i].slice(Math.min(fence.indent, lines[i].length - lines[i].trimStart().length)));
i++; // the closing fence; a fence still open at the end runs to the end
const pre = make(doc, 'pre');
pre.appendChild(make(doc, 'code', body.join('\n')));
out.appendChild(pre); continue;
}
const atx = ATX.exec(line);
if (atx) {
const heading = make(doc, 'h' + atx[1].length);
inline(stripClosingHashes((atx[2] ?? '').trim()).trim(), heading, doc, 0, false);
out.appendChild(heading); i++; continue;
}
if (!deep && QUOTE.test(line)) {
const inner = [];
while (i < n) {
const l = lines[i];
if (QUOTE.test(l)) inner.push(l.replace(QUOTE, ''));
else if (l.trim() && inner.length && inner.at(-1).trim() && !starts(l)) inner.push(l); // a lazy continuation line
else break;
i++;
}
const quote = make(doc, 'blockquote');
parse(inner, depth + 1, quote, doc, false);
out.appendChild(quote); continue;
}
const first = !deep && !isRule(line) && itemAt(line, false);
if (first) {
const ordered = isOrdered(first[2][0]), sameList = l => {
const m = !isRule(l) && itemAt(l, false);
return m && ordered === isOrdered(m[2][0]) && m[2].slice(-1) === first[2].slice(-1);
};
const list = make(doc, ordered ? 'ol' : 'ul'), items = [];
if (ordered && parseInt(first[2], 10) !== 1) list.setAttribute('start', String(parseInt(first[2], 10)));
let loose = false;
while (i < n && sameList(lines[i])) {
const m = itemAt(lines[i], false), empty = !m[4].trim();
const spaces = empty || m[3].length > 4 ? 1 : m[3].length, offset = m[1].length + m[2].length + spaces;
const body = [empty ? '' : m[3].slice(spaces) + m[4]];
let blanks = 0;
for (i++; i < n; i++) {
const l = lines[i];
if (!l.trim()) { blanks++; body.push(''); continue; }
if (l.length - l.trimStart().length >= offset) { if (blanks) loose = true; blanks = 0; body.push(l.slice(offset)); continue; }
if (!blanks && !starts(l) && !(!isRule(l) && itemAt(l, false))) { body.push(l.trimStart()); continue; } // a lazy continuation line
break;
}
while (body.length && !body.at(-1).trim()) body.pop();
items.push(body);
if (blanks && i < n && sameList(lines[i])) loose = true;
}
for (const body of items) {
const li = make(doc, 'li');
parse(body, depth + 1, li, doc, !loose);
list.appendChild(li);
}
out.appendChild(list); continue;
}
// A paragraph, or a heading when a setext underline follows. A thematic break lands here as text.
const para = [line.trimStart()];
let level = 0;
for (i++; i < n && lines[i].trim() && !starts(lines[i]); i++) {
const underline = SETEXT.exec(lines[i]);
if (underline) { level = underline[1][0] === '=' ? 1 : 2; i++; break; }
para.push(lines[i].trimStart());
}
const text = para.map(trimBlanksEnd).join('\n');
if (level) { const heading = make(doc, 'h' + level); inline(text, heading, doc, 0, false); out.appendChild(heading); }
else if (tight) inline(text, out, doc, 0, false);
else { const p = make(doc, 'p'); inline(text, p, doc, 0, false); out.appendChild(p); }
}
}
// `meter`, when given, receives the render's look-ahead account: {work, budget}. The page does not
// pass one; the tests do, so they can assert on the count and never on the clock.
function render(source, doc = document, meter = null) {
const fragment = doc.createDocumentFragment();
const text = String(source).replace(/\r\n?/g, '\n');
work = 0; budget = Math.max(BUDGET_FLOOR, BUDGET_PER_CHAR * text.length);
const lines = text.split('\n').map(l => l.replace(/^[ \t]+/, w => w.replace(/\t/g, ' ')));
parse(lines, 0, fragment, doc, false);
if (meter) { meter.work = work; meter.budget = budget; }
return fragment;
}
window.MosaicMarkdown = Object.freeze({ render, linkTarget });
})();