/** * 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/rust/bridge * * Typed bindings for the Rust cdylib (`rust-bridge/src/lib.rs`). * * Invariants: * - The library is opened through `src/native/loader.ts`, which refuses a * library whose `bxc_bridge_abi_version()` differs from * {@link BXC_BRIDGE_ABI_VERSION}. * - String arguments are passed as NUL-terminated `Uint8Array`s directly to * the FFI call so Bun keeps them alive for the whole call. * - DOM trees are owned by {@link DomTree}: `dispose()` is idempotent and a * `FinalizationRegistry` frees trees that were never disposed. * - Network-bound operations have `*Async` variants backed by native job * handles; they never block the event loop. */ import { CString, FFIType, suffix, type Pointer } from "bun:ffi"; import { dirname, join } from "node:path"; import { resolveBxcConfig } from "../config/resolve.ts"; import { cString, cStringOrNull, createLazyLibrary } from "../native/loader.ts"; import { hasEmbedded, rustBridgeAsset } from "./embedded-assets.ts"; /** C ABI version these bindings were written against (see `lib.rs`). */ export const BXC_BRIDGE_ABI_VERSION = 2; /** Scope id meaning "the whole document" for node-level queries. */ export const DOCUMENT_SCOPE = 0xffff_ffff; const LIBRARY_FILE = process.platform === "win32" ? `bxc_rust_bridge.${suffix}` : `libbxc_rust_bridge.${suffix}`; const SYMBOLS = { bxc_bridge_abi_version: { args: [], returns: FFIType.u32 }, bxc_free_string: { args: [FFIType.ptr], returns: FFIType.void }, // DOM trees bxc_parse_html: { args: [FFIType.ptr], returns: FFIType.ptr }, bxc_tree_destroy: { args: [FFIType.ptr], returns: FFIType.void }, bxc_query_selector: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr }, bxc_query_selector_all: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr }, bxc_query_selector_all_nodes: { args: [FFIType.ptr, FFIType.u32, FFIType.ptr], returns: FFIType.ptr, }, bxc_query_selector_node: { args: [FFIType.ptr, FFIType.u32, FFIType.ptr], returns: FFIType.i32, }, bxc_node_outer_html: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.ptr }, bxc_node_inner_html: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.ptr }, bxc_node_text_content: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.ptr }, bxc_node_tag_name: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.ptr }, bxc_node_attribute: { args: [FFIType.ptr, FFIType.u32, FFIType.ptr], returns: FFIType.ptr, }, bxc_node_attributes_json: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.ptr }, // Text helpers bxc_html_to_markdown: { args: [FFIType.ptr], returns: FFIType.ptr }, bxc_extract_title: { args: [FFIType.ptr], returns: FFIType.ptr }, bxc_strip_tags: { args: [FFIType.ptr], returns: FFIType.ptr }, bxc_extract_links: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr }, bxc_extract_anchors: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr }, bxc_extract_text: { args: [FFIType.ptr], returns: FFIType.ptr }, bxc_normalize_url: { args: [FFIType.ptr], returns: FFIType.ptr }, // Main-content extraction (bxc-extract) bxc_extract_main: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.ptr }, bxc_html_to_markdown_with_base: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr }, bxc_simhash64: { args: [FFIType.ptr], returns: FFIType.ptr }, // Vector index (bxc-index) bxc_index_open: { args: [FFIType.ptr, FFIType.u32, FFIType.ptr, FFIType.i32], returns: FFIType.u64_fast }, bxc_index_len: { args: [FFIType.u64], returns: FFIType.i64_fast }, bxc_index_dim: { args: [FFIType.u64], returns: FFIType.u32 }, bxc_index_add: { args: [FFIType.u64, FFIType.u64, FFIType.ptr, FFIType.u32], returns: FFIType.i32 }, bxc_index_add_batch: { args: [FFIType.u64, FFIType.ptr, FFIType.ptr, FFIType.u32, FFIType.u32], returns: FFIType.i32, }, bxc_index_search: { args: [FFIType.u64, FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.u32], returns: FFIType.ptr, }, bxc_index_remove: { args: [FFIType.u64, FFIType.u64], returns: FFIType.i32 }, bxc_index_save: { args: [FFIType.u64], returns: FFIType.i32 }, bxc_index_compact: { args: [FFIType.u64], returns: FFIType.i32 }, bxc_index_stats: { args: [FFIType.u64], returns: FFIType.ptr }, bxc_index_close: { args: [FFIType.u64], returns: FFIType.i32 }, bxc_index_last_error: { args: [], returns: FFIType.ptr }, // Local I/O bxc_get_chromium_cookies: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.ptr, }, // Network (blocking legacy) bxc_dns_recon: { args: [FFIType.ptr], returns: FFIType.ptr }, bxc_gemini_web_ask: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.ptr, }, bxc_x_user_by_screen_name: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.ptr, }, bxc_x_user_tweets: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.ptr, }, bxc_x_community_by_rest_id: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.ptr, }, bxc_x_community_tweets: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.ptr, }, bxc_x_community_info_and_tweets: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.ptr, }, bxc_x_algorithm_rank: { args: [FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.ptr, }, // Network (non-blocking job handles) bxc_dns_recon_submit: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.u64_fast }, bxc_gemini_web_ask_submit: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.u64_fast, }, bxc_x_user_by_screen_name_submit: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.u64_fast, }, bxc_x_user_tweets_submit: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32, FFIType.u32], returns: FFIType.u64_fast, }, bxc_x_community_by_rest_id_submit: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.u64_fast, }, bxc_x_community_tweets_submit: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32, FFIType.u32], returns: FFIType.u64_fast, }, bxc_x_community_info_and_tweets_submit: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u32, FFIType.u32], returns: FFIType.u64_fast, }, bxc_job_completed_seq: { args: [], returns: FFIType.u64_fast }, bxc_job_pending_count: { args: [], returns: FFIType.u32 }, bxc_job_status: { args: [FFIType.u64], returns: FFIType.i32 }, bxc_job_take: { args: [FFIType.u64], returns: FFIType.ptr }, bxc_job_cancel: { args: [FFIType.u64], returns: FFIType.i32 }, } as const; /** * Candidate locations, most specific first: next to the running executable * (standalone release), the user bin dir (`bxc install`), then the source * tree's cargo output. */ function bridgeCandidates(): string[] { const repoRoot = join(import.meta.dir, "..", ".."); const userBin = Bun.env.BXC_BIN_DIR ?? resolveBxcConfig().settings.binDir; return [ join(dirname(process.execPath), LIBRARY_FILE), join(userBin, LIBRARY_FILE), join(userBin, "native", LIBRARY_FILE), join(repoRoot, "rust-bridge", "target", "release", LIBRARY_FILE), ]; } const bridge = createLazyLibrary({ name: "bxc rust-bridge", envVar: "BXC_RUST_BRIDGE_LIB", embedded: () => hasEmbedded && rustBridgeAsset ? { asset: rustBridgeAsset, filename: LIBRARY_FILE } : null, candidates: bridgeCandidates, symbols: SYMBOLS, abi: { symbol: "bxc_bridge_abi_version", expected: BXC_BRIDGE_ABI_VERSION }, installHint: "Install it with `bxc install --full`, build it with `bun run build:linux` " + "(or `cargo build -p bxc-rust-bridge --release`), or set BXC_RUST_BRIDGE_LIB.", }); function symbols() { return bridge.symbols(); } /** `true` when the Rust bridge can be loaded with a matching ABI. */ export function isBridgeAvailable(): boolean { return bridge.available(); } /** Path of the loaded (or loadable) bridge library, if any. */ export function bridgeLibraryPath(): string | null { return bridge.path(); } // --------------------------------------------------------------------------- // Owned strings // --------------------------------------------------------------------------- type OwnedPointer = Pointer | number | bigint | null; /** Copy and free a string owned by the native side. */ function readOwnedString(resultPtr: OwnedPointer): string | null { if (!resultPtr) return null; const sym = symbols(); try { return new CString(resultPtr as Pointer).toString(); } finally { sym.bxc_free_string(resultPtr as Pointer); } } function readOwnedJson(resultPtr: OwnedPointer, fallback: T): T { const value = readOwnedString(resultPtr); if (value === null) return fallback; try { return JSON.parse(value) as T; } catch { return fallback; } } export type NativeJson = | null | boolean | number | string | NativeJson[] | { [key: string]: NativeJson }; export function bridgeAbiVersion(): number { return symbols().bxc_bridge_abi_version(); } // --------------------------------------------------------------------------- // DOM trees // --------------------------------------------------------------------------- /** Raw tree pointer. Prefer {@link DomTree}, which guards its lifetime. */ export type DomTreePtr = number; const liveTreePointers = new Set(); function destroyPointer(handle: number): void { if (!liveTreePointers.delete(handle)) return; symbols().bxc_tree_destroy(handle as Pointer); } const treeFinalizer = new FinalizationRegistry((handle) => { try { destroyPointer(handle); } catch { // The library cannot be unloaded while trees exist; nothing to report. } }); /** Error thrown when a disposed {@link DomTree} is used. */ export class DisposedTreeError extends Error { constructor() { super("DomTree has been disposed"); this.name = "DisposedTreeError"; } } /** * Owned native DOM tree. * * Nodes are addressed by numeric ids that stay valid until the tree is * disposed, so nested queries never re-parse HTML. `dispose()` is idempotent * and every other method throws {@link DisposedTreeError} afterwards, which * turns a use-after-free into an exception. Trees that are never disposed are * released by a `FinalizationRegistry`. */ export class DomTree implements Disposable { #handle: number | null; private constructor(handle: number) { this.#handle = handle; liveTreePointers.add(handle); treeFinalizer.register(this, handle, this); } /** Parse `html`. Throws when the native parser rejects the input. */ static parse(html: string): DomTree { const handle = symbols().bxc_parse_html(cString(html)) as number | null; if (!handle) throw new Error("bxc_parse_html returned NULL"); return new DomTree(handle); } get disposed(): boolean { return this.#handle === null; } #ptr(): Pointer { if (this.#handle === null) throw new DisposedTreeError(); return this.#handle as Pointer; } /** Outer HTML of the first match in the document. */ querySelector(selector: string): string | null { return readOwnedString(symbols().bxc_query_selector(this.#ptr(), cString(selector))); } /** Outer HTML of every match in the document. */ querySelectorAll(selector: string): string[] { const result = readOwnedJson( symbols().bxc_query_selector_all(this.#ptr(), cString(selector)), [], ); return Array.isArray(result) ? result : []; } /** Id of the first element matching `selector` inside `scope`. */ selectNode(selector: string, scope: number = DOCUMENT_SCOPE): number | null { const id = symbols().bxc_query_selector_node(this.#ptr(), scope, cString(selector)); if (id === -2) throw new SyntaxError(`Invalid selector or scope: ${selector}`); return id < 0 ? null : id; } /** Ids (document order) of elements matching `selector` inside `scope`. */ selectNodes(selector: string, scope: number = DOCUMENT_SCOPE): number[] { const result = readOwnedJson( symbols().bxc_query_selector_all_nodes(this.#ptr(), scope, cString(selector)), { error: "null result" }, ); if (!Array.isArray(result)) { throw new SyntaxError(`${result.error}: ${selector}`); } return result; } outerHtml(node: number): string { return readOwnedString(symbols().bxc_node_outer_html(this.#ptr(), node)) ?? ""; } innerHtml(node: number): string { return readOwnedString(symbols().bxc_node_inner_html(this.#ptr(), node)) ?? ""; } textContent(node: number): string { return readOwnedString(symbols().bxc_node_text_content(this.#ptr(), node)) ?? ""; } tagName(node: number): string { return readOwnedString(symbols().bxc_node_tag_name(this.#ptr(), node)) ?? ""; } attribute(node: number, name: string): string | null { return readOwnedString( symbols().bxc_node_attribute(this.#ptr(), node, cString(name)), ); } attributes(node: number): Record { return readOwnedJson>( symbols().bxc_node_attributes_json(this.#ptr(), node), {}, ); } /** Release the native tree. Safe to call more than once. */ dispose(): void { const handle = this.#handle; if (handle === null) return; this.#handle = null; treeFinalizer.unregister(this); destroyPointer(handle); } [Symbol.dispose](): void { this.dispose(); } } /** * Parse `html` into a raw tree pointer. * @deprecated Use {@link DomTree.parse}; raw pointers are not lifetime-checked. */ export function parseHtml(html: string): DomTreePtr { const handle = symbols().bxc_parse_html(cString(html)) as number | null; if (handle) liveTreePointers.add(handle); return handle ?? 0; } /** * Destroy a raw tree pointer. Unknown or already-destroyed pointers are * ignored instead of double-freeing. * @deprecated Use {@link DomTree.dispose}. */ export function destroyTree(tree: DomTreePtr): void { if (tree) destroyPointer(tree); } function assertLivePointer(tree: DomTreePtr): Pointer { if (!liveTreePointers.has(tree)) throw new DisposedTreeError(); return tree as Pointer; } /** @deprecated Use {@link DomTree.querySelector}. */ export function querySelector(tree: DomTreePtr, selector: string): string | null { return readOwnedString( symbols().bxc_query_selector(assertLivePointer(tree), cString(selector)), ); } /** @deprecated Use {@link DomTree.querySelectorAll}. */ export function querySelectorAll(tree: DomTreePtr, selector: string): string[] { const result = readOwnedJson( symbols().bxc_query_selector_all(assertLivePointer(tree), cString(selector)), [], ); return Array.isArray(result) ? result : []; } // --------------------------------------------------------------------------- // Text helpers // --------------------------------------------------------------------------- /** * Whole-document HTML → GitHub-flavoured Markdown (the single canonical * converter, `bxc-extract`). Links resolve against `baseUrl` when given. */ export function htmlToMarkdown(html: string, baseUrl?: string): string { if (baseUrl) { return ( readOwnedString( symbols().bxc_html_to_markdown_with_base(cString(html), cString(baseUrl)), ) ?? "" ); } return readOwnedString(symbols().bxc_html_to_markdown(cString(html))) ?? ""; } export type ExtractedBlockKind = "heading" | "paragraph" | "list_item" | "code" | "quote" | "table"; export interface ExtractedBlock { kind: ExtractedBlockKind; level: number | null; heading_path: string[]; text: string; } export interface ExtractedChunk { headingPath: string[]; text: string; startBlock: number; endBlock: number; /** Start offset (UTF-16 code units) into {@link ExtractedDocument.text}. */ charStart: number; /** End offset (exclusive, UTF-16 code units) into {@link ExtractedDocument.text}. */ charEnd: number; } export interface ExtractedDocument { title: string; byline: string | null; published: string | null; lang: string | null; canonical: string | null; siteName: string | null; description: string | null; /** Main text, blocks separated by blank lines. */ text: string; markdown: string; /** 16 lowercase hex digits. */ simhash: string; wordCount: number; blocks: ExtractedBlock[]; chunks: ExtractedChunk[]; } export interface ExtractMainOptions { maxChunkChars?: number; chunkOverlap?: number; includeComments?: boolean; includeImages?: boolean; includeLinks?: boolean; } /** `true` when native main-content extraction is available. */ export function isExtractAvailable(): boolean { return bridge.available(); } /** * Main-content extraction (text/link density + DOM distance scoring) with * metadata, Markdown, structural blocks, chunks with offsets and SimHash. */ export function extractMain( html: string, url?: string, options: ExtractMainOptions = {}, ): ExtractedDocument { const result = readOwnedJson( symbols().bxc_extract_main(cString(html), cStringOrNull(url), cString(JSON.stringify(options))), { error: "null result" }, ); if ("error" in result) throw new Error(`bxc_extract_main failed: ${result.error}`); return result; } /** 64-bit SimHash of `text` (16 lowercase hex digits). */ export function simhash64(text: string): string { return readOwnedString(symbols().bxc_simhash64(cString(text))) ?? "0000000000000000"; } /** Number of differing bits between two 16-hex-digit SimHashes. */ export function simhashDistance(a: string, b: string): number { let x = BigInt(`0x${a}`) ^ BigInt(`0x${b}`); let bits = 0; while (x) { x &= x - 1n; bits++; } return bits; } export function extractTitle(html: string): string { return readOwnedString(symbols().bxc_extract_title(cString(html))) ?? ""; } export function stripTags(html: string): string { return readOwnedString(symbols().bxc_strip_tags(cString(html))) ?? html; } /** * Absolute, fragment-free links of `html`. Falls back to a regex scan when the * bridge is unavailable so link discovery keeps working on hosts without it. */ export function extractLinks(html: string, baseUrl?: string): string[] { if (!bridge.available()) return extractLinksFallback(html, baseUrl); const result = readOwnedJson( symbols().bxc_extract_links(cString(html), cStringOrNull(baseUrl)), [], ); return Array.isArray(result) ? result : []; } function extractLinksFallback(html: string, baseUrl?: string): string[] { const links: string[] = []; const seen = new Set(); for (const match of html.matchAll(/]*\bhref\s*=\s*["']([^"'#]+)["']/gi)) { const href = (match[1] ?? "").trim(); if (!href || /^(javascript|mailto|tel|data):/i.test(href)) continue; try { const resolved = new URL(href, baseUrl).href; if (!seen.has(resolved)) { seen.add(resolved); links.push(resolved); } } catch { // Relative link without a base, or malformed URL. } } return links; } export interface ExtractedAnchor { /** Absolute URL without fragment. */ url: string; /** Collapsed anchor text (≤ 200 chars). */ text: string; /** `rel` contains nofollow/ugc/sponsored on every occurrence. */ nofollow: boolean; } /** * Links of `html` with their anchor text, parsed with the HTML5 tree builder * (honours ``, merges duplicates). Falls back to URLs without text * when the bridge is unavailable. */ export function extractAnchors(html: string, baseUrl?: string): ExtractedAnchor[] { if (!bridge.available()) { return extractLinksFallback(html, baseUrl).map((url) => ({ url, text: "", nofollow: false })); } const result = readOwnedJson( symbols().bxc_extract_anchors(cString(html), cStringOrNull(baseUrl)), [], ); return Array.isArray(result) ? result : []; } /** Visible text of `html` (scripts/styles removed, entities decoded). */ export function extractText(html: string): string { if (!bridge.available()) return html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); return readOwnedString(symbols().bxc_extract_text(cString(html))) ?? ""; } /** Canonical form of `url` (lowercase host, sorted query, tracking params removed). */ export function normalizeUrl(url: string): string { if (!bridge.available()) { try { const parsed = new URL(url); parsed.hash = ""; return parsed.toString(); } catch { return url; } } return readOwnedString(symbols().bxc_normalize_url(cString(url))) ?? url; } // --------------------------------------------------------------------------- // Vector index (HNSW, int8 quantisation, mmap persistence) // --------------------------------------------------------------------------- export interface NativeIndexParams { /** Max neighbours per node on upper layers (layer 0 uses 2M). Default 16. */ m?: number; ef_construction?: number; ef_search?: number; metric?: "cosine" | "l2"; /** Keep float vectors to rescore candidates exactly. Default true. */ keep_float?: boolean; } function lastIndexError(): string { const payload = readOwnedJson<{ error: string | null }>(symbols().bxc_index_last_error(), { error: null }); return payload.error ?? "unknown index error"; } /** * Native HNSW index bound to a file. Implements the `VectorIndex` contract of * `src/index/vector-index.ts` (keys are non-negative integers < 2^53, scores * are cosine similarities). */ export class NativeVectorIndex { #handle: number; readonly path: string; /** `true` when the file existed but was corrupt and a fresh index was created. */ readonly rebuiltFromCorruptFile: boolean; private constructor(handle: number, path: string, rebuilt: boolean) { this.#handle = handle; this.path = path; this.rebuiltFromCorruptFile = rebuilt; } /** * Open (or lazily create) the index at `path`. A corrupt file is replaced * by an empty index (check {@link rebuiltFromCorruptFile} and re-add). */ static open(path: string, dim: number, params: NativeIndexParams = {}): NativeVectorIndex { const handle = Number(symbols().bxc_index_open(cString(path), dim, cString(JSON.stringify(params)), 1)); if (!handle) throw new Error(`bxc_index_open(${path}) failed: ${lastIndexError()}`); const rebuilt = lastIndexError().startsWith("corrupt"); return new NativeVectorIndex(handle, path, rebuilt); } #id(): number { if (!this.#handle) throw new Error("NativeVectorIndex is closed"); return this.#handle; } get dim(): number { return symbols().bxc_index_dim(this.#id()); } get size(): number { return Math.max(0, Number(symbols().bxc_index_len(this.#id()))); } add(key: number, vector: Float32Array): void { if (symbols().bxc_index_add(this.#id(), key, vector, vector.length) !== 0) { throw new Error(`bxc_index_add failed: ${lastIndexError()}`); } } /** Bulk insert; `vectors` must all have the index dimension. */ addBatch(keys: readonly number[], vectors: readonly Float32Array[]): void { if (keys.length === 0) return; const dim = vectors[0]?.length ?? 0; const flat = new Float32Array(keys.length * dim); vectors.forEach((v, i) => flat.set(v, i * dim)); const keyArray = BigUint64Array.from(keys, (k) => BigInt(k)); if (symbols().bxc_index_add_batch(this.#id(), keyArray, flat, keys.length, dim) !== 0) { throw new Error(`bxc_index_add_batch failed: ${lastIndexError()}`); } } remove(key: number): boolean { return symbols().bxc_index_remove(this.#id(), key) === 1; } search(query: Float32Array, k: number, ef = Math.max(128, k * 2)): Array<{ key: number; score: number }> { const result = readOwnedJson | { error: string }>( symbols().bxc_index_search(this.#id(), query, query.length, k, ef), { error: "null result" }, ); if (!Array.isArray(result)) throw new Error(`bxc_index_search failed: ${result.error}`); return result; } save(): void { if (symbols().bxc_index_save(this.#id()) !== 0) throw new Error(`bxc_index_save failed: ${lastIndexError()}`); } compact(): void { if (symbols().bxc_index_compact(this.#id()) !== 0) { throw new Error(`bxc_index_compact failed: ${lastIndexError()}`); } } stats(): Record { return readOwnedJson>(symbols().bxc_index_stats(this.#id()), {}); } /** Release the handle (idempotent). Call {@link save} first to persist. */ close(): void { if (!this.#handle) return; symbols().bxc_index_close(this.#handle); this.#handle = 0; } } // --------------------------------------------------------------------------- // Local I/O // --------------------------------------------------------------------------- export function getChromiumCookies( userDataPath: string, profile: string, hostKey: string, ): NativeJson[] { return readOwnedJson( symbols().bxc_get_chromium_cookies( cString(userDataPath), cString(profile), cString(hostKey), ), [], ); } // --------------------------------------------------------------------------- // Native jobs (non-blocking network calls) // --------------------------------------------------------------------------- export interface NativeJobOptions { /** Native-side timeout; `0` disables it. Default: 60 000 ms. */ timeoutMs?: number; /** Cancels the native job and rejects with an `AbortError`. */ signal?: AbortSignal; } interface PendingJob { resolve: (json: string) => void; reject: (error: Error) => void; } const MIN_POLL_MS = 1; const MAX_POLL_MS = 25; const pendingJobs = new Map(); let lastCompletedSeq = -1; let pollTimer: ReturnType | null = null; let pollDelay = MIN_POLL_MS; function schedulePoll(): void { if (pollTimer !== null || pendingJobs.size === 0) return; pollTimer = setTimeout(pollJobs, pollDelay); } /** * Collect finished jobs. A single `completed_seq` read tells whether anything * finished since the last tick, so idle polling costs one FFI call. The delay * backs off exponentially while nothing completes. */ function pollJobs(): void { pollTimer = null; const sym = symbols(); const seq = Number(sym.bxc_job_completed_seq()); if (seq !== lastCompletedSeq) { lastCompletedSeq = seq; for (const [id, job] of pendingJobs) { const result = sym.bxc_job_take(id); if (!result) continue; pendingJobs.delete(id); job.resolve(readOwnedString(result) ?? ""); } pollDelay = MIN_POLL_MS; } else { pollDelay = Math.min(pollDelay * 2, MAX_POLL_MS); } schedulePoll(); } function abortError(): Error { return new DOMException("The native job was aborted", "AbortError"); } /** * Await a job submitted through any `*_submit` symbol of the bridge library * (the job registry is process-wide) and return its raw JSON string. */ export function awaitNativeJob(id: number, signal?: AbortSignal): Promise { return awaitJob(id, signal); } function awaitJob(id: number, signal?: AbortSignal): Promise { return new Promise((resolve, reject) => { if (signal?.aborted) { symbols().bxc_job_cancel(id); reject(abortError()); return; } const onAbort = () => { if (pendingJobs.delete(id)) { symbols().bxc_job_cancel(id); reject(abortError()); } }; signal?.addEventListener("abort", onAbort, { once: true }); pendingJobs.set(id, { resolve: (json) => { signal?.removeEventListener("abort", onAbort); resolve(json); }, reject, }); pollDelay = MIN_POLL_MS; schedulePoll(); }); } async function runJson( submit: (timeoutMs: number) => number | bigint, opts: NativeJobOptions, ): Promise { const id = Number(submit(opts.timeoutMs ?? 60_000)); const json = await awaitJob(id, opts.signal); return JSON.parse(json) as T; } /** Number of native jobs still running (diagnostics). */ export function nativePendingJobCount(): number { return symbols().bxc_job_pending_count(); } function isErrorPayload(value: unknown): value is { error: string } { return ( typeof value === "object" && value !== null && !Array.isArray(value) && typeof (value as { error?: unknown }).error === "string" ); } /** DNS OSINT without blocking the event loop. Rejects on native errors. */ export async function dnsReconAsync( domain: string, opts: NativeJobOptions = {}, ): Promise { const result = await runJson( (timeout) => symbols().bxc_dns_recon_submit(cString(domain), timeout), opts, ); if (isErrorPayload(result)) throw new Error(result.error); return result; } export interface GeminiNativeResponse { [key: string]: NativeJson | undefined; error?: string; text: string; conversation_id?: string; response_id?: string; choice_id?: string; } /** Gemini web prompt without blocking the event loop. Errors are returned in `error`. */ export async function geminiWebAskAsync( cookiePath: string, prompt: string, model?: string, opts: NativeJobOptions = {}, ): Promise { const result = await runJson( (timeout) => symbols().bxc_gemini_web_ask_submit( cString(cookiePath), cString(prompt), cStringOrNull(model), timeout, ), opts, ); return { ...result, text: result.text ?? "" }; } export interface XNativeSession { authToken: string; ct0: string; } export function xUserByScreenNameAsync( session: XNativeSession, handle: string, opts: NativeJobOptions = {}, ): Promise { return runJson( (timeout) => symbols().bxc_x_user_by_screen_name_submit( cString(session.authToken), cString(session.ct0), cString(handle), timeout, ), opts, ); } export function xUserTweetsAsync( session: XNativeSession, handle: string, count = 20, opts: NativeJobOptions = {}, ): Promise { return runJson( (timeout) => symbols().bxc_x_user_tweets_submit( cString(session.authToken), cString(session.ct0), cString(handle), count, timeout, ), opts, ); } export function xCommunityByRestIdAsync( session: XNativeSession, communityId: string, opts: NativeJobOptions = {}, ): Promise { return runJson( (timeout) => symbols().bxc_x_community_by_rest_id_submit( cString(session.authToken), cString(session.ct0), cString(communityId), timeout, ), opts, ); } export function xCommunityTweetsAsync( session: XNativeSession, communityId: string, count = 20, opts: NativeJobOptions = {}, ): Promise { return runJson( (timeout) => symbols().bxc_x_community_tweets_submit( cString(session.authToken), cString(session.ct0), cString(communityId), count, timeout, ), opts, ); } export function xCommunityInfoAndTweetsAsync( session: XNativeSession, communityId: string, count = 20, opts: NativeJobOptions = {}, ): Promise { return runJson( (timeout) => symbols().bxc_x_community_info_and_tweets_submit( cString(session.authToken), cString(session.ct0), cString(communityId), count, timeout, ), opts, ); } // --------------------------------------------------------------------------- // Blocking legacy network calls // --------------------------------------------------------------------------- function ffiError(): T { return { error: "Null or invalid response returned from FFI" } as unknown as T; } /** * @deprecated Blocks the event loop for the whole network round trip. Use * {@link dnsReconAsync}. */ export function dnsRecon(domain: string): string[] { return readOwnedJson(symbols().bxc_dns_recon(cString(domain)), []); } /** @deprecated Blocks the event loop. Use {@link geminiWebAskAsync}. */ export function geminiWebAsk( cookiePath: string, prompt: string, model?: string, ): GeminiNativeResponse { return readOwnedJson( symbols().bxc_gemini_web_ask( cString(cookiePath), cString(prompt), cStringOrNull(model), ), { error: "Null or invalid response returned from FFI", text: "" }, ); } /** @deprecated Blocks the event loop. Use {@link xUserByScreenNameAsync}. */ export function xUserByScreenName( session: XNativeSession, handle: string, ): T { return readOwnedJson( symbols().bxc_x_user_by_screen_name( cString(session.authToken), cString(session.ct0), cString(handle), ), ffiError(), ); } /** @deprecated Blocks the event loop. Use {@link xUserTweetsAsync}. */ export function xUserTweets( session: XNativeSession, handle: string, count = 20, ): T { return readOwnedJson( symbols().bxc_x_user_tweets( cString(session.authToken), cString(session.ct0), cString(handle), count, ), ffiError(), ); } /** @deprecated Blocks the event loop. Use {@link xCommunityByRestIdAsync}. */ export function xCommunityByRestId( session: XNativeSession, communityId: string, ): T { return readOwnedJson( symbols().bxc_x_community_by_rest_id( cString(session.authToken), cString(session.ct0), cString(communityId), ), ffiError(), ); } /** @deprecated Blocks the event loop. Use {@link xCommunityTweetsAsync}. */ export function xCommunityTweets( session: XNativeSession, communityId: string, count = 20, ): T { return readOwnedJson( symbols().bxc_x_community_tweets( cString(session.authToken), cString(session.ct0), cString(communityId), count, ), ffiError(), ); } /** @deprecated Blocks the event loop. Use {@link xCommunityInfoAndTweetsAsync}. */ export function xCommunityInfoAndTweets( session: XNativeSession, communityId: string, count = 20, ): T { return readOwnedJson( symbols().bxc_x_community_info_and_tweets( cString(session.authToken), cString(session.ct0), cString(communityId), count, ), ffiError(), ); } /** Rank X post candidates with the native For You algorithm (CPU-only, synchronous). */ export function xAlgorithmRank( candidates: readonly unknown[], context: unknown = null, topK = 20, ): T { return readOwnedJson( symbols().bxc_x_algorithm_rank( cString(JSON.stringify(candidates)), context === null ? null : cString(JSON.stringify(context)), topK, ), ffiError(), ); }