/** * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ /** * @module bxc/ffi/curl-worker * * Worker-thread entry for off-thread libcurl-impersonate requests. Each * worker owns one `ImpersonatedClient` per client key (so connection reuse and * cookies behave as on the main thread) and runs the blocking * `curl_easy_perform` here instead of on the JavaScript event loop. */ declare const self: Worker; import { CurlError, type FetchOptions, ImpersonatedClient, type ImpersonatedClientOptions, } from "./curl-impersonate.ts"; import type { CurlWorkerRequest, CurlWorkerResponse } from "./curl-worker-pool.ts"; const clients = new Map(); function clientFor(key: string, options: ImpersonatedClientOptions): ImpersonatedClient { let client = clients.get(key); if (!client) { client = new ImpersonatedClient({ ...options, offThread: false }); clients.set(key, client); } return client; } self.onmessage = async (event: MessageEvent) => { const message = event.data; if (message.type === "close") { clients.get(message.clientKey)?.close(); clients.delete(message.clientKey); return; } let reply: CurlWorkerResponse; try { const client = clientFor(message.clientKey, message.clientOptions); const response = await client.fetch(message.url, message.options as FetchOptions); const body = await response.arrayBuffer(); reply = { type: "response", id: message.id, status: response.status, statusText: response.statusText, headers: [...response.headers.entries()], url: response.effectiveUrl, body, }; self.postMessage(reply, [body]); return; } catch (err) { reply = { type: "error", id: message.id, message: err instanceof Error ? err.message : String(err), curlCode: err instanceof CurlError ? err.curlCode : null, }; } self.postMessage(reply); }; self.postMessage({ type: "ready" } satisfies CurlWorkerResponse);