| 51 | * @returns {Fetch} fn |
| 52 | */ |
| 53 | const proxyFetch = (request, proxy) => (url, options, callback) => { |
| 54 | /** @type {EventEmitter<EventsMap>} */ |
| 55 | const eventEmitter = new EventEmitter(); |
| 56 | |
| 57 | /** |
| 58 | * Processes the provided socket. |
| 59 | * @param {Socket=} socket socket |
| 60 | * @returns {void} |
| 61 | */ |
| 62 | const doRequest = (socket) => { |
| 63 | request |
| 64 | .get(url, { ...options, ...(socket && { socket }) }, callback) |
| 65 | .on("error", eventEmitter.emit.bind(eventEmitter, "error")); |
| 66 | }; |
| 67 | |
| 68 | if (proxy) { |
| 69 | const { hostname: host, port } = new URL(proxy); |
| 70 | |
| 71 | getHttp() |
| 72 | .request({ |
| 73 | host, // IP address of proxy server |
| 74 | port, // port of proxy server |
| 75 | method: "CONNECT", |
| 76 | path: url.host |
| 77 | }) |
| 78 | .on("connect", (res, socket) => { |
| 79 | if (res.statusCode === 200) { |
| 80 | // connected to proxy server |
| 81 | doRequest(socket); |
| 82 | } else { |
| 83 | eventEmitter.emit( |
| 84 | "error", |
| 85 | new Error( |
| 86 | `Failed to connect to proxy server "${proxy}": ${res.statusCode} ${res.statusMessage}` |
| 87 | ) |
| 88 | ); |
| 89 | } |
| 90 | }) |
| 91 | .on("error", (err) => { |
| 92 | eventEmitter.emit( |
| 93 | "error", |
| 94 | new Error( |
| 95 | `Failed to connect to proxy server "${proxy}": ${err.message}` |
| 96 | ) |
| 97 | ); |
| 98 | }) |
| 99 | .end(); |
| 100 | } else { |
| 101 | doRequest(); |
| 102 | } |
| 103 | |
| 104 | return eventEmitter; |
| 105 | }; |
| 106 | |
| 107 | /** @typedef {() => void} InProgressWriteItem */ |
| 108 | /** @type {InProgressWriteItem[] | undefined} */ |