| 1 | import { RequestOptions } from "@continuedev/config-types"; |
| 2 | import * as followRedirects from "follow-redirects"; |
| 3 | import { HttpProxyAgent } from "http-proxy-agent"; |
| 4 | import { HttpsProxyAgent } from "https-proxy-agent"; |
| 5 | import { BodyInit, RequestInit, Response } from "node-fetch"; |
| 6 | import { getAgentOptions } from "./getAgentOptions.js"; |
| 7 | import patchedFetch from "./node-fetch-patch.js"; |
| 8 | import { getProxy, shouldBypassProxy } from "./util.js"; |
| 9 | |
| 10 | const { http, https } = (followRedirects as any).default; |
| 11 | |
| 12 | function logRequest( |
| 13 | method: string, |
| 14 | url: URL, |
| 15 | headers: { [key: string]: string }, |
| 16 | body: BodyInit | null | undefined, |
| 17 | proxy?: string, |
| 18 | shouldBypass?: boolean, |
| 19 | ) { |
| 20 | console.log("=== FETCH REQUEST ==="); |
| 21 | console.log(`Method: ${method}`); |
| 22 | console.log(`URL: ${url.toString()}`); |
| 23 | |
| 24 | // Log headers in curl format |
| 25 | console.log("Headers:"); |
| 26 | for (const [key, value] of Object.entries(headers)) { |
| 27 | console.log(` -H '${key}: ${value}'`); |
| 28 | } |
| 29 | |
| 30 | // Log proxy information |
| 31 | if (proxy && !shouldBypass) { |
| 32 | console.log(`Proxy: ${proxy}`); |
| 33 | } |
| 34 | |
| 35 | // Log body |
| 36 | if (body) { |
| 37 | console.log(`Body: ${body}`); |
| 38 | } |
| 39 | |
| 40 | // Generate equivalent curl command |
| 41 | let curlCommand = `curl -X ${method}`; |
| 42 | for (const [key, value] of Object.entries(headers)) { |
| 43 | curlCommand += ` -H '${key}: ${value}'`; |
| 44 | } |
| 45 | if (body) { |
| 46 | curlCommand += ` -d '${body}'`; |
| 47 | } |
| 48 | if (proxy && !shouldBypass) { |
| 49 | curlCommand += ` --proxy '${proxy}'`; |
| 50 | } |
| 51 | curlCommand += ` '${url.toString()}'`; |
| 52 | console.log(`Equivalent curl: ${curlCommand}`); |
| 53 | console.log("====================="); |
| 54 | } |
| 55 | |
| 56 | async function logResponse(resp: Response) { |
| 57 | console.log("=== FETCH RESPONSE ==="); |
| 58 | console.log(`Status: ${resp.status} ${resp.statusText}`); |
| 59 | console.log("Response Headers:"); |
| 60 | resp.headers.forEach((value, key) => { |
| 61 | console.log(` ${key}: ${value}`); |
| 62 | }); |
| 63 | |
| 64 | // TODO: For streamed responses, this caused the response to be consumed and the connection would just hang open |
| 65 | // Clone response to read body without consuming it |
| 66 | // const respClone = resp.clone(); |
| 67 | // try { |
| 68 | // const responseText = await respClone.text(); |
| 69 | // console.log(`Response Body: ${responseText}`); |
| 70 | // } catch (e) { |
| 71 | // console.log("Could not read response body:", e); |
| 72 | // } |
| 73 | console.log("======================"); |
| 74 | } |
| 75 | |
| 76 | function logError(error: unknown) { |
| 77 | console.log("=== FETCH ERROR ==="); |
| 78 | console.log(`Error: ${error}`); |
| 79 | console.log("==================="); |
| 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 |
| 140 | if (url.hostname === "localhost") { |
| 141 | url.hostname = "127.0.0.1"; |
| 142 | } |
| 143 | |
| 144 | // add extra body properties if provided |
| 145 | let updatedBody: string | undefined = undefined; |
| 146 | try { |
| 147 | if (requestOptions?.extraBodyProperties && typeof init?.body === "string") { |
| 148 | const parsedBody = JSON.parse(init.body); |
| 149 | updatedBody = JSON.stringify({ |
| 150 | ...parsedBody, |
| 151 | ...requestOptions.extraBodyProperties, |
| 152 | }); |
| 153 | } |
| 154 | } catch (e) { |
| 155 | console.log("Unable to parse HTTP request body: ", e); |
| 156 | } |
| 157 | |
| 158 | const finalBody = updatedBody ?? init?.body; |
| 159 | const method = init?.method || "GET"; |
| 160 | |
| 161 | // Verbose logging for debugging - log request details |
| 162 | if (process.env.VERBOSE_FETCH) { |
| 163 | logRequest(method, url, headers, finalBody, proxy, shouldBypass); |
| 164 | } |
| 165 | |
| 166 | // fetch the request with the provided options |
| 167 | try { |
| 168 | const resp = await patchedFetch(url, { |
| 169 | ...init, |
| 170 | body: finalBody, |
| 171 | headers: headers, |
| 172 | agent: agent, |
| 173 | }); |
| 174 | |
| 175 | // Verbose logging for debugging - log response details |
| 176 | if (process.env.VERBOSE_FETCH) { |
| 177 | await logResponse(resp); |
| 178 | } |
| 179 | |
| 180 | if (!resp.ok) { |
| 181 | const requestId = resp.headers.get("x-request-id"); |
| 182 | if (requestId) { |
| 183 | console.log(`Request ID: ${requestId}, Status: ${resp.status}`); |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | return resp; |
| 188 | } catch (error) { |
| 189 | // Verbose logging for errors |
| 190 | if (process.env.VERBOSE_FETCH) { |
| 191 | logError(error); |
| 192 | } |
| 193 | |
| 194 | if (error instanceof Error && error.name === "AbortError") { |
| 195 | // Return a Response object that streamResponse etc can handle |
| 196 | return new Response(null, { |
| 197 | status: 499, // Client Closed Request |
| 198 | statusText: "Client Closed Request", |
| 199 | }); |
| 200 | } |
| 201 | throw error; |
| 202 | } |
| 203 | } |