@mswjs/interceptors 0.41.7 → 0.41.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/lib/browser/{XMLHttpRequest-DP9ps_69.mjs → XMLHttpRequest-DrZAf3w6.mjs} +5 -5
  2. package/lib/{node/XMLHttpRequest-BgkpwNOu.mjs.map → browser/XMLHttpRequest-DrZAf3w6.mjs.map} +1 -1
  3. package/lib/browser/{XMLHttpRequest-CHqOQWxg.cjs → XMLHttpRequest-gXuzzX1g.cjs} +5 -5
  4. package/lib/{node/XMLHttpRequest-CUbLHiq6.cjs.map → browser/XMLHttpRequest-gXuzzX1g.cjs.map} +1 -1
  5. package/lib/browser/{fetch-Ddj5TV04.mjs → fetch-5IMPqr9e.mjs} +4 -4
  6. package/lib/browser/fetch-5IMPqr9e.mjs.map +1 -0
  7. package/lib/browser/{fetch-CtkfZi4Z.cjs → fetch-Bt9rMY9c.cjs} +4 -4
  8. package/lib/browser/fetch-Bt9rMY9c.cjs.map +1 -0
  9. package/lib/browser/{handleRequest-tUNU616J.cjs → handleRequest-CJim54xG.cjs} +7 -5
  10. package/lib/browser/handleRequest-CJim54xG.cjs.map +1 -0
  11. package/lib/browser/{handleRequest-BHrC8Flw.mjs → handleRequest-CPPgsG7s.mjs} +7 -5
  12. package/lib/browser/handleRequest-CPPgsG7s.mjs.map +1 -0
  13. package/lib/browser/{hasConfigurableGlobal-FTYwno1G.mjs → hasConfigurableGlobal-C8zq1MCg.mjs} +10 -3
  14. package/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs.map +1 -0
  15. package/lib/browser/{hasConfigurableGlobal-BS75Oulv.cjs → hasConfigurableGlobal-CS7adEvV.cjs} +10 -3
  16. package/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs.map +1 -0
  17. package/lib/browser/index.cjs +1 -1
  18. package/lib/browser/index.cjs.map +1 -1
  19. package/lib/browser/index.mjs +1 -1
  20. package/lib/browser/index.mjs.map +1 -1
  21. package/lib/browser/interceptors/WebSocket/index.cjs +2 -2
  22. package/lib/browser/interceptors/WebSocket/index.cjs.map +1 -1
  23. package/lib/browser/interceptors/WebSocket/index.mjs +2 -2
  24. package/lib/browser/interceptors/WebSocket/index.mjs.map +1 -1
  25. package/lib/browser/interceptors/XMLHttpRequest/index.cjs +3 -3
  26. package/lib/browser/interceptors/XMLHttpRequest/index.d.cts +1 -1
  27. package/lib/browser/interceptors/XMLHttpRequest/index.d.mts +1 -1
  28. package/lib/browser/interceptors/XMLHttpRequest/index.mjs +3 -3
  29. package/lib/browser/interceptors/fetch/index.cjs +3 -3
  30. package/lib/browser/interceptors/fetch/index.mjs +3 -3
  31. package/lib/browser/presets/browser.cjs +4 -4
  32. package/lib/browser/presets/browser.mjs +4 -4
  33. package/lib/node/{BatchInterceptor-Z1lwK23r.cjs → BatchInterceptor-BGhH8z1z.cjs} +2 -2
  34. package/lib/node/BatchInterceptor-BGhH8z1z.cjs.map +1 -0
  35. package/lib/node/{BatchInterceptor-DdMNfSUY.mjs → BatchInterceptor-C4-RX5rg.mjs} +2 -2
  36. package/lib/node/BatchInterceptor-C4-RX5rg.mjs.map +1 -0
  37. package/lib/node/{ClientRequest-DFs7FPNi.cjs → ClientRequest-2loAH7xM.cjs} +3 -3
  38. package/lib/node/{ClientRequest-DFs7FPNi.cjs.map → ClientRequest-2loAH7xM.cjs.map} +1 -1
  39. package/lib/node/{ClientRequest-dRpI9v1o.mjs → ClientRequest-DGhBX21V.mjs} +3 -3
  40. package/lib/node/{ClientRequest-dRpI9v1o.mjs.map → ClientRequest-DGhBX21V.mjs.map} +1 -1
  41. package/lib/node/RemoteHttpInterceptor.cjs +7 -7
  42. package/lib/node/RemoteHttpInterceptor.cjs.map +1 -1
  43. package/lib/node/RemoteHttpInterceptor.mjs +7 -7
  44. package/lib/node/RemoteHttpInterceptor.mjs.map +1 -1
  45. package/lib/node/{XMLHttpRequest-CUbLHiq6.cjs → XMLHttpRequest-BtDNZipW.cjs} +5 -5
  46. package/lib/{browser/XMLHttpRequest-CHqOQWxg.cjs.map → node/XMLHttpRequest-BtDNZipW.cjs.map} +1 -1
  47. package/lib/node/{XMLHttpRequest-BgkpwNOu.mjs → XMLHttpRequest-Dw6Wm-UU.mjs} +5 -5
  48. package/lib/{browser/XMLHttpRequest-DP9ps_69.mjs.map → node/XMLHttpRequest-Dw6Wm-UU.mjs.map} +1 -1
  49. package/lib/node/{fetch-BciBtVqm.mjs → fetch-CaC3rGEu.mjs} +4 -4
  50. package/lib/node/fetch-CaC3rGEu.mjs.map +1 -0
  51. package/lib/node/{fetch-znfXVEPe.cjs → fetch-D2ClLNN-.cjs} +4 -4
  52. package/lib/node/fetch-D2ClLNN-.cjs.map +1 -0
  53. package/lib/node/{handleRequest-DVOthWJo.cjs → handleRequest-C-cKYjIh.cjs} +6 -4
  54. package/lib/node/{handleRequest-DVOthWJo.cjs.map → handleRequest-C-cKYjIh.cjs.map} +1 -1
  55. package/lib/node/{handleRequest-DCLzePtS.mjs → handleRequest-FIQv5pwH.mjs} +6 -4
  56. package/lib/node/handleRequest-FIQv5pwH.mjs.map +1 -0
  57. package/lib/node/{hasConfigurableGlobal-Cwrs35Xo.mjs → hasConfigurableGlobal-BiTmog1u.mjs} +10 -3
  58. package/lib/node/hasConfigurableGlobal-BiTmog1u.mjs.map +1 -0
  59. package/lib/node/{hasConfigurableGlobal-BtHi5OlL.cjs → hasConfigurableGlobal-MjY06_Ok.cjs} +10 -3
  60. package/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs.map +1 -0
  61. package/lib/node/index.cjs +1 -1
  62. package/lib/node/index.mjs +1 -1
  63. package/lib/node/interceptors/ClientRequest/index.cjs +2 -2
  64. package/lib/node/interceptors/ClientRequest/index.mjs +2 -2
  65. package/lib/node/interceptors/XMLHttpRequest/index.cjs +3 -3
  66. package/lib/node/interceptors/XMLHttpRequest/index.d.cts +1 -1
  67. package/lib/node/interceptors/XMLHttpRequest/index.d.mts +1 -1
  68. package/lib/node/interceptors/XMLHttpRequest/index.mjs +3 -3
  69. package/lib/node/interceptors/fetch/index.cjs +3 -3
  70. package/lib/node/interceptors/fetch/index.mjs +3 -3
  71. package/lib/node/presets/node.cjs +5 -5
  72. package/lib/node/presets/node.mjs +5 -5
  73. package/package.json +1 -1
  74. package/src/BatchInterceptor.ts +9 -8
  75. package/src/RemoteHttpInterceptor.ts +1 -1
  76. package/src/interceptors/ClientRequest/index.ts +1 -1
  77. package/src/interceptors/WebSocket/index.ts +1 -1
  78. package/src/interceptors/XMLHttpRequest/index.ts +2 -2
  79. package/src/interceptors/fetch/index.ts +1 -1
  80. package/src/utils/handleRequest.ts +6 -7
  81. package/src/utils/patchesRegistry.test.ts +57 -1
  82. package/src/utils/patchesRegistry.ts +17 -5
  83. package/lib/browser/fetch-CtkfZi4Z.cjs.map +0 -1
  84. package/lib/browser/fetch-Ddj5TV04.mjs.map +0 -1
  85. package/lib/browser/handleRequest-BHrC8Flw.mjs.map +0 -1
  86. package/lib/browser/handleRequest-tUNU616J.cjs.map +0 -1
  87. package/lib/browser/hasConfigurableGlobal-BS75Oulv.cjs.map +0 -1
  88. package/lib/browser/hasConfigurableGlobal-FTYwno1G.mjs.map +0 -1
  89. package/lib/node/BatchInterceptor-DdMNfSUY.mjs.map +0 -1
  90. package/lib/node/BatchInterceptor-Z1lwK23r.cjs.map +0 -1
  91. package/lib/node/fetch-BciBtVqm.mjs.map +0 -1
  92. package/lib/node/fetch-znfXVEPe.cjs.map +0 -1
  93. package/lib/node/handleRequest-DCLzePtS.mjs.map +0 -1
  94. package/lib/node/hasConfigurableGlobal-BtHi5OlL.cjs.map +0 -1
  95. package/lib/node/hasConfigurableGlobal-Cwrs35Xo.mjs.map +0 -1
