blob: 69e7f554e60c9752cb3e34cf3d2c52e4a1edf939 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2const url = require('url');
3const getProxy = require('get-proxy');
4const isurl = require('isurl');
5const tunnelAgent = require('tunnel-agent');
6const urlToOptions = require('url-to-options');
7
8module.exports = (proxy, opts) => {
9 proxy = proxy || getProxy();
10 opts = Object.assign({}, opts);
11
12 if (typeof proxy === 'object') {
13 opts = proxy;
14 proxy = getProxy();
15 }
16
17 if (!proxy) {
18 return null;
19 }
20
21 proxy = isurl.lenient(proxy) ? urlToOptions(proxy) : url.parse(proxy);
22
23 const uriProtocol = opts.protocol === 'https' ? 'https' : 'http';
24 const proxyProtocol = proxy.protocol === 'https:' ? 'Https' : 'Http';
25 const port = proxy.port || (proxyProtocol === 'Https' ? 443 : 80);
26 const method = `${uriProtocol}Over${proxyProtocol}`;
27
28 delete opts.protocol;
29
30 return tunnelAgent[method](Object.assign({
31 proxy: {
32 port,
33 host: proxy.hostname,
34 proxyAuth: proxy.auth
35 }
36 }, opts));
37};