index.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. 'use strict'
  2. const Client = require('./lib/dispatcher/client')
  3. const Dispatcher = require('./lib/dispatcher/dispatcher')
  4. const Pool = require('./lib/dispatcher/pool')
  5. const BalancedPool = require('./lib/dispatcher/balanced-pool')
  6. const RoundRobinPool = require('./lib/dispatcher/round-robin-pool')
  7. const Agent = require('./lib/dispatcher/agent')
  8. const ProxyAgent = require('./lib/dispatcher/proxy-agent')
  9. const Socks5ProxyAgent = require('./lib/dispatcher/socks5-proxy-agent')
  10. const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent')
  11. const RetryAgent = require('./lib/dispatcher/retry-agent')
  12. const H2CClient = require('./lib/dispatcher/h2c-client')
  13. const errors = require('./lib/core/errors')
  14. const util = require('./lib/core/util')
  15. const { InvalidArgumentError } = errors
  16. const api = require('./lib/api')
  17. const buildConnector = require('./lib/core/connect')
  18. const MockClient = require('./lib/mock/mock-client')
  19. const { MockCallHistory, MockCallHistoryLog } = require('./lib/mock/mock-call-history')
  20. const MockAgent = require('./lib/mock/mock-agent')
  21. const MockPool = require('./lib/mock/mock-pool')
  22. const SnapshotAgent = require('./lib/mock/snapshot-agent')
  23. const mockErrors = require('./lib/mock/mock-errors')
  24. const RetryHandler = require('./lib/handler/retry-handler')
  25. const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global')
  26. const DecoratorHandler = require('./lib/handler/decorator-handler')
  27. const RedirectHandler = require('./lib/handler/redirect-handler')
  28. Object.assign(Dispatcher.prototype, api)
  29. module.exports.Dispatcher = Dispatcher
  30. module.exports.Client = Client
  31. module.exports.Pool = Pool
  32. module.exports.BalancedPool = BalancedPool
  33. module.exports.RoundRobinPool = RoundRobinPool
  34. module.exports.Agent = Agent
  35. module.exports.ProxyAgent = ProxyAgent
  36. module.exports.Socks5ProxyAgent = Socks5ProxyAgent
  37. module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent
  38. module.exports.RetryAgent = RetryAgent
  39. module.exports.H2CClient = H2CClient
  40. module.exports.RetryHandler = RetryHandler
  41. module.exports.DecoratorHandler = DecoratorHandler
  42. module.exports.RedirectHandler = RedirectHandler
  43. module.exports.interceptors = {
  44. redirect: require('./lib/interceptor/redirect'),
  45. responseError: require('./lib/interceptor/response-error'),
  46. retry: require('./lib/interceptor/retry'),
  47. dump: require('./lib/interceptor/dump'),
  48. dns: require('./lib/interceptor/dns'),
  49. cache: require('./lib/interceptor/cache'),
  50. decompress: require('./lib/interceptor/decompress'),
  51. deduplicate: require('./lib/interceptor/deduplicate')
  52. }
  53. module.exports.cacheStores = {
  54. MemoryCacheStore: require('./lib/cache/memory-cache-store')
  55. }
  56. const SqliteCacheStore = require('./lib/cache/sqlite-cache-store')
  57. module.exports.cacheStores.SqliteCacheStore = SqliteCacheStore
  58. module.exports.buildConnector = buildConnector
  59. module.exports.errors = errors
  60. module.exports.util = {
  61. parseHeaders: util.parseHeaders,
  62. headerNameToString: util.headerNameToString
  63. }
  64. function makeDispatcher (fn) {
  65. return (url, opts, handler) => {
  66. if (typeof opts === 'function') {
  67. handler = opts
  68. opts = null
  69. }
  70. if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
  71. throw new InvalidArgumentError('invalid url')
  72. }
  73. if (opts != null && typeof opts !== 'object') {
  74. throw new InvalidArgumentError('invalid opts')
  75. }
  76. if (opts && opts.path != null) {
  77. if (typeof opts.path !== 'string') {
  78. throw new InvalidArgumentError('invalid opts.path')
  79. }
  80. let path = opts.path
  81. if (!opts.path.startsWith('/')) {
  82. path = `/${path}`
  83. }
  84. url = new URL(util.parseOrigin(url).origin + path)
  85. } else {
  86. if (!opts) {
  87. opts = typeof url === 'object' ? url : {}
  88. }
  89. url = util.parseURL(url)
  90. }
  91. const { agent, dispatcher = getGlobalDispatcher() } = opts
  92. if (agent) {
  93. throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
  94. }
  95. return fn.call(dispatcher, {
  96. ...opts,
  97. origin: url.origin,
  98. path: url.search ? `${url.pathname}${url.search}` : url.pathname,
  99. method: opts.method || (opts.body ? 'PUT' : 'GET')
  100. }, handler)
  101. }
  102. }
  103. module.exports.setGlobalDispatcher = setGlobalDispatcher
  104. module.exports.getGlobalDispatcher = getGlobalDispatcher
  105. const fetchImpl = require('./lib/web/fetch').fetch
  106. // Capture __filename at module load time for stack trace augmentation.
  107. // This may be undefined when bundled in environments like Node.js internals.
  108. const currentFilename = typeof __filename !== 'undefined' ? __filename : undefined
  109. function appendFetchStackTrace (err, filename) {
  110. if (!err || typeof err !== 'object') {
  111. return
  112. }
  113. const stack = typeof err.stack === 'string' ? err.stack : ''
  114. const normalizedFilename = filename.replace(/\\/g, '/')
  115. if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) {
  116. return
  117. }
  118. const capture = {}
  119. Error.captureStackTrace(capture, appendFetchStackTrace)
  120. if (!capture.stack) {
  121. return
  122. }
  123. const captureLines = capture.stack.split('\n').slice(1).join('\n')
  124. err.stack = stack ? `${stack}\n${captureLines}` : capture.stack
  125. }
  126. module.exports.fetch = function fetch (init, options = undefined) {
  127. return fetchImpl(init, options).catch(err => {
  128. if (currentFilename) {
  129. appendFetchStackTrace(err, currentFilename)
  130. } else if (err && typeof err === 'object') {
  131. Error.captureStackTrace(err, module.exports.fetch)
  132. }
  133. throw err
  134. })
  135. }
  136. module.exports.Headers = require('./lib/web/fetch/headers').Headers
  137. module.exports.Response = require('./lib/web/fetch/response').Response
  138. module.exports.Request = require('./lib/web/fetch/request').Request
  139. module.exports.FormData = require('./lib/web/fetch/formdata').FormData
  140. const { setGlobalOrigin, getGlobalOrigin } = require('./lib/web/fetch/global')
  141. module.exports.setGlobalOrigin = setGlobalOrigin
  142. module.exports.getGlobalOrigin = getGlobalOrigin
  143. const { CacheStorage } = require('./lib/web/cache/cachestorage')
  144. const { kConstruct } = require('./lib/core/symbols')
  145. module.exports.caches = new CacheStorage(kConstruct)
  146. const { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = require('./lib/web/cookies')
  147. module.exports.deleteCookie = deleteCookie
  148. module.exports.getCookies = getCookies
  149. module.exports.getSetCookies = getSetCookies
  150. module.exports.setCookie = setCookie
  151. module.exports.parseCookie = parseCookie
  152. const { parseMIMEType, serializeAMimeType } = require('./lib/web/fetch/data-url')
  153. module.exports.parseMIMEType = parseMIMEType
  154. module.exports.serializeAMimeType = serializeAMimeType
  155. const { CloseEvent, ErrorEvent, MessageEvent } = require('./lib/web/websocket/events')
  156. const { WebSocket, ping } = require('./lib/web/websocket/websocket')
  157. module.exports.WebSocket = WebSocket
  158. module.exports.CloseEvent = CloseEvent
  159. module.exports.ErrorEvent = ErrorEvent
  160. module.exports.MessageEvent = MessageEvent
  161. module.exports.ping = ping
  162. module.exports.WebSocketStream = require('./lib/web/websocket/stream/websocketstream').WebSocketStream
  163. module.exports.WebSocketError = require('./lib/web/websocket/stream/websocketerror').WebSocketError
  164. module.exports.request = makeDispatcher(api.request)
  165. module.exports.stream = makeDispatcher(api.stream)
  166. module.exports.pipeline = makeDispatcher(api.pipeline)
  167. module.exports.connect = makeDispatcher(api.connect)
  168. module.exports.upgrade = makeDispatcher(api.upgrade)
  169. module.exports.MockClient = MockClient
  170. module.exports.MockCallHistory = MockCallHistory
  171. module.exports.MockCallHistoryLog = MockCallHistoryLog
  172. module.exports.MockPool = MockPool
  173. module.exports.MockAgent = MockAgent
  174. module.exports.SnapshotAgent = SnapshotAgent
  175. module.exports.mockErrors = mockErrors
  176. const { EventSource } = require('./lib/web/eventsource/eventsource')
  177. module.exports.EventSource = EventSource
  178. function install () {
  179. globalThis.fetch = module.exports.fetch
  180. globalThis.Headers = module.exports.Headers
  181. globalThis.Response = module.exports.Response
  182. globalThis.Request = module.exports.Request
  183. globalThis.FormData = module.exports.FormData
  184. globalThis.WebSocket = module.exports.WebSocket
  185. globalThis.CloseEvent = module.exports.CloseEvent
  186. globalThis.ErrorEvent = module.exports.ErrorEvent
  187. globalThis.MessageEvent = module.exports.MessageEvent
  188. globalThis.EventSource = module.exports.EventSource
  189. }
  190. module.exports.install = install