|
| 1 | +import { ProxyAgent } from 'undici' |
| 2 | + |
| 3 | +import { getEnvVar } from './api/metadata' |
| 4 | +import { runtime } from './utils' |
| 5 | + |
| 6 | +function getProxyUrl(): string | undefined { |
| 7 | + return ( |
| 8 | + getEnvVar('https_proxy') || |
| 9 | + getEnvVar('HTTPS_PROXY') || |
| 10 | + getEnvVar('http_proxy') || |
| 11 | + getEnvVar('HTTP_PROXY') || |
| 12 | + getEnvVar('all_proxy') || |
| 13 | + getEnvVar('ALL_PROXY') || |
| 14 | + undefined |
| 15 | + ) |
| 16 | +} |
| 17 | + |
| 18 | +let cachedProxyFetch: typeof fetch | null = null |
| 19 | +let proxyResolved = false |
| 20 | + |
| 21 | +/** |
| 22 | + * Returns a proxy-aware fetch function if HTTPS_PROXY/HTTP_PROXY/ALL_PROXY |
| 23 | + * env vars are set. In browser environments, returns undefined (browsers |
| 24 | + * handle proxies natively via OS settings). |
| 25 | + * |
| 26 | + * Uses undici's ProxyAgent. |
| 27 | + */ |
| 28 | +export function getProxyFetch(): typeof fetch | undefined { |
| 29 | + if (proxyResolved) return cachedProxyFetch ?? undefined |
| 30 | + proxyResolved = true |
| 31 | + |
| 32 | + if (runtime === 'browser') return undefined |
| 33 | + |
| 34 | + const proxyUrl = getProxyUrl() |
| 35 | + if (!proxyUrl) return undefined |
| 36 | + |
| 37 | + const agent = new ProxyAgent(proxyUrl) |
| 38 | + cachedProxyFetch = ((input: any, init?: any) => |
| 39 | + fetch(input, { ...init, dispatcher: agent })) as typeof fetch |
| 40 | + return cachedProxyFetch |
| 41 | +} |
0 commit comments