proxy-bootstrap.cjs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // 让 Vercel CLI(经典 https/node-fetch,不读 HTTP(S)_PROXY 环境变量)走本地代理。
  2. // 用法:PROXY_URL=http://127.0.0.1:10087 NODE_OPTIONS="-r ./proxy-bootstrap.cjs" vercel ...
  3. const http = require('http')
  4. const https = require('https')
  5. const { HttpProxyAgent } = require('http-proxy-agent')
  6. const { HttpsProxyAgent } = require('https-proxy-agent')
  7. const proxyUrl = process.env.PROXY_URL || process.env.HTTPS_PROXY || process.env.https_proxy
  8. if (!proxyUrl) {
  9. console.warn('[proxy-bootstrap] 未设置 PROXY_URL,跳过代理注入')
  10. module.exports = {}
  11. } else {
  12. const httpAgent = new HttpProxyAgent(proxyUrl)
  13. const httpsAgent = new HttpsProxyAgent(proxyUrl)
  14. http.globalAgent = httpAgent
  15. https.globalAgent = httpsAgent
  16. const makePatch = (orig, agent) => function (arg1, arg2, arg3) {
  17. let url, options, cb
  18. if (typeof arg1 === 'string' || arg1 instanceof URL) {
  19. url = arg1
  20. if (typeof arg2 === 'function') { options = {}; cb = arg2 } else { options = arg2 || {}; cb = arg3 }
  21. } else {
  22. options = arg1 || {}; cb = arg2
  23. }
  24. if (!options.agent) options.agent = agent
  25. return url !== undefined ? orig.call(this, url, options, cb) : orig.call(this, options, cb)
  26. }
  27. const origHttpRequest = http.request
  28. const origHttpsRequest = https.request
  29. const origHttpGet = http.get
  30. const origHttpsGet = https.get
  31. http.request = makePatch(origHttpRequest, httpAgent)
  32. https.request = makePatch(origHttpsRequest, httpsAgent)
  33. http.get = makePatch(origHttpGet, httpAgent)
  34. https.get = makePatch(origHttpsGet, httpsAgent)
  35. console.warn('[proxy-bootstrap] 已注入代理:' + proxyUrl)
  36. }