Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

outboundHttp.ts

43 lines1.8 KB

1import * as NodeModule from "node:module";
2​
3import type * as Undici from "undici";
4​
5// undici stays external to the CLI bundle (scripts/lib/cli-external-packages.ts).
6// Inside a Node single-executable only `require` can load it from disk.
7const requireUndici = NodeModule.createRequire(import.meta.url);
8​
9/**
10 * Node 26 bundles undici 8, which offers h2 over ALPN to every HTTPS origin.
11 * Node 22/24 (and Electron) bundle undici 6/7, whose fetch stays on HTTP/1.1.
12 */
13export const builtinFetchUsesHttp2 = (bundledUndiciVersion: string | undefined) =>
14 Number.parseInt(bundledUndiciVersion ?? "", 10) >= 8;
15​
16/**
17 * Node's `--use-env-proxy` / `NODE_USE_ENV_PROXY` installs an
18 * `EnvHttpProxyAgent` at startup; that choice is kept so proxies still apply.
19 */
20export function installHttp1FetchDispatcher(): void {
21 const undici = requireUndici("undici") as typeof Undici;
22 // Node's agent comes from its internal undici copy, so `instanceof` against the npm class is false.
23 const usesEnvProxy = undici.getGlobalDispatcher().constructor.name === "EnvHttpProxyAgent";
24 undici.setGlobalDispatcher(
25 usesEnvProxy
26 ? new undici.EnvHttpProxyAgent({
27 allowH2: false,
28 // The connection to an HTTPS proxy is built here, not from `allowH2`. ProxyAgent's
29 // `connect` option is dropped on purpose: its connector has h2 fixed on.
30 clientFactory: (origin) => new undici.Pool(origin, { allowH2: false }),
31 })
32 : new undici.Agent({ allowH2: false }),
33 );
35​
36/**
37 * An undici HTTP/2 session that hits its idle timeout can emit `'error'` on a
38 * stream with no listener, which Node turns into an uncaught exception that
39 * exits the server (https://github.com/nodejs/undici/issues/5936).
40 */
41export function keepOutboundFetchOnHttp1(): void {
42 if (builtinFetchUsesHttp2(process.versions.undici)) installHttp1FetchDispatcher();