@mswjs/interceptors 0.41.6 → 0.41.7

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 (96) hide show
  1. package/lib/browser/{XMLHttpRequest-DNly-bu0.cjs → XMLHttpRequest-CHqOQWxg.cjs} +10 -8
  2. package/lib/browser/{XMLHttpRequest-DNly-bu0.cjs.map → XMLHttpRequest-CHqOQWxg.cjs.map} +1 -1
  3. package/lib/browser/{XMLHttpRequest-DaQ73vVt.mjs → XMLHttpRequest-DP9ps_69.mjs} +10 -8
  4. package/lib/{node/XMLHttpRequest-Cj07Pos7.mjs.map → browser/XMLHttpRequest-DP9ps_69.mjs.map} +1 -1
  5. package/lib/browser/{fetch-BmrYPMQ0.cjs → fetch-CtkfZi4Z.cjs} +11 -8
  6. package/lib/browser/{fetch-BmrYPMQ0.cjs.map → fetch-CtkfZi4Z.cjs.map} +1 -1
  7. package/lib/browser/{fetch-BS6cxWzo.mjs → fetch-Ddj5TV04.mjs} +11 -8
  8. package/lib/browser/{fetch-BS6cxWzo.mjs.map → fetch-Ddj5TV04.mjs.map} +1 -1
  9. package/lib/browser/{getRawRequest-BP--nUwn.mjs → getRawRequest-B1BqgWG6.mjs} +39 -15
  10. package/lib/browser/getRawRequest-B1BqgWG6.mjs.map +1 -0
  11. package/lib/browser/{getRawRequest-B6GjFKAr.cjs → getRawRequest-DdfaiPVH.cjs} +39 -15
  12. package/lib/browser/getRawRequest-DdfaiPVH.cjs.map +1 -0
  13. package/lib/browser/{handleRequest-CnDA8MVO.mjs → handleRequest-BHrC8Flw.mjs} +3 -3
  14. package/lib/browser/{handleRequest-CnDA8MVO.mjs.map → handleRequest-BHrC8Flw.mjs.map} +1 -1
  15. package/lib/browser/{handleRequest-BIte-8l8.cjs → handleRequest-tUNU616J.cjs} +3 -3
  16. package/lib/browser/{handleRequest-BIte-8l8.cjs.map → handleRequest-tUNU616J.cjs.map} +1 -1
  17. package/lib/browser/{hasConfigurableGlobal-B5o6PHq3.cjs → hasConfigurableGlobal-BS75Oulv.cjs} +30 -26
  18. package/lib/browser/hasConfigurableGlobal-BS75Oulv.cjs.map +1 -0
  19. package/lib/browser/{hasConfigurableGlobal-B39W0thh.mjs → hasConfigurableGlobal-FTYwno1G.mjs} +27 -23
  20. package/lib/browser/hasConfigurableGlobal-FTYwno1G.mjs.map +1 -0
  21. package/lib/browser/index.cjs +1 -1
  22. package/lib/browser/index.d.cts +2 -0
  23. package/lib/browser/index.d.mts +2 -0
  24. package/lib/browser/index.mjs +1 -1
  25. package/lib/browser/interceptors/WebSocket/index.cjs +2 -2
  26. package/lib/browser/interceptors/WebSocket/index.cjs.map +1 -1
  27. package/lib/browser/interceptors/WebSocket/index.mjs +2 -2
  28. package/lib/browser/interceptors/WebSocket/index.mjs.map +1 -1
  29. package/lib/browser/interceptors/XMLHttpRequest/index.cjs +4 -4
  30. package/lib/browser/interceptors/XMLHttpRequest/index.mjs +4 -4
  31. package/lib/browser/interceptors/fetch/index.cjs +4 -4
  32. package/lib/browser/interceptors/fetch/index.mjs +4 -4
  33. package/lib/browser/presets/browser.cjs +5 -5
  34. package/lib/browser/presets/browser.mjs +5 -5
  35. package/lib/node/{BatchInterceptor-0prNZ0wK.mjs → BatchInterceptor-DdMNfSUY.mjs} +2 -2
  36. package/lib/node/{BatchInterceptor-0prNZ0wK.mjs.map → BatchInterceptor-DdMNfSUY.mjs.map} +1 -1
  37. package/lib/node/{BatchInterceptor-Bo8JunSK.cjs → BatchInterceptor-Z1lwK23r.cjs} +2 -2
  38. package/lib/node/{BatchInterceptor-Bo8JunSK.cjs.map → BatchInterceptor-Z1lwK23r.cjs.map} +1 -1
  39. package/lib/node/{ClientRequest-OY5NnrOh.cjs → ClientRequest-DFs7FPNi.cjs} +8 -7
  40. package/lib/node/ClientRequest-DFs7FPNi.cjs.map +1 -0
  41. package/lib/node/{ClientRequest-BquJl6T-.mjs → ClientRequest-dRpI9v1o.mjs} +8 -7
  42. package/lib/node/ClientRequest-dRpI9v1o.mjs.map +1 -0
  43. package/lib/node/RemoteHttpInterceptor.cjs +7 -7
  44. package/lib/node/RemoteHttpInterceptor.mjs +7 -7
  45. package/lib/node/{XMLHttpRequest-Cj07Pos7.mjs → XMLHttpRequest-BgkpwNOu.mjs} +10 -8
  46. package/lib/{browser/XMLHttpRequest-DaQ73vVt.mjs.map → node/XMLHttpRequest-BgkpwNOu.mjs.map} +1 -1
  47. package/lib/node/{XMLHttpRequest-C1KTngEF.cjs → XMLHttpRequest-CUbLHiq6.cjs} +10 -8
  48. package/lib/node/{XMLHttpRequest-C1KTngEF.cjs.map → XMLHttpRequest-CUbLHiq6.cjs.map} +1 -1
  49. package/lib/node/{fetch-UxWd1aQX.mjs → fetch-BciBtVqm.mjs} +11 -8
  50. package/lib/node/{fetch-UxWd1aQX.mjs.map → fetch-BciBtVqm.mjs.map} +1 -1
  51. package/lib/node/{fetch-B9UiBg-M.cjs → fetch-znfXVEPe.cjs} +11 -8
  52. package/lib/node/{fetch-B9UiBg-M.cjs.map → fetch-znfXVEPe.cjs.map} +1 -1
  53. package/lib/node/{fetchUtils-Bq0Mdmkv.mjs → fetchUtils-BKJ1XmiO.mjs} +39 -15
  54. package/lib/node/{fetchUtils-Bq0Mdmkv.mjs.map → fetchUtils-BKJ1XmiO.mjs.map} +1 -1
  55. package/lib/node/{fetchUtils-BAlG765A.cjs → fetchUtils-umV5xXBy.cjs} +39 -15
  56. package/lib/node/{fetchUtils-BAlG765A.cjs.map → fetchUtils-umV5xXBy.cjs.map} +1 -1
  57. package/lib/node/{handleRequest-u6jpjgrr.mjs → handleRequest-DCLzePtS.mjs} +2 -2
  58. package/lib/node/{handleRequest-u6jpjgrr.mjs.map → handleRequest-DCLzePtS.mjs.map} +1 -1
  59. package/lib/node/{handleRequest-DUPo40Df.cjs → handleRequest-DVOthWJo.cjs} +2 -2
  60. package/lib/node/{handleRequest-DUPo40Df.cjs.map → handleRequest-DVOthWJo.cjs.map} +1 -1
  61. package/lib/node/{hasConfigurableGlobal-Befl_QJD.cjs → hasConfigurableGlobal-BtHi5OlL.cjs} +30 -26
  62. package/lib/node/hasConfigurableGlobal-BtHi5OlL.cjs.map +1 -0
  63. package/lib/node/{hasConfigurableGlobal-jN_-v3gp.mjs → hasConfigurableGlobal-Cwrs35Xo.mjs} +27 -23
  64. package/lib/node/hasConfigurableGlobal-Cwrs35Xo.mjs.map +1 -0
  65. package/lib/node/index.cjs +2 -2
  66. package/lib/node/index.d.cts +2 -0
  67. package/lib/node/index.d.mts +2 -0
  68. package/lib/node/index.mjs +2 -2
  69. package/lib/node/interceptors/ClientRequest/index.cjs +3 -3
  70. package/lib/node/interceptors/ClientRequest/index.mjs +3 -3
  71. package/lib/node/interceptors/XMLHttpRequest/index.cjs +4 -4
  72. package/lib/node/interceptors/XMLHttpRequest/index.mjs +4 -4
  73. package/lib/node/interceptors/fetch/index.cjs +4 -4
  74. package/lib/node/interceptors/fetch/index.mjs +4 -4
  75. package/lib/node/presets/node.cjs +6 -6
  76. package/lib/node/presets/node.mjs +6 -6
  77. package/package.json +1 -1
  78. package/src/interceptors/ClientRequest/utils/recordRawHeaders.test.ts +33 -0
  79. package/src/interceptors/ClientRequest/utils/recordRawHeaders.ts +19 -4
  80. package/src/interceptors/WebSocket/index.ts +2 -2
  81. package/src/interceptors/XMLHttpRequest/index.ts +4 -5
  82. package/src/interceptors/fetch/index.ts +13 -8
  83. package/src/utils/fetchUtils.test.ts +22 -0
  84. package/src/utils/fetchUtils.ts +61 -16
  85. package/src/utils/hasConfigurableGlobal.ts +1 -1
  86. package/src/utils/{globalUtils.test.ts → patchesRegistry.test.ts} +59 -19
  87. package/src/utils/patchesRegistry.ts +122 -0
  88. package/lib/browser/getRawRequest-B6GjFKAr.cjs.map +0 -1
  89. package/lib/browser/getRawRequest-BP--nUwn.mjs.map +0 -1
  90. package/lib/browser/hasConfigurableGlobal-B39W0thh.mjs.map +0 -1
  91. package/lib/browser/hasConfigurableGlobal-B5o6PHq3.cjs.map +0 -1
  92. package/lib/node/ClientRequest-BquJl6T-.mjs.map +0 -1
  93. package/lib/node/ClientRequest-OY5NnrOh.cjs.map +0 -1
  94. package/lib/node/hasConfigurableGlobal-Befl_QJD.cjs.map +0 -1
  95. package/lib/node/hasConfigurableGlobal-jN_-v3gp.mjs.map +0 -1
  96. package/src/utils/globalsRegistry.ts +0 -107
