( url_: URL | string, init?: RequestInit, requestOptions?: RequestOptions, )
| 80 | } |
| 81 | |
| 82 | export async function fetchwithRequestOptions( |
| 83 | url_: URL | string, |
| 84 | init?: RequestInit, |
| 85 | requestOptions?: RequestOptions, |
| 86 | ): Promise<Response> { |
| 87 | const url = typeof url_ === "string" ? new URL(url_) : url_; |
| 88 | if (url.host === "localhost") { |
| 89 | url.host = "127.0.0.1"; |
| 90 | } |
| 91 | |
| 92 | const agentOptions = await getAgentOptions(requestOptions); |
| 93 | |
| 94 | // Get proxy from options or environment variables |
| 95 | const proxy = getProxy(url.protocol, requestOptions); |
| 96 | |
| 97 | // Check if should bypass proxy based on requestOptions or NO_PROXY env var |
| 98 | const shouldBypass = shouldBypassProxy(url.hostname, requestOptions); |
| 99 | |
| 100 | // Create agent |
| 101 | const protocol = url.protocol === "https:" ? https : http; |
| 102 | const agent = |
| 103 | proxy && !shouldBypass |
| 104 | ? protocol === https |
| 105 | ? new HttpsProxyAgent(proxy, agentOptions) |
| 106 | : new HttpProxyAgent(proxy, agentOptions) |
| 107 | : new protocol.Agent(agentOptions); |
| 108 | |
| 109 | let headers: { [key: string]: string } = {}; |
| 110 | |
| 111 | // Handle different header formats |
| 112 | if (init?.headers) { |
| 113 | const headersSource = init.headers as any; |
| 114 | |
| 115 | // Check if it's a Headers-like object (OpenAI v5 HeadersList, standard Headers) |
| 116 | if (headersSource && typeof headersSource.forEach === "function") { |
| 117 | // Use forEach method which works reliably on Headers objects |
| 118 | headersSource.forEach((value: string, key: string) => { |
| 119 | headers[key] = value; |
| 120 | }); |
| 121 | } else if (Array.isArray(headersSource)) { |
| 122 | // This is an array of [key, value] tuples |
| 123 | for (const [key, value] of headersSource) { |
| 124 | headers[key] = value as string; |
| 125 | } |
| 126 | } else if (headersSource && typeof headersSource === "object") { |
| 127 | // This is a plain object |
| 128 | for (const [key, value] of Object.entries(headersSource)) { |
| 129 | headers[key] = value as string; |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | headers = { |
| 135 | ...headers, |
| 136 | ...requestOptions?.headers, |
| 137 | }; |
| 138 | |
| 139 | // Replace localhost with 127.0.0.1 |
no test coverage detected