Elffuss BraidHub

kikocis/continue public

1cfd9a0cd983 · 5.2 KiBRawPermalink
1import { RequestOptions } from "@continuedev/config-types";
2import * as followRedirects from "follow-redirects";
3import { HttpProxyAgent } from "http-proxy-agent";
4import { HttpsProxyAgent } from "https-proxy-agent";
5import fetch, { BodyInit, RequestInit, Response } from "node-fetch";
6import { getAgentOptions } from "./getAgentOptions.js";
7import { getProxyFromEnv, shouldBypassProxy } from "./util.js";
8
9const { http, https } = (followRedirects as any).default;
10
11function logRequest(
12 method: string,
13 url: URL,
14 headers: { [key: string]: string },
15 body: BodyInit | null | undefined,
16 proxy?: string,
17 shouldBypass?: boolean,
18) {
19 console.log("=== FETCH REQUEST ===");
20 console.log(`Method: ${method}`);
21 console.log(`URL: ${url.toString()}`);
22
23 // Log headers in curl format
24 console.log("Headers:");
25 for (const [key, value] of Object.entries(headers)) {
26 console.log(` -H '${key}: ${value}'`);
27 }
28
29 // Log proxy information
30 if (proxy && !shouldBypass) {
31 console.log(`Proxy: ${proxy}`);
32 }
33
34 // Log body
35 if (body) {
36 console.log(`Body: ${body}`);
37 }
38
39 // Generate equivalent curl command
40 let curlCommand = `curl -X ${method}`;
41 for (const [key, value] of Object.entries(headers)) {
42 curlCommand += ` -H '${key}: ${value}'`;
43 }
44 if (body) {
45 curlCommand += ` -d '${body}'`;
46 }
47 if (proxy && !shouldBypass) {
48 curlCommand += ` --proxy '${proxy}'`;
49 }
50 curlCommand += ` '${url.toString()}'`;
51 console.log(`Equivalent curl: ${curlCommand}`);
52 console.log("=====================");
53}
54
55async function logResponse(resp: Response) {
56 console.log("=== FETCH RESPONSE ===");
57 console.log(`Status: ${resp.status} ${resp.statusText}`);
58 console.log("Response Headers:");
59 resp.headers.forEach((value, key) => {
60 console.log(` ${key}: ${value}`);
61 });
62
63 // TODO: For streamed responses, this caused the response to be consumed and the connection would just hang open
64 // Clone response to read body without consuming it
65 // const respClone = resp.clone();
66 // try {
67 // const responseText = await respClone.text();
68 // console.log(`Response Body: ${responseText}`);
69 // } catch (e) {
70 // console.log("Could not read response body:", e);
71 // }
72 console.log("======================");
73}
74
75function logError(error: unknown) {
76 console.log("=== FETCH ERROR ===");
77 console.log(`Error: ${error}`);
78 console.log("===================");
79}
80
81export async function fetchwithRequestOptions(
82 url_: URL | string,
83 init?: RequestInit,
84 requestOptions?: RequestOptions,
85): Promise<Response> {
86 const url = typeof url_ === "string" ? new URL(url_) : url_;
87 if (url.host === "localhost") {
88 url.host = "127.0.0.1";
89 }
90
91 const agentOptions = getAgentOptions(requestOptions);
92
93 // Get proxy from options or environment variables
94 let proxy = requestOptions?.proxy;
95 if (!proxy) {
96 proxy = getProxyFromEnv(url.protocol);
97 }
98
99 // Check if should bypass proxy based on requestOptions or NO_PROXY env var
100 const shouldBypass =
101 requestOptions?.noProxy?.includes(url.hostname) ||
102 shouldBypassProxy(url.hostname);
103
104 // Create agent
105 const protocol = url.protocol === "https:" ? https : http;
106 const agent =
107 proxy && !shouldBypass
108 ? protocol === https
109 ? new HttpsProxyAgent(proxy, agentOptions)
110 : new HttpProxyAgent(proxy, agentOptions)
111 : new protocol.Agent(agentOptions);
112
113 let headers: { [key: string]: string } = {};
114 for (const [key, value] of Object.entries(init?.headers || {})) {
115 headers[key] = value as string;
116 }
117 headers = {
118 ...headers,
119 ...requestOptions?.headers,
120 };
121
122 // Replace localhost with 127.0.0.1
123 if (url.hostname === "localhost") {
124 url.hostname = "127.0.0.1";
125 }
126
127 // add extra body properties if provided
128 let updatedBody: string | undefined = undefined;
129 try {
130 if (requestOptions?.extraBodyProperties && typeof init?.body === "string") {
131 const parsedBody = JSON.parse(init.body);
132 updatedBody = JSON.stringify({
133 ...parsedBody,
134 ...requestOptions.extraBodyProperties,
135 });
136 }
137 } catch (e) {
138 console.log("Unable to parse HTTP request body: ", e);
139 }
140
141 const finalBody = updatedBody ?? init?.body;
142 const method = init?.method || "GET";
143
144 // Verbose logging for debugging - log request details
145 if (process.env.VERBOSE_FETCH) {
146 logRequest(method, url, headers, finalBody, proxy, shouldBypass);
147 }
148
149 // fetch the request with the provided options
150 try {
151 const resp = await fetch(url, {
152 ...init,
153 body: finalBody,
154 headers: headers,
155 agent: agent,
156 });
157
158 // Verbose logging for debugging - log response details
159 if (process.env.VERBOSE_FETCH) {
160 await logResponse(resp);
161 }
162
163 if (!resp.ok) {
164 const requestId = resp.headers.get("x-request-id");
165 if (requestId) {
166 console.log(`Request ID: ${requestId}, Status: ${resp.status}`);
167 }
168 }
169
170 return resp;
171 } catch (error) {
172 // Verbose logging for errors
173 if (process.env.VERBOSE_FETCH) {
174 logError(error);
175 }
176
177 if (error instanceof Error && error.name === "AbortError") {
178 // Return a Response object that streamResponse etc can handle
179 return new Response(null, {
180 status: 499, // Client Closed Request
181 statusText: "Client Closed Request",
182 });
183 }
184 throw error;
185 }
186}