(request: RequestMessage)
| 171 | } |
| 172 | |
| 173 | private async handleRequest(request: RequestMessage) { |
| 174 | if (!this.socket) { |
| 175 | throw new Error("Socket is not connected"); |
| 176 | } |
| 177 | |
| 178 | const url = new URL(request.url); |
| 179 | // Construct the original url to be the same as the request URL but with a different hostname and using http instead of https |
| 180 | const originalUrl = new URL( |
| 181 | `${this.https ? "https" : "http"}://${this.address}${url.pathname}${url.search}${url.hash}` |
| 182 | ); |
| 183 | |
| 184 | let response: Response | null = null; |
| 185 | |
| 186 | this.log("Sending local request", { |
| 187 | originalUrl: originalUrl.href, |
| 188 | requestId: request.id, |
| 189 | headers: request.headers, |
| 190 | }); |
| 191 | |
| 192 | try { |
| 193 | const agent = new https.Agent({ |
| 194 | rejectUnauthorized: false, // Ignore self-signed certificates |
| 195 | }); |
| 196 | response = await fetch(originalUrl.href, { |
| 197 | method: request.method, |
| 198 | headers: stripHeaders(request.headers), |
| 199 | body: request.body, |
| 200 | ...(this.https && { agent }), |
| 201 | }); |
| 202 | } catch (error) { |
| 203 | if (error instanceof Error) { |
| 204 | this.log("Error sending local request", { |
| 205 | error: error.message, |
| 206 | name: error.name, |
| 207 | stack: error.stack, |
| 208 | requestId: request.id, |
| 209 | cause: "cause" in error ? error.cause : undefined, |
| 210 | }); |
| 211 | } else { |
| 212 | this.log("Error sending local request", { error, requestId: request.id }); |
| 213 | } |
| 214 | |
| 215 | // Return a 502 response |
| 216 | response = new Response( |
| 217 | JSON.stringify({ |
| 218 | message: `Could not connect to ${originalUrl.href}. Make sure you are running your local app server`, |
| 219 | }), |
| 220 | { status: 502, headers: { "Content-Type": "application/json" } } |
| 221 | ); |
| 222 | } |
| 223 | |
| 224 | try { |
| 225 | await this.sendResponse(request.id, response, this.socket); |
| 226 | } catch (error) { |
| 227 | console.error(error); |
| 228 | } |
| 229 | } |
| 230 |
no test coverage detected