import { type HTMLElement as ParsedHTMLElement, parse } from 'node-html-parser' import type { ExtractedFormData, ExtractedPageData, HeadingData, ImageData, JsonLdData, LinkData, MetaTagData, ScriptData, StylesheetData, } from './types.ts' /** * Parse HTML and extract all data needed by checks. * Parses once per page — all checks receive the same ExtractedPageData. */ export function analyzeHtml(html: string): { root: ParsedHTMLElement; pageData: ExtractedPageData } { const root = parse(html, { lowerCaseTagName: false, comment: true, blockTextElements: { script: true, noscript: true, style: true, pre: true, }, }) const head = root.querySelector('head') const body = root.querySelector('body') const htmlElement = root.querySelector('html') const lineIndex = buildLineIndex(html) // Extract body text length once for content quality checks const bodyTextLength = (body?.querySelector('main')?.textContent ?? body?.textContent ?? '').trim().length const pageData: ExtractedPageData = { metaTags: [], openGraph: {}, twitterCard: {}, jsonLd: [], headings: [], images: [], links: [], scripts: [], stylesheets: [], forms: [], htmlLang: htmlElement?.getAttribute('lang') || undefined, htmlSize: Buffer.byteLength(html, 'utf8'), bodyTextLength, hasViewport: false, hasNoindex: false, inlineScriptBytes: 0, inlineStyleBytes: 0, } if (head) { pageData.title = extractTitle(head, html, lineIndex) pageData.metaTags = extractMetaTags(head, html, lineIndex) categorizeMetaTags(pageData) pageData.canonical = extractCanonical(head, html, lineIndex) pageData.jsonLd = extractJsonLd(root, html, lineIndex) pageData.scripts = extractScripts(root, html, lineIndex) pageData.stylesheets = extractStylesheets(head, html, lineIndex) // Compute inline sizes from extracted data pageData.inlineScriptBytes = pageData.scripts .filter(s => s.isInline) .reduce((sum, s) => sum + s.size, 0) for (const style of root.querySelectorAll('style')) { const content = style.textContent ?? '' if (content) pageData.inlineStyleBytes += Buffer.byteLength(content, 'utf8') } } if (body) { pageData.headings = extractHeadings(body, html, lineIndex) pageData.images = extractImages(root, html, lineIndex) pageData.links = extractLinks(body, html, lineIndex) pageData.forms = extractForms(body, html, lineIndex) } return { root, pageData } } // ── Line index for efficient offset → line conversion ────────────────────────── /** Precompute newline offsets for O(log n) offset-to-line lookups */ function buildLineIndex(html: string): number[] { const offsets = [0] for (let i = 0; i < html.length; i++) { if (html[i] === '\n') offsets.push(i + 1) } return offsets } /** Binary search to convert a character offset to a 1-based line number */ function offsetToLine(lineIndex: number[], offset: number): number { let lo = 0 let hi = lineIndex.length - 1 while (lo <= hi) { const mid = (lo + hi) >>> 1 if (lineIndex[mid]! <= offset) lo = mid + 1 else hi = mid - 1 } return lo // 1-based since offsets[0] = 0 means line 1 } /** * Advancing line finder — tracks position to handle duplicate elements correctly. * Each call advances the search start so identical markup gets distinct line numbers. */ function createLineFinder(html: string, lineIndex: number[]) { let pos = 0 return (search: string): number => { const idx = html.indexOf(search, pos) if (idx !== -1) { pos = idx + 1 return offsetToLine(lineIndex, idx) } // Fallback: search from beginning for edge cases const fallback = html.indexOf(search) if (fallback !== -1) return offsetToLine(lineIndex, fallback) return 1 } } function extractTitle(head: ParsedHTMLElement, html: string, lineIndex: number[]): ExtractedPageData['title'] { const titleEl = head.querySelector('title') if (!titleEl) return undefined const content = titleEl.textContent?.trim() || '' const findLine = createLineFinder(html, lineIndex) return { content, line: findLine('