/** * 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/render/native-render * * Bindings for `libbxc_render` (`rust-bridge/crates/bxc-render`): in-process * JavaScript rendering with V8 over an html5ever DOM, without spawning a * browser. * * Invariants: * - The library is opened lazily through `src/native/loader.ts` with an ABI * equality check, so importing this module never maps V8. * - Every call is a native job (`bxc_render_submit`) awaited through * `src/native/job-poller.ts`; the event loop is never blocked. * - The library is shipped next to the executable (not embedded) because it * statically links V8 (~60 MB). */ import { CString, FFIType, suffix, type Pointer } from "bun:ffi"; import { dirname, join } from "node:path"; import { resolveBxcConfig } from "../config/resolve.ts"; import { createJobPoller } from "../native/job-poller.ts"; import { cString, createLazyLibrary } from "../native/loader.ts"; /** C ABI version these bindings were written against (see `lib.rs`). */ export const BXC_RENDER_ABI_VERSION = 1; export const RENDER_LIBRARY_FILE = process.platform === "win32" ? `bxc_render.${suffix}` : `libbxc_render.${suffix}`; export const RENDER_INSTALL_HINT = "Build it with `bun run build:render` (cargo build --release in rust-bridge/crates/bxc-render), " + "place libbxc_render next to the bxc executable or in the BXC bin dir, or set BXC_RENDER_LIB."; const SYMBOLS = { bxc_render_abi_version: { args: [], returns: FFIType.u32 }, bxc_render_submit: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.u64_fast }, bxc_render_job_completed_seq: { args: [], returns: FFIType.u64_fast }, bxc_render_job_take: { args: [FFIType.u64], returns: FFIType.ptr }, bxc_render_job_cancel: { args: [FFIType.u64], returns: FFIType.i32 }, bxc_render_pending_count: { args: [], returns: FFIType.u32 }, bxc_render_stats_json: { args: [], returns: FFIType.ptr }, bxc_render_free_string: { args: [FFIType.ptr], returns: FFIType.void }, } as const; function renderCandidates(): string[] { const repoRoot = join(import.meta.dir, "..", ".."); let userBin: string | null = Bun.env.BXC_BIN_DIR ?? null; if (!userBin) { try { userBin = resolveBxcConfig().settings.binDir; } catch { userBin = null; } } const execDir = dirname(process.execPath); const candidates = [join(execDir, RENDER_LIBRARY_FILE), join(execDir, "native", RENDER_LIBRARY_FILE)]; if (userBin) { candidates.push(join(userBin, RENDER_LIBRARY_FILE), join(userBin, "native", RENDER_LIBRARY_FILE)); } candidates.push( join(repoRoot, "rust-bridge", "crates", "bxc-render", "target", "release", RENDER_LIBRARY_FILE), join(repoRoot, "rust-bridge", "target-render", "release", RENDER_LIBRARY_FILE), join(repoRoot, "rust-bridge", "target", "release", RENDER_LIBRARY_FILE), ); return candidates; } const library = createLazyLibrary({ name: "bxc-render", envVar: "BXC_RENDER_LIB", candidates: renderCandidates, symbols: SYMBOLS, abi: { symbol: "bxc_render_abi_version", expected: BXC_RENDER_ABI_VERSION }, installHint: RENDER_INSTALL_HINT, }); function symbols() { return library.symbols(); } /** `true` when libbxc_render can be loaded with a matching ABI. Never throws. */ export function isRenderAvailable(): boolean { return library.available(); } /** Path of the loaded (or loadable) library, if any. */ export function renderLibraryPath(): string | null { return library.path(); } /** Why the library could not be loaded, after a failed attempt. */ export function renderLoadError(): Error | null { return library.error(); } function readOwnedString(pointer: number | bigint): string { const sym = symbols(); try { return new CString(pointer as Pointer).toString(); } finally { sym.bxc_render_free_string(pointer as Pointer); } } let poller: ReturnType | null = null; function jobPoller() { poller ??= createJobPoller({ completedSeq: () => symbols().bxc_render_job_completed_seq(), take: (id) => symbols().bxc_render_job_take(id) as number | null, cancel: (id) => symbols().bxc_render_job_cancel(id), readString: (pointer) => readOwnedString(pointer), }); return poller; } // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export type RenderWaitUntil = "load" | "domcontentloaded" | "networkidle0" | "networkidle2"; export interface RenderCookie { name: string; value: string; domain: string; path?: string; secure?: boolean; httpOnly?: boolean; } /** Options shared by one-shot renders and sessions (one browser context). */ export interface RenderContextOptions { userAgent?: string; /** Upstream proxy URL (`http://`, `https://`, `socks5://`). */ proxy?: string; /** Blocks known trackers; TLS impersonation is not part of this profile. */ stealth?: boolean; /** Substring or `*`-glob URL patterns never fetched as subresources. */ blockPatterns?: string[]; cookies?: RenderCookie[]; extraHeaders?: Record; /** Lets public pages reach loopback/private addresses (private pages always may). */ allowPrivateNetwork?: boolean; /** Serialized HTML above this size is truncated (default 8 MiB). */ maxHtmlBytes?: number; /** Settle budget in virtual milliseconds after `load` (default 3000/8000). */ settleMs?: number; } export interface RenderCallOptions { /** Native deadline; `0` disables it. Default 30 000 ms. */ timeoutMs?: number; /** Cancels the native job. */ signal?: AbortSignal; } export interface RenderOptions extends RenderContextOptions, RenderCallOptions { waitUntil?: RenderWaitUntil; /** Expression (or statements) evaluated after load; promises are awaited. */ evaluate?: string; } export interface RenderTimings { fetchMs: number; navigateMs: number; scriptsMs: number; settleMs: number; totalMs: number; } export interface RenderNavigation { url: string; finalUrl: string; status: number; /** Lower-cased document response headers. */ headers: Record; title: string; timings: RenderTimings; networkRequests: number; jsErrors: string[]; consoleErrors: string[]; } export interface RenderResult extends RenderNavigation { html: string; truncated?: boolean; evaluate?: unknown; evaluateError?: string; } export interface RenderContent { html: string; title: string; url: string; truncated?: boolean; } export interface RenderStats { abiVersion: number; started: boolean; threads: number; livePages: number; sessionPages: number; pendingJobs: number; unclaimedResults: number; completedSeq: number; workers: Array<{ index: number; livePages: number; activeJobs: number; completedJobs: number }>; } /** Native render failure (navigation error, timeout, JS exception, ...). */ export class RenderError extends Error { constructor(message: string) { super(message); this.name = "RenderError"; } } // --------------------------------------------------------------------------- // Calls // --------------------------------------------------------------------------- const DEFAULT_TIMEOUT_MS = 30_000; async function call(request: Record, opts: RenderCallOptions = {}): Promise { opts.signal?.throwIfAborted(); const timeout = Math.max(0, Math.min(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, 0xffff_ffff)); const id = Number(symbols().bxc_render_submit(cString(JSON.stringify(request)), timeout)); const raw = await jobPoller().awaitJob(id, opts.signal); let parsed: unknown; try { parsed = JSON.parse(raw); } catch { throw new RenderError(`bxc-render returned invalid JSON: ${raw.slice(0, 200)}`); } if ( parsed && typeof parsed === "object" && !Array.isArray(parsed) && typeof (parsed as { error?: unknown }).error === "string" ) { throw new RenderError((parsed as { error: string }).error); } return parsed as T; } function contextFields(opts: RenderContextOptions): Record { const out: Record = {}; for (const key of [ "userAgent", "proxy", "stealth", "blockPatterns", "cookies", "extraHeaders", "allowPrivateNetwork", "maxHtmlBytes", "settleMs", ] as const) { if (opts[key] !== undefined) out[key] = opts[key]; } return out; } /** Renders `url` in a fresh page (open, navigate, evaluate, serialize, close). */ export async function renderPage(url: string, opts: RenderOptions = {}): Promise { return call( { op: "render", url, waitUntil: opts.waitUntil ?? "load", ...(opts.evaluate !== undefined ? { evaluate: opts.evaluate } : {}), ...contextFields(opts), }, opts, ); } /** Library and render-thread statistics. Starts nothing. */ export function renderStats(): RenderStats { const pointer = symbols().bxc_render_stats_json(); if (!pointer) throw new RenderError("bxc_render_stats_json returned NULL"); return JSON.parse(readOwnedString(pointer as number)) as RenderStats; } const sessionFinalizer = new FinalizationRegistry((pageId) => { try { call({ op: "close", page: pageId }, { timeoutMs: 10_000 }).catch(() => undefined); } catch { // The library cannot be unloaded while sessions exist; nothing to do. } }); /** * A page kept alive across calls, pinned to one render thread. Navigations * replace the document (and its V8 isolate); `close()` releases everything. */ export class RenderSession implements AsyncDisposable { readonly id: string; #closed = false; private constructor(id: string) { this.id = id; sessionFinalizer.register(this, id, this); } static async open(opts: RenderContextOptions & RenderCallOptions = {}): Promise { const { page } = await call<{ page: string }>({ op: "open", ...contextFields(opts) }, opts); return new RenderSession(page); } get closed(): boolean { return this.#closed; } #assertOpen(): void { if (this.#closed) throw new RenderError("RenderSession is closed"); } async navigate( url: string, opts: RenderCallOptions & { waitUntil?: RenderWaitUntil } = {}, ): Promise { this.#assertOpen(); return call( { op: "navigate", page: this.id, url, waitUntil: opts.waitUntil ?? "load" }, opts, ); } /** Evaluates an expression or statements; promises are awaited. */ async evaluate(expression: string, opts: RenderCallOptions = {}): Promise { this.#assertOpen(); const { value } = await call<{ value: T }>( { op: "evaluate", page: this.id, expression }, opts, ); return value; } /** Serialized current DOM, title and URL. */ async content(opts: RenderCallOptions = {}): Promise { this.#assertOpen(); return call({ op: "content", page: this.id }, opts); } async close(): Promise { if (this.#closed) return; this.#closed = true; sessionFinalizer.unregister(this); await call({ op: "close", page: this.id }, { timeoutMs: 30_000 }).catch(() => undefined); } async [Symbol.asyncDispose](): Promise { await this.close(); } }