| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | const url = require('url'); |
| 3 | const getProxy = require('get-proxy'); |
| 4 | const isurl = require('isurl'); |
| 5 | const tunnelAgent = require('tunnel-agent'); |
| 6 | const urlToOptions = require('url-to-options'); |
| 7 | |
| 8 | module.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 | }; |