|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + * Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | + *--------------------------------------------------------------------------------------------*/ |
| 5 | + |
| 6 | +/** |
| 7 | + * Lightweight HTML-to-Markdown converter. |
| 8 | + * |
| 9 | + * Handles a small set of common inline and block elements so that content |
| 10 | + * pasted from web pages keeps its basic structure (headings, links, bold, |
| 11 | + * italic, code, lists) when inserted into a Markdown-aware surface such as |
| 12 | + * the chat input. |
| 13 | + */ |
| 14 | +const maxInputLength = 200_000; |
| 15 | + |
| 16 | +export function convertHtmlToMarkdown(html: string): string { |
| 17 | + // Bail out on very large inputs to avoid regex backtracking cost |
| 18 | + if (html.length > maxInputLength) { |
| 19 | + return html.replace(/<[^>]+>/g, ''); |
| 20 | + } |
| 21 | + |
| 22 | + // Work on a mutable copy |
| 23 | + let md = html; |
| 24 | + |
| 25 | + // Normalise line endings |
| 26 | + md = md.replace(/\r\n?/g, '\n'); |
| 27 | + |
| 28 | + // --- block elements --------------------------------------------------- |
| 29 | + |
| 30 | + // Headings |
| 31 | + md = md.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/gi, (_m, inner) => `\n# ${inlineClean(inner)}\n`); |
| 32 | + md = md.replace(/<h2[^>]*>([\s\S]*?)<\/h2>/gi, (_m, inner) => `\n## ${inlineClean(inner)}\n`); |
| 33 | + md = md.replace(/<h3[^>]*>([\s\S]*?)<\/h3>/gi, (_m, inner) => `\n### ${inlineClean(inner)}\n`); |
| 34 | + md = md.replace(/<h4[^>]*>([\s\S]*?)<\/h4>/gi, (_m, inner) => `\n#### ${inlineClean(inner)}\n`); |
| 35 | + md = md.replace(/<h5[^>]*>([\s\S]*?)<\/h5>/gi, (_m, inner) => `\n##### ${inlineClean(inner)}\n`); |
| 36 | + md = md.replace(/<h6[^>]*>([\s\S]*?)<\/h6>/gi, (_m, inner) => `\n###### ${inlineClean(inner)}\n`); |
| 37 | + |
| 38 | + // Code blocks: <pre><code>…</code></pre> |
| 39 | + md = md.replace(/<pre[^>]*>\s*<code[^>]*>([\s\S]*?)<\/code>\s*<\/pre>/gi, (_m, inner) => `\n\`\`\`\n${cleanCodeBlock(inner)}\n\`\`\`\n`); |
| 40 | + |
| 41 | + // Standalone <pre> without <code> |
| 42 | + md = md.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi, (_m, inner) => `\n\`\`\`\n${cleanCodeBlock(inner)}\n\`\`\`\n`); |
| 43 | + |
| 44 | + // Blockquote |
| 45 | + md = md.replace(/<blockquote[^>]*>([\s\S]*?)<\/blockquote>/gi, (_m, inner) => { |
| 46 | + const lines = inlineClean(inner).split('\n').map(l => `> ${l.trim()}`); |
| 47 | + return `\n${lines.join('\n')}\n`; |
| 48 | + }); |
| 49 | + |
| 50 | + // Ordered list items — number them before stripping the <ol> wrapper |
| 51 | + md = md.replace(/<ol[^>]*>([\s\S]*?)<\/ol>/gi, (_m, inner) => { |
| 52 | + let index = 0; |
| 53 | + const numbered = inner.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, (_liM: string, liInner: string) => { |
| 54 | + index++; |
| 55 | + return `${index}. ${inlineClean(liInner).trim()}\n`; |
| 56 | + }); |
| 57 | + return `\n${numbered.replace(/<[^>]+>/g, '')}\n`; |
| 58 | + }); |
| 59 | + |
| 60 | + // Unordered list items - convert before stripping the list wrapper |
| 61 | + md = md.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, (_m, inner) => `- ${inlineClean(inner).trim()}\n`); |
| 62 | + md = md.replace(/<\/?ul[^>]*>/gi, '\n'); |
| 63 | + |
| 64 | + // Paragraphs and divs → double newline |
| 65 | + md = md.replace(/<\/p>/gi, '\n\n'); |
| 66 | + md = md.replace(/<p[^>]*>/gi, ''); |
| 67 | + md = md.replace(/<\/div>/gi, '\n'); |
| 68 | + md = md.replace(/<div[^>]*>/gi, ''); |
| 69 | + |
| 70 | + // Line breaks |
| 71 | + md = md.replace(/<br\s*\/?>/gi, '\n'); |
| 72 | + |
| 73 | + // Horizontal rules |
| 74 | + md = md.replace(/<hr[^>]*\/?>/gi, '\n---\n'); |
| 75 | + |
| 76 | + // --- inline elements -------------------------------------------------- |
| 77 | + |
| 78 | + // Links - must come before we strip remaining tags |
| 79 | + md = md.replace(/<a\s[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, (_m, href, text) => sanitizeLink(href, inlineClean(text).trim())); |
| 80 | + |
| 81 | + // Images |
| 82 | + md = md.replace(/<img\s[^>]*alt="([^"]*)"[^>]*src="([^"]*)"[^>]*\/?>/gi, ''); |
| 83 | + md = md.replace(/<img\s[^>]*src="([^"]*)"[^>]*alt="([^"]*)"[^>]*\/?>/gi, ''); |
| 84 | + md = md.replace(/<img\s[^>]*src="([^"]*)"[^>]*\/?>/gi, ''); |
| 85 | + |
| 86 | + // Bold / strong |
| 87 | + md = md.replace(/<(strong|b)(\s[^>]*)?>([\s\S]*?)<\/\1>/gi, (_m, _tag, _attrs, inner) => `**${inlineClean(inner)}**`); |
| 88 | + |
| 89 | + // Italic / emphasis |
| 90 | + md = md.replace(/<(em|i)(\s[^>]*)?>([\s\S]*?)<\/\1>/gi, (_m, _tag, _attrs, inner) => `*${inlineClean(inner)}*`); |
| 91 | + |
| 92 | + // Inline code |
| 93 | + md = md.replace(/<code(\s[^>]*)?>([\s\S]*?)<\/code>/gi, (_m, _attrs, inner) => `\`${decodeEntities(inner)}\``); |
| 94 | + |
| 95 | + // Strikethrough |
| 96 | + md = md.replace(/<(del|s|strike)(\s[^>]*)?>([\s\S]*?)<\/\1>/gi, (_m, _tag, _attrs, inner) => `~~${inlineClean(inner)}~~`); |
| 97 | + |
| 98 | + // --- cleanup ---------------------------------------------------------- |
| 99 | + |
| 100 | + // Strip any remaining HTML tags |
| 101 | + md = md.replace(/<[^>]+>/g, ''); |
| 102 | + |
| 103 | + // Decode common HTML entities |
| 104 | + md = decodeEntities(md); |
| 105 | + |
| 106 | + // Collapse runs of 3+ newlines into 2 |
| 107 | + md = md.replace(/\n{3,}/g, '\n\n'); |
| 108 | + |
| 109 | + return md.trim(); |
| 110 | +} |
| 111 | + |
| 112 | +/** Recursively strip tags for use inside an inline markdown construct. */ |
| 113 | +function inlineClean(html: string): string { |
| 114 | + // Process nested inline elements first |
| 115 | + let result = html; |
| 116 | + result = result.replace(/<a\s[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, (_m, href, text) => sanitizeLink(href, inlineClean(text).trim())); |
| 117 | + result = result.replace(/<(strong|b)(\s[^>]*)?>([\s\S]*?)<\/\1>/gi, (_m, _tag, _attrs, inner) => `**${inlineClean(inner)}**`); |
| 118 | + result = result.replace(/<(em|i)(\s[^>]*)?>([\s\S]*?)<\/\1>/gi, (_m, _tag, _attrs, inner) => `*${inlineClean(inner)}*`); |
| 119 | + result = result.replace(/<code(\s[^>]*)?>([\s\S]*?)<\/code>/gi, (_m, _attrs, inner) => `\`${decodeEntities(inner)}\``); |
| 120 | + result = result.replace(/<(del|s|strike)(\s[^>]*)?>([\s\S]*?)<\/\1>/gi, (_m, _tag, _attrs, inner) => `~~${inlineClean(inner)}~~`); |
| 121 | + result = result.replace(/<br\s*\/?>/gi, '\n'); |
| 122 | + result = result.replace(/<[^>]+>/g, ''); |
| 123 | + return decodeEntities(result); |
| 124 | +} |
| 125 | + |
| 126 | +/** Strip tags, normalise <br>, and decode entities inside a code block while preserving indentation. */ |
| 127 | +function cleanCodeBlock(html: string): string { |
| 128 | + let result = html; |
| 129 | + // Normalise <br> to newlines |
| 130 | + result = result.replace(/<br\s*\/?>/gi, '\n'); |
| 131 | + // Strip all HTML tags (e.g. syntax-highlighting <span>s) |
| 132 | + result = result.replace(/<[^>]+>/g, ''); |
| 133 | + result = decodeEntities(result); |
| 134 | + // Trim only leading/trailing newlines, preserving indentation |
| 135 | + result = result.replace(/^\n+|\n+$/g, ''); |
| 136 | + return result; |
| 137 | +} |
| 138 | + |
| 139 | +/** Produce a markdown link, stripping dangerous schemes like `javascript:`. */ |
| 140 | +function sanitizeLink(href: string, text: string): string { |
| 141 | + if (/^(javascript|vbscript|data):/i.test(href.trim())) { |
| 142 | + return text; |
| 143 | + } |
| 144 | + return `[${text}](${href})`; |
| 145 | +} |
| 146 | + |
| 147 | +/** Decode the most common HTML entities, including numeric character references. */ |
| 148 | +function decodeEntities(text: string): string { |
| 149 | + return text |
| 150 | + .replace(/&/g, '&') |
| 151 | + .replace(/</g, '<') |
| 152 | + .replace(/>/g, '>') |
| 153 | + .replace(/"/g, '"') |
| 154 | + .replace(/'/g, '\'') |
| 155 | + .replace(/ /g, ' ') |
| 156 | + .replace(/&#x(?<hex>[0-9a-fA-F]+);/g, (...args) => safeFromCodePoint(parseInt(args.at(-1).hex, 16))) |
| 157 | + .replace(/&#(?<dec>\d+);/g, (...args) => safeFromCodePoint(parseInt(args.at(-1).dec, 10))); |
| 158 | +} |
| 159 | + |
| 160 | +function safeFromCodePoint(code: number): string { |
| 161 | + if (code >= 0 && code <= 0x10FFFF) { |
| 162 | + try { |
| 163 | + return String.fromCodePoint(code); |
| 164 | + } catch { |
| 165 | + // invalid code point |
| 166 | + } |
| 167 | + } |
| 168 | + return ''; |
| 169 | +} |
0 commit comments