@mswjs/interceptors 0.41.6 → 0.41.8
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.
- package/lib/browser/{XMLHttpRequest-DNly-bu0.cjs → XMLHttpRequest-B11I9TBx.cjs} +10 -8
- package/lib/browser/{XMLHttpRequest-DNly-bu0.cjs.map → XMLHttpRequest-B11I9TBx.cjs.map} +1 -1
- package/lib/browser/{XMLHttpRequest-DaQ73vVt.mjs → XMLHttpRequest-DHEkSoRN.mjs} +10 -8
- package/lib/{node/XMLHttpRequest-Cj07Pos7.mjs.map → browser/XMLHttpRequest-DHEkSoRN.mjs.map} +1 -1
- package/lib/browser/{fetch-BS6cxWzo.mjs → fetch-BJwfdses.mjs} +11 -8
- package/lib/browser/{fetch-BS6cxWzo.mjs.map → fetch-BJwfdses.mjs.map} +1 -1
- package/lib/browser/{fetch-BmrYPMQ0.cjs → fetch-M8iXkZ3L.cjs} +11 -8
- package/lib/browser/{fetch-BmrYPMQ0.cjs.map → fetch-M8iXkZ3L.cjs.map} +1 -1
- package/lib/browser/{getRawRequest-BP--nUwn.mjs → getRawRequest-B1BqgWG6.mjs} +39 -15
- package/lib/browser/getRawRequest-B1BqgWG6.mjs.map +1 -0
- package/lib/browser/{getRawRequest-B6GjFKAr.cjs → getRawRequest-DdfaiPVH.cjs} +39 -15
- package/lib/browser/getRawRequest-DdfaiPVH.cjs.map +1 -0
- package/lib/browser/{handleRequest-CnDA8MVO.mjs → handleRequest-1Yqu_ho_.mjs} +3 -3
- package/lib/browser/{handleRequest-CnDA8MVO.mjs.map → handleRequest-1Yqu_ho_.mjs.map} +1 -1
- package/lib/browser/{handleRequest-BIte-8l8.cjs → handleRequest-Cz4_wmQ9.cjs} +3 -3
- package/lib/browser/{handleRequest-BIte-8l8.cjs.map → handleRequest-Cz4_wmQ9.cjs.map} +1 -1
- package/lib/browser/{hasConfigurableGlobal-B39W0thh.mjs → hasConfigurableGlobal-C8zq1MCg.mjs} +34 -23
- package/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs.map +1 -0
- package/lib/browser/{hasConfigurableGlobal-B5o6PHq3.cjs → hasConfigurableGlobal-CS7adEvV.cjs} +37 -26
- package/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs.map +1 -0
- package/lib/browser/index.cjs +1 -1
- package/lib/browser/index.d.cts +2 -0
- package/lib/browser/index.d.mts +2 -0
- package/lib/browser/index.mjs +1 -1
- package/lib/browser/interceptors/WebSocket/index.cjs +2 -2
- package/lib/browser/interceptors/WebSocket/index.cjs.map +1 -1
- package/lib/browser/interceptors/WebSocket/index.mjs +2 -2
- package/lib/browser/interceptors/WebSocket/index.mjs.map +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.cjs +4 -4
- package/lib/browser/interceptors/XMLHttpRequest/index.mjs +4 -4
- package/lib/browser/interceptors/fetch/index.cjs +4 -4
- package/lib/browser/interceptors/fetch/index.mjs +4 -4
- package/lib/browser/presets/browser.cjs +5 -5
- package/lib/browser/presets/browser.mjs +5 -5
- package/lib/node/{BatchInterceptor-0prNZ0wK.mjs → BatchInterceptor-DdMNfSUY.mjs} +2 -2
- package/lib/node/{BatchInterceptor-0prNZ0wK.mjs.map → BatchInterceptor-DdMNfSUY.mjs.map} +1 -1
- package/lib/node/{BatchInterceptor-Bo8JunSK.cjs → BatchInterceptor-Z1lwK23r.cjs} +2 -2
- package/lib/node/{BatchInterceptor-Bo8JunSK.cjs.map → BatchInterceptor-Z1lwK23r.cjs.map} +1 -1
- package/lib/node/{ClientRequest-OY5NnrOh.cjs → ClientRequest-DFs7FPNi.cjs} +8 -7
- package/lib/node/ClientRequest-DFs7FPNi.cjs.map +1 -0
- package/lib/node/{ClientRequest-BquJl6T-.mjs → ClientRequest-dRpI9v1o.mjs} +8 -7
- package/lib/node/ClientRequest-dRpI9v1o.mjs.map +1 -0
- package/lib/node/RemoteHttpInterceptor.cjs +7 -7
- package/lib/node/RemoteHttpInterceptor.mjs +7 -7
- package/lib/node/{XMLHttpRequest-Cj07Pos7.mjs → XMLHttpRequest-DhupxLHX.mjs} +10 -8
- package/lib/{browser/XMLHttpRequest-DaQ73vVt.mjs.map → node/XMLHttpRequest-DhupxLHX.mjs.map} +1 -1
- package/lib/node/{XMLHttpRequest-C1KTngEF.cjs → XMLHttpRequest-Dyi6ahGz.cjs} +10 -8
- package/lib/node/{XMLHttpRequest-C1KTngEF.cjs.map → XMLHttpRequest-Dyi6ahGz.cjs.map} +1 -1
- package/lib/node/{fetch-UxWd1aQX.mjs → fetch-BqMcbuYR.mjs} +11 -8
- package/lib/node/{fetch-UxWd1aQX.mjs.map → fetch-BqMcbuYR.mjs.map} +1 -1
- package/lib/node/{fetch-B9UiBg-M.cjs → fetch-aQJu1Gf_.cjs} +11 -8
- package/lib/node/{fetch-B9UiBg-M.cjs.map → fetch-aQJu1Gf_.cjs.map} +1 -1
- package/lib/node/{fetchUtils-Bq0Mdmkv.mjs → fetchUtils-BKJ1XmiO.mjs} +39 -15
- package/lib/node/{fetchUtils-Bq0Mdmkv.mjs.map → fetchUtils-BKJ1XmiO.mjs.map} +1 -1
- package/lib/node/{fetchUtils-BAlG765A.cjs → fetchUtils-umV5xXBy.cjs} +39 -15
- package/lib/node/{fetchUtils-BAlG765A.cjs.map → fetchUtils-umV5xXBy.cjs.map} +1 -1
- package/lib/node/{handleRequest-u6jpjgrr.mjs → handleRequest-DCLzePtS.mjs} +2 -2
- package/lib/node/{handleRequest-u6jpjgrr.mjs.map → handleRequest-DCLzePtS.mjs.map} +1 -1
- package/lib/node/{handleRequest-DUPo40Df.cjs → handleRequest-DVOthWJo.cjs} +2 -2
- package/lib/node/{handleRequest-DUPo40Df.cjs.map → handleRequest-DVOthWJo.cjs.map} +1 -1
- package/lib/node/{hasConfigurableGlobal-jN_-v3gp.mjs → hasConfigurableGlobal-BiTmog1u.mjs} +34 -23
- package/lib/node/hasConfigurableGlobal-BiTmog1u.mjs.map +1 -0
- package/lib/node/{hasConfigurableGlobal-Befl_QJD.cjs → hasConfigurableGlobal-MjY06_Ok.cjs} +37 -26
- package/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs.map +1 -0
- package/lib/node/index.cjs +2 -2
- package/lib/node/index.d.cts +2 -0
- package/lib/node/index.d.mts +2 -0
- package/lib/node/index.mjs +2 -2
- package/lib/node/interceptors/ClientRequest/index.cjs +3 -3
- package/lib/node/interceptors/ClientRequest/index.mjs +3 -3
- package/lib/node/interceptors/XMLHttpRequest/index.cjs +4 -4
- package/lib/node/interceptors/XMLHttpRequest/index.mjs +4 -4
- package/lib/node/interceptors/fetch/index.cjs +4 -4
- package/lib/node/interceptors/fetch/index.mjs +4 -4
- package/lib/node/presets/node.cjs +6 -6
- package/lib/node/presets/node.mjs +6 -6
- package/package.json +1 -1
- package/src/interceptors/ClientRequest/utils/recordRawHeaders.test.ts +33 -0
- package/src/interceptors/ClientRequest/utils/recordRawHeaders.ts +19 -4
- package/src/interceptors/WebSocket/index.ts +2 -2
- package/src/interceptors/XMLHttpRequest/index.ts +4 -5
- package/src/interceptors/fetch/index.ts +13 -8
- package/src/utils/fetchUtils.test.ts +22 -0
- package/src/utils/fetchUtils.ts +61 -16
- package/src/utils/hasConfigurableGlobal.ts +1 -1
- package/src/utils/patchesRegistry.test.ts +240 -0
- package/src/utils/patchesRegistry.ts +134 -0
- package/lib/browser/getRawRequest-B6GjFKAr.cjs.map +0 -1
- package/lib/browser/getRawRequest-BP--nUwn.mjs.map +0 -1
- package/lib/browser/hasConfigurableGlobal-B39W0thh.mjs.map +0 -1
- package/lib/browser/hasConfigurableGlobal-B5o6PHq3.cjs.map +0 -1
- package/lib/node/ClientRequest-BquJl6T-.mjs.map +0 -1
- package/lib/node/ClientRequest-OY5NnrOh.cjs.map +0 -1
- package/lib/node/hasConfigurableGlobal-Befl_QJD.cjs.map +0 -1
- package/lib/node/hasConfigurableGlobal-jN_-v3gp.mjs.map +0 -1
- package/src/utils/globalUtils.test.ts +0 -144
- 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;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;;;;ACnBvC,SAAgB,SAAY,OAAY,QAAQ,OAAmB;AACjE,QAAO,QACH,OAAO,UAAU,S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;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,SAAO;SACD;AACN,SAAO;;;;;;;;;;;ACTX,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,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A6B,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,39 +1,50 @@
|
|
|
1
1
|
import { invariant } from "outvariant";
|
|
2
2
|
|
|
3
|
-
//#region src/utils/
|
|
4
|
-
var
|
|
5
|
-
#
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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(
|
|
14
|
-
value:
|
|
14
|
+
if (match.descriptor.configurable) Object.defineProperty(owner, key, {
|
|
15
|
+
value: getNextValue(owner[key]),
|
|
15
16
|
enumerable: true,
|
|
16
17
|
configurable: true
|
|
17
18
|
});
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
else if (match.descriptor.writable) owner[key] = getNextValue(owner[key]);
|
|
20
|
+
else throw new Error(`Failed to patch a non-configurable non-writable property "${key.toString()}"`);
|
|
21
|
+
const restorePatch = () => {
|
|
22
|
+
const currentReplacements = this.#replacements.get(owner);
|
|
23
|
+
if (!currentReplacements?.has(key)) return;
|
|
24
|
+
if (match.owner === owner)
|
|
25
|
+
/**
|
|
26
|
+
* @note Restoring non-configurable properties works as long as "writable: true"
|
|
27
|
+
* and none of the other descriptor properties except for "value" have changed.
|
|
28
|
+
*/
|
|
29
|
+
Object.defineProperty(match.owner, key, match.descriptor);
|
|
21
30
|
else
|
|
22
31
|
/**
|
|
23
32
|
* @todo Delete the proxy property set by the registry.
|
|
24
|
-
* If the owner isn't
|
|
33
|
+
* If the match's owner isn't the original owner, the property is likely nested in the prototype.
|
|
25
34
|
* The registry does not meddle with those, they are left intact.
|
|
26
35
|
*/
|
|
27
|
-
Reflect.deleteProperty(
|
|
28
|
-
|
|
36
|
+
Reflect.deleteProperty(owner, key);
|
|
37
|
+
currentReplacements.delete(key);
|
|
38
|
+
if (currentReplacements.size === 0) this.#replacements.delete(owner);
|
|
29
39
|
};
|
|
30
|
-
|
|
31
|
-
|
|
40
|
+
if (ownerReplacements) ownerReplacements.set(key, restorePatch);
|
|
41
|
+
else this.#replacements.set(owner, new Map([[key, restorePatch]]));
|
|
42
|
+
return restorePatch;
|
|
32
43
|
}
|
|
33
|
-
|
|
44
|
+
restoreAllPatches() {
|
|
34
45
|
const errors = [];
|
|
35
|
-
for (const [,
|
|
36
|
-
|
|
46
|
+
for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try {
|
|
47
|
+
restorePatch();
|
|
37
48
|
} catch (error) {
|
|
38
49
|
if (error instanceof Error) errors.push(error);
|
|
39
50
|
else throw error;
|
|
@@ -41,7 +52,7 @@ var GlobalsRegistry = class {
|
|
|
41
52
|
if (errors.length > 0) throw new AggregateError(errors, "FOO!");
|
|
42
53
|
}
|
|
43
54
|
};
|
|
44
|
-
const
|
|
55
|
+
const patchesRegistry = new PatchesRegistry();
|
|
45
56
|
/**
|
|
46
57
|
* Returns a property descriptor for the given property on the owner.
|
|
47
58
|
* Walks down the prototype chain if the property does not exist on the owner.
|
|
@@ -81,5 +92,5 @@ function hasConfigurableGlobal(propertyName) {
|
|
|
81
92
|
}
|
|
82
93
|
|
|
83
94
|
//#endregion
|
|
84
|
-
export {
|
|
85
|
-
//# sourceMappingURL=hasConfigurableGlobal-
|
|
95
|
+
export { patchesRegistry as n, hasConfigurableGlobal as t };
|
|
96
|
+
//# sourceMappingURL=hasConfigurableGlobal-BiTmog1u.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hasConfigurableGlobal-BiTmog1u.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 if (match.descriptor.configurable) {\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n } else if (match.descriptor.writable) {\n owner[key] = getNextValue(owner[key])\n } else {\n throw new Error(\n `Failed to patch a non-configurable non-writable property \"${key.toString()}\"`\n )\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 /**\n * @note Restoring non-configurable properties works as long as \"writable: true\"\n * and none of the other descriptor properties except for \"value\" have changed.\n */\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,MAAI,MAAM,WAAW,aACnB,QAAO,eAAe,OAAO,KAAK;GAChC,OAAO,aAAa,MAAM,KAAK;GAC/B,YAAY;GACZ,cAAc;GACf,CAAC;WACO,MAAM,WAAW,SAC1B,OAAM,OAAO,aAAa,MAAM,KAAK;MAErC,OAAM,IAAI,MACR,6DAA6D,IAAI,UAAU,CAAC,GAC7E;EAGH,MAAM,qBAAqB;GACzB,MAAM,sBAAsB,MAAKA,aAAc,IAAI,MAAM;AAEzD,OAAI,CAAC,qBAAqB,IAAI,IAAI,CAChC;AAGF,OAAI,MAAM,UAAU;;;;;AAKlB,UAAO,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;;;;;;;;;;AC7HtD,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,40 +1,51 @@
|
|
|
1
1
|
const require_chunk = require('./chunk-CbDLau6x.cjs');
|
|
2
2
|
let outvariant = require("outvariant");
|
|
3
3
|
|
|
4
|
-
//#region src/utils/
|
|
5
|
-
var
|
|
6
|
-
#
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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(
|
|
15
|
-
value:
|
|
15
|
+
if (match.descriptor.configurable) Object.defineProperty(owner, key, {
|
|
16
|
+
value: getNextValue(owner[key]),
|
|
16
17
|
enumerable: true,
|
|
17
18
|
configurable: true
|
|
18
19
|
});
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
else if (match.descriptor.writable) owner[key] = getNextValue(owner[key]);
|
|
21
|
+
else throw new Error(`Failed to patch a non-configurable non-writable property "${key.toString()}"`);
|
|
22
|
+
const restorePatch = () => {
|
|
23
|
+
const currentReplacements = this.#replacements.get(owner);
|
|
24
|
+
if (!currentReplacements?.has(key)) return;
|
|
25
|
+
if (match.owner === owner)
|
|
26
|
+
/**
|
|
27
|
+
* @note Restoring non-configurable properties works as long as "writable: true"
|
|
28
|
+
* and none of the other descriptor properties except for "value" have changed.
|
|
29
|
+
*/
|
|
30
|
+
Object.defineProperty(match.owner, key, match.descriptor);
|
|
22
31
|
else
|
|
23
32
|
/**
|
|
24
33
|
* @todo Delete the proxy property set by the registry.
|
|
25
|
-
* If the owner isn't
|
|
34
|
+
* If the match's owner isn't the original owner, the property is likely nested in the prototype.
|
|
26
35
|
* The registry does not meddle with those, they are left intact.
|
|
27
36
|
*/
|
|
28
|
-
Reflect.deleteProperty(
|
|
29
|
-
|
|
37
|
+
Reflect.deleteProperty(owner, key);
|
|
38
|
+
currentReplacements.delete(key);
|
|
39
|
+
if (currentReplacements.size === 0) this.#replacements.delete(owner);
|
|
30
40
|
};
|
|
31
|
-
|
|
32
|
-
|
|
41
|
+
if (ownerReplacements) ownerReplacements.set(key, restorePatch);
|
|
42
|
+
else this.#replacements.set(owner, new Map([[key, restorePatch]]));
|
|
43
|
+
return restorePatch;
|
|
33
44
|
}
|
|
34
|
-
|
|
45
|
+
restoreAllPatches() {
|
|
35
46
|
const errors = [];
|
|
36
|
-
for (const [,
|
|
37
|
-
|
|
47
|
+
for (const [, ownerReplacements] of this.#replacements) for (const [, restorePatch] of ownerReplacements) try {
|
|
48
|
+
restorePatch();
|
|
38
49
|
} catch (error) {
|
|
39
50
|
if (error instanceof Error) errors.push(error);
|
|
40
51
|
else throw error;
|
|
@@ -42,7 +53,7 @@ var GlobalsRegistry = class {
|
|
|
42
53
|
if (errors.length > 0) throw new AggregateError(errors, "FOO!");
|
|
43
54
|
}
|
|
44
55
|
};
|
|
45
|
-
const
|
|
56
|
+
const patchesRegistry = new PatchesRegistry();
|
|
46
57
|
/**
|
|
47
58
|
* Returns a property descriptor for the given property on the owner.
|
|
48
59
|
* Walks down the prototype chain if the property does not exist on the owner.
|
|
@@ -82,16 +93,16 @@ function hasConfigurableGlobal(propertyName) {
|
|
|
82
93
|
}
|
|
83
94
|
|
|
84
95
|
//#endregion
|
|
85
|
-
Object.defineProperty(exports, '
|
|
96
|
+
Object.defineProperty(exports, 'hasConfigurableGlobal', {
|
|
86
97
|
enumerable: true,
|
|
87
98
|
get: function () {
|
|
88
|
-
return
|
|
99
|
+
return hasConfigurableGlobal;
|
|
89
100
|
}
|
|
90
101
|
});
|
|
91
|
-
Object.defineProperty(exports, '
|
|
102
|
+
Object.defineProperty(exports, 'patchesRegistry', {
|
|
92
103
|
enumerable: true,
|
|
93
104
|
get: function () {
|
|
94
|
-
return
|
|
105
|
+
return patchesRegistry;
|
|
95
106
|
}
|
|
96
107
|
});
|
|
97
|
-
//# sourceMappingURL=hasConfigurableGlobal-
|
|
108
|
+
//# sourceMappingURL=hasConfigurableGlobal-MjY06_Ok.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hasConfigurableGlobal-MjY06_Ok.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 if (match.descriptor.configurable) {\n Object.defineProperty(owner, key, {\n value: getNextValue(owner[key]),\n enumerable: true,\n configurable: true,\n })\n } else if (match.descriptor.writable) {\n owner[key] = getNextValue(owner[key])\n } else {\n throw new Error(\n `Failed to patch a non-configurable non-writable property \"${key.toString()}\"`\n )\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 /**\n * @note Restoring non-configurable properties works as long as \"writable: true\"\n * and none of the other descriptor properties except for \"value\" have changed.\n */\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,MAAI,MAAM,WAAW,aACnB,QAAO,eAAe,OAAO,KAAK;GAChC,OAAO,aAAa,MAAM,KAAK;GAC/B,YAAY;GACZ,cAAc;GACf,CAAC;WACO,MAAM,WAAW,SAC1B,OAAM,OAAO,aAAa,MAAM,KAAK;MAErC,OAAM,IAAI,MACR,6DAA6D,IAAI,UAAU,CAAC,GAC7E;EAGH,MAAM,qBAAqB;GACzB,MAAM,sBAAsB,MAAKA,aAAc,IAAI,MAAM;AAEzD,OAAI,CAAC,qBAAqB,IAAI,IAAI,CAChC;AAGF,OAAI,MAAM,UAAU;;;;;AAKlB,UAAO,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;;;;;;;;;;AC7HtD,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"}
|
package/lib/node/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const require_fetchUtils = require('./fetchUtils-
|
|
2
|
-
const require_BatchInterceptor = require('./BatchInterceptor-
|
|
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
|
|
package/lib/node/index.d.cts
CHANGED
|
@@ -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
|
package/lib/node/index.d.mts
CHANGED
|
@@ -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
|
package/lib/node/index.mjs
CHANGED
|
@@ -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-
|
|
2
|
-
import { t as BatchInterceptor } from "./BatchInterceptor-
|
|
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-
|
|
2
|
-
const require_ClientRequest = require('../../ClientRequest-
|
|
3
|
-
require('../../handleRequest-
|
|
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-
|
|
2
|
-
import { t as ClientRequestInterceptor } from "../../ClientRequest-
|
|
3
|
-
import "../../handleRequest-
|
|
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-
|
|
1
|
+
require('../../fetchUtils-umV5xXBy.cjs');
|
|
2
2
|
require('../../bufferUtils-S5_-2eN4.cjs');
|
|
3
|
-
require('../../handleRequest-
|
|
4
|
-
const require_XMLHttpRequest = require('../../XMLHttpRequest-
|
|
5
|
-
require('../../hasConfigurableGlobal-
|
|
3
|
+
require('../../handleRequest-DVOthWJo.cjs');
|
|
4
|
+
const require_XMLHttpRequest = require('../../XMLHttpRequest-Dyi6ahGz.cjs');
|
|
5
|
+
require('../../hasConfigurableGlobal-MjY06_Ok.cjs');
|
|
6
6
|
|
|
7
7
|
exports.XMLHttpRequestInterceptor = require_XMLHttpRequest.XMLHttpRequestInterceptor;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import "../../fetchUtils-
|
|
1
|
+
import "../../fetchUtils-BKJ1XmiO.mjs";
|
|
2
2
|
import "../../bufferUtils-DxPxwff_.mjs";
|
|
3
|
-
import "../../handleRequest-
|
|
4
|
-
import { t as XMLHttpRequestInterceptor } from "../../XMLHttpRequest-
|
|
5
|
-
import "../../hasConfigurableGlobal-
|
|
3
|
+
import "../../handleRequest-DCLzePtS.mjs";
|
|
4
|
+
import { t as XMLHttpRequestInterceptor } from "../../XMLHttpRequest-DhupxLHX.mjs";
|
|
5
|
+
import "../../hasConfigurableGlobal-BiTmog1u.mjs";
|
|
6
6
|
|
|
7
7
|
export { XMLHttpRequestInterceptor };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
require('../../fetchUtils-
|
|
2
|
-
require('../../handleRequest-
|
|
3
|
-
require('../../hasConfigurableGlobal-
|
|
4
|
-
const require_fetch = require('../../fetch-
|
|
1
|
+
require('../../fetchUtils-umV5xXBy.cjs');
|
|
2
|
+
require('../../handleRequest-DVOthWJo.cjs');
|
|
3
|
+
require('../../hasConfigurableGlobal-MjY06_Ok.cjs');
|
|
4
|
+
const require_fetch = require('../../fetch-aQJu1Gf_.cjs');
|
|
5
5
|
|
|
6
6
|
exports.FetchInterceptor = require_fetch.FetchInterceptor;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "../../fetchUtils-
|
|
2
|
-
import "../../handleRequest-
|
|
3
|
-
import "../../hasConfigurableGlobal-
|
|
4
|
-
import { t as FetchInterceptor } from "../../fetch-
|
|
1
|
+
import "../../fetchUtils-BKJ1XmiO.mjs";
|
|
2
|
+
import "../../handleRequest-DCLzePtS.mjs";
|
|
3
|
+
import "../../hasConfigurableGlobal-BiTmog1u.mjs";
|
|
4
|
+
import { t as FetchInterceptor } from "../../fetch-BqMcbuYR.mjs";
|
|
5
5
|
|
|
6
6
|
export { FetchInterceptor };
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
require('../fetchUtils-
|
|
1
|
+
require('../fetchUtils-umV5xXBy.cjs');
|
|
2
2
|
require('../bufferUtils-S5_-2eN4.cjs');
|
|
3
|
-
const require_ClientRequest = require('../ClientRequest-
|
|
4
|
-
require('../handleRequest-
|
|
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-
|
|
7
|
-
require('../hasConfigurableGlobal-
|
|
8
|
-
const require_fetch = require('../fetch-
|
|
6
|
+
const require_XMLHttpRequest = require('../XMLHttpRequest-Dyi6ahGz.cjs');
|
|
7
|
+
require('../hasConfigurableGlobal-MjY06_Ok.cjs');
|
|
8
|
+
const require_fetch = require('../fetch-aQJu1Gf_.cjs');
|
|
9
9
|
|
|
10
10
|
//#region src/presets/node.ts
|
|
11
11
|
/**
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import "../fetchUtils-
|
|
1
|
+
import "../fetchUtils-BKJ1XmiO.mjs";
|
|
2
2
|
import "../bufferUtils-DxPxwff_.mjs";
|
|
3
|
-
import { t as ClientRequestInterceptor } from "../ClientRequest-
|
|
4
|
-
import "../handleRequest-
|
|
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-
|
|
7
|
-
import "../hasConfigurableGlobal-
|
|
8
|
-
import { t as FetchInterceptor } from "../fetch-
|
|
6
|
+
import { t as XMLHttpRequestInterceptor } from "../XMLHttpRequest-DhupxLHX.mjs";
|
|
7
|
+
import "../hasConfigurableGlobal-BiTmog1u.mjs";
|
|
8
|
+
import { t as FetchInterceptor } from "../fetch-BqMcbuYR.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.
|
|
5
|
+
"version": "0.41.8",
|
|
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
|
-
[
|
|
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
|
-
...
|
|
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
|
-
|
|
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
|
-
|
|
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 {
|
|
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
|
-
|
|
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 {
|
|
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
|
-
|
|
28
|
-
|
|
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(
|