import { parseHtmlDocument } from "../../html-document.js";
import { stripHiddenHtml } from "./visibility.js";
export async function extractReadabilityFromHtml(html, url) {
    try {
        const cleanedHtml = stripCssFromHtml(stripHiddenHtml(html));
        const { Readability } = await import("@mozilla/readability");
        const parsed = parseHtmlDocument(cleanedHtml, url);
        try {
            const article = new Readability(parsed.document).parse();
            if (!article)
                return null;
            const text = (article.textContent ?? "").replace(/\s+/g, " ").trim();
            return {
                text,
                html: article.content ?? null,
                title: article.title ?? null,
                excerpt: article.excerpt ?? null,
            };
        }
        finally {
            parsed.close();
        }
    }
    catch {
        return null;
    }
}
export function toReadabilityHtml(result) {
    if (!result)
        return null;
    if (result.html)
        return result.html;
    if (!result.text)
        return null;
    return `<article><p>${escapeHtml(result.text)}</p></article>`;
}
function escapeHtml(input) {
    return input
        .replaceAll("&", "&amp;")
        .replaceAll("<", "&lt;")
        .replaceAll(">", "&gt;")
        .replaceAll('"', "&quot;")
        .replaceAll("'", "&#39;");
}
function stripCssFromHtml(html) {
    // Readability doesn't need CSS; stylesheet parsing can be extremely slow on some pages.
    return html.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, "");
}
//# sourceMappingURL=readability.js.map