Open History to see the last commit
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 * True when the runtime's built-in `fetch` negotiates HTTP/2 by default.
11 * Node 26 bundles undici 8, which offers h2 over ALPN to every HTTPS origin.
12 * Node 22/24 (and Electron) bundle undici 6/7, whose fetch stays on HTTP/1.1.
13 */
14export const builtinFetchUsesHttp2 = (bundledUndiciVersion: string | undefined) =>
15 Number.parseInt(bundledUndiciVersion ?? "", 10) >= 8;
16
17/**
18 * Replaces the process-wide fetch dispatcher with one that only speaks HTTP/1.1.
19 *
20 * Node's built-in fetch reads its dispatcher from the
21 * `Symbol.for("undici.globalDispatcher.1"/".2")` globals, and the npm package's
22 * `setGlobalDispatcher` writes both. This covers requests using the default
23 * fetch dispatcher, including Effect's `FetchHttpClient`; `node:http` callers
24 * (e.g. `cli/sshHelper.ts`) are unaffected and already speak HTTP/1.1.
25 *
26 * Node's `--use-env-proxy` / `NODE_USE_ENV_PROXY` installs an
27 * `EnvHttpProxyAgent` at startup; that choice is kept so proxies still apply.
28 */
29export function installHttp1FetchDispatcher(): void {
30 const undici = requireUndici("undici") as typeof Undici;
31 // Node's agent comes from its internal undici copy, so `instanceof` against the npm class is false.
32 const usesEnvProxy = undici.getGlobalDispatcher().constructor.name === "EnvHttpProxyAgent";
33 undici.setGlobalDispatcher(
34 usesEnvProxy
35 ? new undici.EnvHttpProxyAgent({
36 allowH2: false,
37 // The connection to an HTTPS proxy is built here, not from `allowH2`. ProxyAgent's
38 // `connect` option is dropped on purpose: its connector has h2 fixed on.
39 clientFactory: (origin) => new undici.Pool(origin, { allowH2: false }),
40 })
41 : new undici.Agent({ allowH2: false }),
42 );
43}
44
45/**
46 * Keeps outbound fetch on HTTP/1.1. An undici HTTP/2 session that hits its
47 * idle timeout can emit `'error'` on a stream with no listener, which Node
48 * turns into an uncaught exception that exits the server
49 * (https://github.com/nodejs/undici/issues/5936). Runtimes whose fetch never
50 * negotiates h2 are left untouched.
51 */
52export function keepOutboundFetchOnHttp1(): void {
53 if (builtinFetchUsesHttp2(process.versions.undici)) installHttp1FetchDispatcher();
54}