/**
* Copyright 2026 aphrody-code
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @module bxc/crawler/document-pipeline
*
* HTML → agent-ready document: main content, Markdown, structural chunks with
* heading paths and offsets, canonical URL, content hash, SimHash and links
* with anchor text. One native pass (`bxc-extract` through the Rust bridge)
* when available; a degraded pure-TypeScript path otherwise.
*/
import type { ChunkInput } from "../db/BxcDB.ts";
import {
type ExtractedAnchor,
extractAnchors,
extractMain,
extractText,
extractTitle,
isExtractAvailable,
} from "../rust/bridge.ts";
import { ensureCrawlMarkdown } from "./markdown-fallback.ts";
export interface ProcessedDocument {
url: string;
title: string;
byline: string | null;
published: string | null;
lang: string | null;
description: string | null;
siteName: string | null;
/** Absolute canonical URL declared by the page, if any. */
canonicalUrl: string | null;
/** Main text (blocks separated by blank lines). */
text: string;
markdown: string;
wordCount: number;
/** SHA-256 (hex) of the normalised main text: exact-duplicate / change key. */
contentHash: string;
/** 16-hex-digit SimHash of the main text, `null` on the degraded path. */
simhash: string | null;
chunks: ChunkInput[];
anchors: ExtractedAnchor[];
/** `native` = bxc-extract; `fallback` = whole-body text without boilerplate removal. */
engine: "native" | "fallback";
}
export interface DocumentPipelineOptions {
/** Maximum characters per chunk. Default: 1200. */
maxChunkChars?: number;
/** Characters of overlap between consecutive chunks. Default: 150. */
chunkOverlap?: number;
}
function sha256Hex(value: string): string {
return new Bun.CryptoHasher("sha256").update(value).digest("hex");
}
/** Whitespace/case-insensitive hash so cosmetic re-renders are not "changes". */
export function contentHashOf(text: string): string {
return sha256Hex(text.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim());
}
function canonicalFromHtml(html: string, url: string): string | null {
const link =
/]*\brel=["'][^"']*\bcanonical\b[^"']*["'][^>]*\bhref=["']([^"']+)["']/i.exec(html) ??
/]*\bhref=["']([^"']+)["'][^>]*\brel=["'][^"']*\bcanonical\b[^"']*["']/i.exec(html) ??
/]*\bproperty=["']og:url["'][^>]*\bcontent=["']([^"']+)["']/i.exec(html);
if (!link?.[1]) return null;
try {
const resolved = new URL(link[1], url);
if (resolved.protocol !== "http:" && resolved.protocol !== "https:") return null;
resolved.hash = "";
return resolved.toString();
} catch {
return null;
}
}
/** Heading-aware Markdown chunker used only on the degraded path. */
function chunkMarkdown(markdown: string, maxChars: number): ChunkInput[] {
const chunks: ChunkInput[] = [];
const headingPath: string[] = [];
let current = "";
let currentPath: string[] = [];
let offset = 0;
let start = 0;
const flush = () => {
const text = current.trim();
if (text) chunks.push({ text, headingPath: currentPath, charStart: start, charEnd: start + current.length });
current = "";
};
for (const paragraph of markdown.split(/\n{2,}/)) {
const heading = /^(#{1,6})\s+(.*)$/.exec(paragraph.trim());
if (heading) {
flush();
const level = (heading[1] as string).length;
headingPath.length = level - 1;
headingPath[level - 1] = (heading[2] as string).trim();
}
if (current.length + paragraph.length > maxChars) flush();
if (!current) {
start = offset;
currentPath = headingPath.filter(Boolean);
}
current += `${paragraph}\n\n`;
offset += paragraph.length + 2;
}
flush();
return chunks;
}
/** Run the document pipeline on a fetched page. */
export function processDocument(
html: string,
url: string,
options: DocumentPipelineOptions = {},
): ProcessedDocument {
const maxChunkChars = options.maxChunkChars ?? 1200;
const chunkOverlap = options.chunkOverlap ?? 150;
const anchors = extractAnchors(html, url);
if (isExtractAvailable()) {
const extracted = extractMain(html, url, { maxChunkChars, chunkOverlap });
return {
url,
title: extracted.title,
byline: extracted.byline,
published: extracted.published,
lang: extracted.lang,
description: extracted.description,
siteName: extracted.siteName,
canonicalUrl: extracted.canonical,
text: extracted.text,
markdown: extracted.markdown,
wordCount: extracted.wordCount,
contentHash: contentHashOf(extracted.text),
simhash: extracted.simhash,
chunks: extracted.chunks.map((chunk) => ({
text: chunk.text,
headingPath: chunk.headingPath,
charStart: chunk.charStart,
charEnd: chunk.charEnd,
})),
anchors,
engine: "native",
};
}
const title = extractTitle(html);
const text = extractText(html);
const markdown = ensureCrawlMarkdown({ html, markdown: "", title, url });
return {
url,
title,
byline: null,
published: null,
lang: /]*\blang=["']([^"']+)["']/i.exec(html)?.[1] ?? null,
description: null,
siteName: null,
canonicalUrl: canonicalFromHtml(html, url),
text,
markdown,
wordCount: text.split(/\s+/).filter(Boolean).length,
contentHash: contentHashOf(text),
simhash: null,
chunks: chunkMarkdown(markdown, maxChunkChars),
anchors,
engine: "fallback",
};
}