class MDRenderer { constructor() { this.rules = { heading: /^[ \t]{0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/gm, paragraph: /^(?!<|@@MDRENDER_|[ \t]{0,3}(?:#{1,6}[ \t]|[-*+][ \t]|\d{1,9}[.)][ \t])|[ \t]*(?:[-*_][ \t]*){3,}[ \t]*$|[ \t]*={3,}[ \t]*$)(.*\S.*)$/gm, boldItalic: /\*\*\*([^*]+?)\*\*\*/g, boldItalicU: /___([^_]+?)___/g, bold: /\*\*([^*]+?)\*\*/g, boldU: /__([^_]+?)__/g, italic: /\*([^*\n]+?)\*/g, italicU: /(??@[\\\]^_`{|}~])/g, refLink: /\[([^\]\n]+)\]\[([^\]\n]*)\]/g, refShortcut: /\[([^\]\n]+)\](?![\(\[])/g, refImage: /!\[([^\]\n]+)\]\[([^\]\n]*)\]/g, emoji: /:([a-zA-Z0-9_+-]+):/g, }; this.footnotes = new Map(); this.abbreviations = new Map(); this.references = new Map(); this._stash = []; this._nonce = ''; this._headingIds = {}; this.emojis = { 'smile': '😊', 'laugh': '😄', 'joy': '😂', 'wink': '😉', 'heart': 'â¤ī¸', 'heart_eyes': '😍', 'thinking': '🤔', 'clap': '👏', 'wave': '👋', 'eyes': '👀', 'check': '✅', 'x': '❌', 'warning': 'âš ī¸', 'info': 'â„šī¸', 'thumbsup': '👍', 'thumbsdown': '👎', 'rocket': '🚀', 'star': '⭐', 'fire': 'đŸ”Ĩ', 'sunny': 'â˜€ī¸', 'sun': 'â˜€ī¸', 'moon': '🌙', 'cloud': 'â˜ī¸', 'coffee': '☕', 'pizza': '🍕', 'cake': '🍰', 'apple': '🍎', 'tada': '🎉', 'bug': '🐛', 'zap': '⚡', }; } render(markdown) { this.footnotes = new Map(); this.abbreviations = new Map(); this.references = new Map(); this._stash = []; this._nonce = Math.random().toString(36).slice(2, 10); this._headingIds = {}; let html = this._render(String(markdown ?? '')); if (this.footnotes.size > 0) { html += this.renderFootnotesSection(); } const tokenRe = new RegExp(`@@MDRENDER_${this._nonce}_(\\d+)@@`, 'g'); const resolve = (s) => s.replace(tokenRe, (m, i) => { const v = this._stash[+i]; return v === undefined ? m : resolve(v); }); html = resolve(html); return `
${html}
`; } _render(markdown) { let html = markdown.replace(/\r\n?/g, '\n'); // Protect raw HTML blocks that must not be touched by inline rules html = html.replace(//gi, m => this._stashHtml(m)); html = html.replace(//gi, m => this._stashHtml(m)); html = html.replace(//g, m => this._stashHtml(m)); // Code blocks first so their content is never parsed as markdown html = this.renderCodeBlocks(html); // Extract footnote/reference/abbreviation definitions before block parsing html = this.collectFootnotes(html); html = this.collectReferences(html); html = this.collectAbbreviations(html); // Block-level elements html = this.renderBlockquotes(html); html = this.renderHorizontalRules(html); html = this.renderHeadings(html); html = this.renderTables(html); html = this.renderLists(html); html = this.renderDefinitions(html); html = this.renderParagraphs(html); // Inline elements return this.renderInline(html); } _stashHtml(html) { const token = `@@MDRENDER_${this._nonce}_${this._stash.length}@@`; this._stash.push(html); return token; } _escapeHtml(s) { return s.replace(/&/g, '&').replace(//g, '>'); } _escapeAttr(s) { return this._escapeHtml(s).replace(/"/g, '"'); } _escapeRegExp(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } _indentWidth(indent) { return indent.replace(/\t/g, ' ').length; } _fnId(ref) { return ref.replace(/[^\w-]+/g, '-').replace(/^-+|-+$/g, '') || 'fn'; } // ---------- Block-level rendering ---------- renderCodeBlocks(text) { return text.replace(this.rules.codeblock, (m, lang, code) => { lang = (lang || '').trim(); const cls = lang ? ` class="language-${this._escapeAttr(lang)}"` : ''; return this._stashHtml(`
${this._escapeHtml(code.trim())}
`); }); } collectFootnotes(text) { const lines = text.split('\n'); const out = []; for (let i = 0; i < lines.length; i++) { const m = lines[i].match(/^\[\^([^\]\n]+)\]:[ \t]*(.*)$/); if (!m) { out.push(lines[i]); continue; } let defLines = [m[2]]; let j = i + 1; while (j < lines.length) { if (/^[ \t]+\S/.test(lines[j])) { defLines.push(lines[j].trim()); j++; } else if (/^[ \t]*$/.test(lines[j]) && j + 1 < lines.length && /^[ \t]+\S/.test(lines[j + 1])) { defLines.push(''); j++; } else { break; } } this.footnotes.set(m[1], defLines.join('\n').trim()); i = j - 1; } return out.join('\n'); } collectReferences(text) { return text.replace(/^[ \t]{0,3}\[([^\]\n]+)\]:[ \t]*(\S+)(?:[ \t]+["']([^"']*)["'])?[ \t]*$/gm, (m, label, url, title) => { this.references.set(label.toLowerCase(), { url, title }); return ''; }); } collectAbbreviations(text) { return text.replace(/^[ \t]{0,3}\*\[([^\]\n]+)\]:[ \t]*(.+?)[ \t]*$/gm, (m, abbr, def) => { this.abbreviations.set(abbr, def); return ''; }); } renderBlockquotes(text) { const lines = text.split('\n'); const out = []; let i = 0; while (i < lines.length) { if (/^[ \t]{0,3}>/.test(lines[i])) { const quoteLines = []; while (i < lines.length && /^[ \t]{0,3}>/.test(lines[i])) { quoteLines.push(lines[i].replace(/^[ \t]{0,3}>[ \t]?/, '')); i++; } const inner = this._render(quoteLines.join('\n')); out.push(this._stashHtml(`
\n${inner}\n
`)); } else { out.push(lines[i]); i++; } } return out.join('\n'); } renderHorizontalRules(text) { return text.replace(this.rules.horizontalRule, '
'); } renderHeadings(text) { return text.replace(this.rules.heading, (m, level, content) => { const n = level.length; let id = content.toLowerCase() .replace(/[^\w\s-]+/g, '') .trim() .replace(/[\s]+/g, '-') .replace(/-+/g, '-') .replace(/^-+|-+$/g, ''); if (!id) id = 'section'; const count = this._headingIds[id] = (this._headingIds[id] || 0) + 1; if (count > 1) id = `${id}-${count}`; return `${content}`; }); } _isTableDelimiter(line) { return this.rules.tableDelimiter.test(line); } _isTableRow(line) { return this.rules.tableRow.test(line); } _splitTableRow(line) { return line.split(/(? c.trim().replace(/\\\|/g, '|')); } _parseAlignment(delimLine) { return this._splitTableRow(delimLine).map(cell => { const left = cell.startsWith(':'); const right = cell.endsWith(':'); if (left && right) return 'center'; if (right) return 'right'; if (left) return 'left'; return ''; }); } _alignAttr(alignments, index) { const a = alignments && alignments[index]; return a ? ` style="text-align: ${a}"` : ''; } renderTables(text) { const lines = text.split('\n'); // First pass: find header rows (a table row directly followed by a delimiter) const alignments = new Map(); for (let i = 0; i < lines.length - 1; i++) { if (this._isTableRow(lines[i]) && this._isTableDelimiter(lines[i + 1])) { alignments.set(i, this._parseAlignment(lines[i + 1])); } } if (alignments.size === 0) return text; const out = []; let inTable = false; let currentAlign = []; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (this._isTableDelimiter(line)) continue; if (alignments.has(i)) { inTable = true; currentAlign = alignments.get(i); out.push('', '', ''); this._splitTableRow(line).forEach((cell, idx) => { out.push(`${cell}`); }); out.push('', '', ''); } else if (inTable && this._isTableRow(line)) { out.push(''); this._splitTableRow(line).forEach((cell, idx) => { out.push(`${cell}`); }); out.push(''); } else { if (inTable) { inTable = false; out.push('', '
'); } out.push(line); } } if (inTable) out.push('', ''); return out.join('\n'); } _isTaskItem(content) { return /^\[[ xX]\][ \t]/.test(content); } _renderListLevel(items, start, indent) { let html = ''; let i = start; while (i < items.length) { const it = items[i]; if (it.indent < indent) break; if (it.indent > indent) { const r = this._renderListLevel(items, i, it.indent); html += r.html; i = r.next; continue; } const type = it.ordered ? 'ol' : 'ul'; // Scan direct members of this list run (for task-list detection) let memberCount = 0; let allTask = type === 'ul'; for (let j = i; j < items.length; j++) { const jt = items[j]; if (jt.indent < indent) break; if (jt.indent === indent && (jt.ordered ? 'ol' : 'ul') !== type) break; if (jt.indent === indent) { memberCount++; if (!this._isTaskItem(jt.content)) allTask = false; } } if (memberCount === 0) { i++; continue; } let attrs = ''; if (type === 'ol' && it.num !== 1) attrs += ` start="${it.num}"`; if (type === 'ul' && allTask) attrs += ' class="task-list"'; html += `<${type}${attrs}>`; while (i < items.length && items[i].indent === indent && (items[i].ordered ? 'ol' : 'ul') === type) { const item = items[i]; i++; let children = ''; if (i < items.length && items[i].indent > indent) { const r = this._renderListLevel(items, i, items[i].indent); children = r.html; i = r.next; } const task = item.content.match(/^\[([ xX])\][ \t]+(.*)$/); if (task) { const chk = task[1].toLowerCase() === 'x' ? ' checked' : ''; html += `
  • ${task[2]}${children}
  • `; } else { html += `
  • ${item.content}${children}
  • `; } } html += ``; } return { html, next: i }; } renderLists(text) { const lines = text.split('\n'); const out = []; let i = 0; while (i < lines.length) { const um = lines[i].match(this.rules.unorderedItem); const om = um ? null : lines[i].match(this.rules.orderedItem); if (!um && !om) { out.push(lines[i]); i++; continue; } const items = []; while (i < lines.length) { const um2 = lines[i].match(this.rules.unorderedItem); const om2 = um2 ? null : lines[i].match(this.rules.orderedItem); if (um2) { items.push({ indent: this._indentWidth(um2[1]), ordered: false, num: 0, content: um2[2] }); } else if (om2) { items.push({ indent: this._indentWidth(om2[1]), ordered: true, num: parseInt(om2[2], 10), content: om2[3] }); } else { break; } i++; } const baseIndent = Math.min(...items.map(it => it.indent)); out.push(this._renderListLevel(items, 0, baseIndent).html); } return out.join('\n'); } renderDefinitions(text) { const defRe = /^[ \t]{0,3}:[ \t]+(.*)$/; const isTerm = (s) => { const t = s.trim(); if (!t) return false; if (/^[ \t]{0,3}(?:#{1,6}[ \t]|[-*+][ \t]|\d{1,9}[.)][ \t]|\||>|<|@@MDRENDER_)/.test(s)) return false; if (/^[ \t]*(?:[-*_][ \t]*){3,}[ \t]*$/.test(s)) return false; if (defRe.test(s)) return false; return true; }; const lines = text.split('\n'); const out = []; for (let i = 0; i < lines.length; i++) { if (i + 1 < lines.length && isTerm(lines[i]) && defRe.test(lines[i + 1])) { const term = lines[i]; const defs = []; let j = i + 1; while (j < lines.length) { const dm = lines[j].match(defRe); if (!dm) break; defs.push(dm[1]); j++; } out.push(`
    ${term}
    ${defs.map(d => `
    ${d}
    `).join('')}
    `); i = j - 1; } else { out.push(lines[i]); } } return out.join('\n'); } renderParagraphs(text) { return text .replace(this.rules.paragraph, '

    $1

    ') .replace(/<\/p>\n

    /g, ' '); } // ---------- Inline rendering ---------- renderInline(text) { let html = text; html = html.replace(this.rules.escapes, (m, c) => this._stashHtml(this._escapeHtml(c))); html = html.replace(this.rules.inlineCode, (m, code) => this._stashHtml(`${this._escapeHtml(code)}`)); html = this.renderImages(html); html = this.renderLinks(html); html = html.replace(this.rules.boldItalic, '$1'); html = html.replace(this.rules.boldItalicU, '$1'); html = html.replace(this.rules.bold, '$1'); html = html.replace(this.rules.boldU, '$1'); html = html.replace(this.rules.italic, '$1'); html = html.replace(this.rules.italicU, '$1'); html = html.replace(this.rules.strikethrough, '$1'); html = html.replace(this.rules.highlight, '$1'); html = this.renderFootnoteRefs(html); html = this.renderSuperscript(html); html = this.renderSubscript(html); html = this.renderAbbreviations(html); return this.renderEmojis(html); } _refLinkHtml(text, ref) { const title = ref.title ? ` title="${this._escapeAttr(ref.title)}"` : ''; return `${text}`; } renderLinks(text) { text = text.replace(this.rules.refImage, (m, alt, label) => { const ref = this.references.get((label || alt).toLowerCase()); if (!ref) return m; const title = ref.title ? ` title="${this._escapeAttr(ref.title)}"` : ''; return `${this._escapeAttr(alt)}`; }); text = text.replace(this.rules.refLink, (m, t, l) => { const ref = this.references.get((l || t).toLowerCase()); return ref ? this._refLinkHtml(t, ref) : m; }); text = text.replace(this.rules.refShortcut, (m, t) => { if (t.startsWith('^')) return m; // leave footnote refs alone const ref = this.references.get(t.toLowerCase()); return ref ? this._refLinkHtml(t, ref) : m; }); return text.replace(this.rules.link, (m, text, url, title) => { const titleAttr = title ? ` title="${this._escapeAttr(title)}"` : ''; return `${text}`; }); } renderImages(text) { return text.replace(this.rules.image, (m, alt, url, title) => { const titleAttr = title ? ` title="${this._escapeAttr(title)}"` : ''; return `${this._escapeAttr(alt)}`; }); } renderFootnoteRefs(text) { return text.replace(this.rules.footnoteRef, (m, ref) => { if (this.footnotes.has(ref)) { const fid = this._fnId(ref); return `${this._escapeHtml(ref)}`; } return m; }); } renderFootnotesSection() { let html = '


      '; for (const [ref, content] of this.footnotes) { const fid = this._fnId(ref); html += `
    1. ${this._render(content)}↩
    2. `; } return html + '
    '; } renderAbbreviations(text) { for (const [abbr, def] of this.abbreviations) { const re = new RegExp(`(?${abbr}`); } return text; } renderSuperscript(text) { return text.replace(this.rules.superscript, '$1'); } renderSubscript(text) { return text.replace(this.rules.subscript, '$1'); } renderEmojis(text) { return text.replace(this.rules.emoji, (m, name) => this.emojis[name.toLowerCase()] || m); } }