/** * ============================================================ * src/network/httpFetch.ts —— 走应用内代理配置的 fetch * ------------------------------------------------------------ * 为什么不能直接用全局 fetch + proxy.ts 里的 setGlobalDispatcher: * Node 24+ 的内置 fetch 由 Node 自带的 undici 提供,它读取的是「内建 undici * 实例」自己的全局 dispatcher 槽;而本项目依赖的 undici@6 包是另一个模块 * 实例。对 undici@6 调用 setGlobalDispatcher() 不会影响内置 fetch * (Node 26 实测:/config 开启代理后请求仍直连,在 DNS 污染网络下直接超时); * 把 undici@6 的 Dispatcher 作为 init.dispatcher 传给内置 fetch 也会被 * 跨实例品牌检查拒绝(UND_ERR_INVALID_ARG)。 * * 解法:代理启用时,用「同一个 undici@6 实例」自己的 fetch 并显式传入 * proxy.ts 维护的 Dispatcher;未启用代理时直接调用全局 fetch —— 行为与 * 历史完全一致,且测试对 globalThis.fetch 的 stub 依旧生效。 * ============================================================ */ import { fetch as undiciFetch, type Dispatcher } from 'undici'; import { getActiveProxyDispatcher } from './proxy.js'; /** 两个 LLM 调用点实际用到的 init 字段,同时兼容全局 fetch 与 undici fetch。 */ export interface HttpFetchInit { method?: string; headers?: Record | Headers | ReadonlyArray; body?: string | Uint8Array | null; signal?: AbortSignal | null; } export function httpFetch( input: string | URL, init?: HttpFetchInit, ): Promise { const dispatcher = getActiveProxyDispatcher(); if (!dispatcher) return fetch(input, init as RequestInit); // undici Response 与全局 Response 同属 WHATWG 规范实现(body 为 web stream), // 但来自不同模块实例、品牌类型不同,这里做跨实例桥接,调用方按全局 Response 使用。 return undiciFetch(input, { ...init, dispatcher, } as Parameters[1]) as unknown as Promise; }