index.js 908 B

12345678910111213141516171819202122232425262728293031323334353637
  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. module.exports = (proxy, opts) => {
  8. proxy = proxy || getProxy();
  9. opts = Object.assign({}, opts);
  10. if (typeof proxy === 'object') {
  11. opts = proxy;
  12. proxy = getProxy();
  13. }
  14. if (!proxy) {
  15. return null;
  16. }
  17. proxy = isurl.lenient(proxy) ? urlToOptions(proxy) : url.parse(proxy);
  18. const uriProtocol = opts.protocol === 'https' ? 'https' : 'http';
  19. const proxyProtocol = proxy.protocol === 'https:' ? 'Https' : 'Http';
  20. const port = proxy.port || (proxyProtocol === 'Https' ? 443 : 80);
  21. const method = `${uriProtocol}Over${proxyProtocol}`;
  22. delete opts.protocol;
  23. return tunnelAgent[method](Object.assign({
  24. proxy: {
  25. port,
  26. host: proxy.hostname,
  27. proxyAuth: proxy.auth
  28. }
  29. }, opts));
  30. };