global.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict'
  2. // In case of breaking changes, increase the version
  3. // number to avoid conflicts.
  4. const globalOrigin = Symbol.for('undici.globalOrigin.1')
  5. function getGlobalOrigin () {
  6. return globalThis[globalOrigin]
  7. }
  8. function setGlobalOrigin (newOrigin) {
  9. if (
  10. newOrigin !== undefined &&
  11. typeof newOrigin !== 'string' &&
  12. !(newOrigin instanceof URL)
  13. ) {
  14. throw new Error('Invalid base url')
  15. }
  16. if (newOrigin === undefined) {
  17. Object.defineProperty(globalThis, globalOrigin, {
  18. value: undefined,
  19. writable: true,
  20. enumerable: false,
  21. configurable: false
  22. })
  23. return
  24. }
  25. const parsedURL = new URL(newOrigin)
  26. if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
  27. throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
  28. }
  29. Object.defineProperty(globalThis, globalOrigin, {
  30. value: parsedURL,
  31. writable: true,
  32. enumerable: false,
  33. configurable: false
  34. })
  35. }
  36. module.exports = {
  37. getGlobalOrigin,
  38. setGlobalOrigin
  39. }