@mswjs/interceptors 0.32.1 → 0.33.0

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 (121) hide show
  1. package/README.md +35 -7
  2. package/lib/browser/{chunk-732REFPX.mjs → chunk-5ETVT6GU.mjs} +28 -79
  3. package/lib/browser/chunk-5ETVT6GU.mjs.map +1 -0
  4. package/lib/browser/chunk-6MBJUL74.js +142 -0
  5. package/lib/browser/chunk-6MBJUL74.js.map +1 -0
  6. package/lib/browser/chunk-7A4UJNSW.mjs +196 -0
  7. package/lib/browser/chunk-7A4UJNSW.mjs.map +1 -0
  8. package/lib/browser/{chunk-PSX5J3RF.js → chunk-7GVJEW45.js} +30 -81
  9. package/lib/browser/chunk-7GVJEW45.js.map +1 -0
  10. package/lib/browser/{chunk-2CRB3JAQ.js → chunk-FXSPMSSQ.js} +1 -1
  11. package/lib/browser/chunk-FXSPMSSQ.js.map +1 -0
  12. package/lib/browser/{chunk-OMISYKWR.mjs → chunk-GGUENBDN.mjs} +1 -1
  13. package/lib/browser/chunk-GGUENBDN.mjs.map +1 -0
  14. package/lib/browser/chunk-NU2MPFD6.mjs +142 -0
  15. package/lib/browser/chunk-NU2MPFD6.mjs.map +1 -0
  16. package/lib/browser/chunk-VRKVKT62.js +196 -0
  17. package/lib/browser/chunk-VRKVKT62.js.map +1 -0
  18. package/lib/browser/glossary-7d7adb4b.d.ts +66 -0
  19. package/lib/browser/index.d.ts +1 -1
  20. package/lib/browser/index.js +2 -2
  21. package/lib/browser/index.mjs +1 -1
  22. package/lib/browser/interceptors/XMLHttpRequest/index.d.ts +2 -6
  23. package/lib/browser/interceptors/XMLHttpRequest/index.js +4 -4
  24. package/lib/browser/interceptors/XMLHttpRequest/index.mjs +3 -3
  25. package/lib/browser/interceptors/fetch/index.d.ts +1 -1
  26. package/lib/browser/interceptors/fetch/index.js +4 -4
  27. package/lib/browser/interceptors/fetch/index.mjs +3 -3
  28. package/lib/browser/presets/browser.d.ts +1 -1
  29. package/lib/browser/presets/browser.js +6 -6
  30. package/lib/browser/presets/browser.mjs +4 -4
  31. package/lib/node/{BatchInterceptor-2badedde.d.ts → BatchInterceptor-13d40c95.d.ts} +1 -1
  32. package/lib/node/{Interceptor-88ee47c0.d.ts → Interceptor-a31b1217.d.ts} +35 -13
  33. package/lib/node/RemoteHttpInterceptor.d.ts +2 -2
  34. package/lib/node/RemoteHttpInterceptor.js +55 -52
  35. package/lib/node/RemoteHttpInterceptor.js.map +1 -1
  36. package/lib/node/RemoteHttpInterceptor.mjs +53 -50
  37. package/lib/node/RemoteHttpInterceptor.mjs.map +1 -1
  38. package/lib/node/{chunk-5JMJ55U7.js → chunk-2MWIWEWV.js} +144 -113
  39. package/lib/node/chunk-2MWIWEWV.js.map +1 -0
  40. package/lib/node/{chunk-2COJKQQB.js → chunk-42632LKH.js} +3 -3
  41. package/lib/node/chunk-5WWNCLB3.js +196 -0
  42. package/lib/node/chunk-5WWNCLB3.js.map +1 -0
  43. package/lib/node/{chunk-TGTPXCLF.mjs → chunk-BUCULLYM.mjs} +1 -1
  44. package/lib/node/{chunk-TGTPXCLF.mjs.map → chunk-BUCULLYM.mjs.map} +1 -1
  45. package/lib/node/{chunk-OJ6O4LSC.mjs → chunk-BZ3Y7YV5.mjs} +1 -1
  46. package/lib/node/chunk-BZ3Y7YV5.mjs.map +1 -0
  47. package/lib/node/{chunk-3OJLYEWA.mjs → chunk-CU3YXMM4.mjs} +138 -107
  48. package/lib/node/chunk-CU3YXMM4.mjs.map +1 -0
  49. package/lib/node/{chunk-PNWPIDEL.mjs → chunk-HGQLG7KE.mjs} +2 -2
  50. package/lib/node/{chunk-EIBTX65O.js → chunk-IDEEMJ3F.js} +1 -1
  51. package/lib/node/chunk-IDEEMJ3F.js.map +1 -0
  52. package/lib/node/chunk-KY3RJ2M3.mjs +196 -0
  53. package/lib/node/chunk-KY3RJ2M3.mjs.map +1 -0
  54. package/lib/node/{chunk-PYD4E2EJ.js → chunk-P6QG76R3.js} +34 -85
  55. package/lib/node/chunk-P6QG76R3.js.map +1 -0
  56. package/lib/node/{chunk-DV4PBH4D.mjs → chunk-TOV4TYIX.mjs} +29 -80
  57. package/lib/node/chunk-TOV4TYIX.mjs.map +1 -0
  58. package/lib/node/{chunk-BFLYGQ6D.js → chunk-YGM3BCJU.js} +1 -1
  59. package/lib/node/chunk-YGM3BCJU.js.map +1 -0
  60. package/lib/node/index.d.ts +2 -2
  61. package/lib/node/index.js +4 -4
  62. package/lib/node/index.mjs +3 -3
  63. package/lib/node/interceptors/ClientRequest/index.d.ts +2 -2
  64. package/lib/node/interceptors/ClientRequest/index.js +4 -4
  65. package/lib/node/interceptors/ClientRequest/index.mjs +3 -3
  66. package/lib/node/interceptors/XMLHttpRequest/index.d.ts +2 -6
  67. package/lib/node/interceptors/XMLHttpRequest/index.js +5 -5
  68. package/lib/node/interceptors/XMLHttpRequest/index.mjs +4 -4
  69. package/lib/node/interceptors/fetch/index.d.ts +1 -1
  70. package/lib/node/interceptors/fetch/index.js +52 -123
  71. package/lib/node/interceptors/fetch/index.js.map +1 -1
  72. package/lib/node/interceptors/fetch/index.mjs +50 -121
  73. package/lib/node/interceptors/fetch/index.mjs.map +1 -1
  74. package/lib/node/presets/node.d.ts +1 -1
  75. package/lib/node/presets/node.js +7 -7
  76. package/lib/node/presets/node.mjs +5 -5
  77. package/package.json +2 -2
  78. package/src/InterceptorError.ts +7 -0
  79. package/src/RemoteHttpInterceptor.ts +62 -57
  80. package/src/RequestController.test.ts +49 -0
  81. package/src/RequestController.ts +81 -0
  82. package/src/glossary.ts +4 -6
  83. package/src/interceptors/ClientRequest/MockHttpSocket.ts +22 -16
  84. package/src/interceptors/ClientRequest/index.test.ts +2 -33
  85. package/src/interceptors/ClientRequest/index.ts +32 -82
  86. package/src/interceptors/ClientRequest/utils/recordRawHeaders.ts +170 -0
  87. package/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +1 -1
  88. package/src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts +27 -108
  89. package/src/interceptors/XMLHttpRequest/index.ts +0 -6
  90. package/src/interceptors/fetch/index.ts +52 -169
  91. package/src/utils/handleRequest.ts +213 -0
  92. package/src/utils/responseUtils.ts +4 -4
  93. package/lib/browser/chunk-2CRB3JAQ.js.map +0 -1
  94. package/lib/browser/chunk-732REFPX.mjs.map +0 -1
  95. package/lib/browser/chunk-MAEPOYB6.mjs +0 -213
  96. package/lib/browser/chunk-MAEPOYB6.mjs.map +0 -1
  97. package/lib/browser/chunk-MQJ3JOOK.js +0 -49
  98. package/lib/browser/chunk-MQJ3JOOK.js.map +0 -1
  99. package/lib/browser/chunk-OMISYKWR.mjs.map +0 -1
  100. package/lib/browser/chunk-OUWBQF3Z.mjs +0 -49
  101. package/lib/browser/chunk-OUWBQF3Z.mjs.map +0 -1
  102. package/lib/browser/chunk-PSX5J3RF.js.map +0 -1
  103. package/lib/browser/chunk-WBHIW62P.js +0 -213
  104. package/lib/browser/chunk-WBHIW62P.js.map +0 -1
  105. package/lib/browser/glossary-1c204f45.d.ts +0 -44
  106. package/lib/node/chunk-3OJLYEWA.mjs.map +0 -1
  107. package/lib/node/chunk-5JMJ55U7.js.map +0 -1
  108. package/lib/node/chunk-BFLYGQ6D.js.map +0 -1
  109. package/lib/node/chunk-DV4PBH4D.mjs.map +0 -1
  110. package/lib/node/chunk-EIBTX65O.js.map +0 -1
  111. package/lib/node/chunk-KWV3JXSI.mjs +0 -49
  112. package/lib/node/chunk-KWV3JXSI.mjs.map +0 -1
  113. package/lib/node/chunk-OJ6O4LSC.mjs.map +0 -1
  114. package/lib/node/chunk-PYD4E2EJ.js.map +0 -1
  115. package/lib/node/chunk-UXCYRE4F.js +0 -49
  116. package/lib/node/chunk-UXCYRE4F.js.map +0 -1
  117. package/src/utils/getRawFetchHeaders.test.ts +0 -50
  118. package/src/utils/getRawFetchHeaders.ts +0 -56
  119. package/src/utils/toInteractiveRequest.ts +0 -23
  120. /package/lib/node/{chunk-2COJKQQB.js.map → chunk-42632LKH.js.map} +0 -0
  121. /package/lib/node/{chunk-PNWPIDEL.mjs.map → chunk-HGQLG7KE.mjs.map} +0 -0
