/** * 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 extraction to a schema without an LLM for the common case. * * 1. Cache: a plan learned earlier for the same registrable domain and schema * hash is applied directly; when the fill rate of required fields drops * below `relearnThreshold` (default 0.6) the plan is re-learned and replaced. * 2. Learning: record groups are detected on the native DOM (repeated * structures, periodic rows, tables); each top group gets field locators * and the group with the best applied fit wins. Single-object schemas map * JSON-LD / microdata / OpenGraph first, then the main content region. * 3. LLM fallback: only when required leaves stay unresolved and an * {@link LlmFallback} is injected (no network client is created here). * * Usage: * const result = await extractWithSchema(html, { title: "string", price: "number" }, { url }); * const live = await extractUrlWithSchema("https://example.com/list", schema, { cache: new SelectorCache() }); */ import { parseHtml } from "../ffi/native-dom.ts"; import { DomSnapshot } from "./dom.ts"; import { type ApplyResult, type ExtractionPlan, type FieldLocator, appliedFit, applyPlan, learnListPlan, learnObjectPlan, } from "./field-matcher.ts"; import { type CoerceContext, type LeafField, type NormalizedSchema, type ValidationIssue, coerceField, coerceRecord, fillRate, isFilled, leafFields, normalizeSchema, toJsonSchema, validateRecord, valueAt, } from "./schema.ts"; import { SelectorCache, cacheDomain } from "./selector-cache.ts"; import { type StructuredEntry, collectStructuredEntries } from "./structured-data.ts"; import { detectRecordGroups } from "./structure.ts"; export { SelectorCache, cacheDomain } from "./selector-cache.ts"; export type { CachedPlan, SelectorCacheOptions } from "./selector-cache.ts"; export type { Accessor, ExtractionPlan, FieldLocator } from "./field-matcher.ts"; export { SchemaError, coerceBoolean, coerceDate, coerceEmail, coerceNumber, coerceUri, normalizeSchema, toJsonSchema, validateRecord, } from "./schema.ts"; export type { FieldSpec, NormalizedSchema, ValidationIssue } from "./schema.ts"; export { detectRecordGroups } from "./structure.ts"; export type { RecordGroup } from "./structure.ts"; /** Minimal LLM contract used for leaves the DOM could not resolve. */ export interface LlmFallback { /** Return JSON (object, array, or a string containing JSON) matching `jsonSchema`. */ complete(prompt: string, jsonSchema: object): Promise; } export type ExtractSource = "cache" | "learned" | "llm" | "structured-data"; export interface ExtractOptions { /** Page URL: resolves relative links and keys the selector cache. */ url?: string; /** Selector cache; omitted or `false` disables caching. */ cache?: SelectorCache | false; /** Fallback for unresolved required leaves. */ llm?: LlmFallback; /** Locator confidence below which a leaf counts as unresolved. Default 0.3. */ minConfidence?: number; /** Required-leaf fill rate below which a cached plan is re-learned. Default 0.6. */ relearnThreshold?: number; /** Reference time for relative dates. Default `Date.now()`. */ now?: number; /** Day-first interpretation of ambiguous `05/06/2026`. */ dayFirst?: boolean; /** Maximum record groups evaluated for list schemas. Default 8. */ maxGroups?: number; /** Maximum characters of page text sent to the LLM. Default 12000. */ llmTextLimit?: number; } export interface ExtractResult { /** Records (list schemas). */ records?: Array>; /** Record (object schemas). */ record?: Record; /** The plan used (cacheable, reproducible). */ selectors: ExtractionPlan; /** Weighted locator confidence × fill rate, in [0, 1]. */ confidence: number; /** Leaves without a confident locator or filled in fewer than half of the records. */ missingFields: string[]; source: ExtractSource; /** Fill rate of required leaves (all leaves when none is required). */ fillRate: number; /** Validation issues of the returned records (at most 50). */ issues: ValidationIssue[]; cache: { domain: string | null; hit: boolean; relearned: boolean; stored: boolean }; /** Leaves filled by the LLM fallback. */ llmFields: string[]; } interface Outcome { plan: ExtractionPlan; applied: ApplyResult; source: ExtractSource; } function learn( snap: DomSnapshot, schema: NormalizedSchema, ctx: CoerceContext, structured: () => readonly StructuredEntry[], options: ExtractOptions, ): Outcome { if (schema.kind === "object") { const learned = learnObjectPlan(snap, schema, structured(), { ctx }); const applied = applyPlan(snap, learned.plan, schema, ctx, structured); const fields = learned.plan.fields; const source: ExtractSource = fields.length > 0 && fields.every((f) => f.strategy === "structured") ? "structured-data" : "learned"; return { plan: learned.plan, applied, source }; } const groups = detectRecordGroups(snap, { maxGroups: options.maxGroups ?? 8 }); let best: (Outcome & { score: number }) | null = null; const top = groups[0]?.score ?? 0; for (const group of groups) { if (group.score < top * 0.01) continue; const startedAt = performance.now(); const learned = learnListPlan(snap, group, schema, { ctx }); if (learned.plan.fields.length === 0) continue; const applied = applyPlan(snap, learned.plan, schema, ctx, structured); if (applied.records.length === 0) continue; // Records dropped as empty and single-record "groups" (page wrappers) weigh down the fit. const kept = applied.records.length / Math.max(applied.records.length, group.anchors.length); const score = appliedFit(schema, learned.plan, applied.fill) * kept * (applied.records.length >= 2 ? 1 + 0.05 * Math.log2(applied.records.length) : 0.3) * (group.exact ? 1 : 0.97); if (process.env.BXC_EXTRACT_DEBUG) { console.error(`[extract] group ${group.selector} span=${group.span} records=${applied.records.length}/${group.anchors.length} score=${score.toFixed(3)} ${(performance.now() - startedAt).toFixed(1)}ms`); } if (!best || score > best.score) best = { plan: learned.plan, applied, source: "learned", score }; } if (best) return best; const plan: ExtractionPlan = { version: 1, kind: "list", recordSelector: "", span: 1, fields: [] }; return { plan, applied: { records: [], fill: new Map() }, source: "learned" }; } function missingLeaves( leaves: readonly LeafField[], plan: ExtractionPlan, records: ReadonlyArray>, minConfidence: number, ): LeafField[] { const byKey = new Map(plan.fields.map((f) => [f.key, f])); return leaves.filter((leaf) => { const locator = byKey.get(leaf.key); if (!locator || locator.confidence < minConfidence) { return !records.some((r) => isFilled(valueAt(r, leaf.path))); } if (records.length === 0) return true; const filled = records.filter((r) => isFilled(valueAt(r, leaf.path))).length; return filled / records.length < 0.5; }); } /** Main text of a page for LLM prompts (native main-content extraction when available). */ async function pageText(html: string, url: string | undefined): Promise { try { const bridge = await import("../rust/bridge.ts"); if (typeof bridge.extractMain === "function") { const main = bridge.extractMain(html, url); if (main.markdown?.trim()) return main.markdown; if (main.text?.trim()) return main.text; } return bridge.extractText(html); } catch { return html.replace(/|/gi, " ").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); } } function parseLlmJson(answer: unknown): unknown { if (typeof answer !== "string") return answer; const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(answer); const body = (fenced?.[1] ?? answer).trim(); const start = body.search(/[[{]/); if (start < 0) return null; try { return JSON.parse(body.slice(start)); } catch { const end = Math.max(body.lastIndexOf("}"), body.lastIndexOf("]")); try { return end > start ? JSON.parse(body.slice(start, end + 1)) : null; } catch { return null; } } } function setLeaf(record: Record, leaf: LeafField, value: unknown): void { if (leaf.path.length === 1) { record[leaf.path[0] as string] = value; return; } const [parent, child] = leaf.path as [string, string]; const target = record[parent] && typeof record[parent] === "object" ? (record[parent] as Record) : {}; target[child] = value; record[parent] = target; } async function runLlmFallback( llm: LlmFallback, html: string, schema: NormalizedSchema, records: Array>, missing: readonly LeafField[], ctx: CoerceContext, options: ExtractOptions, ): Promise<{ records: Array>; filled: string[] }> { const keys = missing.map((leaf) => leaf.key); const text = (await pageText(html, options.url)).slice(0, options.llmTextLimit ?? 12_000); const partial = schema.kind === "list" && records.length === 0 ? undefined : new Set(keys); const jsonSchema = toJsonSchema(schema, partial); const prompt = [ "Extract structured data from the web page text below.", `Page URL: ${options.url ?? "unknown"}`, schema.kind === "list" ? `Return a JSON array with one object per record in page order${records.length ? ` (${records.length} records)` : ""}.` : "Return one JSON object.", `Fields needed: ${partial ? keys.join(", ") : leafFields(schema).map((l) => l.key).join(", ")}. Use null when a value is absent.`, "Answer with JSON only, matching the provided JSON schema.", "", "Page text:", text, ].join("\n"); const parsed = parseLlmJson(await llm.complete(prompt, jsonSchema)); const filled = new Set(); const coerceMissing = (target: Record, source: unknown) => { if (!source || typeof source !== "object") return; for (const leaf of missing) { if (isFilled(valueAt(target, leaf.path))) continue; const value = coerceField(valueAt(source as Record, leaf.path), leaf.spec, ctx); if (!isFilled(value)) continue; setLeaf(target, leaf, value); filled.add(leaf.key); } }; if (schema.kind === "object") { const record = records[0] ?? coerceRecord({}, schema, ctx); coerceMissing(record, Array.isArray(parsed) ? parsed[0] : parsed); return { records: [record], filled: [...filled] }; } const items = Array.isArray(parsed) ? parsed : parsed && typeof parsed === "object" ? ((Object.values(parsed).find(Array.isArray) as unknown[] | undefined) ?? []) : []; if (records.length === 0) { const out = items .filter((item): item is Record => !!item && typeof item === "object") .map((item) => coerceRecord(item, schema, ctx)); if (out.length > 0) for (const leaf of leafFields(schema)) filled.add(leaf.key); return { records: out, filled: [...filled] }; } records.forEach((record, i) => coerceMissing(record, items[i])); return { records, filled: [...filled] }; } function weightedConfidence( leaves: readonly LeafField[], plan: ExtractionPlan, records: ReadonlyArray>, llmFields: ReadonlySet, ): number { if (records.length === 0) return 0; const byKey = new Map(plan.fields.map((f) => [f.key, f])); let total = 0; let weights = 0; for (const leaf of leaves) { const weight = leaf.required ? 2 : 1; weights += weight; const fill = records.filter((r) => isFilled(valueAt(r, leaf.path))).length / records.length; const confidence = llmFields.has(leaf.key) ? 0.5 : (byKey.get(leaf.key)?.confidence ?? 0); // Optional leaves that are legitimately absent should not drag the score down. const effectiveFill = leaf.required || fill > 0 ? fill : 1; total += weight * confidence * effectiveFill; } return weights ? Math.round((total / weights) * 1000) / 1000 : 0; } /** * Extract typed records from `html` according to `schema` (JSON Schema subset * or shorthand, see {@link normalizeSchema}). */ export async function extractWithSchema(html: string, schemaInput: unknown, options: ExtractOptions = {}): Promise { const schema = normalizeSchema(schemaInput); const ctx: CoerceContext = { baseUrl: options.url, now: options.now, dayFirst: options.dayFirst }; const threshold = options.relearnThreshold ?? 0.6; const cache = options.cache || null; const url = options.url; const leaves = leafFields(schema); const doc = await parseHtml(html); try { const snap = DomSnapshot.build(doc); let entries: StructuredEntry[] | undefined; const structured = () => (entries ??= collectStructuredEntries(html, url)); const cacheInfo = { domain: cacheDomain(url), hit: false, relearned: false, stored: false }; let outcome: Outcome | null = null; if (cache && url && cacheInfo.domain) { const cached = cache.get(url, schema.hash); if (cached && cached.plan.kind === schema.kind) { const applied = applyPlan(snap, cached.plan, schema, ctx, structured); if (applied.records.length > 0 && fillRate(applied.records, schema) >= threshold) { cache.recordSuccess(url, schema.hash); outcome = { plan: cached.plan, applied, source: "cache" }; cacheInfo.hit = true; } else { cache.recordFailure(url, schema.hash); cacheInfo.relearned = true; } } } if (!outcome) { outcome = learn(snap, schema, ctx, structured, options); if (cache && url && cacheInfo.domain && outcome.applied.records.length > 0 && fillRate(outcome.applied.records, schema) >= threshold) { cacheInfo.stored = cache.put(url, schema.hash, outcome.plan); } } let records = outcome.applied.records; let source = outcome.source; const minConfidence = options.minConfidence ?? 0.3; let missing = missingLeaves(leaves, outcome.plan, records, minConfidence); const llmFields = new Set(); const unresolvedRequired = missing.filter((leaf) => leaf.required); if (options.llm && unresolvedRequired.length > 0) { const merged = await runLlmFallback(options.llm, html, schema, records, unresolvedRequired, ctx, options); records = merged.records; for (const key of merged.filled) llmFields.add(key); if (llmFields.size > 0) source = "llm"; missing = missingLeaves(leaves, outcome.plan, records, minConfidence).filter((leaf) => !llmFields.has(leaf.key)); } const issues: ValidationIssue[] = []; for (const record of records) { for (const issue of validateRecord(record, schema)) { if (issues.length < 50) issues.push(issue); } } const result: ExtractResult = { selectors: outcome.plan, confidence: weightedConfidence(leaves, outcome.plan, records, llmFields), missingFields: missing.map((leaf) => leaf.key), source, fillRate: Math.round(fillRate(records, schema) * 1000) / 1000, issues, cache: cacheInfo, llmFields: [...llmFields], }; if (schema.kind === "object") result.record = records[0] ?? coerceRecord({}, schema, ctx); else result.records = records; return result; } finally { doc.destroy(); } } export type FetchProfile = "static" | "http" | "fast" | "stealth" | "max"; export interface FetchedPage { html: string; /** Final URL after redirects. */ url: string; status: number; profile: string; } export interface ExtractUrlOptions extends Omit { /** First fetch profile. Default `http` (TLS-fingerprinted curl). */ profile?: FetchProfile; /** Escalate through `autoEscalate` when the page looks blocked. Default `true`. */ escalate?: boolean; /** Page fetcher override (tests, pools). */ fetchPage?: (url: string, profile: FetchProfile) => Promise; /** Base URL (link resolution and cache key) for `file://` inputs. */ baseUrl?: string; } export interface ExtractUrlResult extends ExtractResult { url: string; finalUrl: string; profile: string; status: number; } async function defaultFetchPage(url: string, profile: FetchProfile): Promise { const { Browser } = await import("../api/browser.ts"); const page = await Browser.newPage({ profile }); try { const response = await page.goto(url); const html = (await page.content()) || ""; return { html, url: response?.url || url, status: response?.status ?? 200, profile }; } finally { await page.close().catch(() => {}); } } /** Fetch `url` (escalating when blocked) and extract it with {@link extractWithSchema}. */ export async function extractUrlWithSchema(url: string, schemaInput: unknown, options: ExtractUrlOptions = {}): Promise { let fetched: FetchedPage; if (url.startsWith("file://")) { const html = await Bun.file(new URL(url)).text(); fetched = { html, url: options.baseUrl ?? url, status: 200, profile: "file" }; } else { const profile = options.profile ?? "http"; const fetchPage = options.fetchPage ?? defaultFetchPage; fetched = await fetchPage(url, profile); if (options.escalate !== false) { const escalation = await import("../profiles/auto-escalation.ts"); const signal = escalation.detectEscalationSignal(fetched.html, fetched.status, { url }); if (signal) { const next = escalation.nextProfile(profile as never) ?? "stealth"; if (options.fetchPage) { fetched = await options.fetchPage(url, next as FetchProfile); } else { const result = await escalation.autoEscalate(url, { startProfile: next }); try { fetched = { html: (await result.page.content()) || "", url, status: 200, profile: result.profile }; } finally { await result.page.close().catch(() => {}); } } } } } const result = await extractWithSchema(fetched.html, schemaInput, { ...options, url: fetched.url || url }); return { ...result, url, finalUrl: fetched.url || url, profile: fetched.profile, status: fetched.status }; }