index.js 8.1 KB

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