@@ -0,0 +1,213 @@
1
+ import type { Emitter } from 'strict-event-emitter'
2
+ import { DeferredPromise } from '@open-draft/deferred-promise'
3
+ import { until } from '@open-draft/until'
4
+ import type { HttpRequestEventMap } from '../glossary'
5
+ import { emitAsync } from './emitAsync'
6
+ import { kResponsePromise, RequestController } from '../RequestController'
7
+ import {
8
+ createServerErrorResponse,
9
+ isResponseError,
10
+ ResponseError,
11
+ } from './responseUtils'
12
+ import { InterceptorError } from '../InterceptorError'
13
+ import { isNodeLikeError } from './isNodeLikeError'
14
+
15
+ interface HandleRequestOptions {
16
+ requestId: string
17
+ request: Request
18
+ emitter: Emitter<HttpRequestEventMap>
19
+ controller: RequestController
20
+
21
+ /**
22
+ * Called when the request has been handled
23
+ * with the given `Response` instance.
24
+ */
25
+ onResponse: (response: Response) => void
26
+
27
+ /**
28
+ * Called when the request has been handled
29
+ * with the given `Response.error()` instance.
30
+ */
31
+ onRequestError: (response: ResponseError) => void
32
+
33
+ /**
34
+ * Called when an unhandled error happens during the
35
+ * request handling. This is never a thrown error/response.
36
+ */
37
+ onError: (error: unknown) => void
38
+ }
39
+
40
+ /**
41
+ * @returns {Promise<boolean>} Indicates whether the request has been handled.
42
+ */
43
+ export async function handleRequest(
44
+ options: HandleRequestOptions
45
+ ): Promise<boolean> {
46
+ const handleResponse = (response: Response | Error): true => {
47
+ if (response instanceof Error) {
48
+ options.onError(response)
49
+ }
50
+
51
+ // Handle "Response.error()" instances.
52
+ else if (isResponseError(response)) {
53
+ options.onRequestError(response)
54
+ } else {
55
+ options.onResponse(response)
56
+ }
57
+
58
+ return true
59
+ }
60
+
61
+ const handleResponseError = (error: unknown): boolean => {
62
+ // Forward the special interceptor error instances
63
+ // to the developer. These must not be handled in any way.
64
+ if (error instanceof InterceptorError) {
65
+ throw result.error
66
+ }
67
+
68
+ // Support mocking Node.js-like errors.
69
+ if (isNodeLikeError(error)) {
70
+ options.onError(error)
71
+ return true
72
+ }
73
+
74
+ // Handle thrown responses.
75
+ if (error instanceof Response) {
76
+ return handleResponse(error)
77
+ }
78
+
79
+ return false
80
+ }
81
+
82
+ // Add the last "request" listener to check if the request
83
+ // has been handled in any way. If it hasn't, resolve the
84
+ // response promise with undefined.
85
+ options.emitter.once('request', ({ requestId: pendingRequestId }) => {
86
+ if (pendingRequestId !== options.requestId) {
87
+ return
88
+ }
89
+
90
+ if (options.controller[kResponsePromise].state === 'pending') {
91
+ options.controller[kResponsePromise].resolve(undefined)
92
+ }
93
+ })
94
+
95
+ const requestAbortPromise = new DeferredPromise<void, unknown>()
96
+
97
+ /**
98
+ * @note `signal` is not always defined in React Native.
99
+ */
100
+ if (options.request.signal) {
101
+ options.request.signal.addEventListener(
102
+ 'abort',
103
+ () => {
104
+ requestAbortPromise.reject(options.request.signal.reason)
105
+ },
106
+ { once: true }
107
+ )
108
+ }
109
+
110
+ const result = await until(async () => {
111
+ // Emit the "request" event and wait until all the listeners
112
+ // for that event are finished (e.g. async listeners awaited).
113
+ // By the end of this promise, the developer cannot affect the
114
+ // request anymore.
115
+ const requestListtenersPromise = emitAsync(options.emitter, 'request', {
116
+ requestId: options.requestId,
117
+ request: options.request,
118
+ controller: options.controller,
119
+ })
120
+
121
+ await Promise.race([
122
+ // Short-circuit the request handling promise if the request gets aborted.
123
+ requestAbortPromise,
124
+ requestListtenersPromise,
125
+ options.controller[kResponsePromise],
126
+ ])
127
+
128
+ // The response promise will settle immediately once
129
+ // the developer calls either "respondWith" or "errorWith".
130
+ const mockedResponse = await options.controller[kResponsePromise]
131
+ return mockedResponse
132
+ })
133
+
134
+ // Handle the request being aborted while waiting for the request listeners.
135
+ if (requestAbortPromise.state === 'rejected') {
136
+ options.onError(requestAbortPromise.rejectionReason)
137
+ return true
138
+ }
139
+
140
+ if (result.error) {
141
+ // Handle the error during the request listener execution.
142
+ // These can be thrown responses or request errors.
143
+ if (handleResponseError(result.error)) {
144
+ return true
145
+ }
146
+
147
+ // If the developer has added "unhandledException" listeners,
148
+ // allow them to handle the error. They can translate it to a
149
+ // mocked response, network error, or forward it as-is.
150
+ if (options.emitter.listenerCount('unhandledException') > 0) {
151
+ // Create a new request controller just for the unhandled exception case.
152
+ // This is needed because the original controller might have been already
153
+ // interacted with (e.g. "respondWith" or "errorWith" called on it).
154
+ const unhandledExceptionController = new RequestController(
155
+ options.request
156
+ )
157
+
158
+ await emitAsync(options.emitter, 'unhandledException', {
159
+ error: result.error,
160
+ request: options.request,
161
+ requestId: options.requestId,
162
+ controller: unhandledExceptionController,
163
+ }).then(() => {
164
+ // If all the "unhandledException" listeners have finished
165
+ // but have not handled the response in any way, preemptively
166
+ // resolve the pending response promise from the new controller.
167
+ // This prevents it from hanging forever.
168
+ if (
169
+ unhandledExceptionController[kResponsePromise].state === 'pending'
170
+ ) {
171
+ unhandledExceptionController[kResponsePromise].resolve(undefined)
172
+ }
173
+ })
174
+
175
+ const nextResult = await until(
176
+ () => unhandledExceptionController[kResponsePromise]
177
+ )
178
+
179
+ /**
180
+ * @note Handle the result of the unhandled controller
181
+ * in the same way as the original request controller.
182
+ * The exception here is that thrown errors within the
183
+ * "unhandledException" event do NOT result in another
184
+ * emit of the same event. They are forwarded as-is.
185
+ */
186
+ if (nextResult.error) {
187
+ return handleResponseError(nextResult.error)
188
+ }
189
+
190
+ if (nextResult.data) {
191
+ return handleResponse(nextResult.data)
192
+ }
193
+ }
194
+
195
+ // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.
196
+ options.onResponse(createServerErrorResponse(result.error))
197
+ return true
198
+ }
199
+
200
+ /**
201
+ * Handle a mocked Response instance.
202
+ * @note That this can also be an Error in case
203
+ * the developer called "errorWith". This differentiates
204
+ * unhandled exceptions from intended errors.
205
+ */
206
+ if (result.data) {
207
+ return handleResponse(result.data)
208
+ }
209
+
210
+ // In all other cases, consider the request unhandled.
211
+ // The interceptor must perform it as-is.
212
+ return false
213
+ }
@@ -40,16 +40,16 @@ export function createServerErrorResponse(body: unknown): Response {
40
40
  )
