Files
client/app/renderer/js/markdown/parse.js
T
omar f618d8bce9
ci / linux-arm64-cross (push) Successful in 3m22s
ci / linux-x64 (push) Successful in 3m32s
chat: add safe hybrid Markdown editing with strict CSP
2026-11-02 11:32:31 +03:00

979 lines
37 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Parser for the TeamSpeak 6 chat markdown dialect, including the TS3 BBCode tags it still reads.
//
// Behaviour follows the installed official client's engine (html/client_ui/main.js, module 37702,
// dialect defaults `QO` = {noHtml, strictParagraphLeaf, strictBlockquote, strictLists, enableSetext,
// enableIndentedCode:false, enableTable, enableStrikethrough, enableAutolink}) and the user-facing
// reference in locales/en.json `settings.chat.markdown_help.*`:
// - one physical line is one paragraph; no lazy continuation for quotes or list items;
// - inline and block HTML stay plain text;
// - extensions: ++underline++, ==highlight==, ^sup^, ~sub~, ||spoiler||, $math$, $$ blocks $$,
// ```mermaid, > [!NOTE] callouts, :::details / :::left|center|right|justify, footnotes,
// :emoji: shortcodes, sized images, and [b] [i] [u] [s] [color] [size] [url] [img] [hr]
// [left] [center] [right] BBCode (inline or one tag per line for multi-line blocks).
// The output is a plain object tree; nothing here touches the DOM, so it is safe for any input.
import EMOJI from '../../vendor/emoji/shortcodes.js';
const MAX_DEPTH = 24;
const MAX_NODES = 20000;
const CALLOUTS = new Map([['NOTE', 'note'], ['TIP', 'tip'], ['IMPORTANT', 'important'], ['WARNING', 'warning'], ['CAUTION', 'caution']]);
const CALLOUT_TITLES = { note: 'Note', tip: 'Tip', important: 'Important', warning: 'Warning', caution: 'Caution' };
const BB_SIZES = { '+1': 'large', '+2': 'x-large', '+3': 'xx-large', '+4': 'xxx-large', '-1': 'small', '-2': 'x-small', '-3': 'xx-small' };
const BB_COLOR = /^(#[0-9a-f]{3,8}|[a-z]{3,20}|rgba?\(\s*[\d.,\s%]+\))$/i;
const BB_PAIRED = new Set(['b', 'i', 'u', 's', 'color', 'size', 'center', 'left', 'right']);
const BB_PARAM = new Set(['color', 'size']);
const ASCII_PUNCT = /[!-/:-@[-`{-~]/;
const PUNCT = /[\p{P}\p{S}]/u;
const WS = /\s/u;
const NAMED_ENTITIES = {
amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0', copy: '©', reg: '®', trade: '™', hellip: '…',
mdash: '—', ndash: '–', laquo: '«', raquo: '»', lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”', bull: '•', middot: '·',
deg: '°', plusmn: '±', times: '×', divide: '÷', euro: '€', pound: '£', yen: '¥', cent: '¢', sect: '§', para: '¶',
larr: '←', rarr: '→', uarr: '↑', darr: '↓', harr: '↔', hearts: '♥', spades: '♠', clubs: '♣', diams: '♦', check: '✓',
frac12: '½', frac14: '¼', frac34: '¾', sup2: '²', sup3: '³', micro: 'µ', infin: '∞', ne: '≠', le: '≤', ge: '≥',
alpha: 'α', beta: 'β', gamma: 'γ', delta: 'δ', pi: 'π', sigma: 'σ', omega: 'ω', Omega: 'Ω', shy: '\u00ad', iexcl: '¡', iquest: '¿',
};
/** Decodes one `&…;` entity, or returns null when it is not a known entity (then it stays literal). */
export function decodeEntity(entity) {
const m = /^&#(?:(\d{1,7})|[xX]([0-9a-fA-F]{1,6}));$/.exec(entity);
if (m) {
const code = m[1] ? Number.parseInt(m[1], 10) : Number.parseInt(m[2], 16);
if (code === 0) return '\uFFFD';
if (code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return null;
return String.fromCodePoint(code);
}
const named = /^&([A-Za-z][A-Za-z0-9]{1,31});$/.exec(entity);
if (named && Object.hasOwn(NAMED_ENTITIES, named[1])) return NAMED_ENTITIES[named[1]];
return null;
}
export function emojiForShortcode(code) {
return Object.hasOwn(EMOJI, code) ? EMOJI[code] : null;
}
/** Same normalisation as the official reference-label matcher (`Ea`): collapse spaces, fold case and ß. */
function normalizeLabel(label) {
return label.replace(/[ \t\r\n]+/g, ' ').trim().replace(/[\u00DF\u1E9E]/g, 'ss').toLowerCase();
}
function unescapeText(s) {
return s.replace(/\\([!-/:-@[-`{-~])/g, '$1');
}
const isBlank = (line) => line.trim().length === 0;
const leadingSpaces = (line) => /^[ \t]*/.exec(line)[0].length;
const isThematicBreak = (line) => /^[ \t]{0,3}(?:(?:\*(?:[ \t]*\*){2,})|(?:-(?:[ \t]*-){2,})|(?:_(?:[ \t]*_){2,}))[ \t]*$/.test(line);
const isSetextUnderline = (line) => /^[ \t]{0,3}(?:=+|-+)\s*$/.test(line);
// lezer GFM `delimiterLine`, as used by the official Table extension.
const isTableDelimiter = (line) => line.includes('-') && line.includes('|') && /^\|?(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)?$/.test(line.trim());
/** List marker as parsed by the official strict list parser (`Fr`): `*`/`-` or 1–9 digits with `.`/`)`. */
function listMarker(line) {
let n = 0;
while (n < line.length && (line[n] === ' ' || line[n] === '\t')) n += 1;
const from = n;
const c = line[n];
let to;
let kind;
let start = null;
if (c === '*' || c === '-') {
to = n + 1;
kind = 'bullet';
} else if (c >= '0' && c <= '9') {
let digits = 0;
while (n < line.length && line[n] >= '0' && line[n] <= '9' && digits < 9) { n += 1; digits += 1; }
if (line[n] !== '.' && line[n] !== ')') return null;
start = Number.parseInt(line.slice(from, n), 10);
to = n + 1;
kind = 'ordered';
} else {
return null;
}
if (to < line.length && line[to] !== ' ' && line[to] !== '\t') return null;
let content = to;
while (content < line.length && (line[content] === ' ' || line[content] === '\t')) content += 1;
let task = null;
if (line[content] === '[' && (line[content + 1] === ' ' || line[content + 1] === 'x' || line[content + 1] === 'X') && line[content + 2] === ']' && line[content + 3] === ' ') {
task = line[content + 1] !== ' ';
content += 4;
}
return { kind, from, content, task, start };
}
const ATX = /^[ \t]{0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
const FENCE = /^([ \t]{0,3})(`{3,}|~{3,})(.*)$/;
const LINK_DEF = /^[ \t]{0,3}\[((?:[^\\\]]|\\.){1,999})\]:[ \t]*(<[^>\n]*>|\S+)(?:[ \t]+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^)\\]|\\.)*\)))?[ \t]*$/;
const FOOTNOTE_DEF = /^\[\^([^\]]+)\]:[ \t]*(.*)$/;
const COLON_FENCE = /^[ \t]*(:{3,})[ \t]*([A-Za-z]+)(?:[ \t]+(.*?))?[ \t]*$/;
class Parser {
constructor() {
this.refs = new Map();
this.footnoteDefs = new Map();
this.footnoteOrder = [];
this.nodes = 0;
}
count() {
this.nodes += 1;
if (this.nodes > MAX_NODES) throw new RangeError('markdown too complex');
}
/** First pass: link reference definitions are document-wide metadata (official `link-reference`). */
collectDefinitions(lines) {
let inFence = null;
for (const line of lines) {
const fence = FENCE.exec(line);
if (inFence) {
if (fence && fence[2][0] === inFence[0] && fence[2].length >= inFence.length && !fence[3].trim()) inFence = null;
continue;
}
if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) {
inFence = fence[2];
continue;
}
const stripped = line.replace(/^(?:[ \t]*>[ ]?)+/, '');
const def = LINK_DEF.exec(stripped);
if (def && !def[1].startsWith('^')) {
const key = normalizeLabel(def[1]);
if (key && !this.refs.has(key)) {
let href = def[2];
if (href.startsWith('<') && href.endsWith('>')) href = href.slice(1, -1);
this.refs.set(key, { href: unescapeText(href), title: def[3] ? unescapeText(def[3].slice(1, -1)) : null });
}
}
}
}
parseDocument(text) {
const lines = text.replace(/\r\n?/g, '\n').split('\n');
this.collectDefinitions(lines);
const children = this.parseBlocks(lines, 0);
const notes = [];
// Official footnote supplement: referenced definitions in first-reference order; with no references at
// all, every definition in document order (the Markdown Help "Footnote Definition" example).
for (const label of this.footnoteOrder.length > 0 ? this.footnoteOrder : [...this.footnoteDefs.keys()]) {
const def = this.footnoteDefs.get(label);
if (def) notes.push({ label, number: notes.length + 1, children: def.children, lines: def.lines });
}
return { type: 'doc', children, footnotes: notes };
}
parseBlocks(lines, depth) {
if (depth > MAX_DEPTH) return [{ type: 'paragraph', children: [{ type: 'text', value: lines.join('\n') }] }];
const out = [];
let i = 0;
while (i < lines.length) {
const before = out.length;
const next = this.parseBlock(lines, i, depth, out);
// Source span [first line, end line) of the block within `lines`; at depth 0 these are document
// lines, which the chat editor's preview uses to map rendered blocks back to their source.
if (out.length > before) out[before].lines = [i, Math.min(next, lines.length)];
i = next;
}
return out;
}
/** Parses the block that starts at line `i` (pushing at most one node) and returns the next line index. */
parseBlock(lines, i, depth, out) {
const line = lines[i];
this.count();
if (isBlank(line)) return i + 1;
// Fenced code (``` or ~~~); ```mermaid is a diagram.
const fence = FENCE.exec(line);
if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) {
const marker = fence[2];
const indent = fence[1].length;
const body = [];
let j = i + 1;
for (; j < lines.length; j += 1) {
const close = FENCE.exec(lines[j]);
if (close && close[2][0] === marker[0] && close[2].length >= marker.length && !close[3].trim()) break;
body.push(lines[j].replace(new RegExp(`^[ \\t]{0,${indent}}`), ''));
}
const lang = fence[3].trim().split(/\s+/)[0] ?? '';
const content = body.join('\n');
out.push(lang.toLowerCase() === 'mermaid' ? { type: 'mermaid', text: content } : { type: 'code', lang: unescapeText(lang), text: content });
return j + 1;
}
// $$ math block: needs a closing $$ and some content, otherwise the line is plain text.
if (line.trim() === '$$') {
let j = i + 1;
while (j < lines.length && lines[j].trim() !== '$$') j += 1;
const content = lines.slice(i + 1, j).filter((l) => l.length > 0);
if (j < lines.length && content.length > 0) {
out.push({ type: 'math_block', text: content.join('\n') });
return j + 1;
}
}
// :::details Title / :::left|center|right|justify … ::: (the close needs the same colon count).
const colon = COLON_FENCE.exec(line);
if (colon) {
const keyword = colon[2].toLowerCase();
const header = colon[3] ?? '';
const isDetails = keyword === 'details';
const isAlign = ['left', 'center', 'right', 'justify'].includes(keyword);
if ((isDetails || (isAlign && !header)) && !header.includes(':::')) {
const count = colon[1].length;
let j = i + 1;
while (j < lines.length && !new RegExp(`^[ \\t]*:{${count}}[ \\t]*$`).test(lines[j])) j += 1;
const inner = this.parseBlocks(lines.slice(i + 1, j), depth + 1);
if (isDetails) out.push({ type: 'details', summary: header ? this.parseInline(header, depth + 1) : [], children: inner });
else out.push({ type: 'align', align: keyword, children: inner });
return j + 1;
}
}
// BBCode block mode: an opening tag alone on its line, its closing tag alone on a later line.
const bbOpen = /^[ \t]*\[([a-z]+)(?:[= ]([^\]\n]*))?\][ \t]*$/i.exec(line);
if (bbOpen) {
const tag = bbOpen[1].toLowerCase();
if (tag === 'hr') {
out.push({ type: 'hr' });
return i + 1;
}
if (BB_PAIRED.has(tag) && (bbOpen[2] === undefined || BB_PARAM.has(tag))) {
const closeRe = new RegExp(`^[ \\t]*\\[/${tag}\\][ \\t]*$`, 'i');
let j = i + 1;
while (j < lines.length && !closeRe.test(lines[j])) j += 1;
if (j < lines.length && j > i + 1 && lines.slice(i + 1, j).some((l) => l.trim())) {
out.push(bbBlock(tag, (bbOpen[2] ?? '').trim(), this.parseBlocks(lines.slice(i + 1, j), depth + 1)));
return j + 1;
}
}
}
// Blockquote: every quoted line needs its own `>` (strict, no lazy continuation).
if (/^[ \t]{0,3}>/.test(line)) {
const inner = [];
let j = i;
for (; j < lines.length && /^[ \t]{0,3}>/.test(lines[j]); j += 1) inner.push(lines[j].replace(/^[ \t]{0,3}> ?/, ''));
let callout = null;
const rest = [];
for (const l of inner) {
const marker = /^\s*\[!([A-Za-z]+)\]\s*$/.exec(l);
const type = marker && CALLOUTS.get(marker[1].toUpperCase());
if (type) {
if (!callout) callout = { type, title: CALLOUT_TITLES[type] };
continue;
}
rest.push(l);
}
out.push({ type: 'blockquote', callout, children: this.parseBlocks(rest, depth + 1) });
return j;
}
if (isThematicBreak(line)) {
out.push({ type: 'hr' });
return i + 1;
}
const atx = ATX.exec(line);
if (atx) {
out.push({ type: 'heading', level: atx[1].length, children: this.parseInline(atx[2] ?? '', depth + 1) });
return i + 1;
}
const marker = listMarker(line);
if (marker) {
const { list, next } = this.parseList(lines, i, marker.kind, marker.from, depth);
out.push(list);
return next;
}
const fn = FOOTNOTE_DEF.exec(line);
if (fn) {
const body = [fn[2]];
let j = i + 1;
while (j < lines.length && !isBlank(lines[j]) && leadingSpaces(lines[j]) > 0) body.push(lines[j].trim()), (j += 1);
if (!this.footnoteDefs.has(fn[1])) {
this.footnoteDefs.set(fn[1], { children: this.parseInline(body.join(' '), depth + 1), lines: depth === 0 ? [i, j] : null });
}
return j;
}
const def = LINK_DEF.exec(line);
if (def && !def[1].startsWith('^')) return i + 1;
// GFM table: header row with pipes followed by a delimiter row.
if (line.includes('|') && i + 1 < lines.length && isTableDelimiter(lines[i + 1])) {
const align = splitRow(lines[i + 1]).map((c) => {
const t = c.trim();
if (t.startsWith(':') && t.endsWith(':')) return 'center';
if (t.endsWith(':')) return 'right';
if (t.startsWith(':')) return 'left';
return null;
});
const header = splitRow(line).map((c) => this.parseInline(c.trim(), depth + 1));
const rows = [];
let j = i + 2;
for (; j < lines.length && !isBlank(lines[j]) && lines[j].includes('|'); j += 1) {
rows.push(splitRow(lines[j]).map((c) => this.parseInline(c.trim(), depth + 1)));
}
out.push({ type: 'table', align, header, rows });
return j;
}
// Setext heading: a text line underlined by === or ---.
if (i + 1 < lines.length && isSetextUnderline(lines[i + 1])) {
out.push({ type: 'heading', level: lines[i + 1].trim()[0] === '=' ? 1 : 2, children: this.parseInline(line.trim(), depth + 1) });
return i + 2;
}
out.push({ type: 'paragraph', children: this.parseInline(line.replace(/^[ \t]+/, '').replace(/[ \t]+$/, ''), depth + 1) });
return i + 1;
}
/** Strict single-line list items; deeper markers (≥ marker + 2 columns) open a nested list. */
parseList(lines, i, kind, baseIndent, depth) {
const items = [];
let start = null;
while (i < lines.length) {
const m = listMarker(lines[i]);
if (!m || m.kind !== kind || m.from < baseIndent || isThematicBreak(lines[i])) break;
if (start === null) start = m.start;
const content = lines[i].slice(m.content);
const item = { task: m.task, children: isThematicBreak(content) ? [{ type: 'hr' }] : this.parseInline(content.trim(), depth + 1), sub: null };
i += 1;
const next = i < lines.length ? listMarker(lines[i]) : null;
if (next && next.from >= m.from + 2 && depth < MAX_DEPTH) {
const nested = this.parseList(lines, i, next.kind, next.from, depth + 1);
item.sub = nested.list;
i = nested.next;
}
items.push(item);
this.count();
}
return { list: { type: 'list', ordered: kind === 'ordered', start: start ?? 1, items }, next: i };
}
// ---------------- inline ----------------
parseInline(text, depth) {
if (depth > MAX_DEPTH || !text) return text ? [{ type: 'text', value: text }] : [];
return new InlineParser(this, text, depth).run();
}
footnoteRef(label) {
if (!this.footnoteOrder.includes(label)) this.footnoteOrder.push(label);
return this.footnoteOrder.indexOf(label) + 1;
}
}
function splitRow(line) {
let s = line.trim();
if (s.startsWith('|')) s = s.slice(1);
if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1);
const cells = [];
let cur = '';
for (let k = 0; k < s.length; k += 1) {
if (s[k] === '\\' && s[k + 1] === '|') { cur += '|'; k += 1; continue; }
if (s[k] === '|') { cells.push(cur); cur = ''; continue; }
cur += s[k];
}
cells.push(cur);
return cells;
}
function bbBlock(tag, param, children) {
switch (tag) {
case 'b': return { type: 'bb_block', style: 'strong', children };
case 'i': return { type: 'bb_block', style: 'emphasis', children };
case 'u': return { type: 'bb_block', style: 'underline', children };
case 's': return { type: 'bb_block', style: 'strikethrough', children };
case 'color': return { type: 'bb_block', style: 'color', color: BB_COLOR.test(param) ? param : null, children };
case 'size': return { type: 'bb_block', style: 'size', size: Object.hasOwn(BB_SIZES, param) ? BB_SIZES[param] : null, children };
default: return { type: 'bb_align', align: tag, block: true, children };
}
}
/** Delimiter flanking used by the official ++, ==, || and $ parsers (`uo`, `sb`, `fb`, `ub`). */
function flanking(text, from, to) {
const before = from > 0 ? text[from - 1] : '';
const after = to < text.length ? text[to] : '';
const sBefore = !before || WS.test(before);
const sAfter = !after || WS.test(after);
const pBefore = Boolean(before) && PUNCT.test(before);
const pAfter = Boolean(after) && PUNCT.test(after);
const leftFlanking = !sAfter && (!pAfter || sBefore || pBefore);
const rightFlanking = !sBefore && (!pBefore || sAfter || pAfter);
return { leftFlanking, rightFlanking, pBefore, pAfter };
}
/** Matching `[`/`]` positions computed once per string, so bracket lookups stay linear. */
function bracketPairs(text) {
const pairs = new Map();
const stack = [];
let inCode = 0;
for (let k = 0; k < text.length; k += 1) {
const c = text[k];
if (c === '\\') { k += 1; continue; }
if (c === '`') {
let n = 1;
while (text[k + n] === '`') n += 1;
if (inCode === 0) inCode = n;
else if (inCode === n) inCode = 0;
k += n - 1;
continue;
}
if (inCode) continue;
if (c === '[') stack.push(k);
else if (c === ']' && stack.length) pairs.set(stack.pop(), k);
}
return pairs;
}
const URL_START = /(www\.)|(https?:\/\/)|([\w.+-]{1,100}@)|(mailto:|xmpp:)/y;
const DOMAIN_HTTP = /[\w-]+(?:\.[\w-]+)*(?::\d{1,5})?(?:\/[^\s<]*)?/y;
const DOMAIN_WWW = /[\w-]+(?:\.[\w-]+)+(?::\d{1,5})?(?:\/[^\s<]*)?/y;
const EMAIL = /[\w.+-]+@[\w-]+(\.[\w.-]+)+/y;
function countChar(s, from, to, ch) {
let n = 0;
for (let k = from; k < to; k += 1) if (s[k] === ch) n += 1;
return n;
}
/** GFM extended autolink (the official `LO` extension): returns the end index or -1. */
function plainUrlEnd(text, pos) {
if (pos > 0 && /\w/.test(text[pos - 1])) return -1;
URL_START.lastIndex = pos;
const m = URL_START.exec(text);
if (!m) return -1;
if (m[1] || m[2]) {
const re = m[2] ? DOMAIN_HTTP : DOMAIN_WWW;
const start = pos + m[0].length;
re.lastIndex = start;
const d = re.exec(text);
if (!d) return -1;
const host = /^[\w.-]+/.exec(d[0])[0];
const last = /[\w-]+\.[\w-]+$/.exec(host);
if (last && last[0].includes('_')) return -1;
let end = start + d[0].length;
for (;;) {
const c = text[end - 1];
if (/[?!.,:*_~]/.test(c) || (c === ')' && countChar(text, start, end, ')') > countChar(text, start, end, '('))) end -= 1;
else if (c === ';') {
const ent = /&(?:#\d+|#x[a-f\d]+|\w+);$/.exec(text.slice(start, end));
if (!ent) break;
end = start + ent.index;
} else break;
}
return end > start ? end : -1;
}
const emailFrom = m[3] ? pos : pos + m[0].length;
EMAIL.lastIndex = emailFrom;
const e = EMAIL.exec(text);
if (!e) return -1;
const last = e[0][e[0].length - 1];
if (last === '_' || last === '-') return -1;
return emailFrom + e[0].length - (last === '.' ? 1 : 0);
}
class InlineParser {
constructor(parser, text, depth) {
this.p = parser;
this.text = text;
this.depth = depth;
this.pairs = bracketPairs(text);
this.out = [];
this.buf = '';
this.delims = [];
}
flush() {
if (this.buf) {
this.out.push({ type: 'text', value: this.buf });
this.buf = '';
}
}
push(node) {
this.flush();
this.p.count();
this.out.push(node);
}
inner(text) {
return this.p.parseInline(text, this.depth + 1);
}
run() {
const t = this.text;
let i = 0;
while (i < t.length) {
const next = this.step(i);
if (next > i) { i = next; continue; }
this.buf += t[i];
i += 1;
}
this.flush();
this.processEmphasis();
return mergeText(this.out);
}
/** Tries every inline construct at `i`; returns the new position or `i` when nothing matched. */
step(i) {
const t = this.text;
const c = t[i];
switch (c) {
case '\\':
if (i + 1 < t.length && ASCII_PUNCT.test(t[i + 1])) {
this.buf += t[i + 1];
return i + 2;
}
return i;
case '`': return this.codeSpan(i);
case '$': return this.inlineMath(i);
case '<': return this.angleAutolink(i);
case '&': {
const m = /^&(?:#\d{1,7}|#[xX][0-9a-fA-F]{1,6}|[A-Za-z][A-Za-z0-9]{1,31});/.exec(t.slice(i, i + 40));
const value = m && decodeEntity(m[0]);
if (value === null || !m) return i;
this.buf += value;
return i + m[0].length;
}
case '!':
if (t[i + 1] === '[' && t[i + 2] === '^') {
// Official `FootnoteRefAfterBang`: the reference swallows the bang.
const r = this.footnote(i + 1);
return r > i + 1 ? r : i;
}
if (t[i + 1] === '[') return this.linkOrImage(i + 1, true);
return i;
case '[': {
if (t[i + 1] === '^') {
const r = this.footnote(i);
if (r > i) return r;
}
const bb = this.bbcode(i);
if (bb > i) return bb;
return this.linkOrImage(i, false);
}
case ':': return this.emoji(i);
case '^': return this.subSuper(i, '^', 'sup');
case '~':
if (t[i + 1] === '~') return this.delimiter(i, '~', 2, 'del');
return this.subSuper(i, '~', 'sub');
case '*': case '_': return this.delimiter(i, c, 0, null);
case '+': return t[i + 1] === '+' && t[i - 1] !== '\\' ? this.delimiter(i, '+', 2, 'u') : i;
case '=':
if (t[i + 1] === '=' && t[i - 1] !== '=' && t[i + 2] !== '=') return this.delimiter(i, '=', 2, 'mark');
return i;
case '|': return t[i + 1] === '|' ? this.delimiter(i, '|', 2, 'spoiler') : i;
default: {
if (c === 'w' || c === 'h' || c === 'm' || c === 'x' || /[\w.+-]/.test(c)) {
const end = plainUrlEnd(t, i);
if (end > i) {
const raw = t.slice(i, end);
const email = !/^(?:https?:\/\/|www\.|mailto:|xmpp:)/i.test(raw);
this.push({ type: 'link', href: raw, email, title: null, auto: true, children: [{ type: 'text', value: raw }] });
return end;
}
}
return i;
}
}
}
codeSpan(i) {
const t = this.text;
let n = 0;
while (t[i + n] === '`') n += 1;
let k = i + n;
while (k < t.length) {
const j = t.indexOf('`', k);
if (j < 0) break;
let m = 0;
while (t[j + m] === '`') m += 1;
if (m === n) {
let code = t.slice(i + n, j);
if (code.length > 2 && code.startsWith(' ') && code.endsWith(' ') && code.trim()) code = code.slice(1, -1);
this.push({ type: 'code', value: code });
return j + m;
}
k = j + m;
}
this.buf += t.slice(i, i + n);
return i + n;
}
/** `$…$` exactly as the official `lb` parser: no `$$`, flanking open/close, single line, non-blank. */
inlineMath(i) {
const t = this.text;
if (t[i + 1] === '$' || (i > 0 && t[i - 1] === '\\') || !flanking(t, i, i + 1).leftFlanking) return i;
for (let k = i + 1; k < t.length; k += 1) {
if (t[k] !== '$' || t[k - 1] === '\\') continue;
if (t[k + 1] === '$') return i;
if (!flanking(t, k, k + 1).rightFlanking) continue;
const src = t.slice(i + 1, k);
if (!src.trim()) return i;
this.push({ type: 'math', value: src });
return k + 1;
}
return i;
}
angleAutolink(i) {
const t = this.text;
const close = t.indexOf('>', i + 1);
if (close < 0) return i;
const inner = t.slice(i + 1, close);
if (!inner || /[\s<]/.test(inner)) return i;
const isUrl = /^[A-Za-z][A-Za-z0-9+.-]+:[^\s<>]*$/.test(inner);
const isEmail = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/.test(inner);
if (!isUrl && !isEmail) return i;
this.push({ type: 'link', href: inner, email: !isUrl, title: null, auto: true, children: [{ type: 'text', value: inner }] });
return close + 1;
}
footnote(i) {
const t = this.text;
let k = i + 2;
while (k < t.length && t[k] !== ']' && t[k] !== '\n') k += 1;
if (t[k] !== ']' || k <= i + 2) return i;
const label = t.slice(i + 2, k);
if (!this.p.footnoteDefs.has(label) && !this.p.pendingFootnote?.(label)) return i;
const number = this.p.footnoteRef(label);
this.push({ type: 'fnref', label, number });
return k + 1;
}
emoji(i) {
const t = this.text;
let k = i + 1;
while (k < t.length && /[A-Za-z0-9_+-]/.test(t[k])) k += 1;
if (t[k] !== ':' || k === i + 1) return i;
const code = t.slice(i + 1, k);
const unicode = emojiForShortcode(code);
if (!unicode) return i;
this.push({ type: 'emoji', shortcode: code, unicode });
return k + 1;
}
/** `^sup^` / `~sub~` (lezer GFM `Dr`): single marker, no whitespace inside. */
subSuper(i, ch, type) {
const t = this.text;
if (t[i + 1] === ch) return i;
let value = '';
for (let k = i + 1; k < t.length; k += 1) {
const c = t[k];
if (c === ch) {
if (!value) return i;
this.push({ type, children: this.inner(value) });
return k + 1;
}
if (c === '\\' && k + 1 < t.length) { value += c + t[k + 1]; k += 1; continue; }
if (WS.test(c)) return i;
value += c;
}
return i;
}
linkOrImage(open, image) {
const t = this.text;
const close = this.pairs.get(open);
if (close === undefined) return image ? open - 1 : open;
const label = t.slice(open + 1, close);
const start = image ? open - 1 : open;
let end = -1;
let dest = null;
if (t[close + 1] === '(') {
const parsed = parseDestination(t, close + 2, image);
if (parsed) { dest = parsed; end = parsed.end; }
}
if (!dest) {
let refLabel = null;
if (t[close + 1] === '[') {
const refClose = this.pairs.get(close + 1);
if (refClose !== undefined) {
const inner = t.slice(close + 2, refClose);
refLabel = inner.trim() ? inner : label;
end = refClose + 1;
}
}
if (refLabel === null) { refLabel = label; end = close + 1; }
const ref = this.p.refs.get(normalizeLabel(refLabel));
if (!ref) return start;
dest = { href: ref.href, title: ref.title, width: null, height: null };
}
if (image) {
this.push({ type: 'image', src: dest.href, alt: unescapeText(label), title: dest.title, width: dest.width, height: dest.height });
} else {
if (/\[[^\]]*\]\(/.test(label) && this.inner(label).some((n) => n.type === 'link')) return start;
this.push({ type: 'link', href: dest.href, email: false, title: dest.title, auto: false, children: this.inner(label) });
}
return end;
}
/** BBCode inline tags. Paired tags need a matching close; [url]/[img] are atomic (official `xo`). */
bbcode(i) {
const t = this.text;
const m = /^\[([a-zA-Z]+)(?:([= ])([^\]\n]*))?\]/.exec(t.slice(i, i + 300));
if (!m) return i;
const tag = m[1].toLowerCase();
const param = m[2] ? m[3].trim() : null;
const openEnd = i + m[0].length;
const pair = this.bbPairs().get(i);
if (!pair) return i;
if (tag === 'url' || tag === 'img') {
const content = t.slice(openEnd, pair.from);
if (tag === 'url') {
const href = (param ?? content).trim().replace(/^<(.*)>$/, '$1');
if (!href) return i;
this.push({ type: 'link', href, email: false, title: null, auto: false, children: param !== null ? this.inner(content) : [{ type: 'text', value: content }] });
} else {
const size = param ? bbImageParams(param) : {};
const src = (content.trim() || size.legacyUrl || '').replace(/^<(.*)>$/, '$1');
if (!src) return i;
this.push({ type: 'image', src, alt: size.alt ?? '', title: null, width: size.width ?? null, height: size.height ?? null });
}
return pair.to;
}
if (!BB_PAIRED.has(tag) || (param !== null && !BB_PARAM.has(tag))) return i;
const children = this.inner(t.slice(openEnd, pair.from));
switch (tag) {
case 'b': this.push({ type: 'strong', children }); break;
case 'i': this.push({ type: 'em', children }); break;
case 'u': this.push({ type: 'u', children }); break;
case 's': this.push({ type: 'del', children }); break;
case 'color': this.push({ type: 'color', color: param && BB_COLOR.test(param) ? param : null, children }); break;
case 'size': this.push({ type: 'size', size: param && Object.hasOwn(BB_SIZES, param) ? BB_SIZES[param] : null, children }); break;
default: this.push({ type: 'bb_align', align: tag, block: false, children });
}
return pair.to;
}
/**
* Open-tag index → its close tag, from one pass over the string. Paired tags nest per tag name;
* [url]/[img] take the first close after them (atomic, like the official `xo` "atomic-paired" mode).
*/
bbPairs() {
if (this.bb) return this.bb;
this.bb = new Map();
if (!this.text.includes('[/')) return this.bb;
const stacks = new Map();
const re = /\[(\/?)([a-zA-Z]+)(?:[= ][^\]\n]*)?\]/g;
let m;
while ((m = re.exec(this.text))) {
const tag = m[2].toLowerCase();
if (!BB_PAIRED.has(tag) && tag !== 'url' && tag !== 'img') continue;
let stack = stacks.get(tag);
if (!stack) stacks.set(tag, (stack = []));
if (!m[1]) {
if (!((tag === 'url' || tag === 'img') && stack.length)) stack.push(m.index);
} else if (stack.length) {
this.bb.set(stack.pop(), { from: m.index, to: m.index + m[0].length });
}
}
return this.bb;
}
/** Records a delimiter run; matching happens in processEmphasis (CommonMark style). */
delimiter(i, ch, fixed, type) {
const t = this.text;
let n = 0;
while (t[i + n] === ch) n += 1;
if (fixed && n !== fixed) {
if (ch === '~' || ch === '|' || ch === '+') { this.buf += t.slice(i, i + n); return i + n; }
return i;
}
const f = flanking(t, i, i + n);
let canOpen = f.leftFlanking;
let canClose = f.rightFlanking;
if (ch === '_') {
canOpen = f.leftFlanking && (!f.rightFlanking || f.pBefore);
canClose = f.rightFlanking && (!f.leftFlanking || f.pAfter);
}
this.flush();
const node = { type: 'text', value: t.slice(i, i + n) };
this.out.push(node);
this.delims.push({ ch, node, count: n, orig: n, canOpen, canClose, type, active: true });
return i + n;
}
processEmphasis() {
const ds = this.delims;
for (let ci = 0; ci < ds.length; ci += 1) {
const closer = ds[ci];
if (!closer.canClose || closer.count === 0) continue;
for (let oi = ci - 1; oi >= 0; oi -= 1) {
const opener = ds[oi];
if (opener.ch !== closer.ch || !opener.canOpen || opener.count === 0) continue;
let use;
let type;
if (closer.type) {
use = 2;
type = closer.type;
} else {
if ((opener.canClose || closer.canOpen) && (opener.orig + closer.orig) % 3 === 0 && !(opener.orig % 3 === 0 && closer.orig % 3 === 0)) continue;
use = opener.count >= 2 && closer.count >= 2 ? 2 : 1;
type = use === 2 ? 'strong' : 'em';
}
this.wrap(opener, closer, use, type);
// Delimiters between opener and closer can no longer match.
for (let k = oi + 1; k < ci; k += 1) ds[k].count = ds[k].count && ds[k] !== closer ? 0 : ds[k].count;
if (closer.count > 0) ci -= 1;
break;
}
}
}
wrap(opener, closer, use, type) {
const out = this.out;
const a = out.indexOf(opener.node);
const b = out.indexOf(closer.node);
const inner = out.slice(a + 1, b);
opener.count -= use;
closer.count -= use;
opener.node.value = opener.node.value.slice(0, opener.count);
closer.node.value = closer.node.value.slice(0, closer.count);
const node = { type, children: mergeText(inner) };
out.splice(a + 1, b - a - 1, node);
}
}
function bbImageParams(param) {
const t = param.trim();
if (!t) return {};
const out = {};
const wh = /^(\d+%?)x(\d+%?)$/i.exec(t);
if (wh) return { width: wh[1], height: wh[2] };
const w = /(?:^|\s)width\s*=\s*(\d+%?)/i.exec(t);
if (w) out.width = w[1];
const h = /(?:^|\s)height\s*=\s*(\d+%?)/i.exec(t);
if (h) out.height = h[1];
const alt = /(?:^|\s)alt\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/i.exec(t);
if (alt) out.alt = alt[1] ?? alt[2] ?? alt[3];
if (!out.width && !out.height && out.alt === undefined) out.legacyUrl = t;
return out;
}
/** `(dest "title")`, with the official image size forms ` | width=… height=…` and ` =WxH`. */
function parseDestination(t, k, image) {
while (t[k] === ' ' || t[k] === '\t') k += 1;
let href = '';
if (t[k] === '<') {
const close = t.indexOf('>', k + 1);
if (close < 0) return null;
href = t.slice(k + 1, close);
k = close + 1;
} else {
let level = 0;
const from = k;
for (; k < t.length; k += 1) {
const c = t[k];
if (c === '\\' && k + 1 < t.length) { k += 1; continue; }
if (c === ' ' || c === '\t') break;
if (c === '(') level += 1;
if (c === ')') {
if (level === 0) break;
level -= 1;
}
}
href = t.slice(from, k);
}
let title = null;
let width = null;
let height = null;
while (t[k] === ' ' || t[k] === '\t') k += 1;
if (image && t[k] === '|') {
const close = t.indexOf(')', k);
if (close < 0) return null;
const spec = t.slice(k + 1, close);
const w = /width\s*=\s*(\d+%?)/i.exec(spec);
const h = /height\s*=\s*(\d+%?)/i.exec(spec);
width = w ? w[1] : null;
height = h ? h[1] : null;
k = close;
} else if (image && t[k] === '=') {
const m = /^=(\d+%?)?x(\d+%?)?/i.exec(t.slice(k));
if (!m) return null;
width = m[1] ?? null;
height = m[2] ?? null;
k += m[0].length;
while (t[k] === ' ') k += 1;
} else if (t[k] === '"' || t[k] === "'" || t[k] === '(') {
const q = t[k] === '(' ? ')' : t[k];
let e = k + 1;
for (; e < t.length && t[e] !== q; e += 1) if (t[e] === '\\') e += 1;
if (e >= t.length) return null;
title = unescapeText(t.slice(k + 1, e));
k = e + 1;
while (t[k] === ' ' || t[k] === '\t') k += 1;
}
if (t[k] !== ')') return null;
return { href: unescapeText(href), title, width, height, end: k + 1 };
}
function mergeText(nodes) {
const out = [];
for (const n of nodes) {
if (n.type === 'text') {
if (!n.value) continue;
const prev = out[out.length - 1];
if (prev && prev.type === 'text') {
prev.value += n.value;
continue;
}
out.push({ type: 'text', value: n.value });
} else {
out.push(n);
}
}
return out;
}
/**
* Parses a chat message. Footnote definitions may follow their references, so definitions are
* collected first and references resolved against them (official: footnotes collected document-wide,
* rendered at the end in first-reference order).
*/
export function parseMarkdown(source) {
const text = String(source ?? '');
const p = new Parser();
const pending = new Set();
for (const line of text.replace(/\r\n?/g, '\n').split('\n')) {
const fn = FOOTNOTE_DEF.exec(line);
if (fn) pending.add(fn[1]);
}
p.pendingFootnote = (label) => pending.has(label);
try {
return p.parseDocument(text);
} catch (err) {
if (err instanceof RangeError) return { type: 'doc', children: [{ type: 'paragraph', children: [{ type: 'text', value: text }] }], footnotes: [], tooComplex: true };
throw err;
}
}
/** Plain-text preview of a message (official `text-short` profile): used for notifications and badges. */
export function toPlainText(doc) {
const parts = [];
const walk = (nodes) => {
for (const n of nodes) {
switch (n.type) {
case 'text': parts.push(n.value); break;
case 'code': parts.push(n.value ?? '[code]'); break;
case 'math': parts.push(n.value); break;
case 'emoji': parts.push(n.unicode); break;
case 'image': parts.push('🖼️'); break;
case 'math_block': parts.push('[math]'); break;
case 'mermaid': parts.push('[diagram]'); break;
case 'fnref': parts.push(String(n.number)); break;
case 'hr': parts.push(' '); break;
case 'list': for (const item of n.items) { walk(item.children); parts.push(' '); if (item.sub) walk([item.sub]); } break;
case 'table': for (const row of [n.header, ...n.rows]) for (const cell of row) { walk(cell); parts.push(' '); } break;
case 'details': walk(n.summary); parts.push(' '); walk(n.children); break;
default: if (n.children) { walk(n.children); if (/^(paragraph|heading|blockquote|align|bb_block)$/.test(n.type)) parts.push(' '); }
}
}
};
walk(doc.children);
return parts.join('').replace(/\s+/g, ' ').trim();
}