@@ -141,7 +141,7 @@ export interface RemoveResolverOptions {
141
141
  }
142
142
 
143
143
  export class RemoteHttpResolver extends Interceptor<HttpRequestEventMap> {
144
- static symbol = Symbol('remote-resolver')
144
+ static symbol = Symbol.for('remote-resolver')
145
145
  private process: ChildProcess
146
146
 
147
147
  constructor(options: RemoveResolverOptions) {
@@ -18,7 +18,7 @@ import {
18
18
  } from './utils/recordRawHeaders'
19
19
 
20
20
  export class ClientRequestInterceptor extends Interceptor<HttpRequestEventMap> {
21
- static symbol = Symbol('client-request-interceptor')
21
+ static symbol = Symbol.for('client-request-interceptor')
22
22
 
23
23
  constructor() {
24
24
  super(ClientRequestInterceptor.symbol)
@@ -70,7 +70,7 @@ export type WebSocketConnectionData = {
70
70
  * the global `WebSocket` class.
71
71
  */
72
72
  export class WebSocketInterceptor extends Interceptor<WebSocketEventMap> {
73
- static symbol = Symbol('websocket')
73
+ static symbol = Symbol.for('websocket-interceptor')
74
74
 
75
75
  constructor() {
76
76
  super(WebSocketInterceptor.symbol)
@@ -8,10 +8,10 @@ import { patchesRegistry } from '../../utils/patchesRegistry'
8
8
  export type XMLHttpRequestEmitter = Emitter<HttpRequestEventMap>
9
9
 
10
10
  export class XMLHttpRequestInterceptor extends Interceptor<HttpRequestEventMap> {
11
- static interceptorSymbol = Symbol('xhr')
11
+ static symbol = Symbol.for('xhr-interceptor')
12
12
 
13
13
  constructor() {
14
- super(XMLHttpRequestInterceptor.interceptorSymbol)
14
+ super(XMLHttpRequestInterceptor.symbol)
15
15
  }
16
16
 
17
17
  protected checkEnvironment() {
@@ -17,7 +17,7 @@ import { isResponseError } from '../../utils/responseUtils'
17
17
  import { patchesRegistry } from '../../utils/patchesRegistry'
18
18
 
19
19
  export class FetchInterceptor extends Interceptor<HttpRequestEventMap> {
20
- static symbol = Symbol('fetch')
20
+ static symbol = Symbol.for('fetch-interceptor')
21
21
 
22
22
  constructor() {
23
23
  super(FetchInterceptor.symbol)
@@ -90,6 +90,9 @@ export async function handleRequest(
90
90
  // })
91
91
 
92
92
  const requestAbortPromise = new DeferredPromise<void, unknown>()
93
+ const onAbort = () => {
94
+ requestAbortPromise.reject(options.request.signal?.reason)
95
+ }
93
96
 
94
97
  /**
95
98
  * @note `signal` is not always defined in React Native.
@@ -100,13 +103,7 @@ export async function handleRequest(
100
103
  return
101
104
  }
102
105
 
103
- options.request.signal.addEventListener(
104
- 'abort',
105
- () => {
106
- requestAbortPromise.reject(options.request.signal.reason)
107
- },
108
- { once: true }
109
- )
106
+ options.request.signal.addEventListener('abort', onAbort, { once: true })
110
107
  }
111
108
 
112
109
  const result = await until(async () => {
@@ -128,6 +125,8 @@ export async function handleRequest(
128
125
  ])
129
126
  })
130
127
 
128
+ options.request.signal?.removeEventListener('abort', onAbort)
129
+
131
130
  // Handle the request being aborted while waiting for the request listeners.
132
131
  if (requestAbortPromise.state === 'rejected') {
133
132
  await options.controller.errorWith(requestAbortPromise.rejectionReason)
@@ -8,7 +8,12 @@ declare global {
8
8
  const realGlobalPrototype = Object.getPrototypeOf(global)
9
9
 
10
10
  beforeEach(() => {
11
- global.foo = { original: true }
11
+ Object.defineProperty(global, 'foo', {
12
+ value: { original: true },
13
+ writable: true,
14
+ enumerable: true,
15
+ configurable: true,
16
+ })
12
17
  })
13
18
 
14
19
  afterEach(() => {
@@ -182,3 +187,54 @@ it('restores global to the original property descriptor', () => {
182
187
  expect(global.foo).toEqual({ original: true })
183
188
  expect(Object.getOwnPropertyDescriptor(global, 'foo')).toEqual(descriptor)
184
189
  })
190
+
191
+ it('replaces a non-configurable writable property', () => {
192
+ const owner = {} as { foo: { original: boolean } }
193
+ const descriptor: PropertyDescriptor = {
194
+ value: { original: true },
195
+ enumerable: true,
196
+ writable: true,
197
+ configurable: false,
198
+ }
199
+ Object.defineProperty(owner, 'foo', descriptor)
200
+
201
+ const restoreGlobal = patchesRegistry.applyPatch(owner, 'foo', () => ({
202
+ original: false,
203
+ }))
204
+
205
+ expect(owner.foo).toEqual({ original: false })
206
+ expect(
207
+ Object.getOwnPropertyDescriptor(owner, 'foo'),
208
+ 'Preserves the original descriptor'
209
+ ).toEqual({
210
+ value: { original: false },
211
+ enumerable: true,
212
+ configurable: false,
213
+ writable: true,
214
+ })
215
+
216
+ restoreGlobal()
217
+
218
+ expect(owner.foo).toEqual({ original: true })
219
+ expect(
220
+ Object.getOwnPropertyDescriptor(owner, 'foo'),
221
+ 'Restores the original descriptor'
222
+ ).toEqual(descriptor)
223
+ })
224
+
225
+ it('throws when replacing a non-configurable non-writable property', () => {
226
+ let owner = {} as { foo: { original: boolean } }
227
+ const descriptor: PropertyDescriptor = {
228
+ value: { original: true },
229
+ enumerable: true,
230
+ writable: false,
231
+ configurable: false,
232
+ }
233
+ Object.defineProperty(owner, 'foo', descriptor)
234
+
235
+ expect(() =>
236
+ patchesRegistry.applyPatch(owner, 'foo', () => ({
237
+ original: false,
238
+ }))
239
+ ).toThrow('Failed to patch a non-configurable non-writable property "foo"')
240
+ })
@@ -24,11 +24,19 @@ class PatchesRegistry {
24
24
  return () => {}
25
25
  }
26
26
 
27
- Object.defineProperty(owner, key, {
28
- value: getNextValue(owner[key]),
29
- enumerable: true,
30
- configurable: true,
31
- })
27
+ if (match.descriptor.configurable) {
28
+ Object.defineProperty(owner, key, {
29
+ value: getNextValue(owner[key]),
30
+ enumerable: true,
31
+ configurable: true,
32
+ })
33
+ } else if (match.descriptor.writable) {
34
+ owner[key] = getNextValue(owner[key])
35
+ } else {
36
+ throw new Error(
37
+ `Failed to patch a non-configurable non-writable property "${key.toString()}"`
38
+ )
39
+ }
32
40
 
33
41
  const restorePatch = () => {
34
42
  const currentReplacements = this.#replacements.get(owner)
@@ -38,6 +46,10 @@ class PatchesRegistry {
38
46
  }
39
47
 
40
48
  if (match.owner === owner) {
49
+ /**
50
+ * @note Restoring non-configurable properties works as long as "writable: true"
51
+ * and none of the other descriptor properties except for "value" have changed.
52
+ */
41
53
  Object.defineProperty(match.owner, key, match.descriptor)
42
54
  } else {
43
55
  /**
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch-CtkfZi4Z.cjs","names":["locationUrl: URL","requestInit: RequestInit","readable","Interceptor","hasConfigurableGlobal","fetchProxy: typeof fetch","createRequestId","FetchRequest","canParseUrl","DeferredPromise","RequestController","FetchResponse","emitAsync","isResponseError","response","handleRequest","patchesRegistry"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"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,qBAAgB,QAAQ,SAAS;;IAEnC,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,6BAA6B,EAAE,QAAQ,CAAC;AACzD,qBAAgB,OAAO,OAAO;;IAEjC,CAAC;AAEF,QAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,IAAI;AACxD,QAAK,OAAO,KAAK,sCAAsC;AAEvD,QAAK,OAAO,KACV,wDACA,KAAK,QAAQ,cAAc,UAAU,CACtC;AAED,SAAMI,oCAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KACjBC,8CAAgB,WAAW,YAAY,eAAe,WAAW,CAClE;AAED,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch-Ddj5TV04.mjs","names":["locationUrl: URL","requestInit: RequestInit","readable","fetchProxy: typeof fetch","response"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,KAC7C,QAAO,QAAQ,OAAO,oBAAoB,CAAC;CAG7C,MAAM,aAAa,IAAI,IAAI,QAAQ,IAAI;CAEvC,IAAIA;AACJ,KAAI;AAEF,gBAAc,IAAI,IAAI,SAAS,QAAQ,IAAI,WAAW,EAAG,QAAQ,IAAI;UAC9D,OAAO;AACd,SAAO,QAAQ,OAAO,mBAAmB,MAAM,CAAC;;AAGlD,KACE,EAAE,YAAY,aAAa,WAAW,YAAY,aAAa,UAE/D,QAAO,QAAQ,OACb,mBAAmB,sCAAsC,CAC1D;AAGH,KAAI,QAAQ,IAAI,SAAS,eAAe,GAAG,GACzC,Q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AAY;MACpB,YAAY,YAAY;MACxB,SAAS,YAAY;MACtB,CACF;;;;;;;AAQD,SAAI,cAAc,mBAAmB,SAAS,OAAO,EAAE;AAGrD,UAAI,QAAQ,aAAa,SAAS;AAChC,uBAAgB,OAAO,mBAAmB,sBAAsB,CAAC;AACjE;;AAGF,UAAI,QAAQ,aAAa,UAAU;AACjC,2BAAoB,SAAS,SAAS,CAAC,MACpC,eAAa;AACZ,wBAAgB,QAAQC,WAAS;WAElC,WAAW;AACV,wBAAgB,OAAO,OAAO;SAEjC;AACD;;;AAIJ,SAAI,KAAK,QAAQ,cAAc,WAAW,GAAG,GAAG;AAC9C,WAAK,OAAO,KAAK,qCAAmC;AAKpD,YAAM,UAAU,KAAK,SAAS,YAAY;OAIxC,UAAU,cAAc,MAAM,SAAS;OACvC,kBAAkB;OAClB;OACA;OACD,CAAC;;AAGJ,qBAAgB,QAAQ,SAAS;;IAEnC,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,6BAA6B,EAAE,QAAQ,CAAC;AACzD,qBAAgB,OAAO,OAAO;;IAEjC,CAAC;AAEF,QAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,IAAI;AACxD,QAAK,OAAO,KAAK,sCAAsC;AAEvD,QAAK,OAAO,KACV,wDACA,KAAK,QAAQ,cAAc,UAAU,CACtC;AAED,SAAM,cAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KACjB,gBAAgB,WAAW,YAAY,eAAe,WAAW,CAClE;AAED,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"handleRequest-BHrC8Flw.mjs","names":[],"sources":["../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject<T>(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject<Record<string, any>>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<void> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK;;;;;;;;;;;;;ACEhD,SAAgB,qBACd,KACA,KACA;AACA,KAAI;AACF,MAAI;AACJ,SAAO;SACD;AACN,SAAO;;;;;;;;;ACVX,SAAgB,0BAA0B,MAAyB;AACjE,QAAO,IAAI,SACT,KAAK,UACH,gBAAgB,QACZ;EACE,MAAM,KAAK;EACX,SAAS,KAAK;EACd,OAAO,KAAK;EACb,GACD,KACL,EACD;EACE,QAAQ;EACR,YAAY;EACZ,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;;;;;;;;;AAaH,SAAgB,gBAAgB,UAA8C;AAC5E,QACE,YAAY,QACZ,oBAAoB,YACpB,qBAAqB,UAAU,OAAO,IACtC,SAAS,SAAS;;;;;;;AAStB,SAAgB,eAAe,OAAmC;AAChE,QACE,SAA8B,OAAO,KAAK,IAC1C,qBAAqB,OAAO,SAAS,IACrC,qBAAqB,OAAO,aAAa,IACzC,qBAAqB,OAAO,WAAW;;;;;ACxD3C,SAAgB,gBACd,OACgC;AAChC,KAAI,SAAS,KACX,QAAO;AAGT,KAAI,EAAE,iBAAiB,OACrB,QAAO;AAGT,QAAO,UAAU,SAAS,WAAW;;;;;ACWvC,eAAsB,cACpB,SACe;CACf,MAAM,iBAAiB,OACrB,aACG;AACH,MAA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AM,CACzC;AAMF,MAAI,QAAQ,QAAQ,cAAc,qBAAqB,GAAG,GAAG;GAI3D,MAAM,+BAA+B,IAAI,kBACvC,QAAQ,SACR;IAME,cAAc;IACd,MAAM,YAAY,UAAU;AAC1B,WAAM,eAAe,SAAS;;IAEhC,MAAM,UAAU,QAAQ;;;;;;;;AAQtB,WAAM,QAAQ,WAAW,UAAU,OAAO;;IAE7C,CACF;AAED,SAAM,UAAU,QAAQ,SAAS,sBAAsB;IACrD,OAAO,OAAO;IACd,SAAS,QAAQ;IACjB,WAAW,QAAQ;IACnB,YAAY;IACb,CAAC;AAIF,OACE,6BAA6B,eAAe,kBAAkB,QAE9D;;AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAe,kBAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"handleRequest-tUNU616J.cjs","names":["InterceptorError","DeferredPromise","emitAsync","RequestController"],"sources":["../../src/utils/isObject.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject<T>(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject<Record<string, any>>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<void> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D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AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAeA,wCAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"hasConfigurableGlobal-BS75Oulv.cjs","names":["#replacements","errors: Array<Error>","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/emitAsync.ts","../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","import { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map<object, Map<PropertyKey, () => void>>()\n\n public applyPatch<Owner extends object, K extends keyof Owner>(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array<Error> = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor<Owner extends object>(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";;;;;;;;AAOA,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;ACpBvC,IAAM,kBAAN,MAAsB;CACpB,gCAAgB,IAAI,KAA2C;CAE/D,AAAO,WACL,OACA,KACA,cACY;EACZ,MAAM,oBAAoB,MAAKA,aAAc,IAAI,MAAM;AAEvD,4BACE,CAAC,mBAAmB,IAAI,IAAI,EAC5B,wCAAwC,OAAO,IAAI,CAAC,sBACrD;EAED,MAAM,QAAQ,0BAA0B,OAAO,IAAI;AAEnD,MAAI,OAAO,UAAU,aAAa;AAChC,WAAQ,KACN,wCAAwC,OAAO,IAAI,CAAC,wBACrD;AACD,gBAAa;;AAGf,SAAO,eAAe,OAAO,KAAK;GAChC,OAAO,aAAa,MAAM,KAAK;GAC/B,YAAY;GACZ,cAAc;GACf,CAAC;EAEF,MAAM,qBAAqB;GACzB,MAAM,sBAAsB,MAAKA,aAAc,IAAI,MAAM;AAEzD,OAAI,CAAC,qBAAqB,IAAI,IAAI,CAChC;AAGF,OAAI,MAAM,UAAU,MAClB,QAAO,eAAe,MAAM,OAAO,KAAK,MAAM,WAAW;;;;;;;AAOzD,WAAQ,eAAe,OAAO,IAAI;AAGpC,uBAAoB,OAAO,I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PropertyDescriptor | undefined"],"sources":["../../src/utils/emitAsync.ts","../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","import { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map<object, Map<PropertyKey, () => void>>()\n\n public applyPatch<Owner extends object, K extends keyof Owner>(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array<Error> = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor<Owner extends object>(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";;;;;;;;AAOA,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;ACpBvC,IAAM,kBAAN,MAAsB;CACpB,gCAAgB,IAAI,KAA2C;CAE/D,AAAO,WACL,OACA,KACA,cACY;EACZ,MAAM,oBAAoB,MAAKA,aAAc,IAAI,MAAM;AAEvD,YACE,CAAC,mBAAmB,IAAI,IAAI,EAC5B,wCAAwC,OAAO,IAAI,CAAC,sBACrD;EAED,MAAM,QAAQ,0BAA0B,OAAO,IAAI;AAEnD,MAAI,OAAO,UAAU,aAAa;AAChC,WAAQ,KACN,wCAAwC,OAAO,IAAI,CAAC,wBACrD;AACD,gBAAa;;AAGf,SAAO,eAAe,OAAO,KAAK;GAChC,OAAO,aAAa,MAAM,KAAK;GAC/B,YAAY;GACZ,cAAc;GACf,CAAC;EAEF,MAAM,qBAAqB;GACzB,MAAM,sBAAsB,MAAKA,aAAc,IAAI,MAAM;AAEzD,OAAI,CAAC,qBAAqB,IAAI,IAAI,CAChC;AAGF,OAAI,MAAM,UAAU,MAClB,QAAO,eAAe,MAAM,OAAO,KAAK,MAAM,WAAW;;;;;;;AAOzD,WAAQ,eAAe,OAAO,IAAI;AAGpC,uBAAoB,OAAO,IAAI;AAE/B,OAAI,oBAAoB,SAAS,EAC/B,OAAKA,aAAc,OAAO,MAAM;;AAIpC,MAAI,kBACF,mBAAkB,IAAI,KAAK,aAAa;MAExC,OAAKA,aAAc,IAAI,OAAO,IAAI,IAAI,CAAC,CAAC,KAAK,aAAa,CAAC,CAAC,CAAC;AAG/D,SAAO;;CAGT,AAAO,oBAA0B;EAC/B,MAAMC,SAAuB,EAAE;AAE/B,OAAK,MAAM,GAAG,sBAAsB,MAAKD,aACvC,MAAK,MAAM,GAAG,iBAAiB,kBAC7B,KAAI;AACF,iBAAc;WACP,OAAO;AACd,OAAI,iBAAiB,MACnB,QAAO,KAAK,MAAM;OAElB,OAAM;;AAMd,MAAI,OAAO,SAAS,EAClB,OAAM,IAAI,eAAe,QAAQ,OAAO;;;AAK9C,MAAa,kBAAkB,IAAI,iBAAiB;;;;;;;AAapD,SAAgB,0BACd,OACA,KACiC;CACjC,IAAIE,eAA6B;CACjC,IAAIC;AAEJ,QAAO,cAAc;AACnB,eAAa,OAAO,yBAAyB,cAAc,IAAI;AAE/D,MAAI,WACF,QAAO;GACL,OAAO;GACP;GACD;AAGH,iBAAe,OAAO,eAAe,aAAa;;;;;;;;;;ACjHtD,SAAgB,sBACd,cACS;CACT,MAAM,QAAQ,0BAA0B,YAAY,aAAa;AAGjE,KAAI,OAAO,UAAU,YACnB,QAAO;CAGT,MAAM,EAAE,eAAe;AAGvB,KACE,OAAO,WAAW,QAAQ,cAC1B,OAAO,WAAW,KAAK,KAAK,YAE5B,QAAO;AAIT,KAAI,OAAO,WAAW,QAAQ,eAAe,WAAW,SAAS,KAC/D,QAAO;AAGT,KAAI,OAAO,WAAW,QAAQ,eAAe,CAAC,WAAW,cAAc;AACrE,UAAQ,MACN,mDAAmD,aAAa,oKACjE;AACD,SAAO;;AAGT,QAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"BatchInterceptor-DdMNfSUY.mjs","names":[],"sources":["../../src/BatchInterceptor.ts"],"sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray<Interceptor<any>>\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray<Interceptor<any>>\n> = InterceptorList extends ReadonlyArray<infer InterceptorType>\n ? InterceptorType extends Interceptor<infer EventMap>\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray<Interceptor<any>>,\n Events extends EventMap = ExtractEventMapType<InterceptorList>\n> extends Interceptor<Events> {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions<InterceptorList>) {\n BatchInterceptor.symbol = Symbol(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners<EventName extends ExtractEventNames<Events>>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n"],"mappings":";;;;;;;AAsBA,IAAa,mBAAb,MAAa,yBAGH,YAAoB;CAK5B,YAAY,SAAmD;AAC7D,mBAAiB,SAAS,OAAO,QAAQ,KAAK;AAC9C,QAAM,iBAAiB,OAAO;AAC9B,OAAK,eAAe,QAAQ;;CAG9B,AAAU,QAAQ;EAChB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAE1C,SAAO,KAAK,mCAAmC,KAAK,aAAa,OAAO;AAExE,OAAK,MAAM,eAAe,KAAK,cAAc;AAC3C,UAAO,KAAK,kCAAgC,YAAY,YAAY,KAAK;AACzE,eAAY,OAAO;AAEnB,UAAO,KAAK,0CAA0C;AACtD,QAAK,cAAc,WAAW,YAAY,SAAS,CAAC;;;CAIxD,AAAO,GACL,OACA,UACM;AAGN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,GAAG,OAAO,SAAS;AAGjC,SAAO;;CAGT,AAAO,KACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,KAAK,OAAO,SAAS;AAGnC,SAAO;;CAGT,AAAO,IACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,IAAI,OAAO,SAAS;AAGlC,SAAO;;CAGT,AAAO,mBACL,OACM;AACN,OAAK,MAAM,gBAAgB,KAAK,aAC9B,cAAa,mBAAmB,MAAM;AAGxC,SAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"BatchInterceptor-Z1lwK23r.cjs","names":["Interceptor"],"sources":["../../src/BatchInterceptor.ts"],"sourcesContent":["import { EventMap, Listener } from 'strict-event-emitter'\nimport { Interceptor, ExtractEventNames } from './Interceptor'\n\nexport interface BatchInterceptorOptions<\n InterceptorList extends ReadonlyArray<Interceptor<any>>\n> {\n name: string\n interceptors: InterceptorList\n}\n\nexport type ExtractEventMapType<\n InterceptorList extends ReadonlyArray<Interceptor<any>>\n> = InterceptorList extends ReadonlyArray<infer InterceptorType>\n ? InterceptorType extends Interceptor<infer EventMap>\n ? EventMap\n : never\n : never\n\n/**\n * A batch interceptor that exposes a single interface\n * to apply and operate with multiple interceptors at once.\n */\nexport class BatchInterceptor<\n InterceptorList extends ReadonlyArray<Interceptor<any>>,\n Events extends EventMap = ExtractEventMapType<InterceptorList>\n> extends Interceptor<Events> {\n static symbol: symbol\n\n private interceptors: InterceptorList\n\n constructor(options: BatchInterceptorOptions<InterceptorList>) {\n BatchInterceptor.symbol = Symbol(options.name)\n super(BatchInterceptor.symbol)\n this.interceptors = options.interceptors\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('applying all %d interceptors...', this.interceptors.length)\n\n for (const interceptor of this.interceptors) {\n logger.info('applying \"%s\" interceptor...', interceptor.constructor.name)\n interceptor.apply()\n\n logger.info('adding interceptor dispose subscription')\n this.subscriptions.push(() => interceptor.dispose())\n }\n }\n\n public on<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n // Instead of adding a listener to the batch interceptor,\n // propagate the listener to each of the individual interceptors.\n for (const interceptor of this.interceptors) {\n interceptor.on(event, listener)\n }\n\n return this\n }\n\n public once<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.once(event, listener)\n }\n\n return this\n }\n\n public off<EventName extends ExtractEventNames<Events>>(\n event: EventName,\n listener: Listener<Events[EventName]>\n ): this {\n for (const interceptor of this.interceptors) {\n interceptor.off(event, listener)\n }\n\n return this\n }\n\n public removeAllListeners<EventName extends ExtractEventNames<Events>>(\n event?: EventName | undefined\n ): this {\n for (const interceptors of this.interceptors) {\n interceptors.removeAllListeners(event)\n }\n\n return this\n }\n}\n"],"mappings":";;;;;;;AAsBA,IAAa,mBAAb,MAAa,yBAGHA,+BAAoB;CAK5B,YAAY,SAAmD;AAC7D,mBAAiB,SAAS,OAAO,QAAQ,KAAK;AAC9C,QAAM,iBAAiB,OAAO;AAC9B,OAAK,eAAe,QAAQ;;CAG9B,AAAU,QAAQ;EAChB,MAAM,SAAS,KAAK,OAAO,OAAO,QAAQ;AAE1C,SAAO,KAAK,mCAAmC,KAAK,aAAa,OAAO;AAExE,OAAK,MAAM,eAAe,KAAK,cAAc;AAC3C,UAAO,KAAK,kCAAgC,YAAY,YAAY,KAAK;AACzE,eAAY,OAAO;AAEnB,UAAO,KAAK,0CAA0C;AACtD,QAAK,cAAc,WAAW,YAAY,SAAS,CAAC;;;CAIxD,AAAO,GACL,OACA,UACM;AAGN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,GAAG,OAAO,SAAS;AAGjC,SAAO;;CAGT,AAAO,KACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,KAAK,OAAO,SAAS;AAGnC,SAAO;;CAGT,AAAO,IACL,OACA,UACM;AACN,OAAK,MAAM,eAAe,KAAK,aAC7B,aAAY,IAAI,OAAO,SAAS;AAGlC,SAAO;;CAGT,AAAO,mBACL,OACM;AACN,OAAK,MAAM,gBAAgB,KAAK,aAC9B,cAAa,mBAAmB,MAAM;AAGxC,SAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch-BciBtVqm.mjs","names":["locationUrl: URL","requestInit: RequestInit","readable","fetchProxy: typeof fetch","response"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","import zlib from 'node:zlib'\n\nexport class BrotliDecompressionStream extends TransformStream {\n constructor() {\n const decompress = zlib.createBrotliDecompress({\n flush: zlib.constants.BROTLI_OPERATION_FLUSH,\n finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,\n })\n\n super({\n async transform(chunk, controller) {\n const buffer = Buffer.from(chunk)\n\n const decompressed = await new Promise<Buffer>((resolve, reject) => {\n decompress.write(buffer, (error) => {\n if (error) reject(error)\n })\n\n decompress.flush()\n decompress.once('data', (data) => resolve(data))\n decompress.once('error', (error) => reject(error))\n decompress.once('end', () => controller.terminate())\n }).catch((error) => {\n controller.error(error)\n })\n\n controller.enqueue(decompressed)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,KAC7C,QAAO,QAAQ,OAAO,oBAAoB,CAAC;CAG7C,MAAM,aAAa,IAAI,IAAI,QAAQ,IAAI;CAEvC,IAAIA;AACJ,KAAI;AAEF,gB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OACD,CAAC;;AAGJ,qBAAgB,QAAQ,SAAS;;IAEnC,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,6BAA6B,EAAE,QAAQ,CAAC;AACzD,qBAAgB,OAAO,OAAO;;IAEjC,CAAC;AAEF,QAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,IAAI;AACxD,QAAK,OAAO,KAAK,sCAAsC;AAEvD,QAAK,OAAO,KACV,wDACA,KAAK,QAAQ,cAAc,UAAU,CACtC;AAED,SAAM,cAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KACjB,gBAAgB,WAAW,YAAY,eAAe,WAAW,CAClE;AAED,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch-znfXVEPe.cjs","names":["locationUrl: URL","requestInit: RequestInit","zlib","readable","Interceptor","hasConfigurableGlobal","fetchProxy: typeof fetch","createRequestId","FetchRequest","canParseUrl","DeferredPromise","RequestController","FetchResponse","emitAsync","isResponseError","response","handleRequest","patchesRegistry"],"sources":["../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/interceptors/fetch/index.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","import zlib from 'node:zlib'\n\nexport class BrotliDecompressionStream extends TransformStream {\n constructor() {\n const decompress = zlib.createBrotliDecompress({\n flush: zlib.constants.BROTLI_OPERATION_FLUSH,\n finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,\n })\n\n super({\n async transform(chunk, controller) {\n const buffer = Buffer.from(chunk)\n\n const decompressed = await new Promise<Buffer>((resolve, reject) => {\n decompress.write(buffer, (error) => {\n if (error) reject(error)\n })\n\n decompress.flush()\n decompress.once('data', (data) => resolve(data))\n decompress.once('error', (error) => reject(error))\n decompress.once('end', () => controller.terminate())\n }).catch((error) => {\n controller.error(error)\n })\n\n controller.enqueue(decompressed)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { until } from '@open-draft/until'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchRequest, FetchResponse } from '../../utils/fetchUtils'\nimport { setRawRequest } from '../../getRawRequest'\nimport { isResponseError } from '../../utils/responseUtils'\nimport { patchesRegistry } from '../../utils/patchesRegistry'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const logger = this.logger.extend('setup')\n\n const pureFetch = globalThis.fetch\n\n const fetchProxy: typeof fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new FetchRequest(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n setRawRequest(request, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const controller = new RequestController(request, {\n passthrough: async () => {\n this.logger.info('request has not been handled, passthrough...')\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n // Perform the intercepted request as-is.\n const { error: responseError, data: originalResponse } = await until(\n () => pureFetch(request)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n this.logger.info('original fetch performed', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = FetchResponse.clone(originalResponse)\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n this.logger.info('request has errored!', { response: rawResponse })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: FetchResponse.clone(response),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n this.logger.info('request has been aborted!', { reason })\n responsePromise.reject(reason)\n },\n })\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n })\n\n return responsePromise\n }\n\n logger.info('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', () => fetchProxy)\n )\n\n logger.info('global fetch patched!', globalThis.fetch.name)\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAgB,mBAAmB,OAAiB;AAClD,QAAO,OAAO,uBAAO,IAAI,UAAU,kBAAkB,EAAE,EACrD,OACD,CAAC;;;;;ACDJ,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,OAAO,iBAAiB;;;;AAK/C,eAAsB,oBACpB,SACA,UACmB;AACnB,KAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,KAC7C,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AAG,GAAG;AAC9C,WAAK,OAAO,KAAK,qCAAmC;AAKpD,YAAMF,gCAAU,KAAK,SAAS,YAAY;OAIxC,UAAUD,iCAAc,MAAM,SAAS;OACvC,kBAAkB;OAClB;OACA;OACD,CAAC;;AAGJ,qBAAgB,QAAQ,SAAS;;IAEnC,YAAY,WAAW;AACrB,UAAK,OAAO,KAAK,6BAA6B,EAAE,QAAQ,CAAC;AACzD,qBAAgB,OAAO,OAAO;;IAEjC,CAAC;AAEF,QAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,IAAI;AACxD,QAAK,OAAO,KAAK,sCAAsC;AAEvD,QAAK,OAAO,KACV,wDACA,KAAK,QAAQ,cAAc,UAAU,CACtC;AAED,SAAMI,oCAAc;IAClB;IACA;IACA,SAAS,KAAK;IACd;IACD,CAAC;AAEF,UAAO;;AAGT,SAAO,KAAK,2BAA2B;AAEvC,OAAK,cAAc,KACjBC,8CAAgB,WAAW,YAAY,eAAe,WAAW,CAClE;AAED,SAAO,KAAK,yBAAyB,WAAW,MAAM,KAAK"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"handleRequest-DCLzePtS.mjs","names":[],"sources":["../../src/utils/isPropertyAccessible.ts","../../src/utils/emitAsync.ts","../../src/utils/isObject.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts","../../src/utils/handleRequest.ts"],"sourcesContent":["/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","/**\n * Determines if a given value is an instance of object.\n */\nexport function isObject<T>(value: any, loose = false): value is T {\n return loose\n ? Object.prototype.toString.call(value).startsWith('[object ')\n : Object.prototype.toString.call(value) === '[object Object]'\n}\n","import { isObject } from './isObject'\nimport { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: unknown): response is ResponseError {\n return (\n response != null &&\n response instanceof Response &&\n isPropertyAccessible(response, 'type') &&\n response.type === 'error'\n )\n}\n\n/**\n * Check if the given value is a `Response` or a Response-like object.\n * This is different from `value instanceof Response` because it supports\n * custom `Response` constructors, like the one when using Undici directly.\n */\nexport function isResponseLike(value: unknown): value is Response {\n return (\n isObject<Record<string, any>>(value, true) &&\n isPropertyAccessible(value, 'status') &&\n isPropertyAccessible(value, 'statusText') &&\n isPropertyAccessible(value, 'bodyUsed')\n )\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n isResponseLike,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\nimport { isObject } from './isObject'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n}\n\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<void> {\n const handleResponse = async (\n response: Response | Error | Record<string, any>\n ) => {\n if (response instanceof Error) {\n await options.controller.errorWith(response)\n return true\n }\n\n // Handle \"Response.error()\" instances.\n if (isResponseError(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n /**\n * Handle normal responses or response-like objects.\n * @note This must come before the arbitrary object check\n * since Response instances are, in fact, objects.\n */\n if (isResponseLike(response)) {\n await options.controller.respondWith(response)\n return true\n }\n\n // Handle arbitrary objects provided to `.errorWith(reason)`.\n if (isObject(response)) {\n await options.controller.errorWith(response)\n return true\n }\n\n return false\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n await options.controller.errorWith(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n // options.emitter.once('request', async ({ requestId: pendingRequestId }) => {\n // if (\n // pendingRequestId === options.requestId &&\n // options.controller.readyState === RequestController.PENDING\n // ) {\n // await options.controller.passthrough()\n // }\n // })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n await options.controller.errorWith(options.request.signal.reason)\n return\n }\n\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListenersPromise,\n options.controller.handled,\n ])\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n await options.controller.errorWith(requestAbortPromise.rejectionReason)\n return\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request,\n {\n /**\n * @note Intentionally empty passthrough handle.\n * This controller is created within another controller and we only need\n * to know if `unhandledException` listeners handled the request.\n */\n passthrough() {},\n async respondWith(response) {\n await handleResponse(response)\n },\n async errorWith(reason) {\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n await options.controller.errorWith(reason)\n },\n }\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n })\n\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the request in any way, passthrough.\n if (\n unhandledExceptionController.readyState !== RequestController.PENDING\n ) {\n return\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n await options.controller.respondWith(\n createServerErrorResponse(result.error)\n )\n return\n }\n\n // If the request hasn't been handled by this point, passthrough.\n if (options.controller.readyState === RequestController.PENDING) {\n return await options.controller.passthrough()\n }\n\n return options.controller.handled\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,SAAgB,qBACd,KACA,KACA;AACA,KAAI;AACF,MAAI;AACJ,SAAO;SACD;AACN,SAAO;;;;;;;;;;;ACTX,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;;;;ACnBvC,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,SAAS,KAAK,MAAM,CAAC,WAAW,WAAW,GAC5D,OAAO,UAAU,SAAS,KAAK,MAAM,KAAK;;;;;;;;ACAhD,SAAgB,0BAA0B,MAAyB;AACjE,QAAO,IAAI,SACT,KAAK,UACH,gBAAgB,QACZ;EACE,MAAM,KAAK;EACX,SAAS,KAAK;EACd,OAAO,KAAK;EACb,GACD,KACL,EACD;EACE,QAAQ;EACR,YAAY;EACZ,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;;;;;;;;;AAaH,SAAgB,gBAAgB,UAA8C;AAC5E,QACE,YAAY,QACZ,oBAAoB,YACpB,qBAAqB,UAAU,OAAO,IACtC,SAAS,SAAS;;;;;;;AAStB,SAAgB,eAAe,OAAmC;AAChE,QACE,SAA8B,OAAO,KAAK,IAC1C,qBAAqB,OAAO,SAAS,IACrC,qBAAqB,OAAO,aAAa,IACzC,qBAAqB,OAAO,WAAW;;;;;ACxD3C,SAAgB,gBACd,OACgC;AAChC,KAAI,SAAS,KACX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,KAAI,oBAAoB,UAAU,YAAY;AAC5C,QAAM,QAAQ,WAAW,UAAU,oBAAoB,gBAAgB;AACvE;;AAGF,KAAI,OAAO,OAAO;AAGhB,MAAI,MAAM,oBAAoB,OAAO,MAAM,CACzC;AAMF,MAAI,QAAQ,QAAQ,cAAc,qBAAqB,GAAG,GAAG;GAI3D,MAAM,+BAA+B,IAAI,kBACvC,QAAQ,SACR;IAME,cAAc;IACd,MAAM,YAAY,UAAU;AAC1B,WAAM,eAAe,SAAS;;IAEhC,MAAM,UAAU,QAAQ;;;;;;;;AAQtB,WAAM,QAAQ,WAAW,UAAU,OAAO;;IAE7C,CACF;AAED,SAAM,UAAU,QAAQ,SAAS,sBAAsB;IACrD,OAAO,OAAO;IACd,SAAS,QAAQ;IACjB,WAAW,QAAQ;IACnB,YAAY;IACb,CAAC;AAIF,OACE,6BAA6B,eAAe,kBAAkB,QAE9D;;AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAe,kBAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"hasConfigurableGlobal-BtHi5OlL.cjs","names":["#replacements","errors: Array<Error>","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map<object, Map<PropertyKey, () => void>>()\n\n public applyPatch<Owner extends object, K extends keyof Owner>(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array<Error> = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor<Owner extends object>(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";;;;AAEA,IAAM,kBAAN,MAAsB;CACpB,gCAAgB,IAAI,KAA2C;CAE/D,AAAO,WACL,OACA,KACA,cACY;EACZ,MAAM,oBAAoB,MAAKA,aAAc,IAAI,MAAM;AAEvD,4BACE,CAAC,mBAAmB,IAAI,IAAI,EAC5B,wCAAwC,OAAO,IAAI,CAAC,sBACrD;EAED,MAAM,QAAQ,0BAA0B,OAAO,IAAI;AAEnD,MAAI,OAAO,UAAU,aAAa;AAChC,WAAQ,KACN,wCAAwC,OAAO,IAAI,CAAC,wBACrD;AACD,gBAAa;;AAGf,SAAO,eAAe,OAAO,KAAK;GAChC,OAAO,aAAa,MAAM,KAAK;GAC/B,YAAY;GACZ,cAAc;GACf,CAAC;EAEF,MAAM,qBAAqB;GACzB,MAAM,sBAAsB,MAAKA,aAAc,IAAI,MAAM;AAEzD,OAAI,CAAC,qBAAqB,IAAI,IAAI,CAChC;AAGF,OAAI,MAAM,UAAU,MAClB,QAAO,eAAe,MAAM,OAAO,KAAK,MAAM,WAAW;;;;;;;AAOzD,WAAQ,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","names":["#replacements","errors: Array<Error>","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/patchesRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { invariant } from 'outvariant'\n\nclass PatchesRegistry {\n #replacements = new Map<object, Map<PropertyKey, () => void>>()\n\n public applyPatch<Owner extends object, K extends keyof Owner>(\n owner: Owner,\n key: K,\n getNextValue: (realValue: Owner[K]) => Owner[K]\n ): () => void {\n const ownerReplacements = this.#replacements.get(owner)\n\n invariant(\n !ownerReplacements?.has(key),\n `Failed to replace a global value at \"${String(key)}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(owner, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${String(key)}\": not a global value.`\n )\n return () => {}\n }\n\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n\n const restorePatch = () => {\n const currentReplacements = this.#replacements.get(owner)\n\n if (!currentReplacements?.has(key)) {\n return\n }\n\n if (match.owner === owner) {\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the match's owner isn't the original owner, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(owner, key)\n }\n\n currentReplacements.delete(key)\n\n if (currentReplacements.size === 0) {\n this.#replacements.delete(owner)\n }\n }\n\n if (ownerReplacements) {\n ownerReplacements.set(key, restorePatch)\n } else {\n this.#replacements.set(owner, new Map([[key, restorePatch]]))\n }\n\n return restorePatch\n }\n\n public restoreAllPatches(): void {\n const errors: Array<Error> = []\n\n for (const [, ownerReplacements] of this.#replacements) {\n for (const [, restorePatch] of ownerReplacements) {\n try {\n restorePatch()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const patchesRegistry = new PatchesRegistry()\n\ninterface DeepDescriptorMatch {\n owner: object\n descriptor: PropertyDescriptor\n}\n\n/**\n * Returns a property descriptor for the given property on the owner.\n * Walks down the prototype chain if the property does not exist on the owner.\n * Handy for getting a global property descriptor where `globalThis` is\n * replaced with a controlled class (e.g. ServiceWorkerGlobalScope).\n */\nexport function getDeepPropertyDescriptor<Owner extends object>(\n owner: Owner,\n key: keyof Owner\n): DeepDescriptorMatch | undefined {\n let currentOwner: Owner | null = owner\n let descriptor: PropertyDescriptor | undefined\n\n while (currentOwner) {\n descriptor = Object.getOwnPropertyDescriptor(currentOwner, key)\n\n if (descriptor) {\n return {\n owner: currentOwner,\n descriptor,\n }\n }\n\n currentOwner = Object.getPrototypeOf(currentOwner)\n }\n}\n","import { getDeepPropertyDescriptor } from './patchesRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";;;AAEA,IAAM,kBAAN,MAAsB;CACpB,gCAAgB,IAAI,KAA2C;CAE/D,AAAO,WACL,OACA,KACA,cACY;EACZ,MAAM,oBAAoB,MAAKA,aAAc,IAAI,MAAM;AAEvD,YACE,CAAC,mBAAmB,IAAI,IAAI,EAC5B,wCAAwC,OAAO,IAAI,CAAC,sBACrD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