41
41
  }
42
42
 
43
+ export type ResponseError = Response & { type: 'error' }
44
+
43
45
  /**
44
- * Checks if the given response is a `Response.error()`.
46
+ * Check if the given response is a `Response.error()`.
45
47
  *
46
48
  * @note Some environments, like Miniflare (Cloudflare) do not
47
49
  * implement the "Response.type" property and throw on its access.
48
50
  * Safely check if we can access "type" on "Response" before continuing.
49
51
  * @see https://github.com/mswjs/msw/issues/1834
50
52
  */
51
- export function isResponseError(
52
- response: Response
53
- ): response is Response & { type: 'error' } {
53
+ export function isResponseError(response: Response): response is ResponseError {
54
54
  return isPropertyAccessible(response, 'type') && response.type === 'error'
55
55
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/glossary.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts"],"names":[],"mappings":";AAEO,IAAM,oBAAmC,OAAO,iBAAiB;;;ACMjE,SAAS,qBACd,KACA,KACA;AACA,MAAI;AACF,QAAI,GAAG;AACP,WAAO;AAAA,EACT,SAAQ,GAAN;AACA,WAAO;AAAA,EACT;AACF;;;ACZO,IAAM,qCAAqC,oBAAI,IAAI;AAAA,EACxD;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AACtB,CAAC;AAMM,SAAS,sBAAsB,QAAyB;AAC7D,SAAO,mCAAmC,IAAI,MAAM;AACtD;AAKO,SAAS,0BAA0B,MAAyB;AACjE,SAAO,IAAI;AAAA,IACT,KAAK;AAAA,MACH,gBAAgB,QACZ;AAAA,QACE,MAAM,KAAK;AAAA,QACX,SAAS,KAAK;AAAA,QACd,OAAO,KAAK;AAAA,MACd,IACA;AAAA,IACN;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,SAAS;AAAA,QACP,gBAAgB;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AACF;AAUO,SAAS,gBACd,UAC0C;AAC1C,SAAO,qBAAqB,UAAU,MAAM,KAAK,SAAS,SAAS;AACrE","sourcesContent":["import type { InteractiveRequest } from './utils/toInteractiveRequest'\n\nexport const IS_PATCHED_MODULE: unique symbol = Symbol('isPatchedModule')\n\nexport type RequestCredentials = 'omit' | 'include' | 'same-origin'\n\nexport type HttpRequestEventMap = {\n request: [\n args: {\n request: InteractiveRequest\n requestId: string\n }\n ]\n response: [\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ]\n unhandledException: [\n args: {\n error: unknown\n request: Request\n requestId: string\n controller: {\n respondWith(response: Response): void\n errorWith(error?: Error): void\n }\n }\n ]\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 { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Response status codes for responses that cannot have body.\n * @see https://fetch.spec.whatwg.org/#statuses\n */\nexport const RESPONSE_STATUS_CODES_WITHOUT_BODY = new Set([\n 101, 103, 204, 205, 304,\n])\n\n/**\n * Returns a boolean indicating whether the given response status\n * code represents a response that cannot have a body.\n */\nexport function isResponseWithoutBody(status: number): boolean {\n return RESPONSE_STATUS_CODES_WITHOUT_BODY.has(status)\n}\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\n/**\n * Checks 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(\n response: Response\n): response is Response & { type: 'error' } {\n return isPropertyAccessible(response, 'type') && response.type === 'error'\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/interceptors/XMLHttpRequest/index.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts","../../src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts","../../src/interceptors/XMLHttpRequest/utils/concatArrayBuffer.ts","../../src/interceptors/XMLHttpRequest/polyfills/EventPolyfill.ts","../../src/interceptors/XMLHttpRequest/polyfills/ProgressEventPolyfill.ts","../../src/interceptors/XMLHttpRequest/utils/createEvent.ts","../../src/utils/findPropertySource.ts","../../src/utils/createProxy.ts","../../src/interceptors/XMLHttpRequest/utils/isDomParserSupportedType.ts","../../src/utils/parseJson.ts","../../src/interceptors/XMLHttpRequest/utils/createResponse.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { Emitter } from 'strict-event-emitter'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { InteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { Interceptor } from '../../Interceptor'\nimport { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'\n\nexport type XMLHttpRequestEventListener = (args: {\n request: InteractiveRequest\n requestId: string\n}) => Promise<void> | void\n\nexport type XMLHttpRequestEmitter = Emitter<HttpRequestEventMap>\n\nexport class XMLHttpRequestInterceptor extends Interceptor<HttpRequestEventMap> {\n static interceptorSymbol = Symbol('xhr')\n\n constructor() {\n super(XMLHttpRequestInterceptor.interceptorSymbol)\n }\n\n protected checkEnvironment() {\n return typeof globalThis.XMLHttpRequest !== 'undefined'\n }\n\n protected setup() {\n const logger = this.logger.extend('setup')\n\n logger.info('patching \"XMLHttpRequest\" module...')\n\n const PureXMLHttpRequest = globalThis.XMLHttpRequest\n\n invariant(\n !(PureXMLHttpRequest as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"XMLHttpRequest\" module: already patched.'\n )\n\n globalThis.XMLHttpRequest = createXMLHttpRequestProxy({\n emitter: this.emitter,\n logger: this.logger,\n })\n\n logger.info(\n 'native \"XMLHttpRequest\" module patched!',\n globalThis.XMLHttpRequest.name\n )\n\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.XMLHttpRequest, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.XMLHttpRequest = PureXMLHttpRequest\n logger.info(\n 'native \"XMLHttpRequest\" module restored!',\n globalThis.XMLHttpRequest.name\n )\n })\n }\n}\n","import { until } from '@open-draft/until'\nimport type { Logger } from '@open-draft/logger'\nimport { XMLHttpRequestEmitter } from '.'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { XMLHttpRequestController } from './XMLHttpRequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\n\nexport interface XMLHttpRequestProxyOptions {\n emitter: XMLHttpRequestEmitter\n logger: Logger\n}\n\n/**\n * Create a proxied `XMLHttpRequest` class.\n * The proxied class establishes spies on certain methods,\n * allowing us to intercept requests and respond to them.\n */\nexport function createXMLHttpRequestProxy({\n emitter,\n logger,\n}: XMLHttpRequestProxyOptions) {\n const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {\n construct(target, args, newTarget) {\n logger.info('constructed new XMLHttpRequest')\n\n const originalRequest = Reflect.construct(\n target,\n args,\n newTarget\n ) as XMLHttpRequest\n\n /**\n * @note Forward prototype descriptors onto the proxied object.\n * XMLHttpRequest is implemented in JSDOM in a way that assigns\n * a bunch of descriptors, like \"set responseType()\" on the prototype.\n * With this propagation, we make sure that those descriptors trigger\n * when the user operates with the proxied request instance.\n */\n const prototypeDescriptors = Object.getOwnPropertyDescriptors(\n target.prototype\n )\n for (const propertyName in prototypeDescriptors) {\n Reflect.defineProperty(\n originalRequest,\n propertyName,\n prototypeDescriptors[propertyName]\n )\n }\n\n const xhrRequestController = new XMLHttpRequestController(\n originalRequest,\n logger\n )\n\n xhrRequestController.onRequest = async function ({ request, requestId }) {\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info('awaiting mocked response...')\n\n emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.respondWith(undefined)\n }\n })\n\n const resolverResult = await until(async () => {\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n emitter.listenerCount('request')\n )\n\n await emitAsync(emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n this.logger.info('all \"request\" listeners settled!')\n\n const mockedResponse = await requestController.responsePromise\n\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n })\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listener threw an exception, aborting request...',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n if (isResponseError(resolverResult.error)) {\n xhrRequestController.errorWith(new TypeError('Network error'))\n } else {\n this.respondWith(resolverResult.error)\n }\n\n return\n }\n\n if (emitter.listenerCount('unhandledException') > 0) {\n // Emit the \"unhandledException\" event so the client can opt-out\n // from the default exception handling (producing 500 error responses).\n await emitAsync(emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith:\n xhrRequestController.respondWith.bind(xhrRequestController),\n errorWith:\n xhrRequestController.errorWith.bind(xhrRequestController),\n },\n })\n\n // If any of the \"unhandledException\" listeners handled the request,\n // do nothing. Note that mocked responses will dispatch\n // HEADERS_RECEIVED (2), then LOADING (3), and DONE (4) can take\n // time as the mocked response body finishes streaming.\n if (originalRequest.readyState > XMLHttpRequest.OPENED) {\n return\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n xhrRequestController.respondWith(\n createServerErrorResponse(resolverResult.error)\n )\n\n return\n }\n\n const mockedResponse = resolverResult.data\n\n if (typeof mockedResponse !== 'undefined') {\n this.logger.info(\n 'received mocked response: %d %s',\n mockedResponse.status,\n mockedResponse.statusText\n )\n\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n xhrRequestController.errorWith(new TypeError('Network error'))\n return\n }\n\n return xhrRequestController.respondWith(mockedResponse)\n }\n\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n }\n\n xhrRequestController.onResponse = async function ({\n response,\n isMockedResponse,\n request,\n requestId,\n }) {\n this.logger.info(\n 'emitting the \"response\" event for %s listener(s)...',\n emitter.listenerCount('response')\n )\n\n emitter.emit('response', {\n response,\n isMockedResponse,\n request,\n requestId,\n })\n }\n\n // Return the proxied request from the controller\n // so that the controller can react to the consumer's interactions\n // with this request (opening/sending/etc).\n return xhrRequestController.request\n },\n })\n\n return XMLHttpRequestProxy\n}\n","import { invariant } from 'outvariant'\nimport { isNodeProcess } from 'is-node-process'\nimport type { Logger } from '@open-draft/logger'\nimport { concatArrayBuffer } from './utils/concatArrayBuffer'\nimport { createEvent } from './utils/createEvent'\nimport {\n decodeBuffer,\n encodeBuffer,\n toArrayBuffer,\n} from '../../utils/bufferUtils'\nimport { createProxy } from '../../utils/createProxy'\nimport { isDomParserSupportedType } from './utils/isDomParserSupportedType'\nimport { parseJson } from '../../utils/parseJson'\nimport { createResponse } from './utils/createResponse'\nimport { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'\nimport { createRequestId } from '../../createRequestId'\n\nconst IS_MOCKED_RESPONSE = Symbol('isMockedResponse')\nconst IS_NODE = isNodeProcess()\n\n/**\n * An `XMLHttpRequest` instance controller that allows us\n * to handle any given request instance (e.g. responding to it).\n */\nexport class XMLHttpRequestController {\n public request: XMLHttpRequest\n public requestId: string\n public onRequest?: (\n this: XMLHttpRequestController,\n args: {\n request: Request\n requestId: string\n }\n ) => Promise<void>\n public onResponse?: (\n this: XMLHttpRequestController,\n args: {\n response: Response\n isMockedResponse: boolean\n request: Request\n requestId: string\n }\n ) => void\n\n private method: string = 'GET'\n private url: URL = null as any\n private requestHeaders: Headers\n private requestBody?: XMLHttpRequestBodyInit | Document | null\n private responseBuffer: Uint8Array\n private events: Map<keyof XMLHttpRequestEventTargetEventMap, Array<Function>>\n\n constructor(readonly initialRequest: XMLHttpRequest, public logger: Logger) {\n this.events = new Map()\n this.requestId = createRequestId()\n this.requestHeaders = new Headers()\n this.responseBuffer = new Uint8Array()\n\n this.request = createProxy(initialRequest, {\n setProperty: ([propertyName, nextValue], invoke) => {\n switch (propertyName) {\n case 'ontimeout': {\n const eventName = propertyName.slice(\n 2\n ) as keyof XMLHttpRequestEventTargetEventMap\n\n /**\n * @note Proxy callbacks to event listeners because JSDOM has trouble\n * translating these properties to callbacks. It seemed to be operating\n * on events exclusively.\n */\n this.request.addEventListener(eventName, nextValue as any)\n\n return invoke()\n }\n\n default: {\n return invoke()\n }\n }\n },\n methodCall: ([methodName, args], invoke) => {\n switch (methodName) {\n case 'open': {\n const [method, url] = args as [string, string | undefined]\n\n if (typeof url === 'undefined') {\n this.method = 'GET'\n this.url = toAbsoluteUrl(method)\n } else {\n this.method = method\n this.url = toAbsoluteUrl(url)\n }\n\n this.logger = this.logger.extend(`${this.method} ${this.url.href}`)\n this.logger.info('open', this.method, this.url.href)\n\n return invoke()\n }\n\n case 'addEventListener': {\n const [eventName, listener] = args as [\n keyof XMLHttpRequestEventTargetEventMap,\n Function\n ]\n\n this.registerEvent(eventName, listener)\n this.logger.info('addEventListener', eventName, listener)\n\n return invoke()\n }\n\n case 'setRequestHeader': {\n const [name, value] = args as [string, string]\n this.requestHeaders.set(name, value)\n\n this.logger.info('setRequestHeader', name, value)\n\n return invoke()\n }\n\n case 'send': {\n const [body] = args as [\n body?: XMLHttpRequestBodyInit | Document | null\n ]\n\n if (body != null) {\n this.requestBody =\n typeof body === 'string' ? encodeBuffer(body) : body\n }\n\n this.request.addEventListener('load', () => {\n if (typeof this.onResponse !== 'undefined') {\n // Create a Fetch API Response representation of whichever\n // response this XMLHttpRequest received. Note those may\n // be either a mocked and the original response.\n const fetchResponse = createResponse(\n this.request,\n /**\n * The `response` property is the right way to read\n * the ambiguous response body, as the request's \"responseType\" may differ.\n * @see https://xhr.spec.whatwg.org/#the-response-attribute\n */\n this.request.response\n )\n\n // Notify the consumer about the response.\n this.onResponse.call(this, {\n response: fetchResponse,\n isMockedResponse: IS_MOCKED_RESPONSE in this.request,\n request: fetchRequest,\n requestId: this.requestId!,\n })\n }\n })\n\n // Delegate request handling to the consumer.\n const fetchRequest = this.toFetchApiRequest()\n const onceRequestSettled =\n this.onRequest?.call(this, {\n request: fetchRequest,\n requestId: this.requestId!,\n }) || Promise.resolve()\n\n onceRequestSettled.finally(() => {\n // If the consumer didn't handle the request perform it as-is.\n // Note that the request may not yet be DONE and may, in fact,\n // be LOADING while the \"respondWith\" method does its magic.\n if (this.request.readyState < this.request.LOADING) {\n this.logger.info(\n 'request callback settled but request has not been handled (readystate %d), performing as-is...',\n this.request.readyState\n )\n\n /**\n * @note Set the intercepted request ID on the original request in Node.js\n * so that if it triggers any other interceptors, they don't attempt\n * to process it once again.\n *\n * For instance, XMLHttpRequest is often implemented via \"http.ClientRequest\"\n * and we don't want for both XHR and ClientRequest interceptors to\n * handle the same request at the same time (e.g. emit the \"response\" event twice).\n */\n if (IS_NODE) {\n this.request.setRequestHeader(\n INTERNAL_REQUEST_ID_HEADER_NAME,\n this.requestId!\n )\n }\n\n return invoke()\n }\n })\n\n break\n }\n\n default: {\n return invoke()\n }\n }\n },\n })\n }\n\n private registerEvent(\n eventName: keyof XMLHttpRequestEventTargetEventMap,\n listener: Function\n ): void {\n const prevEvents = this.events.get(eventName) || []\n const nextEvents = prevEvents.concat(listener)\n this.events.set(eventName, nextEvents)\n\n this.logger.info('registered event \"%s\"', eventName, listener)\n }\n\n /**\n * Responds to the current request with the given\n * Fetch API `Response` instance.\n */\n public respondWith(response: Response): void {\n this.logger.info(\n 'responding with a mocked response: %d %s',\n response.status,\n response.statusText\n )\n\n /**\n * @note Since `XMLHttpRequestController` delegates the handling of the responses\n * to the \"load\" event listener that doesn't distinguish between the mocked and original\n * responses, mark the request that had a mocked response with a corresponding symbol.\n */\n define(this.request, IS_MOCKED_RESPONSE, true)\n\n define(this.request, 'status', response.status)\n define(this.request, 'statusText', response.statusText)\n define(this.request, 'responseURL', this.url.href)\n\n this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {\n apply: (_, __, args: [name: string]) => {\n this.logger.info('getResponseHeader', args[0])\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning null')\n\n // Headers not received yet, nothing to return.\n return null\n }\n\n const headerValue = response.headers.get(args[0])\n this.logger.info(\n 'resolved response header \"%s\" to',\n args[0],\n headerValue\n )\n\n return headerValue\n },\n })\n\n this.request.getAllResponseHeaders = new Proxy(\n this.request.getAllResponseHeaders,\n {\n apply: () => {\n this.logger.info('getAllResponseHeaders')\n\n if (this.request.readyState < this.request.HEADERS_RECEIVED) {\n this.logger.info('headers not received yet, returning empty string')\n\n // Headers not received yet, nothing to return.\n return ''\n }\n\n const headersList = Array.from(response.headers.entries())\n const allHeaders = headersList\n .map(([headerName, headerValue]) => {\n return `${headerName}: ${headerValue}`\n })\n .join('\\r\\n')\n\n this.logger.info('resolved all response headers to', allHeaders)\n\n return allHeaders\n },\n }\n )\n\n // Update the response getters to resolve against the mocked response.\n Object.defineProperties(this.request, {\n response: {\n enumerable: true,\n configurable: false,\n get: () => this.response,\n },\n responseText: {\n enumerable: true,\n configurable: false,\n get: () => this.responseText,\n },\n responseXML: {\n enumerable: true,\n configurable: false,\n get: () => this.responseXML,\n },\n })\n\n const totalResponseBodyLength = response.headers.has('Content-Length')\n ? Number(response.headers.get('Content-Length'))\n : /**\n * @todo Infer the response body length from the response body.\n */\n undefined\n\n this.logger.info('calculated response body length', totalResponseBodyLength)\n\n this.trigger('loadstart', {\n loaded: 0,\n total: totalResponseBodyLength,\n })\n\n this.setReadyState(this.request.HEADERS_RECEIVED)\n this.setReadyState(this.request.LOADING)\n\n const finalizeResponse = () => {\n this.logger.info('finalizing the mocked response...')\n\n this.setReadyState(this.request.DONE)\n\n this.trigger('load', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n\n this.trigger('loadend', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n if (response.body) {\n this.logger.info('mocked response has body, streaming...')\n\n const reader = response.body.getReader()\n\n const readNextResponseBodyChunk = async () => {\n const { value, done } = await reader.read()\n\n if (done) {\n this.logger.info('response body stream done!')\n finalizeResponse()\n return\n }\n\n if (value) {\n this.logger.info('read response body chunk:', value)\n this.responseBuffer = concatArrayBuffer(this.responseBuffer, value)\n\n this.trigger('progress', {\n loaded: this.responseBuffer.byteLength,\n total: totalResponseBodyLength,\n })\n }\n\n readNextResponseBodyChunk()\n }\n\n readNextResponseBodyChunk()\n } else {\n finalizeResponse()\n }\n }\n\n private responseBufferToText(): string {\n return decodeBuffer(this.responseBuffer)\n }\n\n get response(): unknown {\n this.logger.info(\n 'getResponse (responseType: %s)',\n this.request.responseType\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n switch (this.request.responseType) {\n case 'json': {\n const responseJson = parseJson(this.responseBufferToText())\n this.logger.info('resolved response JSON', responseJson)\n\n return responseJson\n }\n\n case 'arraybuffer': {\n const arrayBuffer = toArrayBuffer(this.responseBuffer)\n this.logger.info('resolved response ArrayBuffer', arrayBuffer)\n\n return arrayBuffer\n }\n\n case 'blob': {\n const mimeType =\n this.request.getResponseHeader('Content-Type') || 'text/plain'\n const responseBlob = new Blob([this.responseBufferToText()], {\n type: mimeType,\n })\n\n this.logger.info(\n 'resolved response Blob (mime type: %s)',\n responseBlob,\n mimeType\n )\n\n return responseBlob\n }\n\n default: {\n const responseText = this.responseBufferToText()\n this.logger.info(\n 'resolving \"%s\" response type as text',\n this.request.responseType,\n responseText\n )\n\n return responseText\n }\n }\n }\n\n get responseText(): string {\n /**\n * Throw when trying to read the response body as text when the\n * \"responseType\" doesn't expect text. This just respects the spec better.\n * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute\n */\n invariant(\n this.request.responseType === '' || this.request.responseType === 'text',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (\n this.request.readyState !== this.request.LOADING &&\n this.request.readyState !== this.request.DONE\n ) {\n return ''\n }\n\n const responseText = this.responseBufferToText()\n this.logger.info('getResponseText: \"%s\"', responseText)\n\n return responseText\n }\n\n get responseXML(): Document | null {\n invariant(\n this.request.responseType === '' ||\n this.request.responseType === 'document',\n 'InvalidStateError: The object is in invalid state.'\n )\n\n if (this.request.readyState !== this.request.DONE) {\n return null\n }\n\n const contentType = this.request.getResponseHeader('Content-Type') || ''\n\n if (typeof DOMParser === 'undefined') {\n console.warn(\n 'Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.'\n )\n return null\n }\n\n if (isDomParserSupportedType(contentType)) {\n return new DOMParser().parseFromString(\n this.responseBufferToText(),\n contentType\n )\n }\n\n return null\n }\n\n public errorWith(error: Error): void {\n this.logger.info('responding with an error')\n\n this.setReadyState(this.request.DONE)\n this.trigger('error')\n this.trigger('loadend')\n }\n\n /**\n * Transitions this request's `readyState` to the given one.\n */\n private setReadyState(nextReadyState: number): void {\n this.logger.info(\n 'setReadyState: %d -> %d',\n this.request.readyState,\n nextReadyState\n )\n\n if (this.request.readyState === nextReadyState) {\n this.logger.info('ready state identical, skipping transition...')\n return\n }\n\n define(this.request, 'readyState', nextReadyState)\n\n this.logger.info('set readyState to: %d', nextReadyState)\n\n if (nextReadyState !== this.request.UNSENT) {\n this.logger.info('triggerring \"readystatechange\" event...')\n\n this.trigger('readystatechange')\n }\n }\n\n /**\n * Triggers given event on the `XMLHttpRequest` instance.\n */\n private trigger<\n EventName extends keyof (XMLHttpRequestEventTargetEventMap & {\n readystatechange: ProgressEvent<XMLHttpRequestEventTarget>\n })\n >(eventName: EventName, options?: ProgressEventInit): void {\n const callback = this.request[`on${eventName}`]\n const event = createEvent(this.request, eventName, options)\n\n this.logger.info('trigger \"%s\"', eventName, options || '')\n\n // Invoke direct callbacks.\n if (typeof callback === 'function') {\n this.logger.info('found a direct \"%s\" callback, calling...', eventName)\n callback.call(this.request, event)\n }\n\n // Invoke event listeners.\n for (const [registeredEventName, listeners] of this.events) {\n if (registeredEventName === eventName) {\n this.logger.info(\n 'found %d listener(s) for \"%s\" event, calling...',\n listeners.length,\n eventName\n )\n\n listeners.forEach((listener) => listener.call(this.request, event))\n }\n }\n }\n\n /**\n * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.\n */\n public toFetchApiRequest(): Request {\n this.logger.info('converting request to a Fetch API Request...')\n\n const fetchRequest = new Request(this.url.href, {\n method: this.method,\n headers: this.requestHeaders,\n /**\n * @see https://xhr.spec.whatwg.org/#cross-origin-credentials\n */\n credentials: this.request.withCredentials ? 'include' : 'same-origin',\n body: ['GET', 'HEAD'].includes(this.method)\n ? null\n : (this.requestBody as BodyInit),\n })\n\n const proxyHeaders = createProxy(fetchRequest.headers, {\n methodCall: ([methodName, args], invoke) => {\n // Forward the latest state of the internal request headers\n // because the interceptor might have modified them\n // without responding to the request.\n switch (methodName) {\n case 'append':\n case 'set': {\n const [headerName, headerValue] = args as [string, string]\n this.request.setRequestHeader(headerName, headerValue)\n break\n }\n\n case 'delete': {\n const [headerName] = args as [string]\n console.warn(\n `XMLHttpRequest: Cannot remove a \"${headerName}\" header from the Fetch API representation of the \"${fetchRequest.method} ${fetchRequest.url}\" request. XMLHttpRequest headers cannot be removed.`\n )\n break\n }\n }\n\n return invoke()\n },\n })\n define(fetchRequest, 'headers', proxyHeaders)\n\n this.logger.info('converted request to a Fetch API Request!', fetchRequest)\n\n return fetchRequest\n }\n}\n\nfunction toAbsoluteUrl(url: string | URL): URL {\n /**\n * @note XMLHttpRequest interceptor may run in environments\n * that implement XMLHttpRequest but don't implement \"location\"\n * (for example, React Native). If that's the case, return the\n * input URL as-is (nothing to be relative to).\n * @see https://github.com/mswjs/msw/issues/1777\n */\n if (typeof location === 'undefined') {\n return new URL(url)\n }\n\n return new URL(url.toString(), location.href)\n}\n\nfunction define(\n target: object,\n property: string | symbol,\n value: unknown\n): void {\n Reflect.defineProperty(target, property, {\n // Ensure writable properties to allow redefining readonly properties.\n writable: true,\n enumerable: true,\n value,\n })\n}\n","/**\n * Concatenate two `Uint8Array` buffers.\n */\nexport function concatArrayBuffer(\n left: Uint8Array,\n right: Uint8Array\n): Uint8Array {\n const result = new Uint8Array(left.byteLength + right.byteLength)\n result.set(left, 0)\n result.set(right, left.byteLength)\n return result\n}\n","export class EventPolyfill implements Event {\n readonly AT_TARGET: number = 0\n readonly BUBBLING_PHASE: number = 0\n readonly CAPTURING_PHASE: number = 0\n readonly NONE: number = 0\n\n public type: string = ''\n public srcElement: EventTarget | null = null\n public target: EventTarget | null\n public currentTarget: EventTarget | null = null\n public eventPhase: number = 0\n public timeStamp: number\n public isTrusted: boolean = true\n public composed: boolean = false\n public cancelable: boolean = true\n public defaultPrevented: boolean = false\n public bubbles: boolean = true\n public lengthComputable: boolean = true\n public loaded: number = 0\n public total: number = 0\n\n cancelBubble: boolean = false\n returnValue: boolean = true\n\n constructor(\n type: string,\n options?: { target: EventTarget; currentTarget: EventTarget }\n ) {\n this.type = type\n this.target = options?.target || null\n this.currentTarget = options?.currentTarget || null\n this.timeStamp = Date.now()\n }\n\n public composedPath(): EventTarget[] {\n return []\n }\n\n public initEvent(type: string, bubbles?: boolean, cancelable?: boolean) {\n this.type = type\n this.bubbles = !!bubbles\n this.cancelable = !!cancelable\n }\n\n public preventDefault() {\n this.defaultPrevented = true\n }\n\n public stopPropagation() {}\n public stopImmediatePropagation() {}\n}\n","import { EventPolyfill } from './EventPolyfill'\n\nexport class ProgressEventPolyfill extends EventPolyfill {\n readonly lengthComputable: boolean\n readonly composed: boolean\n readonly loaded: number\n readonly total: number\n\n constructor(type: string, init?: ProgressEventInit) {\n super(type)\n\n this.lengthComputable = init?.lengthComputable || false\n this.composed = init?.composed || false\n this.loaded = init?.loaded || 0\n this.total = init?.total || 0\n }\n}\n","import { EventPolyfill } from '../polyfills/EventPolyfill'\nimport { ProgressEventPolyfill } from '../polyfills/ProgressEventPolyfill'\n\nconst SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined'\n\nexport function createEvent(\n target: XMLHttpRequest,\n type: string,\n init?: ProgressEventInit\n): EventPolyfill {\n const progressEvents = [\n 'error',\n 'progress',\n 'loadstart',\n 'loadend',\n 'load',\n 'timeout',\n 'abort',\n ]\n\n /**\n * `ProgressEvent` is not supported in React Native.\n * @see https://github.com/mswjs/interceptors/issues/40\n */\n const ProgressEventClass = SUPPORTS_PROGRESS_EVENT\n ? ProgressEvent\n : ProgressEventPolyfill\n\n const event = progressEvents.includes(type)\n ? new ProgressEventClass(type, {\n lengthComputable: true,\n loaded: init?.loaded || 0,\n total: init?.total || 0,\n })\n : new EventPolyfill(type, {\n target,\n currentTarget: target,\n })\n\n return event\n}\n","/**\n * Returns the source object of the given property on the target object\n * (the target itself, any parent in its prototype, or null).\n */\nexport function findPropertySource(\n target: object,\n propertyName: string | symbol\n): object | null {\n if (!(propertyName in target)) {\n return null\n }\n\n const hasProperty = Object.prototype.hasOwnProperty.call(target, propertyName)\n if (hasProperty) {\n return target\n }\n\n const prototype = Reflect.getPrototypeOf(target)\n return prototype ? findPropertySource(prototype, propertyName) : null\n}\n","import { findPropertySource } from './findPropertySource'\n\nexport interface ProxyOptions<Target extends Record<string, any>> {\n constructorCall?(args: Array<unknown>, next: NextFunction<Target>): Target\n\n methodCall?<F extends keyof Target>(\n this: Target,\n data: [methodName: F, args: Array<unknown>],\n next: NextFunction<void>\n ): void\n\n setProperty?(\n data: [propertyName: string | symbol, nextValue: unknown],\n next: NextFunction<boolean>\n ): boolean\n\n getProperty?(\n data: [propertyName: string | symbol, receiver: Target],\n next: NextFunction<void>\n ): void\n}\n\nexport type NextFunction<ReturnType> = () => ReturnType\n\nexport function createProxy<Target extends object>(\n target: Target,\n options: ProxyOptions<Target>\n): Target {\n const proxy = new Proxy(target, optionsToProxyHandler(options))\n\n return proxy\n}\n\nfunction optionsToProxyHandler<T extends Record<string, any>>(\n options: ProxyOptions<T>\n): ProxyHandler<T> {\n const { constructorCall, methodCall, getProperty, setProperty } = options\n const handler: ProxyHandler<T> = {}\n\n if (typeof constructorCall !== 'undefined') {\n handler.construct = function (target, args, newTarget) {\n const next = Reflect.construct.bind(null, target as any, args, newTarget)\n return constructorCall.call(newTarget, args, next)\n }\n }\n\n handler.set = function (target, propertyName, nextValue) {\n const next = () => {\n const propertySource = findPropertySource(target, propertyName) || target\n const ownDescriptors = Reflect.getOwnPropertyDescriptor(\n propertySource,\n propertyName\n )\n\n // Respect any custom setters present for this property.\n if (typeof ownDescriptors?.set !== 'undefined') {\n ownDescriptors.set.apply(target, [nextValue])\n return true\n }\n\n // Otherwise, set the property on the source.\n return Reflect.defineProperty(propertySource, propertyName, {\n writable: true,\n enumerable: true,\n configurable: true,\n value: nextValue,\n })\n }\n\n if (typeof setProperty !== 'undefined') {\n return setProperty.call(target, [propertyName, nextValue], next)\n }\n\n return next()\n }\n\n handler.get = function (target, propertyName, receiver) {\n /**\n * @note Using `Reflect.get()` here causes \"TypeError: Illegal invocation\".\n */\n const next = () => target[propertyName as any]\n\n const value =\n typeof getProperty !== 'undefined'\n ? getProperty.call(target, [propertyName, receiver], next)\n : next()\n\n if (typeof value === 'function') {\n return (...args: Array<any>) => {\n const next = value.bind(target, ...args)\n\n if (typeof methodCall !== 'undefined') {\n return methodCall.call(target, [propertyName as any, args], next)\n }\n\n return next()\n }\n }\n\n return value\n }\n\n return handler\n}\n","export function isDomParserSupportedType(\n type: string\n): type is DOMParserSupportedType {\n const supportedTypes: Array<DOMParserSupportedType> = [\n 'application/xhtml+xml',\n 'application/xml',\n 'image/svg+xml',\n 'text/html',\n 'text/xml',\n ]\n return supportedTypes.some((supportedType) => {\n return type.startsWith(supportedType)\n })\n}\n","/**\n * Parses a given string into JSON.\n * Gracefully handles invalid JSON by returning `null`.\n */\nexport function parseJson(data: string): Record<string, unknown> | null {\n try {\n const json = JSON.parse(data)\n return json\n } catch (_) {\n return null\n }\n}\n","import { isResponseWithoutBody } from '../../../utils/responseUtils'\n\n/**\n * Creates a Fetch API `Response` instance from the given\n * `XMLHttpRequest` instance and a response body.\n */\nexport function createResponse(\n request: XMLHttpRequest,\n body: BodyInit | null\n): Response {\n /**\n * Handle XMLHttpRequest responses that must have null as the\n * response body when represented using Fetch API Response.\n * XMLHttpRequest response will always have an empty string\n * as the \"request.response\" in those cases, resulting in an error\n * when constructing a Response instance.\n * @see https://github.com/mswjs/interceptors/issues/379\n */\n const responseBodyOrNull = isResponseWithoutBody(request.status) ? null : body\n\n return new Response(responseBodyOrNull, {\n status: request.status,\n statusText: request.statusText,\n headers: createHeadersFromXMLHttpReqestHeaders(\n request.getAllResponseHeaders()\n ),\n })\n}\n\nfunction createHeadersFromXMLHttpReqestHeaders(headersString: string): Headers {\n const headers = new Headers()\n\n const lines = headersString.split(/[\\r\\n]+/)\n for (const line of lines) {\n if (line.trim() === '') {\n continue\n }\n\n const [name, ...parts] = line.split(': ')\n const value = parts.join(': ')\n\n headers.append(name, value)\n }\n\n return headers\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,aAAa;;;ACAtB,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;;;ACEvB,SAAS,kBACd,MACA,OACY;AACZ,QAAM,SAAS,IAAI,WAAW,KAAK,aAAa,MAAM,UAAU;AAChE,SAAO,IAAI,MAAM,CAAC;AAClB,SAAO,IAAI,OAAO,KAAK,U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+0,0 @@
1
- import {
2
- emitAsync,
3
- toInteractiveRequest
4
- } from "./chunk-OUWBQF3Z.mjs";
5
- import {
6
- IS_PATCHED_MODULE,
7
- createServerErrorResponse,
8
- isResponseError
9
- } from "./chunk-OMISYKWR.mjs";
10
- import {
11
- Interceptor,
12
- createRequestId
13
- } from "./chunk-QED3Q6Z2.mjs";
14
-
15
- // src/interceptors/fetch/index.ts
16
- import { invariant } from "outvariant";
17
- import { DeferredPromise } from "@open-draft/deferred-promise";
18
- import { until } from "@open-draft/until";
19
-
20
- // src/utils/canParseUrl.ts
21
- function canParseUrl(url) {
22
- try {
23
- new URL(url);
24
- return true;
25
- } catch (_error) {
26
- return false;
27
- }
28
- }
29
-
30
- // src/interceptors/fetch/index.ts
31
- var _FetchInterceptor = class extends Interceptor {
32
- constructor() {
33
- super(_FetchInterceptor.symbol);
34
- }
35
- checkEnvironment() {
36
- return typeof globalThis !== "undefined" && typeof globalThis.fetch !== "undefined";
37
- }
38
- async setup() {
39
- const pureFetch = globalThis.fetch;
40
- invariant(
41
- !pureFetch[IS_PATCHED_MODULE],
42
- 'Failed to patch the "fetch" module: already patched.'
43
- );
44
- globalThis.fetch = async (input, init) => {
45
- var _a;
46
- const requestId = createRequestId();
47
- const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.origin) : input;
48
- const request = new Request(resolvedInput, init);
49
- this.logger.info("[%s] %s", request.method, request.url);
50
- const { interactiveRequest, requestController } = toInteractiveRequest(request);
51
- this.logger.info(
52
- 'emitting the "request" event for %d listener(s)...',
53
- this.emitter.listenerCount("request")
54
- );
55
- this.emitter.once("request", ({ requestId: pendingRequestId }) => {
56
- if (pendingRequestId !== requestId) {
57
- return;
58
- }
59
- if (requestController.responsePromise.state === "pending") {
60
- requestController.responsePromise.resolve(void 0);
61
- }
62
- });
63
- this.logger.info("awaiting for the mocked response...");
64
- const signal = interactiveRequest.signal;
65
- const requestAborted = new DeferredPromise();
66
- if (signal) {
67
- signal.addEventListener(
68
- "abort",
69
- () => {
70
- requestAborted.reject(signal.reason);
71
- },
72
- { once: true }
73
- );
74
- }
75
- const responsePromise = new DeferredPromise();
76
- const respondWith = (response) => {
77
- this.logger.info("responding with a mock response:", response);
78
- if (this.emitter.listenerCount("response") > 0) {
79
- this.logger.info('emitting the "response" event...');
80
- const responseClone = response.clone();
81
- this.emitter.emit("response", {
82
- response: responseClone,
83
- isMockedResponse: true,
84
- request: interactiveRequest,
85
- requestId
86
- });
87
- }
88
- Object.defineProperty(response, "url", {
89
- writable: false,
90
- enumerable: true,
91
- configurable: false,
92
- value: request.url
93
- });
94
- responsePromise.resolve(response);
95
- };
96
- const errorWith = (reason) => {
97
- responsePromise.reject(reason);
98
- };
99
- const resolverResult = await until(
100
- async () => {
101
- const listenersFinished = emitAsync(this.emitter, "request", {
102
- request: interactiveRequest,
103
- requestId
104
- });
105
- await Promise.race([
106
- requestAborted,
107
- // Put the listeners invocation Promise in the same race condition
108
- // with the request abort Promise because otherwise awaiting the listeners
109
- // would always yield some response (or undefined).
110
- listenersFinished,
111
- requestController.responsePromise
112
- ]);
113
- this.logger.info("all request listeners have been resolved!");
114
- const mockedResponse2 = await requestController.responsePromise;
115
- this.logger.info("event.respondWith called with:", mockedResponse2);
116
- return mockedResponse2;
117
- }
118
- );
119
- if (requestAborted.state === "rejected") {
120
- this.logger.info(
121
- "request has been aborted:",
122
- requestAborted.rejectionReason
123
- );
124
- responsePromise.reject(requestAborted.rejectionReason);
125
- return responsePromise;
126
- }
127
- if (resolverResult.error) {
128
- this.logger.info(
129
- "request listerner threw an error:",
130
- resolverResult.error
131
- );
132
- if (resolverResult.error instanceof Response) {
133
- if (isResponseError(resolverResult.error)) {
134
- errorWith(createNetworkError(resolverResult.error));
135
- } else {
136
- respondWith(resolverResult.error);
137
- }
138
- }
139
- if (this.emitter.listenerCount("unhandledException") > 0) {
140
- await emitAsync(this.emitter, "unhandledException", {
141
- error: resolverResult.error,
142
- request,
143
- requestId,
144
- controller: {
145
- respondWith,
146
- errorWith
147
- }
148
- });
149
- if (responsePromise.state !== "pending") {
150
- return responsePromise;
151
- }
152
- }
153
- respondWith(createServerErrorResponse(resolverResult.error));
154
- return responsePromise;
155
- }
156
- const mockedResponse = resolverResult.data;
157
- if (mockedResponse && !((_a = request.signal) == null ? void 0 : _a.aborted)) {
158
- this.logger.info("received mocked response:", mockedResponse);
159
- if (isResponseError(mockedResponse)) {
160
- this.logger.info(
161
- "received a network error response, rejecting the request promise..."
162
- );
163
- errorWith(createNetworkError(mockedResponse));
164
- } else {
165
- respondWith(mockedResponse);
166
- }
167
- return responsePromise;
168
- }
169
- this.logger.info("no mocked response received!");
170
- return pureFetch(request).then((response) => {
171
- this.logger.info("original fetch performed", response);
172
- if (this.emitter.listenerCount("response") > 0) {
173
- this.logger.info('emitting the "response" event...');
174
- const responseClone = response.clone();
175
- this.emitter.emit("response", {
176
- response: responseClone,
177
- isMockedResponse: false,
178
- request: interactiveRequest,
179
- requestId
180
- });
181
- }
182
- return response;
183
- });
184
- };
185
- Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {
186
- enumerable: true,
187
- configurable: true,
188
- value: true
189
- });
190
- this.subscriptions.push(() => {
191
- Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {
192
- value: void 0
193
- });
194
- globalThis.fetch = pureFetch;
195
- this.logger.info(
196
- 'restored native "globalThis.fetch"!',
197
- globalThis.fetch.name
198
- );
199
- });
200
- }
201
- };
202
- var FetchInterceptor = _FetchInterceptor;
203
- FetchInterceptor.symbol = Symbol("fetch");
204
- function createNetworkError(cause) {
205
- return Object.assign(new TypeError("Failed to fetch"), {
206
- cause
207
- });
208
- }
209
-
210
- export {
211
- FetchInterceptor
212
- };
213
- //# sourceMappingURL=chunk-MAEPOYB6.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/interceptors/fetch/index.ts","../../src/utils/canParseUrl.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { toInteractiveRequest } from '../../utils/toInteractiveRequest'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport {\n createServerErrorResponse,\n isResponseError,\n} from '../../utils/responseUtils'\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 (\n typeof globalThis !== 'undefined' &&\n typeof globalThis.fetch !== 'undefined'\n )\n }\n\n protected async setup() {\n const pureFetch = globalThis.fetch\n\n invariant(\n !(pureFetch as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"fetch\" module: already patched.'\n )\n\n globalThis.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.origin)\n : input\n\n const request = new Request(resolvedInput, init)\n\n this.logger.info('[%s] %s', request.method, request.url)\n\n const { interactiveRequest, requestController } =\n toInteractiveRequest(request)\n\n this.logger.info(\n 'emitting the \"request\" event for %d listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n this.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== requestId) {\n return\n }\n\n if (requestController.responsePromise.state === 'pending') {\n requestController.responsePromise.resolve(undefined)\n }\n })\n\n this.logger.info('awaiting for the mocked response...')\n\n const signal = interactiveRequest.signal\n const requestAborted = new DeferredPromise()\n\n // Signal isn't always defined in react-native.\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n requestAborted.reject(signal.reason)\n },\n { once: true }\n )\n }\n\n const responsePromise = new DeferredPromise<Response>()\n\n const respondWith = (response: Response): void => {\n this.logger.info('responding with a mock response:', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\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 const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: true,\n request: interactiveRequest,\n requestId,\n })\n }\n\n // Set the \"response.url\" property to equal the intercepted request URL.\n Object.defineProperty(response, 'url', {\n writable: false,\n enumerable: true,\n configurable: false,\n value: request.url,\n })\n\n responsePromise.resolve(response)\n }\n\n const errorWith = (reason: unknown): void => {\n responsePromise.reject(reason)\n }\n\n const resolverResult = await until<unknown, Response | undefined>(\n async () => {\n const listenersFinished = emitAsync(this.emitter, 'request', {\n request: interactiveRequest,\n requestId,\n })\n\n await Promise.race([\n requestAborted,\n // Put the listeners invocation Promise in the same race condition\n // with the request abort Promise because otherwise awaiting the listeners\n // would always yield some response (or undefined).\n listenersFinished,\n requestController.responsePromise,\n ])\n\n this.logger.info('all request listeners have been resolved!')\n\n const mockedResponse = await requestController.responsePromise\n this.logger.info('event.respondWith called with:', mockedResponse)\n\n return mockedResponse\n }\n )\n\n if (requestAborted.state === 'rejected') {\n this.logger.info(\n 'request has been aborted:',\n requestAborted.rejectionReason\n )\n\n responsePromise.reject(requestAborted.rejectionReason)\n return responsePromise\n }\n\n if (resolverResult.error) {\n this.logger.info(\n 'request listerner threw an error:',\n resolverResult.error\n )\n\n // Treat thrown Responses as mocked responses.\n if (resolverResult.error instanceof Response) {\n // Treat thrown Response.error() as a request error.\n if (isResponseError(resolverResult.error)) {\n errorWith(createNetworkError(resolverResult.error))\n } else {\n // Treat the rest of thrown Responses as mocked responses.\n respondWith(resolverResult.error)\n }\n }\n\n // Emit the \"unhandledException\" interceptor event so the client\n // can opt-out from exceptions translating to 500 error responses.\n\n if (this.emitter.listenerCount('unhandledException') > 0) {\n await emitAsync(this.emitter, 'unhandledException', {\n error: resolverResult.error,\n request,\n requestId,\n controller: {\n respondWith,\n errorWith,\n },\n })\n\n if (responsePromise.state !== 'pending') {\n return responsePromise\n }\n }\n\n // Unhandled exceptions in the request listeners are\n // synonymous to unhandled exceptions on the server.\n // Those are represented as 500 error responses.\n respondWith(createServerErrorResponse(resolverResult.error))\n return responsePromise\n }\n\n const mockedResponse = resolverResult.data\n\n if (mockedResponse && !request.signal?.aborted) {\n this.logger.info('received mocked response:', mockedResponse)\n\n // Reject the request Promise on mocked \"Response.error\" responses.\n if (isResponseError(mockedResponse)) {\n this.logger.info(\n 'received a network error response, rejecting the request promise...'\n )\n\n /**\n * Set the cause of the request promise rejection to the\n * network error Response instance. This differs from Undici.\n * Undici will forward the \"response.error\" custom property\n * as the rejection reason but for \"Response.error()\" static method\n * \"response.error\" will equal to undefined, making \"cause\" an empty Error.\n * @see https://github.com/nodejs/undici/blob/83cb522ae0157a19d149d72c7d03d46e34510d0a/lib/fetch/response.js#L344\n */\n errorWith(createNetworkError(mockedResponse))\n } else {\n respondWith(mockedResponse)\n }\n\n return responsePromise\n }\n\n this.logger.info('no mocked response received!')\n\n return pureFetch(request).then((response) => {\n this.logger.info('original fetch performed', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = response.clone()\n\n this.emitter.emit('response', {\n response: responseClone,\n isMockedResponse: false,\n request: interactiveRequest,\n requestId,\n })\n }\n\n return response\n })\n }\n\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.fetch = pureFetch\n\n this.logger.info(\n 'restored native \"globalThis.fetch\"!',\n globalThis.fetch.name\n )\n })\n }\n}\n\nfunction createNetworkError(cause: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","/**\n * Returns a boolean indicating whether the given URL string\n * can be parsed into a `URL` instance.\n * A substitute for `URL.canParse()` for Node.js 18.\n */\nexport function canParseUrl(url: string): boolean {\n try {\n new URL(url)\n return true\n } catch (_error) {\n return false\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,aAAa;;;ACGf,SAAS,YAAY,KAAsB;AAChD,MAAI;AACF,QAAI,IAAI,GAAG;AACX,WAAO;AAAA,EACT,SAAS,QAAP;AACA,WAAO;AAAA,EACT;AACF;;;ADEO,IAAM,oBAAN,cAA+B,YAAiC;AAAA,EAGrE,cAAc;AACZ,UAAM,kBAAiB,MAAM;AAAA,EAC/B;AAAA,EAEU,mBAAmB;AAC3B,WACE,OAAO,eAAe,eACtB,OAAO,WAAW,UAAU;AAAA,EAEhC;AAAA,EAEA,MAAgB,QAAQ;AACtB,UAAM,YAAY,WAAW;AAE7B;AAAA,MACE,CAAE,UAAkB,iBAAiB;AAAA,MACrC;AAAA,IACF;AAEA,eAAW,QAAQ,OAAO,OAAO,SAAS;AApC9C;AAqCM,YAAM,YAAY,gBAAgB;AAQlC,YAAM,gBACJ,OAAO,UAAU,YACjB,OAAO,aAAa,eACpB,CAAC,YAAY,KAAK,IACd,IAAI,IAAI,OAAO,SAAS,MAAM,IAC9B;AAEN,YAAM,UAAU,IAAI,QAAQ,eAAe,IAAI;AAE/C,WAAK,OAAO,KAAK,WAAW,QAAQ,QAAQ,QAAQ,GAAG;AAEvD,YAAM,EAAE,oBAAoB,kBAAkB,IAC5C,qBAAqB,OAAO;AAE9B,WAAK,OAAO;AAAA,QACV;AAAA,QACA,KAAK,QAAQ,cAAc,SAAS;AAAA,MACtC;AAEA,WAAK,QAAQ,KAAK,WAAW,CAAC,EAAE,WAAW,iBAAiB,MAAM;AAChE,YAAI,qBAAqB,WAAW;AAClC;AAAA,QACF;AAEA,YAAI,kBAA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