const ESCAPE: Record = { "&": "&", "<": "<", ">": ">", '"': """, } function escapeHtml(value: string): string { return value.replace(/[&<>"]/g, (char) => ESCAPE[char] || char) } function renderInline(value: string): string { const codes: string[] = [] let text = escapeHtml(value).replace(/`([^`\n]+)`/g, (_match, code: string) => { const token = `\u0000${codes.length}\u0000` codes.push(code) return token }) text = text.replace( /\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '$1', ) text = text.replace(/\*\*([^*\n]+)\*\*/g, "$1") text = text.replace(/__([^_\n]+)__/g, "$1") text = text .split(/(<[^>]+>)/) .map((part) => (part.startsWith("<") ? part : linkBareUrls(part))) .join("") return text.replace(/\u0000(\d+)\u0000/g, (_match, index: string) => `${codes[Number(index)]}`) } function linkBareUrls(value: string): string { return value.replace(/https?:\/\/[^\s<]+/g, (url) => { const clean = url.replace(/[.,;:!?)]+$/, "") const tail = url.slice(clean.length) return `${clean}${tail}` }) } function splitCells(line: string): string[] { let text = line.trim() if (text.startsWith("|")) text = text.slice(1) if (text.endsWith("|")) text = text.slice(0, -1) const cells: string[] = [] let current = "" for (let index = 0; index < text.length; index += 1) { const char = text[index] if (char === "\\" && text[index + 1] === "|") { current += "|" index += 1 continue } if (char === "|") { cells.push(current.trim()) current = "" continue } current += char } cells.push(current.trim()) return cells } function isSeparatorRow(line: string): boolean { if (!line.includes("|")) return false const cells = splitCells(line) return cells.length > 1 && cells.every((cell) => /^:?-+:?$/.test(cell)) } function isTableStart(lines: string[], index: number): boolean { const line = lines[index]?.trim() || "" const next = lines[index + 1]?.trim() || "" return line.includes("|") && isSeparatorRow(next) } function renderTable(header: string[], rows: string[][]): string { const width = Math.max(header.length, ...rows.map((row) => row.length), 1) const cells = (row: string[], tag: "th" | "td") => { const padded = row.concat(Array(Math.max(0, width - row.length)).fill("")) return padded.slice(0, width).map((cell) => `<${tag}>${renderInline(cell)}`).join("") } const body = rows.map((row) => `${cells(row, "td")}`).join("") return `
${cells(header, "th")}${body}
` } function isList(line: string): "ul" | "ol" | "" { if (/^[-*]\s+\S/.test(line)) return "ul" if (/^\d+\.\s+\S/.test(line)) return "ol" return "" } export function renderAnswerMarkdown(source: string): string { const lines = source.replace(/\r\n/g, "\n").split("\n") const blocks: string[] = [] let index = 0 while (index < lines.length) { const raw = lines[index] const line = raw.trim() if (!line) { index += 1 continue } if (line.startsWith("```")) { const body: string[] = [] index += 1 while (index < lines.length && !lines[index].trim().startsWith("```")) { body.push(escapeHtml(lines[index])) index += 1 } if (index < lines.length) index += 1 blocks.push(`
${body.join("\n")}
`) continue } const heading = /^(#{1,4})\s+(.+)$/.exec(line) if (heading) { const level = heading[1].length blocks.push(`${renderInline(heading[2])}`) index += 1 continue } if (isTableStart(lines, index)) { const header = splitCells(lines[index]) index += 2 const rows: string[][] = [] while (index < lines.length && lines[index].trim().includes("|") && !isSeparatorRow(lines[index].trim())) { rows.push(splitCells(lines[index])) index += 1 } blocks.push(renderTable(header, rows)) continue } const listKind = isList(line) if (listKind) { const items: string[] = [] let start = 1 while (index < lines.length) { const current = lines[index].trim() if (!current) { index += 1 const upcoming = lines[index]?.trim() || "" if (isList(upcoming) !== listKind) break continue } if (isList(current) !== listKind) break if (listKind === "ol" && items.length === 0) start = Number(/^(\d+)\./.exec(current)?.[1] || "1") const body = current.replace(listKind === "ol" ? /^\d+\.\s+/ : /^[-*]\s+/, "") items.push(`
  • ${renderInline(body)}
  • `) index += 1 } const startAttr = listKind === "ol" && start !== 1 ? ` start="${start}"` : "" blocks.push(`<${listKind}${startAttr}>${items.join("")}`) continue } const paragraph = [renderInline(line)] index += 1 while (index < lines.length) { const current = lines[index].trim() if (!current || current.startsWith("```") || /^(#{1,4})\s+/.test(current) || isList(current) || isTableStart(lines, index)) break paragraph.push(renderInline(current)) index += 1 } blocks.push(`

    ${paragraph.join("
    ")}

    `) } return blocks.join("") }