@@ -1 +1 @@
1
- {"version":3,"file":"handleRequest-DUPo40Df.cjs","names":["InterceptorError","DeferredPromise","RequestController"],"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;CAC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AAU,QAAQ,SAAS,sBAAsB;IACrD,OAAO,OAAO;IACd,SAAS,QAAQ;IACjB,WAAW,QAAQ;IACnB,YAAY;IACb,CAAC;AAIF,OACE,6BAA6B,eAAeA,qCAAkB,QAE9D;;AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAeA,qCAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"}
1
+ {"version":3,"file":"handleRequest-DVOthWJo.cjs","names":["InterceptorError","DeferredPromise","RequestController"],"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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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,eAAeA,qCAAkB,QAE9D;;AAKJ,QAAM,QAAQ,WAAW,YACvB,0BAA0B,OAAO,MAAM,CACxC;AACD;;AAIF,KAAI,QAAQ,WAAW,eAAeA,qCAAkB,QACtD,QAAO,MAAM,QAAQ,WAAW,aAAa;AAG/C,QAAO,QAAQ,WAAW"}
@@ -1,40 +1,44 @@
1
1
  const require_chunk = require('./chunk-CbDLau6x.cjs');
2
2
  let outvariant = require("outvariant");
3
3
 
4
- //#region src/utils/globalsRegistry.ts
5
- var GlobalsRegistry = class {
6
- #globals = /* @__PURE__ */ new Map();
7
- replaceGlobal(key, nextValue) {
8
- (0, outvariant.invariant)(!this.#globals.has(key), `Failed to replace a global value at "${key}": already replaced.`);
9
- const match = getDeepPropertyDescriptor(globalThis, key);
4
+ //#region src/utils/patchesRegistry.ts
5
+ var PatchesRegistry = class {
6
+ #replacements = /* @__PURE__ */ new Map();
7
+ applyPatch(owner, key, getNextValue) {
8
+ const ownerReplacements = this.#replacements.get(owner);
9
+ (0, outvariant.invariant)(!ownerReplacements?.has(key), `Failed to replace a global value at "${String(key)}": already replaced.`);
10
+ const match = getDeepPropertyDescriptor(owner, key);
10
11
  if (typeof match === "undefined") {
11
- console.warn(`Failed to replace a global value at "${key}": not a global value.`);
12
+ console.warn(`Failed to replace a global value at "${String(key)}": not a global value.`);
12
13
  return () => {};
13
14
  }
14
- Object.defineProperty(globalThis, key, {
15
- value: nextValue,
15
+ Object.defineProperty(owner, key, {
16
+ value: getNextValue(owner[key]),
16
17
  enumerable: true,
17
18
  configurable: true
18
19
  });
19
- const restoreGlobal = () => {
20
- if (!this.#globals.has(key)) return;
21
- if (match.owner === globalThis) Object.defineProperty(match.owner, key, match.descriptor);
20
+ const restorePatch = () => {
21
+ const currentReplacements = this.#replacements.get(owner);
22
+ if (!currentReplacements?.has(key)) return;
23
+ if (match.owner === owner) Object.defineProperty(match.owner, key, match.descriptor);
22
24
  else
23
25
  /**
24
26
  * @todo Delete the proxy property set by the registry.
25
- * If the owner isn't `globalThis`, the property is likely nested in the prototype.
27
+ * If the match's owner isn't the original owner, the property is likely nested in the prototype.
26
28
  * The registry does not meddle with those, they are left intact.
27
29
  */
28
- Reflect.deleteProperty(globalThis, key);
29
- this.#globals.delete(key);
30
+ Reflect.deleteProperty(owner, key);
31
+ currentReplacements.delete(key);
32
+ if (currentReplacements.size === 0) this.#replacements.delete(owner);
30
33
  };
31
- this.#globals.set(key, restoreGlobal);
32
- return restoreGlobal;
34
+ if (ownerReplacements) ownerReplacements.set(key, restorePatch);
35
+ else this.#replacements.set(owner, new Map([[key, restorePatch]]));
36
+ return restorePatch;
33
37
  }
34
- restoreAllGlobals() {
38
+ restoreAllPatches() {
35
39
  const errors = [];
36
- for (const [, restoreGlobal] of this.#globals) try {
37
- restoreGlobal();
40
+ for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try {
41
+ restorePatch();
38
42
  } catch (error) {
39
43
  if (error instanceof Error) errors.push(error);
40
44
  else throw error;
@@ -42,7 +46,7 @@ var GlobalsRegistry = class {
42
46
  if (errors.length > 0) throw new AggregateError(errors, "FOO!");
43
47
  }
44
48
  };
45
- const globalsRegistry = new GlobalsRegistry();
49
+ const patchesRegistry = new PatchesRegistry();
46
50
  /**
47
51
  * Returns a property descriptor for the given property on the owner.
48
52
  * Walks down the prototype chain if the property does not exist on the owner.
@@ -82,16 +86,16 @@ function hasConfigurableGlobal(propertyName) {
82
86
  }
83
87
 
84
88
  //#endregion
85
- Object.defineProperty(exports, 'globalsRegistry', {
89
+ Object.defineProperty(exports, 'hasConfigurableGlobal', {
86
90
  enumerable: true,
87
91
  get: function () {
88
- return globalsRegistry;
92
+ return hasConfigurableGlobal;
89
93
  }
90
94
  });
91
- Object.defineProperty(exports, 'hasConfigurableGlobal', {
95
+ Object.defineProperty(exports, 'patchesRegistry', {
92
96
  enumerable: true,
93
97
  get: function () {
94
- return hasConfigurableGlobal;
98
+ return patchesRegistry;
95
99
  }
96
100
  });
97
- //# sourceMappingURL=hasConfigurableGlobal-Befl_QJD.cjs.map
101
+ //# sourceMappingURL=hasConfigurableGlobal-BtHi5OlL.cjs.map
@@ -0,0 +1 @@
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,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,39 +1,43 @@
1
1
  import { invariant } from "outvariant";
2
2
 
3
- //#region src/utils/globalsRegistry.ts
4
- var GlobalsRegistry = class {
5
- #globals = /* @__PURE__ */ new Map();
6
- replaceGlobal(key, nextValue) {
7
- invariant(!this.#globals.has(key), `Failed to replace a global value at "${key}": already replaced.`);
8
- const match = getDeepPropertyDescriptor(globalThis, key);
3
+ //#region src/utils/patchesRegistry.ts
4
+ var PatchesRegistry = class {
5
+ #replacements = /* @__PURE__ */ new Map();
6
+ applyPatch(owner, key, getNextValue) {
7
+ const ownerReplacements = this.#replacements.get(owner);
8
+ invariant(!ownerReplacements?.has(key), `Failed to replace a global value at "${String(key)}": already replaced.`);
9
+ const match = getDeepPropertyDescriptor(owner, key);
9
10
  if (typeof match === "undefined") {
10
- console.warn(`Failed to replace a global value at "${key}": not a global value.`);
11
+ console.warn(`Failed to replace a global value at "${String(key)}": not a global value.`);
11
12
  return () => {};
12
13
  }
13
- Object.defineProperty(globalThis, key, {
14
- value: nextValue,
14
+ Object.defineProperty(owner, key, {
15
+ value: getNextValue(owner[key]),
15
16
  enumerable: true,
16
17
  configurable: true
17
18
  });
18
- const restoreGlobal = () => {
19
- if (!this.#globals.has(key)) return;
20
- if (match.owner === globalThis) Object.defineProperty(match.owner, key, match.descriptor);
19
+ const restorePatch = () => {
20
+ const currentReplacements = this.#replacements.get(owner);
21
+ if (!currentReplacements?.has(key)) return;
22
+ if (match.owner === owner) Object.defineProperty(match.owner, key, match.descriptor);
21
23
  else
22
24
  /**
23
25
  * @todo Delete the proxy property set by the registry.
24
- * If the owner isn't `globalThis`, the property is likely nested in the prototype.
26
+ * If the match's owner isn't the original owner, the property is likely nested in the prototype.
25
27
  * The registry does not meddle with those, they are left intact.
26
28
  */
27
- Reflect.deleteProperty(globalThis, key);
28
- this.#globals.delete(key);
29
+ Reflect.deleteProperty(owner, key);
30
+ currentReplacements.delete(key);
31
+ if (currentReplacements.size === 0) this.#replacements.delete(owner);
29
32
  };
30
- this.#globals.set(key, restoreGlobal);
31
- return restoreGlobal;
33
+ if (ownerReplacements) ownerReplacements.set(key, restorePatch);
34
+ else this.#replacements.set(owner, new Map([[key, restorePatch]]));
35
+ return restorePatch;
32
36
  }
33
- restoreAllGlobals() {
37
+ restoreAllPatches() {
34
38
  const errors = [];
35
- for (const [, restoreGlobal] of this.#globals) try {
36
- restoreGlobal();
39
+ for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try {
40
+ restorePatch();
37
41
  } catch (error) {
38
42
  if (error instanceof Error) errors.push(error);
39
43
  else throw error;
@@ -41,7 +45,7 @@ var GlobalsRegistry = class {
41
45
  if (errors.length > 0) throw new AggregateError(errors, "FOO!");
42
46
  }
43
47
  };
44
- const globalsRegistry = new GlobalsRegistry();
48
+ const patchesRegistry = new PatchesRegistry();
45
49
  /**
46
50
  * Returns a property descriptor for the given property on the owner.
47
51
  * Walks down the prototype chain if the property does not exist on the owner.
@@ -81,5 +85,5 @@ function hasConfigurableGlobal(propertyName) {
81
85
  }
82
86
 
83
87
  //#endregion
84
- export { globalsRegistry as n, hasConfigurableGlobal as t };
85
- //# sourceMappingURL=hasConfigurableGlobal-jN_-v3gp.mjs.map
88
+ export { patchesRegistry as n, hasConfigurableGlobal as t };
89
+ //# sourceMappingURL=hasConfigurableGlobal-Cwrs35Xo.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hasConfigurableGlobal-Cwrs35Xo.mjs","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;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,5 +1,5 @@
1
- const require_fetchUtils = require('./fetchUtils-BAlG765A.cjs');
2
- const require_BatchInterceptor = require('./BatchInterceptor-Bo8JunSK.cjs');
1
+ const require_fetchUtils = require('./fetchUtils-umV5xXBy.cjs');
2
+ const require_BatchInterceptor = require('./BatchInterceptor-Z1lwK23r.cjs');
3
3
  const require_bufferUtils = require('./bufferUtils-S5_-2eN4.cjs');
4
4
  const require_getRawRequest = require('./getRawRequest-B6znU6il.cjs');
5
5
 
@@ -58,6 +58,7 @@ declare class FetchResponse extends Response {
58
58
  * code represents a response that can have a body.
59
59
  */
60
60
  static isResponseWithBody(status: number): boolean;
61
+ static setStatus(status: number, response: Response): void;
61
62
  static setUrl(url: string | undefined, response: Response): void;
62
63
  /**
63
64
  * Parses the given raw HTTP headers into a Fetch API `Headers` instance.
@@ -72,6 +73,7 @@ declare class FetchResponse extends Response {
72
73
  */
73
74
  static clone(response: Response): Response;
74
75
  constructor(body?: BodyInit | null, init?: FetchResponseInit);
76
+ clone(): Response;
75
77
  }
76
78
  //#endregion
77
79
  //#region src/getRawRequest.d.ts
@@ -58,6 +58,7 @@ declare class FetchResponse extends Response {
58
58
  * code represents a response that can have a body.
59
59
  */
60
60
  static isResponseWithBody(status: number): boolean;
61
+ static setStatus(status: number, response: Response): void;
61
62
  static setUrl(url: string | undefined, response: Response): void;
62
63
  /**
63
64
  * Parses the given raw HTTP headers into a Fetch API `Headers` instance.
@@ -72,6 +73,7 @@ declare class FetchResponse extends Response {
72
73
  */
73
74
  static clone(response: Response): Response;
74
75
  constructor(body?: BodyInit | null, init?: FetchResponseInit);
76
+ clone(): Response;
75
77
  }
76
78
  //#endregion
77
79
  //#region src/getRawRequest.d.ts
@@ -1,5 +1,5 @@
1
- import { a as RequestController, c as Interceptor, d as getGlobalSymbol, i as createRequestId, l as InterceptorReadyState, n as FetchResponse, s as INTERNAL_REQUEST_ID_HEADER_NAME, t as FetchRequest, u as deleteGlobalSymbol } from "./fetchUtils-Bq0Mdmkv.mjs";
2
- import { t as BatchInterceptor } from "./BatchInterceptor-0prNZ0wK.mjs";
1
+ import { a as RequestController, c as Interceptor, d as getGlobalSymbol, i as createRequestId, l as InterceptorReadyState, n as FetchResponse, s as INTERNAL_REQUEST_ID_HEADER_NAME, t as FetchRequest, u as deleteGlobalSymbol } from "./fetchUtils-BKJ1XmiO.mjs";
2
+ import { t as BatchInterceptor } from "./BatchInterceptor-DdMNfSUY.mjs";
3
3
  import { n as encodeBuffer, t as decodeBuffer } from "./bufferUtils-DxPxwff_.mjs";
4
4
  import { t as getRawRequest } from "./getRawRequest-C2-1urzA.mjs";
5
5
 
@@ -1,6 +1,6 @@
1
- require('../../fetchUtils-BAlG765A.cjs');
2
- const require_ClientRequest = require('../../ClientRequest-OY5NnrOh.cjs');
3
- require('../../handleRequest-DUPo40Df.cjs');
1
+ require('../../fetchUtils-umV5xXBy.cjs');
2
+ const require_ClientRequest = require('../../ClientRequest-DFs7FPNi.cjs');
3
+ require('../../handleRequest-DVOthWJo.cjs');
4
4
  require('../../node-DIKcnzhK.cjs');
5
5
 
6
6
  exports.ClientRequestInterceptor = require_ClientRequest.ClientRequestInterceptor;
@@ -1,6 +1,6 @@
1
- import "../../fetchUtils-Bq0Mdmkv.mjs";
2
- import { t as ClientRequestInterceptor } from "../../ClientRequest-BquJl6T-.mjs";
3
- import "../../handleRequest-u6jpjgrr.mjs";
1
+ import "../../fetchUtils-BKJ1XmiO.mjs";
2
+ import { t as ClientRequestInterceptor } from "../../ClientRequest-dRpI9v1o.mjs";
3
+ import "../../handleRequest-DCLzePtS.mjs";
4
4
  import "../../node-lsdNwZEW.mjs";
5
5
 
6
6
  export { ClientRequestInterceptor };
@@ -1,7 +1,7 @@
1
- require('../../fetchUtils-BAlG765A.cjs');
1
+ require('../../fetchUtils-umV5xXBy.cjs');
2
2
  require('../../bufferUtils-S5_-2eN4.cjs');
3
- require('../../handleRequest-DUPo40Df.cjs');
4
- const require_XMLHttpRequest = require('../../XMLHttpRequest-C1KTngEF.cjs');
5
- require('../../hasConfigurableGlobal-Befl_QJD.cjs');
3
+ require('../../handleRequest-DVOthWJo.cjs');
4
+ const require_XMLHttpRequest = require('../../XMLHttpRequest-CUbLHiq6.cjs');
5
+ require('../../hasConfigurableGlobal-BtHi5OlL.cjs');
6
6
 
7
7
  exports.XMLHttpRequestInterceptor = require_XMLHttpRequest.XMLHttpRequestInterceptor;
@@ -1,7 +1,7 @@
1
- import "../../fetchUtils-Bq0Mdmkv.mjs";
1
+ import "../../fetchUtils-BKJ1XmiO.mjs";
2
2
  import "../../bufferUtils-DxPxwff_.mjs";
3
- import "../../handleRequest-u6jpjgrr.mjs";
4
- import { t as XMLHttpRequestInterceptor } from "../../XMLHttpRequest-Cj07Pos7.mjs";
5
- import "../../hasConfigurableGlobal-jN_-v3gp.mjs";
3
+ import "../../handleRequest-DCLzePtS.mjs";
4
+ import { t as XMLHttpRequestInterceptor } from "../../XMLHttpRequest-BgkpwNOu.mjs";
5
+ import "../../hasConfigurableGlobal-Cwrs35Xo.mjs";
6
6
 
7
7
  export { XMLHttpRequestInterceptor };
@@ -1,6 +1,6 @@
1
- require('../../fetchUtils-BAlG765A.cjs');
2
- require('../../handleRequest-DUPo40Df.cjs');
3
- require('../../hasConfigurableGlobal-Befl_QJD.cjs');
4
- const require_fetch = require('../../fetch-B9UiBg-M.cjs');
1
+ require('../../fetchUtils-umV5xXBy.cjs');
2
+ require('../../handleRequest-DVOthWJo.cjs');
3
+ require('../../hasConfigurableGlobal-BtHi5OlL.cjs');
4
+ const require_fetch = require('../../fetch-znfXVEPe.cjs');
5
5
 
6
6
  exports.FetchInterceptor = require_fetch.FetchInterceptor;
@@ -1,6 +1,6 @@
1
- import "../../fetchUtils-Bq0Mdmkv.mjs";
2
- import "../../handleRequest-u6jpjgrr.mjs";
3
- import "../../hasConfigurableGlobal-jN_-v3gp.mjs";
4
- import { t as FetchInterceptor } from "../../fetch-UxWd1aQX.mjs";
1
+ import "../../fetchUtils-BKJ1XmiO.mjs";
2
+ import "../../handleRequest-DCLzePtS.mjs";
3
+ import "../../hasConfigurableGlobal-Cwrs35Xo.mjs";
4
+ import { t as FetchInterceptor } from "../../fetch-BciBtVqm.mjs";
5
5
 
6
6
  export { FetchInterceptor };
@@ -1,11 +1,11 @@
1
- require('../fetchUtils-BAlG765A.cjs');
1
+ require('../fetchUtils-umV5xXBy.cjs');
2
2
  require('../bufferUtils-S5_-2eN4.cjs');
3
- const require_ClientRequest = require('../ClientRequest-OY5NnrOh.cjs');
4
- require('../handleRequest-DUPo40Df.cjs');
3
+ const require_ClientRequest = require('../ClientRequest-DFs7FPNi.cjs');
4
+ require('../handleRequest-DVOthWJo.cjs');
5
5
  require('../node-DIKcnzhK.cjs');
6
- const require_XMLHttpRequest = require('../XMLHttpRequest-C1KTngEF.cjs');
7
- require('../hasConfigurableGlobal-Befl_QJD.cjs');
8
- const require_fetch = require('../fetch-B9UiBg-M.cjs');
6
+ const require_XMLHttpRequest = require('../XMLHttpRequest-CUbLHiq6.cjs');
7
+ require('../hasConfigurableGlobal-BtHi5OlL.cjs');
8
+ const require_fetch = require('../fetch-znfXVEPe.cjs');
9
9
 
10
10
  //#region src/presets/node.ts
11
11
  /**
@@ -1,11 +1,11 @@
1
- import "../fetchUtils-Bq0Mdmkv.mjs";
1
+ import "../fetchUtils-BKJ1XmiO.mjs";
2
2
  import "../bufferUtils-DxPxwff_.mjs";
3
- import { t as ClientRequestInterceptor } from "../ClientRequest-BquJl6T-.mjs";
4
- import "../handleRequest-u6jpjgrr.mjs";
3
+ import { t as ClientRequestInterceptor } from "../ClientRequest-dRpI9v1o.mjs";
4
+ import "../handleRequest-DCLzePtS.mjs";
5
5
  import "../node-lsdNwZEW.mjs";
6
- import { t as XMLHttpRequestInterceptor } from "../XMLHttpRequest-Cj07Pos7.mjs";
7
- import "../hasConfigurableGlobal-jN_-v3gp.mjs";
8
- import { t as FetchInterceptor } from "../fetch-UxWd1aQX.mjs";
6
+ import { t as XMLHttpRequestInterceptor } from "../XMLHttpRequest-BgkpwNOu.mjs";
7
+ import "../hasConfigurableGlobal-Cwrs35Xo.mjs";
8
+ import { t as FetchInterceptor } from "../fetch-BciBtVqm.mjs";
9
9
 
10
10
  //#region src/presets/node.ts
11
11
  /**
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "type": "commonjs",
3
3
  "name": "@mswjs/interceptors",
4
4
  "description": "Low-level HTTP/HTTPS/XHR/fetch request interception library.",
5
- "version": "0.41.6",
5
+ "version": "0.41.7",
6
6
  "main": "./lib/node/index.cjs",
7
7
  "module": "./lib/node/index.mjs",
8
8
  "types": "./lib/node/index.d.cts",
@@ -256,3 +256,36 @@ it('isolates headers between different headers instances', async () => {
256
256
  expect(firstClone.get('Content-Type')).toBe('application/json')
257
257
  expect(secondClone.get('Content-Type')).toBeNull()
258
258
  })
259
+
260
+ /**
261
+ * Node.js 24+ may pass additional internal arguments to Headers.prototype.set
262
+ * and Headers.prototype.append. This test ensures we only record the first
263
+ * two arguments (name, value) and ignore any additional internal arguments.
264
+ * @see https://github.com/mswjs/interceptors/issues/762
265
+ */
266
+ it('ignores extra internal arguments passed to .set() and .append()', () => {
267
+ recordRawFetchHeaders()
268
+ const headers = new Headers()
269
+
270
+ // Simulate Node.js 24+ behavior where internal calls may pass extra arguments
271
+ // by calling the prototype methods directly with additional arguments.
272
+ Headers.prototype.set.call(
273
+ headers,
274
+ 'X-Set-Header',
275
+ 'set-value',
276
+ // @ts-expect-error Internal argument
277
+ true
278
+ )
279
+ Headers.prototype.append.call(
280
+ headers,
281
+ 'X-Append-Header',
282
+ 'append-value',
283
+ // @ts-expect-error Internal argument
284
+ true
285
+ )
286
+
287
+ expect(getRawFetchHeaders(headers)).toEqual([
288
+ ['X-Set-Header', 'set-value'],
289
+ ['X-Append-Header', 'append-value'],
290
+ ])
291
+ })
@@ -120,9 +120,18 @@ export function recordRawFetchHeaders() {
120
120
  headersInit instanceof Headers &&
121
121
  Reflect.has(headersInit, kRawHeaders)
122
122
  ) {
123
+ // Ensure each header tuple has exactly 2 elements (name, value).
124
+ // Node.js 24+ may have stored tuples with extra internal arguments.
125
+ const rawHeadersFromInit = Reflect.get(
126
+ headersInit,
127
+ kRawHeaders
128
+ ) as RawHeaders
129
+ const sanitizedHeaders = rawHeadersFromInit.map(
130
+ (tuple): HeaderTuple => [tuple[0], tuple[1]]
131
+ )
123
132
  const headers = Reflect.construct(
124
133
  target,
125
- [Reflect.get(headersInit, kRawHeaders)],
134
+ [sanitizedHeaders],
126
135
  newTarget
127
136
  )
128
137
  ensureRawHeadersSymbol(headers, [
@@ -131,7 +140,7 @@ export function recordRawFetchHeaders() {
131
140
  * This prevents multiple Headers instances from pointing
132
141
  * at the same internal "rawHeaders" array.
133
142
  */
134
- ...Reflect.get(headersInit, kRawHeaders),
143
+ ...sanitizedHeaders,
135
144
  ])
136
145
  return headers
137
146
  }
@@ -156,14 +165,20 @@ export function recordRawFetchHeaders() {
156
165
 
157
166
  Headers.prototype.set = new Proxy(Headers.prototype.set, {
158
167
  apply(target, thisArg, args: HeaderTuple) {
159
- recordRawHeader(thisArg, args, 'set')
168
+ // Use only the first two arguments (name, value) to record raw headers.
169
+ // Node.js 24+ may pass additional internal arguments that should not
170
+ // be included in the raw headers array.
171
+ recordRawHeader(thisArg, [args[0], args[1]], 'set')
160
172
  return Reflect.apply(target, thisArg, args)
161
173
  },
162
174
  })
163
175
 
164
176
  Headers.prototype.append = new Proxy(Headers.prototype.append, {
165
177
  apply(target, thisArg, args: HeaderTuple) {
166
- recordRawHeader(thisArg, args, 'append')
178
+ // Use only the first two arguments (name, value) to record raw headers.
179
+ // Node.js 24+ may pass additional internal arguments that should not
180
+ // be included in the raw headers array.
181
+ recordRawHeader(thisArg, [args[0], args[1]], 'append')
167
182
  return Reflect.apply(target, thisArg, args)
168
183
  },
169
184
  })
@@ -18,7 +18,7 @@ import {
18
18
  import { bindEvent } from './utils/bindEvent'
19
19
  import { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'
20
20
  import { emitAsync } from '../../utils/emitAsync'
21
- import { globalsRegistry } from '../../utils/globalsRegistry'
21
+ import { patchesRegistry } from '../../utils/patchesRegistry'
22
22
 
23
23
  export {
24
24
  type WebSocketData,
@@ -176,7 +176,7 @@ export class WebSocketInterceptor extends Interceptor<WebSocketEventMap> {
176
176
  logger.info('patching global WebSocket...')
177
177
 
178
178
  this.subscriptions.push(
179
- globalsRegistry.replaceGlobal('WebSocket', WebSocketProxy)
179
+ patchesRegistry.applyPatch(globalThis, 'WebSocket', () => WebSocketProxy)
180
180
  )
181
181
 
182
182
  logger.info('global WebSocket patched!', globalThis.WebSocket.name)
@@ -3,7 +3,7 @@ import { HttpRequestEventMap } from '../../glossary'
3
3
  import { Interceptor } from '../../Interceptor'
4
4
  import { createXMLHttpRequestProxy } from './XMLHttpRequestProxy'
5
5
  import { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'
6
- import { globalsRegistry } from '../../utils/globalsRegistry'
6
+ import { patchesRegistry } from '../../utils/patchesRegistry'
7
7
 
8
8
  export type XMLHttpRequestEmitter = Emitter<HttpRequestEventMap>
9
9
 
@@ -24,13 +24,12 @@ export class XMLHttpRequestInterceptor extends Interceptor<HttpRequestEventMap>
24
24
  logger.info('patching global XMLHttpRequest...')
25
25
 
26
26
  this.subscriptions.push(
27
- globalsRegistry.replaceGlobal(
28
- 'XMLHttpRequest',
29
- createXMLHttpRequestProxy({
27
+ patchesRegistry.applyPatch(globalThis, 'XMLHttpRequest', () => {
28
+ return createXMLHttpRequestProxy({
30
29
  emitter: this.emitter,
31
30
  logger: this.logger,
32
31
  })
33
- )
32
+ })
34
33
  )
35
34
 
36
35
  logger.info(