// HTTP fetch helper — returns body as Buffer + content-type for routing import type { FetchResult } from "./constants.js"; import { BROWSER_HEADERS, DEFAULT_TIMEOUT_MS } from "./constants.js"; export async function fetchUrlStream( url: string, onProgress?: (loaded: number, total: number) => void, signal?: AbortSignal, ): Promise { const parsed = new URL(url); const headers: Record = { ...BROWSER_HEADERS, Referer: `${parsed.protocol}//${parsed.host}/`, }; const response = await fetch(url, { headers, signal: signal ?? AbortSignal.timeout(DEFAULT_TIMEOUT_MS), }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const contentType = response.headers.get("content-type") ?? ""; const contentLength = parseInt( response.headers.get("content-length") ?? "0", 10, ); if (!response.body) { throw new Error("No response body"); } const reader = response.body.getReader(); let loaded = 0; const chunks: Uint8Array[] = []; while (true) { const { done, value } = await reader.read(); if (done) break; loaded += value.length; chunks.push(value); onProgress?.(loaded, contentLength); } const body = Buffer.concat(chunks); return { body, contentType, contentLength, status: response.status, }; } // DuckDuckGo search fetch (separate because it uses DDG-specific headers) export async function fetchSearchHtml( url: string, signal?: AbortSignal, timeout?: number, ): Promise { const response = await fetch(url, { headers: BROWSER_HEADERS, signal: signal ?? AbortSignal.timeout(timeout ?? DEFAULT_TIMEOUT_MS), }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } return response.text(); }