/** * 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. */ /** * @module bxc/extract/structured-data * * Flattens JSON-LD, microdata, OpenGraph and meta tags (via * `extractComprehensiveStructuredData`) into addressable scalar entries such * as `jsonld:Product:offers.price` so schema leaves can be mapped onto them * and the mapping can be cached as a stable path. */ import { extractComprehensiveStructuredData } from "../utils/structured.ts"; import { type Feature, features } from "./lexicon.ts"; export interface StructuredEntry { /** Stable address, e.g. `jsonld:Product:offers.price` or `og:title`. */ path: string; /** Scalar, or an array of scalars. */ value: unknown; features: Feature[]; /** Nesting depth inside the source object (0 = top-level property). */ depth: number; /** Secondary objects (breadcrumbs, site/organization boilerplate) rank lower. */ secondary: boolean; } const SECONDARY_TYPES: ReadonlySet = new Set([ "BreadcrumbList", "ListItem", "WebSite", "WebPage", "Organization", "SearchAction", "SiteNavigationElement", "WPHeader", "WPFooter", "ImageObject", "EntryPoint", ]); function typeName(value: unknown): string { const type = Array.isArray(value) ? value[0] : value; if (typeof type !== "string") return "Thing"; return type.replace(/^https?:\/\/schema\.org\//i, ""); } function isScalar(value: unknown): value is string | number | boolean { return typeof value === "string" || typeof value === "number" || typeof value === "boolean"; } function flattenObject( prefix: string, object: Record, secondary: boolean, out: StructuredEntry[], seen: Set, path: string[] = [], depth = 0, ): void { if (depth > 3) return; for (const [key, raw] of Object.entries(object)) { if (key.startsWith("@")) continue; const segments = [...path, key]; const address = `${prefix}:${segments.join(".")}`; let value: unknown = raw; if (Array.isArray(raw)) { const scalars = raw.filter(isScalar); if (scalars.length === raw.length && scalars.length > 0) value = scalars; else value = raw.find((item) => item && typeof item === "object") ?? raw[0]; } if (value && typeof value === "object" && !Array.isArray(value)) { let nested = value as Record; // Nested microdata items are `{ type, properties }`. if (prefix.startsWith("microdata:") && nested.properties && typeof nested.properties === "object") { nested = nested.properties as Record; } // `{ "@type": "Brand", "name": "X" }` also answers for its parent key. if (typeof nested.name === "string" && !seen.has(address)) { seen.add(address); out.push({ path: address, value: nested.name, features: pathFeatures(segments), depth, secondary }); } flattenObject(prefix, nested, secondary, out, seen, segments, depth + 1); continue; } if (!isScalar(value) && !Array.isArray(value)) continue; if (seen.has(address)) continue; seen.add(address); out.push({ path: address, value, features: pathFeatures(segments), depth, secondary }); } } function pathFeatures(segments: string[]): Feature[] { const out: Feature[] = []; segments.forEach((segment, i) => { const weight = i === segments.length - 1 ? 1 : 0.6; for (const f of features(segment, weight)) out.push(f); }); return out; } /** All structured entries of a page, primary objects first. */ export function collectStructuredEntries(html: string, baseUrl?: string): StructuredEntry[] { let data: ReturnType; try { data = extractComprehensiveStructuredData(html, baseUrl); } catch { return []; } const out: StructuredEntry[] = []; const seen = new Set(); const jsonLd = data.jsonLd.filter((item): item is Record => !!item && typeof item === "object"); const ordered = [ ...jsonLd.filter((item) => !SECONDARY_TYPES.has(typeName(item["@type"]))), ...jsonLd.filter((item) => SECONDARY_TYPES.has(typeName(item["@type"]))), ]; for (const item of ordered) { const type = typeName(item["@type"]); flattenObject(`jsonld:${type}`, item, SECONDARY_TYPES.has(type), out, seen); } for (const item of data.microdata) { const type = typeName(item.type?.split("/").pop()); flattenObject(`microdata:${type}`, item.properties as Record, SECONDARY_TYPES.has(type), out, seen); } for (const [key, value] of Object.entries(data.openGraph)) { out.push({ path: `og:${key}`, value, features: features(key, 0.8), depth: 1, secondary: true }); } if (data.description) { out.push({ path: "meta:description", value: data.description, features: features("description", 0.8), depth: 1, secondary: true }); } return out; } export function structuredValue(entries: readonly StructuredEntry[], path: string): unknown { return entries.find((entry) => entry.path === path)?.value; }