src/html.js
// Tolerant HTML tokenizer for seo-audit. It never builds a live DOM, runs scripts or loads resources:
// markup is untrusted data that is only scanned for tags, attributes and text.
const NAMED = {
amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\u00A0", copy: "©", reg: "®", trade: "™", hellip: "…",
mdash: "—", ndash: "–", lsquo: "‘", rsquo: "’", ldquo: "“", rdquo: "”", laquo: "«", raquo: "»", middot: "·",
bull: "•", euro: "€", pound: "£", yen: "¥", cent: "¢", sect: "§", para: "¶", deg: "°", times: "×", divide: "÷",
eacute: "é", egrave: "è", ecirc: "ê", aacute: "á", agrave: "à", acirc: "â", ouml: "ö", uuml: "ü", auml: "ä",
szlig: "ß", ntilde: "ñ", ccedil: "ç", oacute: "ó", iacute: "í", uacute: "ú", shy: "\u00AD", zwj: "\u200D", zwnj: "\u200C",
};
export function decodeEntities(s) {
if (!s.includes("&")) return s;
return s.replace(/&(#[xX][0-9a-fA-F]{1,6}|#\d{1,7}|[A-Za-z][A-Za-z0-9]{1,31});?/g, (whole, e) => {
if (e[0] === "#") {
const cp = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
return cp > 0 && cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff) ? String.fromCodePoint(cp) : "�";
}
const v = NAMED[e] ?? NAMED[e.toLowerCase()];
return v !== undefined && whole.endsWith(";") ? v : v !== undefined && ["amp", "lt", "gt", "quot", "nbsp", "copy", "reg"].includes(e.toLowerCase()) ? v : whole;
});
}
const RAW_TEXT = new Set(["script", "style", "xmp", "iframe", "noembed", "noframes", "plaintext"]);
const RCDATA = new Set(["title", "textarea"]);
function parseAttrs(src) {
const attrs = {};
let i = 0;
while (i < src.length) {
while (i < src.length && /[\s/]/.test(src[i])) i++;
if (i >= src.length) break;
let name = "";
while (i < src.length && !/[\s=/>]/.test(src[i])) name += src[i++];
while (i < src.length && /\s/.test(src[i])) i++;
let value = "";
if (src[i] === "=") {
i++;
while (i < src.length && /\s/.test(src[i])) i++;
const q = src[i];
if (q === '"' || q === "'") {
const end = src.indexOf(q, i + 1);
value = src.slice(i + 1, end < 0 ? src.length : end);
i = end < 0 ? src.length : end + 1;
} else {
while (i < src.length && !/\s/.test(src[i])) value += src[i++];
}
}
const key = name.toLowerCase();
if (key && !(key in attrs)) attrs[key] = decodeEntities(value);
}
return attrs;
}
// Finds the end of a start tag, skipping '>' characters inside quoted attribute values.
function tagEnd(html, from) {
let q = null;
for (let i = from; i < html.length; i++) {
const c = html[i];
if (q) { if (c === q) q = null; }
else if (c === '"' || c === "'") {
// Quotes only open a value right after '='.
let j = i - 1;
while (j >= from && /\s/.test(html[j])) j--;
if (html[j] === "=") q = c;
} else if (c === ">") return i;
}
return -1;
}
// Returns an array of tokens: {type:"start", name, attrs, selfClosing} | {type:"end", name} | {type:"text", text, raw?}
export function tokenize(html) {
const tokens = [];
let i = 0;
let text = "";
const flush = () => { if (text) { tokens.push({ type: "text", text: decodeEntities(text) }); text = ""; } };
while (i < html.length) {
const c = html[i];
if (c !== "<") { text += c; i++; continue; }
if (html.startsWith("<!--", i)) {
flush();
const end = html.indexOf("-->", i + 4);
i = end < 0 ? html.length : end + 3;
continue;
}
const next = html[i + 1] ?? "";
if (next === "!" || next === "?") {
flush();
const end = html.indexOf(">", i + 2);
i = end < 0 ? html.length : end + 1;
continue;
}
if (next === "/" && /[A-Za-z]/.test(html[i + 2] ?? "")) {
flush();
const end = html.indexOf(">", i + 2);
const name = /^[A-Za-z][A-Za-z0-9:-]*/.exec(html.slice(i + 2, end < 0 ? undefined : end))[0].toLowerCase();
tokens.push({ type: "end", name });
i = end < 0 ? html.length : end + 1;
continue;
}
if (/[A-Za-z]/.test(next)) {
flush();
const end = tagEnd(html, i + 1);
const inner = html.slice(i + 1, end < 0 ? html.length : end);
const name = /^[A-Za-z][A-Za-z0-9:-]*/.exec(inner)[0].toLowerCase();
const attrSrc = inner.slice(name.length);
const selfClosing = /\/\s*$/.test(attrSrc);
tokens.push({ type: "start", name, attrs: parseAttrs(attrSrc.replace(/\/\s*$/, "")), selfClosing });
i = end < 0 ? html.length : end + 1;
if (RAW_TEXT.has(name) || RCDATA.has(name)) {
const close = new RegExp(`</${name}[\\s>/]`, "i").exec(html.slice(i));
const stop = close ? i + close.index : html.length;
const content = html.slice(i, stop);
// Raw text (script, style, …) is skipped entirely; RCDATA (title, textarea) keeps decoded text.
if (RCDATA.has(name) && content) tokens.push({ type: "text", text: decodeEntities(content) });
tokens.push({ type: "end", name });
const gt = close ? html.indexOf(">", stop) : -1;
i = gt < 0 ? html.length : gt + 1;
}
continue;
}
text += c;
i++;
}
flush();
return tokens;
}