import { parseHTML } from "linkedom";
function escapeHtmlText(text: string): string {
return text
.replace(/&/g, "&")
.replace(//g, ">");
}
export function normalizeHtmlForLinkedom(html: string): string {
const hasHtmlTag = /|\/)/i.test(html);
if (!hasHtmlLikeTag) {
return `
${escapeHtmlText(html)}`;
}
const headMatch = html.match(/]*>([\s\S]*?)<\/head>/i);
const titleMatch = html.match(/]*>[\s\S]*?<\/title>/i);
const bodyMatch = html.match(/]*>([\s\S]*?)(?:<\/body>|$)/i);
const head = headMatch?.[1] ?? titleMatch?.[0] ?? "";
const body = bodyMatch?.[1] ?? html
.replace(/]*>/i, "")
.replace(/<\/?html\b[^>]*>/gi, "")
.replace(/]*>[\s\S]*?<\/head>/i, "")
.replace(/]*>[\s\S]*?<\/title>/i, "");
return `${head}${body}`;
}
export function createArticleWindow(html: string): ReturnType {
return parseHTML(normalizeHtmlForLinkedom(html));
}