import { parseFragment, serialize } from 'parse5'; const tags = new Set(`a abbr address article aside b bdi bdo blockquote br button caption cite code col colgroup data dd del details dfn div dl dt em fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr i img input ins kbd label legend li main mark meter nav ol optgroup option p picture pre progress q rp rt ruby s samp section select small span strong style sub summary sup table tbody td textarea tfoot th thead time tr u ul var wbr svg g path rect circle ellipse line polyline polygon defs lineargradient radialgradient stop text tspan`.split(/\s+/)); const attributes = new Set(`alt aria-hidden aria-label class colspan controls datetime dir fill for height id lang max min multiple name open placeholder readonly reversed role rowspan scope selected start step style tabindex title type value width viewbox d x y x1 y1 x2 y2 cx cy r rx ry points transform stroke stroke-width stroke-linecap stroke-linejoin fill-rule offset stop-color stop-opacity gradientunits`.split(/\s+/)); function safeLink(value) { try { return ['http:', 'https:', 'mailto:', 'tel:'].includes(new URL(value).protocol); } catch { return false; } } function clean(node) { if (node.nodeName === '#text') return true; if (!node.tagName || !tags.has(node.tagName.toLowerCase())) return false; node.attrs = node.attrs.filter(({ name, value, namespace }) => { if (namespace) return false; if (name === 'href') return node.tagName === 'a' && safeLink(value); if (name === 'src') return node.tagName === 'img' && /^data:image\/(png|jpeg|gif|webp|avif);base64,[a-z0-9+/=]+$/i.test(value); return attributes.has(name.toLowerCase()); }); if (node.tagName === 'a') node.attrs.push({ name: 'target', value: '_blank' }, { name: 'rel', value: 'noopener noreferrer' }); node.childNodes = node.childNodes.filter(clean); return true; } export function htmlDocument(markup) { const tree = parseFragment(markup); tree.childNodes = tree.childNodes.filter(clean); return `${serialize(tree)}`; }