* One request against a live server. * * `http.request` rather than `fetch` so `Host` is ours to set — undici treats * it as a forbidden header, and the `Host` allowlist is half of what is being * tested here.
(port: number, requestPath: string, opts: CallOptions = {})
| 68 | * tested here. |
| 69 | */ |
| 70 | function callOn(port: number, requestPath: string, opts: CallOptions = {}): Promise<Res> { |
| 71 | const method = opts.method ?? 'GET'; |
| 72 | const isWrite = method === 'POST' || method === 'DELETE'; |
| 73 | const payload = opts.body === undefined ? null : Buffer.from(JSON.stringify(opts.body), 'utf-8'); |
| 74 | const headers: Record<string, string> = { Host: `127.0.0.1:${port}` }; |
| 75 | if (isWrite && (opts.marker ?? true)) headers['X-CodeGraph-UI'] = '1'; |
| 76 | if (opts.origin) headers['Origin'] = opts.origin; |
| 77 | if (payload) { |
| 78 | const type = opts.contentType === undefined ? 'application/json' : opts.contentType; |
| 79 | if (type !== null) headers['Content-Type'] = type; |
| 80 | headers['Content-Length'] = String(payload.length); |
| 81 | } |
| 82 | |
| 83 | return new Promise((resolve, reject) => { |
| 84 | const req = http.request( |
| 85 | { host: '127.0.0.1', port, path: requestPath, method, headers, setHost: false }, |
| 86 | (res) => { |
| 87 | const chunks: Buffer[] = []; |
| 88 | res.on('data', (c: Buffer) => chunks.push(c)); |
| 89 | res.on('end', () => { |
| 90 | const text = Buffer.concat(chunks).toString('utf-8'); |
| 91 | let parsed: unknown = text; |
| 92 | try { |
| 93 | parsed = JSON.parse(text); |
| 94 | } catch { |
| 95 | /* a text/plain refusal is a legitimate answer on the static side */ |
| 96 | } |
| 97 | resolve({ status: res.statusCode ?? 0, headers: res.headers, body: parsed }); |
| 98 | }); |
| 99 | } |
| 100 | ); |
| 101 | req.on('error', reject); |
| 102 | if (payload) req.write(payload); |
| 103 | req.end(); |
| 104 | }); |
| 105 | } |
| 106 | |
| 107 | function call(requestPath: string, opts: CallOptions = {}): Promise<Res> { |
| 108 | return callOn(server.port, requestPath, opts); |