global.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. 'use strict'
  2. // We include a version number for the Dispatcher API. In case of breaking changes,
  3. // this version number must be increased to avoid conflicts.
  4. const globalDispatcher = Symbol.for('undici.globalDispatcher.2')
  5. const legacyGlobalDispatcher = Symbol.for('undici.globalDispatcher.1')
  6. const { InvalidArgumentError } = require('./core/errors')
  7. const Agent = require('./dispatcher/agent')
  8. if (getGlobalDispatcher() === undefined) {
  9. setGlobalDispatcher(new Agent())
  10. }
  11. function setGlobalDispatcher (agent) {
  12. if (!agent || typeof agent.dispatch !== 'function') {
  13. throw new InvalidArgumentError('Argument agent must implement Agent')
  14. }
  15. Object.defineProperty(globalThis, globalDispatcher, {
  16. value: agent,
  17. writable: true,
  18. enumerable: false,
  19. configurable: false
  20. })
  21. Object.defineProperty(globalThis, legacyGlobalDispatcher, {
  22. value: agent,
  23. writable: true,
  24. enumerable: false,
  25. configurable: false
  26. })
  27. }
  28. function getGlobalDispatcher () {
  29. return globalThis[legacyGlobalDispatcher]
  30. }
  31. // These are the globals that can be installed by undici.install().
  32. // Not exported by index.js to avoid use outside of this module.
  33. const installedExports = /** @type {const} */ (
  34. [
  35. 'fetch',
  36. 'Headers',
  37. 'Response',
  38. 'Request',
  39. 'FormData',
  40. 'WebSocket',
  41. 'CloseEvent',
  42. 'ErrorEvent',
  43. 'MessageEvent',
  44. 'EventSource'
  45. ]
  46. )
  47. module.exports = {
  48. setGlobalDispatcher,
  49. getGlobalDispatcher,
  50. installedExports
  51. }