proxy.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * Pure-JS port of `src/cli/proxy.ts` — installs a global undici
  3. * ProxyAgent so Node native `fetch()` honors `PILOTDECK_PROXY` /
  4. * `HTTPS_PROXY` / `HTTP_PROXY`. Node's native fetch does NOT respect
  5. * those env vars by default; this closes the gap.
  6. *
  7. * Living in `ui/server/utils/` lets the express bridge run from
  8. * source without depending on `dist/src/cli/proxy.js`.
  9. */
  10. import { ProxyAgent, setGlobalDispatcher } from 'undici';
  11. function getProxyUrl(env = process.env) {
  12. return (
  13. env.PILOTDECK_PROXY ||
  14. env.https_proxy ||
  15. env.HTTPS_PROXY ||
  16. env.http_proxy ||
  17. env.HTTP_PROXY
  18. );
  19. }
  20. let installed = false;
  21. /**
  22. * Install a global undici ProxyAgent. Safe to call multiple times —
  23. * only the first effective call wins. Returns the proxy URL that was
  24. * activated, or undefined if no proxy is configured.
  25. *
  26. * @param {string} [explicitUrl] Override the env-driven proxy URL.
  27. * @returns {string | undefined} The activated proxy URL.
  28. */
  29. export function installGlobalProxy(explicitUrl) {
  30. if (installed) return undefined;
  31. const proxyUrl = explicitUrl ?? getProxyUrl();
  32. if (!proxyUrl) return undefined;
  33. try {
  34. const agent = new ProxyAgent(proxyUrl);
  35. setGlobalDispatcher(agent);
  36. installed = true;
  37. console.log(`[proxy] Global fetch proxy → ${proxyUrl}`);
  38. return proxyUrl;
  39. } catch (error) {
  40. console.warn(
  41. `[proxy] Failed to install global proxy (${proxyUrl}):`,
  42. error instanceof Error ? error.message : String(error),
  43. );
  44. return undefined;
  45. }
  46. }