Open History to see the last commit
1import * as NodeModule from "node:module";
2import * as NodeNet from "node:net";
3
4import type * as Undici from "undici";
5
6// undici stays external to the CLI bundle (scripts/lib/cli-external-packages.ts).
7// Inside a Node single-executable only `require` can load it from disk.
8const requireUndici = NodeModule.createRequire(import.meta.url);
9
10/**
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 * Node's `--use-env-proxy` / `NODE_USE_ENV_PROXY` installs an
19 * `EnvHttpProxyAgent` at startup; that choice is kept so proxies still apply.
20 */
21export function installHttp1FetchDispatcher(): void {
22 const undici = requireUndici("undici") as typeof Undici;
23 // Node's agent comes from its internal undici copy, so `instanceof` against the npm class is false.
24 const usesEnvProxy = undici.getGlobalDispatcher().constructor.name === "EnvHttpProxyAgent";
25 undici.setGlobalDispatcher(
26 usesEnvProxy
27 ? new undici.EnvHttpProxyAgent({
28 allowH2: false,
29 // The connection to an HTTPS proxy is built here, not from `allowH2`. ProxyAgent's
30 // `connect` option is dropped on purpose: its connector has h2 fixed on.
31 clientFactory: (origin) => new undici.Pool(origin, { allowH2: false }),
32 })
33 : new undici.Agent({ allowH2: false }),
34 );
35}
36
37/**
38 * An undici HTTP/2 session that hits its idle timeout can emit `'error'` on a
39 * stream with no listener, which Node turns into an uncaught exception that
40 * exits the server (https://github.com/nodejs/undici/issues/5936).
41 */
42export function keepOutboundFetchOnHttp1(): void {
43 if (builtinFetchUsesHttp2(process.versions.undici)) installHttp1FetchDispatcher();
44}
45
46/**
47 * Node's 250 ms Happy Eyeballs attempt timeout abandons a working-but-slow IPv4
48 * connect when IPv6 is advertised but unroutable, which broke the ACP registry
49 * fetch (#15039). A larger `--network-family-autoselection-attempt-timeout` still wins.
50 */
51export function extendConnectionAttemptTimeout(): void {
52 NodeNet.setDefaultAutoSelectFamilyAttemptTimeout(
53 Math.max(NodeNet.getDefaultAutoSelectFamilyAttemptTimeout(), 1_000),
54 );
55}