/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as cheerio from "cheerio"; export interface SemanticMetadata { author: string | null; publishedTime: string | null; modifiedTime: string | null; section: string | null; tags: string[]; headings: Array<{ level: number; text: string }>; breadcrumbs: string[]; } export interface DataTable { caption?: string; headers: string[]; rows: Array>; } export interface MicrodataItem { type?: string; properties: Record; } export interface FeedCardItem { id?: string; title: string; url?: string; description?: string; price?: string; score?: number; author?: string; date?: string; image?: string; metadata?: Record; } export interface ComprehensiveStructuredData { jsonLd: unknown[]; openGraph: Record; twitter: Record; canonical: string | null; description: string | null; microdata: MicrodataItem[]; semantic: SemanticMetadata; tables: DataTable[]; feedItems: FeedCardItem[]; } /** * Extracts comprehensive structured data from an HTML document. * Covers: JSON-LD, Microdata, OpenGraph, Twitter Cards, Semantic Tags, Data Tables, Feed Cards. */ export function extractComprehensiveStructuredData( html: string, baseUrl?: string, ): ComprehensiveStructuredData { const out: ComprehensiveStructuredData = { jsonLd: [], openGraph: {}, twitter: {}, canonical: null, description: null, microdata: [], semantic: { author: null, publishedTime: null, modifiedTime: null, section: null, tags: [], headings: [], breadcrumbs: [], }, tables: [], feedItems: [], }; if (!html || typeof html !== "string") { return out; } const $ = cheerio.load(html); // 1. Canonical & Meta Description const canonHref = $("link[rel='canonical']").attr("href"); if (canonHref) { out.canonical = resolveUrl(canonHref, baseUrl); } const metaDesc = $('meta[name="description"]').attr("content") || $('meta[property="og:description"]').attr("content") || $('meta[name="twitter:description"]').attr("content"); if (metaDesc) { out.description = metaDesc.trim(); } // 2. OpenGraph & Twitter Cards $("meta").each((_, el) => { const prop = $(el).attr("property") || $(el).attr("name"); const content = $(el).attr("content"); if (!prop || !content) return; const key = prop.toLowerCase().trim(); const val = content.trim(); if (key.startsWith("og:")) { out.openGraph[key.slice(3)] = val; } else if (key.startsWith("twitter:")) { out.twitter[key.slice(8)] = val; } else if (key === "author") { out.semantic.author = val; } else if (key === "article:published_time" || key === "date" || key === "pubdate") { out.semantic.publishedTime = val; } else if (key === "article:modified_time") { out.semantic.modifiedTime = val; } else if (key === "article:section") { out.semantic.section = val; } else if (key === "keywords") { out.semantic.tags = val.split(",").map((s) => s.trim()).filter(Boolean); } }); // Fallback OpenGraph / Twitter overrides if (!out.semantic.author) { const authorEl = $('[rel="author"], .author, .byline, [itemprop="author"]').first(); if (authorEl.length) { out.semantic.author = authorEl.text().trim(); } } if (!out.semantic.publishedTime) { const timeEl = $("time[datetime]").first(); if (timeEl.length) { out.semantic.publishedTime = timeEl.attr("datetime") || timeEl.text().trim(); } } // 3. JSON-LD Extraction (Handles multiple scripts, trailing commas, arrays, @graph) $('script[type="application/ld+json"]').each((_, el) => { const raw = $(el).text().trim(); if (!raw) return; try { const cleaned = cleanJsonString(raw); const parsed = JSON.parse(cleaned); if (Array.isArray(parsed)) { out.jsonLd.push(...parsed); } else if (parsed && typeof parsed === "object") { if (Array.isArray(parsed["@graph"])) { out.jsonLd.push(...parsed["@graph"]); } else { out.jsonLd.push(parsed); } } } catch { // Parsing failed on malformed script } }); // 4. Microdata Extraction (W3C Microdata itemscope/itemprop) $("[itemscope]").each((_, el) => { // Only process top-level itemscopes to avoid duplicating nested scopes if ($(el).parents("[itemscope]").length === 0) { const item = parseMicrodataElement($, el, baseUrl); if (item && Object.keys(item.properties).length > 0) { out.microdata.push(item); } } }); // 5. Semantic Headings & Breadcrumbs $("h1, h2, h3").each((_, el) => { const level = parseInt(el.tagName.replace("h", ""), 10) || 1; const text = $(el).text().trim(); if (text) { out.semantic.headings.push({ level, text }); } }); $('nav[aria-label*="breadcrumb" i], .breadcrumb, .breadcrumbs, ol[itemtype*="BreadcrumbList"]') .find("li, a") .each((_, el) => { const text = $(el).text().trim(); if (text && !out.semantic.breadcrumbs.includes(text)) { out.semantic.breadcrumbs.push(text); } }); // 6. Data Tables Extraction $("table").each((_, tableEl) => { const $table = $(tableEl); const caption = $table.find("caption").text().trim() || undefined; const headers: string[] = []; // Look for th in thead or first tr let $headerCells = $table.find("thead th"); if ($headerCells.length === 0) { $headerCells = $table.find("tr").first().find("th, td"); } $headerCells.each((idx, cell) => { const hText = $(cell).text().trim() || `column_${idx + 1}`; headers.push(hText.replace(/\s+/g, " ")); }); if (headers.length === 0) return; const rows: Array> = []; const $dataRows = $table.find("tbody tr").length > 0 ? $table.find("tbody tr") : $table.find("tr").slice(1); $dataRows.each((_, rowEl) => { const $cells = $(rowEl).find("td, th"); if ($cells.length === 0) return; const rowObj: Record = {}; let hasData = false; $cells.each((colIdx, cell) => { const header = headers[colIdx] || `column_${colIdx + 1}`; const text = $(cell).text().trim(); if (text) { hasData = true; } rowObj[header] = text; }); if (hasData) { rows.push(rowObj); } }); if (rows.length > 0) { out.tables.push({ caption, headers, rows }); } }); // 7. Feed / Card Detection Heuristics // A. Hacker News specific structure if ($("tr.athing").length > 0) { $("tr.athing").each((_, el) => { const $row = $(el); const id = $row.attr("id"); const $titleLink = $row.find(".titleline > a").first(); const title = $titleLink.text().trim(); const href = $titleLink.attr("href"); const url = href ? resolveUrl(href, baseUrl) : undefined; // Subtext is on next sibling tr const $sub = $row.next("tr").find(".subtext"); const scoreText = $sub.find(".score").text().trim(); const score = scoreText ? parseInt(scoreText.replace(/\D/g, ""), 10) : undefined; const author = $sub.find(".hnuser").text().trim() || undefined; const date = $sub.find(".age").attr("title") || $sub.find(".age").text().trim() || undefined; if (title) { out.feedItems.push({ id, title, url, score, author, date, }); } }); } // B. Generic Cards (Products / Articles) if (out.feedItems.length === 0) { const cardSelectors = [ ".product-card", ".product-item", ".product", ".article-card", ".post-card", "article", ".feed-item", ".c-card", ]; for (const sel of cardSelectors) { const $cards = $(sel); if ($cards.length >= 2) { $cards.each((_, cardEl) => { const $card = $(cardEl); const $link = $card.find("h1 a, h2 a, h3 a, h4 a, a.title, a").first(); const title = $card.find("h1, h2, h3, h4, .title, .product-title, .name").first().text().trim() || $link.text().trim(); if (!title || title.length < 3) return; const href = $link.attr("href"); const url = href ? resolveUrl(href, baseUrl) : undefined; const description = $card.find("p, .desc, .description, .summary").first().text().trim() || undefined; const price = $card.find(".price, .cost, [itemprop='price']").first().text().trim() || undefined; const image = $card.find("img").attr("src") ? resolveUrl($card.find("img").attr("src")!, baseUrl) : undefined; out.feedItems.push({ title, url, description, price, image, }); }); if (out.feedItems.length > 0) break; } } } return out; } function parseMicrodataElement( $: cheerio.CheerioAPI, element: any, baseUrl?: string, ): MicrodataItem { const $el = $(element); const type = $el.attr("itemtype") || undefined; const properties: Record = {}; $el.find("[itemprop]").each((_, propEl) => { const $prop = $(propEl); // If this itemprop belongs to a deeper child itemscope, skip here const parentScope = $prop.parents("[itemscope]").first()[0]; if (parentScope !== element) return; const propName = $prop.attr("itemprop"); if (!propName) return; let val: any; if ($prop.is("[itemscope]")) { val = parseMicrodataElement($, propEl, baseUrl); } else if ($prop.is("meta")) { val = $prop.attr("content"); } else if ($prop.is("a, link")) { const href = $prop.attr("href"); val = href ? resolveUrl(href, baseUrl) : undefined; } else if ($prop.is("img, audio, video, source")) { const src = $prop.attr("src"); val = src ? resolveUrl(src, baseUrl) : undefined; } else if ($prop.is("time")) { val = $prop.attr("datetime") || $prop.text().trim(); } else { val = $prop.text().trim(); } if (properties[propName] !== undefined) { if (!Array.isArray(properties[propName])) { properties[propName] = [properties[propName]]; } properties[propName].push(val); } else { properties[propName] = val; } }); return { type, properties }; } function resolveUrl(href: string, baseUrl?: string): string { if (!href) return ""; if (href.startsWith("http://") || href.startsWith("https://")) return href; if (baseUrl) { try { return new URL(href, baseUrl).toString(); } catch { return href; } } return href; } function cleanJsonString(raw: string): string { // Remove CDATA tags if present let s = raw.replace(/^\s*\s*$/g, "$1").trim(); // Remove trailing commas before } or ] s = s.replace(/,(\s*[}\]])/g, "$1"); return s; }