UNPKG

@applitools/req

Version:

Applitools fetch-based request library

67 lines (66 loc) 3.41 kB
import { parse as urlToHttpOptions } from 'url'; // should be replaced with `urlToHttpOptions` after supporting node >=16 import { Agent as HttpAgent } from 'http'; import { Agent as HttpsAgent } from 'https'; import { lookupWithCache } from './dns-cache.js'; import createHttpProxyAgent from 'http-proxy-agent'; import createHttpsProxyAgent from 'https-proxy-agent'; import * as utils from '@applitools/utils'; const cachify = utils.general.cachify; const disableHttpAgentReuse = process.env.APPLITOOLS_DISABLE_AGENT_CACHIFY; const cachifiedCreateHttpsProxyAgent = cachify((options) => { const agent = createHttpsProxyAgent(options); agent.callback = utils.general.wrap(agent.callback.bind(agent), (fn, request, options, ...rest) => { return fn(request, { ...options, rejectUnauthorized: false }, ...rest); }); return agent; }); const cachifiedCreateHttpProxyAgent = cachify(createHttpProxyAgent); const cachifiedNewHttpsAgent = cachify((options) => new HttpsAgent(options)); const cachifiedNewHttpAgent = cachify((options) => new HttpAgent(options)); export function makeAgent(options) { var _a; (_a = options.keepAliveOptions) !== null && _a !== void 0 ? _a : (options.keepAliveOptions = { keepAlive: true, }); const { proxy, useDnsCache, keepAliveOptions } = options; return function agent(url) { var _a, _b; const proxyOptions = utils.types.isFunction(proxy) ? proxy(url) : proxy; const lookup = useDnsCache ? lookupWithCache : undefined; if (proxyOptions) { const proxyUrl = new URL(proxyOptions.url); proxyUrl.username = (_a = proxyOptions.username) !== null && _a !== void 0 ? _a : proxyUrl.username; proxyUrl.password = (_b = proxyOptions.password) !== null && _b !== void 0 ? _b : proxyUrl.password; const options = { ...urlToHttpOptions(proxyUrl.href), rejectUnauthorized: false, lookup }; if (url.protocol === 'https:') { if (disableHttpAgentReuse) { const agent = createHttpsProxyAgent(options); agent.callback = utils.general.wrap(agent.callback.bind(agent), (fn, request, options, ...rest) => { return fn(request, { ...options, rejectUnauthorized: false }, ...rest); }); return agent; } return cachifiedCreateHttpsProxyAgent(options); } else if (url.protocol === 'http:') { if (disableHttpAgentReuse) { return createHttpProxyAgent(options); } return cachifiedCreateHttpProxyAgent(options); } } else if (url.protocol === 'https:') { if (disableHttpAgentReuse) { return new HttpsAgent({ rejectUnauthorized: false, lookup, ...keepAliveOptions }); } return cachifiedNewHttpsAgent({ rejectUnauthorized: false, lookup, ...keepAliveOptions }); } else if (url.protocol === 'http:') { if (disableHttpAgentReuse) { // @ts-expect-error due to a wrong type definition for node 12, already fixed in newer versions return new HttpAgent({ lookup, ...keepAliveOptions }); } return cachifiedNewHttpAgent({ lookup, ...keepAliveOptions }); } }; }