Skip to content

Commit

Permalink
build(proxy): reorder to fix cjs build
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Dec 24, 2023
1 parent fa902a2 commit 0063bc1
Showing 1 changed file with 43 additions and 39 deletions.
82 changes: 43 additions & 39 deletions src/proxy.ts
Expand Up @@ -8,45 +8,6 @@ import { HttpsProxyAgent } from "https-proxy-agent";
import type { ProxyOptions } from "../proxy";
import { fetch as _fetch } from "node-fetch-native";

export function createProxy(opts: ProxyOptions = {}) {
const uri =
opts.url ||
process.env.https_proxy ||
process.env.http_proxy ||
process.env.HTTPS_PROXY ||
process.env.HTTP_PROXY;

if (!uri) {
return {
agent: undefined,
dispatcher: undefined,
};
}

const _noProxy = opts.noProxy || process.env.no_proxy || process.env.NO_PROXY;
const noProxy = typeof _noProxy === "string" ? _noProxy.split(",") : _noProxy;

const nodeAgent = new NodeProxyAgent({ uri, noProxy });

// https://undici.nodejs.org/#/docs/api/ProxyAgent
const undiciAgent = new UndiciProxyAgent({
uri,
noProxy,
});

return {
agent: nodeAgent,
dispatcher: undiciAgent,
};
}

export function createFetch(proxyOptions: ProxyOptions = {}) {
const proxy = createProxy(proxyOptions);
return (url, fetchOptions) => _fetch(url, { ...proxy, ...fetchOptions });
}

export const fetch = createFetch({});

// ----------------------------------------------
// Utils
// ----------------------------------------------
Expand Down Expand Up @@ -170,3 +131,46 @@ class NodeProxyAgent extends Agent {
super.destroy();
}
}

// ----------------------------------------------
// Main exports
// ----------------------------------------------

export function createProxy(opts: ProxyOptions = {}) {
const uri =
opts.url ||
process.env.https_proxy ||
process.env.http_proxy ||
process.env.HTTPS_PROXY ||
process.env.HTTP_PROXY;

if (!uri) {
return {
agent: undefined,
dispatcher: undefined,
};
}

const _noProxy = opts.noProxy || process.env.no_proxy || process.env.NO_PROXY;
const noProxy = typeof _noProxy === "string" ? _noProxy.split(",") : _noProxy;

const nodeAgent = new NodeProxyAgent({ uri, noProxy });

// https://undici.nodejs.org/#/docs/api/ProxyAgent
const undiciAgent = new UndiciProxyAgent({
uri,
noProxy,
});

return {
agent: nodeAgent,
dispatcher: undiciAgent,
};
}

export function createFetch(proxyOptions: ProxyOptions = {}) {
const proxy = createProxy(proxyOptions);
return (url, fetchOptions) => _fetch(url, { ...proxy, ...fetchOptions });
}

export const fetch = createFetch({});

0 comments on commit 0063bc1

Please sign in to comment.