/**
* Markdown renderer for the wiki (M17).
*
* Deliberately small: headings, lists, tables, code, quotes, links, emphasis.
* Everything is HTML-escaped **before** any transformation runs, so a page can
* never inject markup — the pages are written by the team, but a renderer that
* relies on that is one mistake away from being a hole.
*/
const escape = (text) =>
String(text ?? '')
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
export const slugify = (text) =>
String(text)
.toLowerCase()
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
/** Inline pass, applied to text that is already escaped. */
function inline(text) {
return text
.replace(/`([^`]+)`/g, '$1')
.replace(
/!\[([^\]]*)\]\(([^)\s]+)\)/g,
(_, alt, src) => ``,
)
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, label, href) => {
// Only http(s) and in-page anchors: no `javascript:` sneaking through.
const safe = /^(https?:\/\/|\/|#)/.test(href) ? href : '#';
const external = safe.startsWith('http');
return `${label}`;
})
.replace(/\*\*([^*]+)\*\*/g, '$1')
.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1$2')
.replace(/~~([^~]+)~~/g, '
$1');
}
const cells = (line) =>
line
.trim()
.replace(/^\||\|$/g, '')
.split('|')
.map((cell) => inline(cell.trim()));
/**
* Renders a page and returns `{ html, headings }`, the headings feeding the
* table of contents.
*/
export function render(markdown) {
const lines = escape(markdown).split('\n');
const out = [];
const headings = [];
let index = 0;
const closeList = (stack) => {
while (stack.length > 0) out.push(`${stack.pop()}>`);
};
const listStack = [];
while (index < lines.length) {
const line = lines[index];
// Fenced code, kept verbatim.
if (/^\s*```/.test(line)) {
closeList(listStack);
const body = [];
index += 1;
while (index < lines.length && !/^\s*```/.test(lines[index])) body.push(lines[index++]);
index += 1;
out.push(`
${body.join('\n')}`);
continue;
}
// Table: a header row followed by a separator row.
if (line.includes('|') && /^\s*\|?[\s:-]+\|[\s:|-]*$/.test(lines[index + 1] ?? '')) {
closeList(listStack);
const header = cells(line);
index += 2;
const rows = [];
while (index < lines.length && lines[index].includes('|') && lines[index].trim() !== '') {
rows.push(cells(lines[index++]));
}
out.push(
`| ${cell} | `) .join('')}
|---|
| ${cell} | `).join('')}
${inline(body.join(' '))}`); continue; } const bullet = /^\s*[-*]\s+(.*)$/.exec(line); const ordered = /^\s*\d+\.\s+(.*)$/.exec(line); if (bullet || ordered) { const tag = bullet ? 'ul' : 'ol'; if (listStack.at(-1) !== tag) { closeList(listStack); out.push(`<${tag}>`); listStack.push(tag); } out.push(`
${inline(paragraph.join(' '))}
`); } closeList(listStack); return { html: out.join('\n'), headings }; }