@mswjs/interceptors 0.41.4 → 0.41.5
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-C2KXXdBy.cjs → XMLHttpRequest-DSAhl6_a.cjs} +9 -21
- package/lib/browser/XMLHttpRequest-DSAhl6_a.cjs.map +1 -0
- package/lib/browser/{XMLHttpRequest-Bbvn_AjX.mjs → XMLHttpRequest-DYyDAIJh.mjs} +9 -21
- package/lib/{node/XMLHttpRequest-BBbs-p9i.mjs.map → browser/XMLHttpRequest-DYyDAIJh.mjs.map} +1 -1
- package/lib/browser/{createRequestId-Cs4oXfa1.cjs → createRequestId-DOf8Ktjs.cjs} +1 -1
- package/lib/browser/{createRequestId-Cs4oXfa1.cjs.map → createRequestId-DOf8Ktjs.cjs.map} +1 -1
- package/lib/browser/{createRequestId-DQcIlohW.mjs → createRequestId-DYCsFHOi.mjs} +1 -1
- package/lib/browser/{createRequestId-DQcIlohW.mjs.map → createRequestId-DYCsFHOi.mjs.map} +1 -1
- package/lib/browser/{fetch-CJYWVliE.cjs → fetch-BMC2en2x.cjs} +10 -18
- package/lib/browser/fetch-BMC2en2x.cjs.map +1 -0
- package/lib/browser/{fetch-D4es-Apw.mjs → fetch-D5LGhx5i.mjs} +10 -18
- package/lib/browser/fetch-D5LGhx5i.mjs.map +1 -0
- package/lib/browser/{getRawRequest-DaxX6uMy.cjs → getRawRequest-B9kRTvjs.cjs} +1 -11
- package/lib/browser/getRawRequest-B9kRTvjs.cjs.map +1 -0
- package/lib/browser/{getRawRequest-Df640uw8.mjs → getRawRequest-BEw5hEOW.mjs} +2 -6
- package/lib/browser/getRawRequest-BEw5hEOW.mjs.map +1 -0
- package/lib/browser/{glossary-BdLS4k1H.d.cts → glossary-1lhZx6Aw.d.cts} +2 -3
- package/lib/browser/{glossary-DYwOrogs.d.mts → glossary-nkHWcwvY.d.mts} +2 -3
- package/lib/browser/{handleRequest--veikAod.cjs → handleRequest-BCtqvFSS.cjs} +3 -3
- package/lib/browser/{handleRequest--veikAod.cjs.map → handleRequest-BCtqvFSS.cjs.map} +1 -1
- package/lib/browser/{handleRequest-Dq1a55b4.mjs → handleRequest-DuUoGpfA.mjs} +3 -3
- package/lib/browser/{handleRequest-Dq1a55b4.mjs.map → handleRequest-DuUoGpfA.mjs.map} +1 -1
- package/lib/browser/hasConfigurableGlobal-B39W0thh.mjs +98 -0
- package/lib/browser/hasConfigurableGlobal-B39W0thh.mjs.map +1 -0
- package/lib/browser/hasConfigurableGlobal-B5o6PHq3.cjs +115 -0
- package/lib/browser/hasConfigurableGlobal-B5o6PHq3.cjs.map +1 -0
- package/lib/browser/index.cjs +2 -3
- package/lib/browser/index.d.cts +2 -2
- package/lib/browser/index.d.mts +2 -2
- package/lib/browser/index.mjs +3 -3
- package/lib/browser/interceptors/WebSocket/index.cjs +6 -10
- package/lib/browser/interceptors/WebSocket/index.cjs.map +1 -1
- package/lib/browser/interceptors/WebSocket/index.mjs +6 -10
- package/lib/browser/interceptors/WebSocket/index.mjs.map +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.cjs +5 -4
- package/lib/browser/interceptors/XMLHttpRequest/index.d.cts +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.d.mts +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.mjs +5 -4
- package/lib/browser/interceptors/fetch/index.cjs +5 -4
- package/lib/browser/interceptors/fetch/index.d.cts +1 -1
- package/lib/browser/interceptors/fetch/index.d.mts +1 -1
- package/lib/browser/interceptors/fetch/index.mjs +5 -4
- package/lib/browser/presets/browser.cjs +6 -5
- package/lib/browser/presets/browser.cjs.map +1 -1
- package/lib/browser/presets/browser.mjs +6 -5
- package/lib/browser/presets/browser.mjs.map +1 -1
- package/lib/node/{BatchInterceptor-7u9fqQIe.cjs → BatchInterceptor-AZr7q8p_.cjs} +2 -2
- package/lib/node/{BatchInterceptor-7u9fqQIe.cjs.map → BatchInterceptor-AZr7q8p_.cjs.map} +1 -1
- package/lib/node/{BatchInterceptor-BxgAXyLw.mjs → BatchInterceptor-B2YAn5m9.mjs} +2 -2
- package/lib/node/{BatchInterceptor-BxgAXyLw.mjs.map → BatchInterceptor-B2YAn5m9.mjs.map} +1 -1
- package/lib/node/{BatchInterceptor-D7mXzHcQ.d.mts → BatchInterceptor-KKF8Q47I.d.cts} +2 -2
- package/lib/node/{BatchInterceptor-D_YqR8qU.d.cts → BatchInterceptor-rSr-NH_H.d.mts} +2 -2
- package/lib/node/{ClientRequest-Cl3Ky7Tw.mjs → ClientRequest-5WjHvs9Y.mjs} +5 -5
- package/lib/node/{ClientRequest-Cl3Ky7Tw.mjs.map → ClientRequest-5WjHvs9Y.mjs.map} +1 -1
- package/lib/node/{ClientRequest-CMSXChAM.cjs → ClientRequest-BgwQG-9G.cjs} +5 -5
- package/lib/node/{ClientRequest-CMSXChAM.cjs.map → ClientRequest-BgwQG-9G.cjs.map} +1 -1
- package/lib/node/{Interceptor-DJ2akVWI.d.cts → Interceptor-BsZ21ue0.d.cts} +2 -3
- package/lib/node/{Interceptor-DEazpLJd.d.mts → Interceptor-soD-WpQO.d.mts} +2 -3
- package/lib/node/RemoteHttpInterceptor.cjs +9 -8
- package/lib/node/RemoteHttpInterceptor.cjs.map +1 -1
- package/lib/node/RemoteHttpInterceptor.d.cts +3 -3
- package/lib/node/RemoteHttpInterceptor.d.mts +3 -3
- package/lib/node/RemoteHttpInterceptor.mjs +9 -8
- package/lib/node/RemoteHttpInterceptor.mjs.map +1 -1
- package/lib/node/{XMLHttpRequest-Dj3xJgke.cjs → XMLHttpRequest-B7sloBex.cjs} +10 -23
- package/lib/node/XMLHttpRequest-B7sloBex.cjs.map +1 -0
- package/lib/node/{XMLHttpRequest-BBbs-p9i.mjs → XMLHttpRequest-DmsdUGmj.mjs} +10 -23
- package/lib/{browser/XMLHttpRequest-Bbvn_AjX.mjs.map → node/XMLHttpRequest-DmsdUGmj.mjs.map} +1 -1
- package/lib/node/{bufferUtils-_8XfKIfX.mjs → bufferUtils-DxPxwff_.mjs} +1 -1
- package/lib/node/{bufferUtils-_8XfKIfX.mjs.map → bufferUtils-DxPxwff_.mjs.map} +1 -1
- package/lib/node/{bufferUtils-DiCTqG-7.cjs → bufferUtils-S5_-2eN4.cjs} +1 -1
- package/lib/node/{bufferUtils-DiCTqG-7.cjs.map → bufferUtils-S5_-2eN4.cjs.map} +1 -1
- package/lib/node/{fetch-DmiwAmpu.mjs → fetch-DDAGTtZi.mjs} +10 -19
- package/lib/node/fetch-DDAGTtZi.mjs.map +1 -0
- package/lib/node/{fetch-BoCFyaYx.cjs → fetch-uc7pNtPg.cjs} +10 -19
- package/lib/node/fetch-uc7pNtPg.cjs.map +1 -0
- package/lib/node/{fetchUtils-BTrdMHGp.mjs → fetchUtils-BJxD7wvl.mjs} +1 -1
- package/lib/node/{fetchUtils-BTrdMHGp.mjs.map → fetchUtils-BJxD7wvl.mjs.map} +1 -1
- package/lib/node/{fetchUtils-DE_q7tpr.cjs → fetchUtils-Dw6kQghF.cjs} +1 -1
- package/lib/node/{fetchUtils-DE_q7tpr.cjs.map → fetchUtils-Dw6kQghF.cjs.map} +1 -1
- package/lib/node/{getRawRequest-BavnMWh_.cjs → getRawRequest-B6znU6il.cjs} +1 -1
- package/lib/node/{getRawRequest-BavnMWh_.cjs.map → getRawRequest-B6znU6il.cjs.map} +1 -1
- package/lib/node/{getRawRequest-DnwmXyOW.mjs → getRawRequest-C2-1urzA.mjs} +1 -1
- package/lib/node/{getRawRequest-DnwmXyOW.mjs.map → getRawRequest-C2-1urzA.mjs.map} +1 -1
- package/lib/node/{handleRequest-CDabRyt1.mjs → handleRequest-DGfUg9bm.mjs} +2 -2
- package/lib/node/{handleRequest-CDabRyt1.mjs.map → handleRequest-DGfUg9bm.mjs.map} +1 -1
- package/lib/node/{handleRequest-pLIe3KKo.cjs → handleRequest-Dzg1d3e5.cjs} +2 -2
- package/lib/node/{handleRequest-pLIe3KKo.cjs.map → handleRequest-Dzg1d3e5.cjs.map} +1 -1
- package/lib/node/hasConfigurableGlobal-Befl_QJD.cjs +97 -0
- package/lib/node/hasConfigurableGlobal-Befl_QJD.cjs.map +1 -0
- package/lib/node/hasConfigurableGlobal-jN_-v3gp.mjs +85 -0
- package/lib/node/hasConfigurableGlobal-jN_-v3gp.mjs.map +1 -0
- package/lib/node/{index-BMbJ8FXL.d.cts → index-BJ5E5aW-.d.cts} +2 -2
- package/lib/node/{index-C0YAQ36w.d.mts → index-DfoF45ih.d.mts} +2 -2
- package/lib/node/index.cjs +4 -6
- package/lib/node/index.cjs.map +1 -1
- package/lib/node/index.d.cts +3 -3
- package/lib/node/index.d.mts +3 -3
- package/lib/node/index.mjs +5 -6
- package/lib/node/index.mjs.map +1 -1
- package/lib/node/interceptors/ClientRequest/index.cjs +4 -4
- package/lib/node/interceptors/ClientRequest/index.d.cts +1 -1
- package/lib/node/interceptors/ClientRequest/index.d.mts +2 -2
- package/lib/node/interceptors/ClientRequest/index.mjs +4 -4
- package/lib/node/interceptors/XMLHttpRequest/index.cjs +5 -4
- package/lib/node/interceptors/XMLHttpRequest/index.d.cts +1 -1
- package/lib/node/interceptors/XMLHttpRequest/index.d.mts +1 -1
- package/lib/node/interceptors/XMLHttpRequest/index.mjs +5 -4
- package/lib/node/interceptors/fetch/index.cjs +4 -3
- package/lib/node/interceptors/fetch/index.d.cts +1 -1
- package/lib/node/interceptors/fetch/index.d.mts +1 -1
- package/lib/node/interceptors/fetch/index.mjs +4 -3
- package/lib/node/{node-dKdAf3tC.cjs → node-DIKcnzhK.cjs} +2 -2
- package/lib/node/{node-dKdAf3tC.cjs.map → node-DIKcnzhK.cjs.map} +1 -1
- package/lib/node/{node-DwCc6iuP.mjs → node-lsdNwZEW.mjs} +2 -2
- package/lib/node/{node-DwCc6iuP.mjs.map → node-lsdNwZEW.mjs.map} +1 -1
- package/lib/node/presets/node.cjs +8 -7
- package/lib/node/presets/node.cjs.map +1 -1
- package/lib/node/presets/node.d.cts +1 -1
- package/lib/node/presets/node.d.mts +2 -2
- package/lib/node/presets/node.mjs +8 -7
- package/lib/node/presets/node.mjs.map +1 -1
- package/lib/node/utils/node/index.cjs +1 -1
- package/lib/node/utils/node/index.mjs +1 -1
- package/package.json +1 -1
- package/src/glossary.ts +3 -5
- package/src/interceptors/WebSocket/index.ts +8 -15
- package/src/interceptors/XMLHttpRequest/index.ts +12 -32
- package/src/interceptors/fetch/index.ts +8 -24
- package/src/utils/globalUtils.test.ts +144 -0
- package/src/utils/globalsRegistry.ts +107 -0
- package/src/utils/hasConfigurableGlobal.test.ts +11 -0
- package/src/utils/hasConfigurableGlobal.ts +9 -3
- package/lib/browser/XMLHttpRequest-C2KXXdBy.cjs.map +0 -1
- package/lib/browser/fetch-CJYWVliE.cjs.map +0 -1
- package/lib/browser/fetch-D4es-Apw.mjs.map +0 -1
- package/lib/browser/getRawRequest-DaxX6uMy.cjs.map +0 -1
- package/lib/browser/getRawRequest-Df640uw8.mjs.map +0 -1
- package/lib/browser/hasConfigurableGlobal-BvCTG97d.cjs +0 -45
- package/lib/browser/hasConfigurableGlobal-BvCTG97d.cjs.map +0 -1
- package/lib/browser/hasConfigurableGlobal-npXitu1-.mjs +0 -33
- package/lib/browser/hasConfigurableGlobal-npXitu1-.mjs.map +0 -1
- package/lib/node/XMLHttpRequest-Dj3xJgke.cjs.map +0 -1
- package/lib/node/fetch-BoCFyaYx.cjs.map +0 -1
- package/lib/node/fetch-DmiwAmpu.mjs.map +0 -1
- package/lib/node/glossary-BLKRyLBd.cjs +0 -12
- package/lib/node/glossary-BLKRyLBd.cjs.map +0 -1
- package/lib/node/glossary-glQBRnVD.mjs +0 -6
- package/lib/node/glossary-glQBRnVD.mjs.map +0 -1
- package/lib/node/hasConfigurableGlobal-C97fWuaA.cjs +0 -26
- package/lib/node/hasConfigurableGlobal-C97fWuaA.cjs.map +0 -1
- package/lib/node/hasConfigurableGlobal-DBJA0vjm.mjs +0 -20
- package/lib/node/hasConfigurableGlobal-DBJA0vjm.mjs.map +0 -1
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { invariant } from "outvariant";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/emitAsync.ts
|
|
4
|
+
/**
|
|
5
|
+
* Emits an event on the given emitter but executes
|
|
6
|
+
* the listeners sequentially. This accounts for asynchronous
|
|
7
|
+
* listeners (e.g. those having "sleep" and handling the request).
|
|
8
|
+
*/
|
|
9
|
+
async function emitAsync(emitter, eventName, ...data) {
|
|
10
|
+
const listeners = emitter.listeners(eventName);
|
|
11
|
+
if (listeners.length === 0) return;
|
|
12
|
+
for (const listener of listeners) await listener.apply(emitter, data);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/utils/globalsRegistry.ts
|
|
17
|
+
var GlobalsRegistry = class {
|
|
18
|
+
#globals = /* @__PURE__ */ new Map();
|
|
19
|
+
replaceGlobal(key, nextValue) {
|
|
20
|
+
invariant(!this.#globals.has(key), `Failed to replace a global value at "${key}": already replaced.`);
|
|
21
|
+
const match = getDeepPropertyDescriptor(globalThis, key);
|
|
22
|
+
if (typeof match === "undefined") {
|
|
23
|
+
console.warn(`Failed to replace a global value at "${key}": not a global value.`);
|
|
24
|
+
return () => {};
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(globalThis, key, {
|
|
27
|
+
value: nextValue,
|
|
28
|
+
enumerable: true,
|
|
29
|
+
configurable: true
|
|
30
|
+
});
|
|
31
|
+
const restoreGlobal = () => {
|
|
32
|
+
if (!this.#globals.has(key)) return;
|
|
33
|
+
if (match.owner === globalThis) Object.defineProperty(match.owner, key, match.descriptor);
|
|
34
|
+
else
|
|
35
|
+
/**
|
|
36
|
+
* @todo Delete the proxy property set by the registry.
|
|
37
|
+
* If the owner isn't `globalThis`, the property is likely nested in the prototype.
|
|
38
|
+
* The registry does not meddle with those, they are left intact.
|
|
39
|
+
*/
|
|
40
|
+
Reflect.deleteProperty(globalThis, key);
|
|
41
|
+
this.#globals.delete(key);
|
|
42
|
+
};
|
|
43
|
+
this.#globals.set(key, restoreGlobal);
|
|
44
|
+
return restoreGlobal;
|
|
45
|
+
}
|
|
46
|
+
restoreAllGlobals() {
|
|
47
|
+
const errors = [];
|
|
48
|
+
for (const [, restoreGlobal] of this.#globals) try {
|
|
49
|
+
restoreGlobal();
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (error instanceof Error) errors.push(error);
|
|
52
|
+
else throw error;
|
|
53
|
+
}
|
|
54
|
+
if (errors.length > 0) throw new AggregateError(errors, "FOO!");
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const globalsRegistry = new GlobalsRegistry();
|
|
58
|
+
/**
|
|
59
|
+
* Returns a property descriptor for the given property on the owner.
|
|
60
|
+
* Walks down the prototype chain if the property does not exist on the owner.
|
|
61
|
+
* Handy for getting a global property descriptor where `globalThis` is
|
|
62
|
+
* replaced with a controlled class (e.g. ServiceWorkerGlobalScope).
|
|
63
|
+
*/
|
|
64
|
+
function getDeepPropertyDescriptor(owner, key) {
|
|
65
|
+
let currentOwner = owner;
|
|
66
|
+
let descriptor;
|
|
67
|
+
while (currentOwner) {
|
|
68
|
+
descriptor = Object.getOwnPropertyDescriptor(currentOwner, key);
|
|
69
|
+
if (descriptor) return {
|
|
70
|
+
owner: currentOwner,
|
|
71
|
+
descriptor
|
|
72
|
+
};
|
|
73
|
+
currentOwner = Object.getPrototypeOf(currentOwner);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/utils/hasConfigurableGlobal.ts
|
|
79
|
+
/**
|
|
80
|
+
* Returns a boolean indicating whether the given global property
|
|
81
|
+
* is defined and is configurable.
|
|
82
|
+
*/
|
|
83
|
+
function hasConfigurableGlobal(propertyName) {
|
|
84
|
+
const match = getDeepPropertyDescriptor(globalThis, propertyName);
|
|
85
|
+
if (typeof match === "undefined") return false;
|
|
86
|
+
const { descriptor } = match;
|
|
87
|
+
if (typeof descriptor.get === "function" && typeof descriptor.get() === "undefined") return false;
|
|
88
|
+
if (typeof descriptor.get === "undefined" && descriptor.value == null) return false;
|
|
89
|
+
if (typeof descriptor.set === "undefined" && !descriptor.configurable) {
|
|
90
|
+
console.error(`[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.`);
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
//#endregion
|
|
97
|
+
export { globalsRegistry as n, emitAsync as r, hasConfigurableGlobal as t };
|
|
98
|
+
//# sourceMappingURL=hasConfigurableGlobal-B39W0thh.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hasConfigurableGlobal-B39W0thh.mjs","names":["#globals","errors: Array<Error>","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/emitAsync.ts","../../src/utils/globalsRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","import { invariant } from 'outvariant'\n\nclass GlobalsRegistry {\n #globals = new Map<keyof typeof globalThis, () => void>()\n\n public replaceGlobal<K extends keyof typeof globalThis>(\n key: K,\n nextValue: (typeof globalThis)[K]\n ): () => void {\n invariant(\n !this.#globals.has(key),\n `Failed to replace a global value at \"${key}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(globalThis, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${key}\": not a global value.`\n )\n return () => {}\n }\n\n Object.defineProperty(globalThis, key, {\n value: nextValue,\n enumerable: true,\n configurable: true,\n })\n\n const restoreGlobal = () => {\n if (!this.#globals.has(key)) {\n return\n }\n\n if (match.owner === globalThis) {\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the owner isn't `globalThis`, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(globalThis, key)\n }\n\n this.#globals.delete(key)\n }\n\n this.#globals.set(key, restoreGlobal)\n\n return restoreGlobal\n }\n\n public restoreAllGlobals(): void {\n const errors: Array<Error> = []\n\n for (const [, restoreGlobal] of this.#globals) {\n try {\n restoreGlobal()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const globalsRegistry = new GlobalsRegistry()\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 './globalsRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";;;;;;;;AAOA,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;ACpBvC,IAAM,kBAAN,MAAsB;CACpB,2BAAW,IAAI,KAA0C;CAEzD,AAAO,cACL,KACA,WACY;AACZ,YACE,CAAC,MAAKA,QAAS,IAAI,IAAI,EACvB,wCAAwC,IAAI,sBAC7C;EAED,MAAM,QAAQ,0BAA0B,YAAY,IAAI;AAExD,MAAI,OAAO,UAAU,aAAa;AAChC,WAAQ,KACN,wCAAwC,IAAI,wBAC7C;AACD,gBAAa;;AAGf,SAAO,eAAe,YAAY,KAAK;GACrC,OAAO;GACP,YAAY;GACZ,cAAc;GACf,CAAC;EAEF,MAAM,sBAAsB;AAC1B,OAAI,CAAC,MAAKA,QAAS,IAAI,IAAI,CACzB;AAGF,OAAI,MAAM,UAAU,WAClB,QAAO,eAAe,MAAM,OAAO,KAAK,MAAM,WAAW;;;;;;;AAOzD,WAAQ,eAAe,YAAY,IAAI;AAGzC,SAAKA,QAAS,OAAO,IAAI;;AAG3B,QAAKA,QAAS,IAAI,KAAK,cAAc;AAErC,SAAO;;CAGT,AAAO,oBAA0B;EAC/B,MAAMC,SAAuB,EAAE;AAE/B,OAAK,MAAM,GAAG,kBAAkB,MAAKD,QACnC,KAAI;AACF,kBAAe;WACR,OAAO;AACd,OAAI,iBAAiB,MACnB,QAAO,KAAK,MAAM;OAElB,OAAM;;AAKZ,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;;;;;;;;;;AClGtD,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"}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
let outvariant = require("outvariant");
|
|
2
|
+
|
|
3
|
+
//#region src/utils/emitAsync.ts
|
|
4
|
+
/**
|
|
5
|
+
* Emits an event on the given emitter but executes
|
|
6
|
+
* the listeners sequentially. This accounts for asynchronous
|
|
7
|
+
* listeners (e.g. those having "sleep" and handling the request).
|
|
8
|
+
*/
|
|
9
|
+
async function emitAsync(emitter, eventName, ...data) {
|
|
10
|
+
const listeners = emitter.listeners(eventName);
|
|
11
|
+
if (listeners.length === 0) return;
|
|
12
|
+
for (const listener of listeners) await listener.apply(emitter, data);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/utils/globalsRegistry.ts
|
|
17
|
+
var GlobalsRegistry = class {
|
|
18
|
+
#globals = /* @__PURE__ */ new Map();
|
|
19
|
+
replaceGlobal(key, nextValue) {
|
|
20
|
+
(0, outvariant.invariant)(!this.#globals.has(key), `Failed to replace a global value at "${key}": already replaced.`);
|
|
21
|
+
const match = getDeepPropertyDescriptor(globalThis, key);
|
|
22
|
+
if (typeof match === "undefined") {
|
|
23
|
+
console.warn(`Failed to replace a global value at "${key}": not a global value.`);
|
|
24
|
+
return () => {};
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(globalThis, key, {
|
|
27
|
+
value: nextValue,
|
|
28
|
+
enumerable: true,
|
|
29
|
+
configurable: true
|
|
30
|
+
});
|
|
31
|
+
const restoreGlobal = () => {
|
|
32
|
+
if (!this.#globals.has(key)) return;
|
|
33
|
+
if (match.owner === globalThis) Object.defineProperty(match.owner, key, match.descriptor);
|
|
34
|
+
else
|
|
35
|
+
/**
|
|
36
|
+
* @todo Delete the proxy property set by the registry.
|
|
37
|
+
* If the owner isn't `globalThis`, the property is likely nested in the prototype.
|
|
38
|
+
* The registry does not meddle with those, they are left intact.
|
|
39
|
+
*/
|
|
40
|
+
Reflect.deleteProperty(globalThis, key);
|
|
41
|
+
this.#globals.delete(key);
|
|
42
|
+
};
|
|
43
|
+
this.#globals.set(key, restoreGlobal);
|
|
44
|
+
return restoreGlobal;
|
|
45
|
+
}
|
|
46
|
+
restoreAllGlobals() {
|
|
47
|
+
const errors = [];
|
|
48
|
+
for (const [, restoreGlobal] of this.#globals) try {
|
|
49
|
+
restoreGlobal();
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (error instanceof Error) errors.push(error);
|
|
52
|
+
else throw error;
|
|
53
|
+
}
|
|
54
|
+
if (errors.length > 0) throw new AggregateError(errors, "FOO!");
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const globalsRegistry = new GlobalsRegistry();
|
|
58
|
+
/**
|
|
59
|
+
* Returns a property descriptor for the given property on the owner.
|
|
60
|
+
* Walks down the prototype chain if the property does not exist on the owner.
|
|
61
|
+
* Handy for getting a global property descriptor where `globalThis` is
|
|
62
|
+
* replaced with a controlled class (e.g. ServiceWorkerGlobalScope).
|
|
63
|
+
*/
|
|
64
|
+
function getDeepPropertyDescriptor(owner, key) {
|
|
65
|
+
let currentOwner = owner;
|
|
66
|
+
let descriptor;
|
|
67
|
+
while (currentOwner) {
|
|
68
|
+
descriptor = Object.getOwnPropertyDescriptor(currentOwner, key);
|
|
69
|
+
if (descriptor) return {
|
|
70
|
+
owner: currentOwner,
|
|
71
|
+
descriptor
|
|
72
|
+
};
|
|
73
|
+
currentOwner = Object.getPrototypeOf(currentOwner);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/utils/hasConfigurableGlobal.ts
|
|
79
|
+
/**
|
|
80
|
+
* Returns a boolean indicating whether the given global property
|
|
81
|
+
* is defined and is configurable.
|
|
82
|
+
*/
|
|
83
|
+
function hasConfigurableGlobal(propertyName) {
|
|
84
|
+
const match = getDeepPropertyDescriptor(globalThis, propertyName);
|
|
85
|
+
if (typeof match === "undefined") return false;
|
|
86
|
+
const { descriptor } = match;
|
|
87
|
+
if (typeof descriptor.get === "function" && typeof descriptor.get() === "undefined") return false;
|
|
88
|
+
if (typeof descriptor.get === "undefined" && descriptor.value == null) return false;
|
|
89
|
+
if (typeof descriptor.set === "undefined" && !descriptor.configurable) {
|
|
90
|
+
console.error(`[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.`);
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
//#endregion
|
|
97
|
+
Object.defineProperty(exports, 'emitAsync', {
|
|
98
|
+
enumerable: true,
|
|
99
|
+
get: function () {
|
|
100
|
+
return emitAsync;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
Object.defineProperty(exports, 'globalsRegistry', {
|
|
104
|
+
enumerable: true,
|
|
105
|
+
get: function () {
|
|
106
|
+
return globalsRegistry;
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
Object.defineProperty(exports, 'hasConfigurableGlobal', {
|
|
110
|
+
enumerable: true,
|
|
111
|
+
get: function () {
|
|
112
|
+
return hasConfigurableGlobal;
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
//# sourceMappingURL=hasConfigurableGlobal-B5o6PHq3.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hasConfigurableGlobal-B5o6PHq3.cjs","names":["#globals","errors: Array<Error>","currentOwner: Owner | null","descriptor: PropertyDescriptor | undefined"],"sources":["../../src/utils/emitAsync.ts","../../src/utils/globalsRegistry.ts","../../src/utils/hasConfigurableGlobal.ts"],"sourcesContent":["import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listeners = emitter.listeners(eventName)\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n await listener.apply(emitter, data)\n }\n}\n","import { invariant } from 'outvariant'\n\nclass GlobalsRegistry {\n #globals = new Map<keyof typeof globalThis, () => void>()\n\n public replaceGlobal<K extends keyof typeof globalThis>(\n key: K,\n nextValue: (typeof globalThis)[K]\n ): () => void {\n invariant(\n !this.#globals.has(key),\n `Failed to replace a global value at \"${key}\": already replaced.`\n )\n\n const match = getDeepPropertyDescriptor(globalThis, key)\n\n if (typeof match === 'undefined') {\n console.warn(\n `Failed to replace a global value at \"${key}\": not a global value.`\n )\n return () => {}\n }\n\n Object.defineProperty(globalThis, key, {\n value: nextValue,\n enumerable: true,\n configurable: true,\n })\n\n const restoreGlobal = () => {\n if (!this.#globals.has(key)) {\n return\n }\n\n if (match.owner === globalThis) {\n Object.defineProperty(match.owner, key, match.descriptor)\n } else {\n /**\n * @todo Delete the proxy property set by the registry.\n * If the owner isn't `globalThis`, the property is likely nested in the prototype.\n * The registry does not meddle with those, they are left intact.\n */\n Reflect.deleteProperty(globalThis, key)\n }\n\n this.#globals.delete(key)\n }\n\n this.#globals.set(key, restoreGlobal)\n\n return restoreGlobal\n }\n\n public restoreAllGlobals(): void {\n const errors: Array<Error> = []\n\n for (const [, restoreGlobal] of this.#globals) {\n try {\n restoreGlobal()\n } catch (error) {\n if (error instanceof Error) {\n errors.push(error)\n } else {\n throw error\n }\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'FOO!')\n }\n }\n}\n\nexport const globalsRegistry = new GlobalsRegistry()\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 './globalsRegistry'\n\n/**\n * Returns a boolean indicating whether the given global property\n * is defined and is configurable.\n */\nexport function hasConfigurableGlobal(\n propertyName: keyof typeof globalThis\n): boolean {\n const match = getDeepPropertyDescriptor(globalThis, propertyName)\n\n // The property is not set at all.\n if (typeof match === 'undefined') {\n return false\n }\n\n const { descriptor } = match\n\n // The property is set to a getter that returns undefined.\n if (\n typeof descriptor.get === 'function' &&\n typeof descriptor.get() === 'undefined'\n ) {\n return false\n }\n\n // The property is set to a value equal to undefined.\n if (typeof descriptor.get === 'undefined' && descriptor.value == null) {\n return false\n }\n\n if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {\n console.error(\n `[MSW] Failed to apply interceptor: the global \\`${propertyName}\\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`\n )\n return false\n }\n\n return true\n}\n"],"mappings":";;;;;;;;AAOA,eAAsB,UAIpB,SACA,WACA,GAAG,MACY;CACf,MAAM,YAAY,QAAQ,UAAU,UAAU;AAE9C,KAAI,UAAU,WAAW,EACvB;AAGF,MAAK,MAAM,YAAY,UACrB,OAAM,SAAS,MAAM,SAAS,KAAK;;;;;ACpBvC,IAAM,kBAAN,MAAsB;CACpB,2BAAW,IAAI,KAA0C;CAEzD,AAAO,cACL,KACA,WACY;AACZ,4BACE,CAAC,MAAKA,QAAS,IAAI,IAAI,EACvB,wCAAwC,IAAI,sBAC7C;EAED,MAAM,QAAQ,0BAA0B,YAAY,IAAI;AAExD,MAAI,OAAO,UAAU,aAAa;AAChC,WAAQ,KACN,wCAAwC,IAAI,wBAC7C;AACD,gBAAa;;AAGf,SAAO,eAAe,YAAY,KAAK;GACrC,OAAO;GACP,YAAY;GACZ,cAAc;GACf,CAAC;EAEF,MAAM,sBAAsB;AAC1B,OAAI,CAAC,MAAKA,QAAS,IAAI,IAAI,CACzB;AAGF,OAAI,MAAM,UAAU,WAClB,QAAO,eAAe,MAAM,OAAO,KAAK,MAAM,WAAW;;;;;;;AAOzD,WAAQ,eAAe,YAAY,IAAI;AAGzC,SAAKA,QAAS,OAAO,IAAI;;AAG3B,QAAKA,QAAS,IAAI,KAAK,cAAc;AAErC,SAAO;;CAGT,AAAO,oBAA0B;EAC/B,MAAMC,SAAuB,EAAE;AAE/B,OAAK,MAAM,GAAG,kBAAkB,MAAKD,QACnC,KAAI;AACF,kBAAe;WACR,OAAO;AACd,OAAI,iBAAiB,MACnB,QAAO,KAAK,MAAM;OAElB,OAAM;;AAKZ,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;;;;;;;;;;AClGtD,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/browser/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const
|
|
2
|
-
const
|
|
1
|
+
const require_createRequestId = require('./createRequestId-DOf8Ktjs.cjs');
|
|
2
|
+
const require_getRawRequest = require('./getRawRequest-B9kRTvjs.cjs');
|
|
3
3
|
const require_bufferUtils = require('./bufferUtils-Uc0eRItL.cjs');
|
|
4
4
|
const require_resolveWebSocketUrl = require('./resolveWebSocketUrl-6K6EgqsA.cjs');
|
|
5
5
|
|
|
@@ -56,7 +56,6 @@ exports.BatchInterceptor = BatchInterceptor;
|
|
|
56
56
|
exports.FetchRequest = require_getRawRequest.FetchRequest;
|
|
57
57
|
exports.FetchResponse = require_getRawRequest.FetchResponse;
|
|
58
58
|
exports.INTERNAL_REQUEST_ID_HEADER_NAME = require_createRequestId.INTERNAL_REQUEST_ID_HEADER_NAME;
|
|
59
|
-
exports.IS_PATCHED_MODULE = require_getRawRequest.IS_PATCHED_MODULE;
|
|
60
59
|
exports.Interceptor = require_createRequestId.Interceptor;
|
|
61
60
|
exports.InterceptorReadyState = require_createRequestId.InterceptorReadyState;
|
|
62
61
|
exports.RequestController = require_getRawRequest.RequestController;
|
package/lib/browser/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as RequestControllerSource, n as RequestCredentials, r as RequestController, t as HttpRequestEventMap } from "./glossary-1lhZx6Aw.cjs";
|
|
2
2
|
import { a as InterceptorReadyState, c as getGlobalSymbol, i as InterceptorEventMap, n as INTERNAL_REQUEST_ID_HEADER_NAME, o as InterceptorSubscription, r as Interceptor, s as deleteGlobalSymbol, t as ExtractEventNames } from "./Interceptor-Deczogc8.cjs";
|
|
3
3
|
import { EventMap, Listener } from "strict-event-emitter";
|
|
4
4
|
|
|
@@ -111,5 +111,5 @@ declare function getRawRequest(request: Request): unknown | undefined;
|
|
|
111
111
|
*/
|
|
112
112
|
declare function resolveWebSocketUrl(url: string | URL): string;
|
|
113
113
|
//#endregion
|
|
114
|
-
export { BatchInterceptor, BatchInterceptorOptions, ExtractEventMapType, ExtractEventNames, FetchRequest, FetchResponse, HttpRequestEventMap, INTERNAL_REQUEST_ID_HEADER_NAME,
|
|
114
|
+
export { BatchInterceptor, BatchInterceptorOptions, ExtractEventMapType, ExtractEventNames, FetchRequest, FetchResponse, HttpRequestEventMap, INTERNAL_REQUEST_ID_HEADER_NAME, Interceptor, InterceptorEventMap, InterceptorReadyState, InterceptorSubscription, RequestController, type RequestControllerSource, RequestCredentials, createRequestId, decodeBuffer, deleteGlobalSymbol, encodeBuffer, getCleanUrl, getGlobalSymbol, getRawRequest, resolveWebSocketUrl };
|
|
115
115
|
//# sourceMappingURL=index.d.cts.map
|
package/lib/browser/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as RequestControllerSource, n as RequestCredentials, r as RequestController, t as HttpRequestEventMap } from "./glossary-nkHWcwvY.mjs";
|
|
2
2
|
import { a as InterceptorReadyState, c as getGlobalSymbol, i as InterceptorEventMap, n as INTERNAL_REQUEST_ID_HEADER_NAME, o as InterceptorSubscription, r as Interceptor, s as deleteGlobalSymbol, t as ExtractEventNames } from "./Interceptor-gqKgs-aF.mjs";
|
|
3
3
|
import { EventMap, Listener } from "strict-event-emitter";
|
|
4
4
|
|
|
@@ -111,5 +111,5 @@ declare function getRawRequest(request: Request): unknown | undefined;
|
|
|
111
111
|
*/
|
|
112
112
|
declare function resolveWebSocketUrl(url: string | URL): string;
|
|
113
113
|
//#endregion
|
|
114
|
-
export { BatchInterceptor, BatchInterceptorOptions, ExtractEventMapType, ExtractEventNames, FetchRequest, FetchResponse, HttpRequestEventMap, INTERNAL_REQUEST_ID_HEADER_NAME,
|
|
114
|
+
export { BatchInterceptor, BatchInterceptorOptions, ExtractEventMapType, ExtractEventNames, FetchRequest, FetchResponse, HttpRequestEventMap, INTERNAL_REQUEST_ID_HEADER_NAME, Interceptor, InterceptorEventMap, InterceptorReadyState, InterceptorSubscription, RequestController, type RequestControllerSource, RequestCredentials, createRequestId, decodeBuffer, deleteGlobalSymbol, encodeBuffer, getCleanUrl, getGlobalSymbol, getRawRequest, resolveWebSocketUrl };
|
|
115
115
|
//# sourceMappingURL=index.d.mts.map
|
package/lib/browser/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { a as deleteGlobalSymbol, i as InterceptorReadyState, n as INTERNAL_REQUEST_ID_HEADER_NAME, o as getGlobalSymbol, r as Interceptor, t as createRequestId } from "./createRequestId-DYCsFHOi.mjs";
|
|
2
|
+
import { i as FetchResponse, o as RequestController, r as FetchRequest, t as getRawRequest } from "./getRawRequest-BEw5hEOW.mjs";
|
|
3
3
|
import { n as encodeBuffer, t as decodeBuffer } from "./bufferUtils-BiiO6HZv.mjs";
|
|
4
4
|
import { t as resolveWebSocketUrl } from "./resolveWebSocketUrl-C83-x9iE.mjs";
|
|
5
5
|
|
|
@@ -52,5 +52,5 @@ function getCleanUrl(url, isAbsolute = true) {
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
//#endregion
|
|
55
|
-
export { BatchInterceptor, FetchRequest, FetchResponse, INTERNAL_REQUEST_ID_HEADER_NAME,
|
|
55
|
+
export { BatchInterceptor, FetchRequest, FetchResponse, INTERNAL_REQUEST_ID_HEADER_NAME, Interceptor, InterceptorReadyState, RequestController, createRequestId, decodeBuffer, deleteGlobalSymbol, encodeBuffer, getCleanUrl, getGlobalSymbol, getRawRequest, resolveWebSocketUrl };
|
|
56
56
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const require_createRequestId = require('../../createRequestId-
|
|
1
|
+
const require_createRequestId = require('../../createRequestId-DOf8Ktjs.cjs');
|
|
2
2
|
const require_resolveWebSocketUrl = require('../../resolveWebSocketUrl-6K6EgqsA.cjs');
|
|
3
|
-
const require_hasConfigurableGlobal = require('../../hasConfigurableGlobal-
|
|
3
|
+
const require_hasConfigurableGlobal = require('../../hasConfigurableGlobal-B5o6PHq3.cjs');
|
|
4
4
|
let _open_draft_deferred_promise = require("@open-draft/deferred-promise");
|
|
5
5
|
let outvariant = require("outvariant");
|
|
6
6
|
|
|
@@ -558,7 +558,7 @@ var WebSocketInterceptor = class WebSocketInterceptor extends require_createRequ
|
|
|
558
558
|
return require_hasConfigurableGlobal.hasConfigurableGlobal("WebSocket");
|
|
559
559
|
}
|
|
560
560
|
setup() {
|
|
561
|
-
const
|
|
561
|
+
const logger = this.logger.extend("setup");
|
|
562
562
|
const WebSocketProxy = new Proxy(globalThis.WebSocket, { construct: (target, args, newTarget) => {
|
|
563
563
|
const [url, protocols] = args;
|
|
564
564
|
const createConnection = () => {
|
|
@@ -600,13 +600,9 @@ var WebSocketInterceptor = class WebSocketInterceptor extends require_createRequ
|
|
|
600
600
|
});
|
|
601
601
|
return socket;
|
|
602
602
|
} });
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
});
|
|
607
|
-
this.subscriptions.push(() => {
|
|
608
|
-
Object.defineProperty(globalThis, "WebSocket", originalWebSocketDescriptor);
|
|
609
|
-
});
|
|
603
|
+
logger.info("patching global WebSocket...");
|
|
604
|
+
this.subscriptions.push(require_hasConfigurableGlobal.globalsRegistry.replaceGlobal("WebSocket", WebSocketProxy));
|
|
605
|
+
logger.info("global WebSocket patched!", globalThis.WebSocket.name);
|
|
610
606
|
}
|
|
611
607
|
};
|
|
612
608
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["kEmitter","kBoundListener","socket: WebSocket","transport: WebSocketTransport","createRequestId","resolveWebSocketUrl","DeferredPromise","client: WebSocketOverride","transport: WebSocketClassTransport","createConnection: () => WebSocket","socket: WebSocketOverride","Interceptor","hasConfigurableGlobal","emitAsync"],"sources":["../../../../src/interceptors/WebSocket/utils/bindEvent.ts","../../../../src/interceptors/WebSocket/utils/events.ts","../../../../src/interceptors/WebSocket/WebSocketClientConnection.ts","../../../../src/interceptors/WebSocket/WebSocketOverride.ts","../../../../src/interceptors/WebSocket/WebSocketServerConnection.ts","../../../../src/interceptors/WebSocket/WebSocketClassTransport.ts","../../../../src/interceptors/WebSocket/index.ts"],"sourcesContent":["type EventWithTarget<E extends Event, T> = E & { target: T }\n\nexport function bindEvent<E extends Event, T>(\n target: T,\n event: E\n): EventWithTarget<E, T> {\n Object.defineProperties(event, {\n target: {\n value: target,\n enumerable: true,\n writable: true,\n },\n currentTarget: {\n value: target,\n enumerable: true,\n writable: true,\n },\n })\n\n return event as EventWithTarget<E, T>\n}\n","const kCancelable = Symbol('kCancelable')\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\n\n/**\n * A `MessageEvent` superset that supports event cancellation\n * in Node.js. It's rather non-intrusive so it can be safely\n * used in the browser as well.\n *\n * @see https://github.com/nodejs/node/issues/51767\n */\nexport class CancelableMessageEvent<T = any> extends MessageEvent<T> {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: MessageEventInit<T>) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number\n reason?: string\n wasClean?: boolean\n}\n\nexport class CloseEvent extends Event {\n public code: number\n public reason: string\n public wasClean: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this.code = init.code === undefined ? 0 : init.code\n this.reason = init.reason === undefined ? '' : init.reason\n this.wasClean = init.wasClean === undefined ? false : init.wasClean\n }\n}\n\nexport class CancelableCloseEvent extends CloseEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n","import type { WebSocketData, WebSocketTransport } from './WebSocketTransport'\nimport type { WebSocketEventListener } from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../createRequestId'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\nexport interface WebSocketClientEventMap {\n message: MessageEvent<WebSocketData>\n close: CloseEvent\n}\n\nexport abstract class WebSocketClientConnectionProtocol {\n abstract id: string\n abstract url: URL\n public abstract send(data: WebSocketData): void\n public abstract close(code?: number, reason?: string): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n type: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket client instance represents an incoming\n * client connection. The user can control the connection,\n * send and receive events.\n */\nexport class WebSocketClientConnection implements WebSocketClientConnectionProtocol {\n public readonly id: string\n public readonly url: URL\n\n private [kEmitter]: EventTarget\n\n constructor(\n public readonly socket: WebSocket,\n private readonly transport: WebSocketTransport\n ) {\n this.id = createRequestId()\n this.url = new URL(socket.url)\n this[kEmitter] = new EventTarget()\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n\n // This is a bit silly but forward the cancellation state\n // of the \"client\" message event to the \"outgoing\" transport event.\n // This way, other agens (like \"server\" connection) can know\n // whether the client listener has pervented the default.\n if (message.defaultPrevented) {\n event.preventDefault()\n }\n })\n\n /**\n * Emit the \"close\" event on the \"client\" connection\n * whenever the underlying transport is closed.\n * @note \"client.close()\" does NOT dispatch the \"close\"\n * event on the WebSocket because it uses non-configurable\n * close status code. Thus, we listen to the transport\n * instead of the WebSocket's \"close\" event.\n */\n this.transport.addEventListener('close', (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.socket, new CloseEvent('close', event))\n )\n })\n }\n\n /**\n * Listen for the outgoing events from the connected WebSocket client.\n */\n public addEventListener<EventType extends keyof WebSocketClientEventMap>(\n type: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n configurable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n type,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Removes the listener for the given event.\n */\n public removeEventListener<EventType extends keyof WebSocketClientEventMap>(\n event: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the connected client.\n */\n public send(data: WebSocketData): void {\n this.transport.send(data)\n }\n\n /**\n * Close the WebSocket connection.\n * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1).\n * @param {string} reason A custom connection close reason.\n */\n public close(code?: number, reason?: string): void {\n this.transport.close(code, reason)\n }\n}\n","import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport type { WebSocketData } from './WebSocketTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CloseEvent } from './utils/events'\nimport { resolveWebSocketUrl } from '../../utils/resolveWebSocketUrl'\n\nexport type WebSocketEventListener<\n EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event,\n> = (this: WebSocket, event: EventType) => void\n\nconst WEBSOCKET_CLOSE_CODE_RANGE_ERROR =\n 'InvalidAccessError: close code out of user configurable range'\n\nexport const kPassthroughPromise = Symbol('kPassthroughPromise')\nexport const kOnSend = Symbol('kOnSend')\nexport const kClose = Symbol('kClose')\n\nexport class WebSocketOverride extends EventTarget implements WebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n readonly CONNECTING = 0\n readonly OPEN = 1\n readonly CLOSING = 2\n readonly CLOSED = 3\n\n public url: string\n public protocol: string\n public extensions: string\n public binaryType: BinaryType\n public readyState: WebSocket['readyState']\n public bufferedAmount: number\n\n private _onopen: WebSocketEventListener | null = null\n private _onmessage: WebSocketEventListener<\n MessageEvent<WebSocketData>\n > | null = null\n private _onerror: WebSocketEventListener | null = null\n private _onclose: WebSocketEventListener<CloseEvent> | null = null\n\n private [kPassthroughPromise]: DeferredPromise<boolean>\n private [kOnSend]?: (data: WebSocketData) => void\n\n constructor(url: string | URL, protocols?: string | Array<string>) {\n super()\n this.url = resolveWebSocketUrl(url)\n this.protocol = ''\n this.extensions = ''\n this.binaryType = 'blob'\n this.readyState = this.CONNECTING\n this.bufferedAmount = 0\n\n this[kPassthroughPromise] = new DeferredPromise<boolean>()\n\n queueMicrotask(async () => {\n if (await this[kPassthroughPromise]) {\n return\n }\n\n this.protocol =\n typeof protocols === 'string'\n ? protocols\n : Array.isArray(protocols) && protocols.length > 0\n ? protocols[0]\n : ''\n\n /**\n * @note Check that nothing has prevented this connection\n * (e.g. called `client.close()` in the connection listener).\n * If the connection has been prevented, never dispatch the open event,.\n */\n if (this.readyState === this.CONNECTING) {\n this.readyState = this.OPEN\n this.dispatchEvent(bindEvent(this, new Event('open')))\n }\n })\n }\n\n set onopen(listener: WebSocketEventListener | null) {\n this.removeEventListener('open', this._onopen)\n this._onopen = listener\n if (listener !== null) {\n this.addEventListener('open', listener)\n }\n }\n get onopen(): WebSocketEventListener | null {\n return this._onopen\n }\n\n set onmessage(\n listener: WebSocketEventListener<MessageEvent<WebSocketData>> | null\n ) {\n this.removeEventListener(\n 'message',\n this._onmessage as WebSocketEventListener\n )\n this._onmessage = listener\n if (listener !== null) {\n this.addEventListener('message', listener)\n }\n }\n get onmessage(): WebSocketEventListener<MessageEvent<WebSocketData>> | null {\n return this._onmessage\n }\n\n set onerror(listener: WebSocketEventListener | null) {\n this.removeEventListener('error', this._onerror)\n this._onerror = listener\n if (listener !== null) {\n this.addEventListener('error', listener)\n }\n }\n get onerror(): WebSocketEventListener | null {\n return this._onerror\n }\n\n set onclose(listener: WebSocketEventListener<CloseEvent> | null) {\n this.removeEventListener('close', this._onclose as WebSocketEventListener)\n this._onclose = listener\n if (listener !== null) {\n this.addEventListener('close', listener)\n }\n }\n get onclose(): WebSocketEventListener<CloseEvent> | null {\n return this._onclose\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0\n */\n public send(data: WebSocketData): void {\n if (this.readyState === this.CONNECTING) {\n this.close()\n throw new DOMException('InvalidStateError')\n }\n\n // Sending when the socket is about to close\n // discards the sent data.\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n // Buffer the data to send in this even loop\n // but send it in the next.\n this.bufferedAmount += getDataSize(data)\n\n queueMicrotask(() => {\n // This is a bit optimistic but since no actual data transfer\n // is involved, all the data will be \"sent\" on the next tick.\n this.bufferedAmount = 0\n\n /**\n * @note Notify the parent about outgoing data.\n * This notifies the transport and the connection\n * listens to the outgoing data to emit the \"message\" event.\n */\n this[kOnSend]?.(data)\n })\n }\n\n public close(code: number = 1000, reason?: string): void {\n invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR)\n invariant(\n code === 1000 || (code >= 3000 && code <= 4999),\n WEBSOCKET_CLOSE_CODE_RANGE_ERROR\n )\n\n this[kClose](code, reason)\n }\n\n private [kClose](\n code: number = 1000,\n reason?: string,\n wasClean = true\n ): void {\n /**\n * @note Move this check here so that even internal closures,\n * like those triggered by the `server` connection, are not\n * performed twice.\n */\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n this.readyState = this.CLOSING\n\n queueMicrotask(() => {\n this.readyState = this.CLOSED\n\n this.dispatchEvent(\n bindEvent(\n this,\n new CloseEvent('close', {\n code,\n reason,\n wasClean,\n })\n )\n )\n\n // Remove all event listeners once the socket is closed.\n this._onopen = null\n this._onmessage = null\n this._onerror = null\n this._onclose = null\n })\n }\n\n public addEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n listener: (this: WebSocket, event: WebSocketEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: unknown,\n listener: unknown,\n options?: unknown\n ): void {\n return super.addEventListener(\n type as string,\n listener as EventListener,\n options as AddEventListenerOptions\n )\n }\n\n removeEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions\n ): void {\n return super.removeEventListener(type, callback, options)\n }\n}\n\nfunction getDataSize(data: WebSocketData): number {\n if (typeof data === 'string') {\n return data.length\n }\n\n if (data instanceof Blob) {\n return data.size\n }\n\n return data.byteLength\n}\n","import { invariant } from 'outvariant'\nimport {\n kClose,\n WebSocketEventListener,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport type { WebSocketData } from './WebSocketTransport'\nimport type { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport {\n CancelableMessageEvent,\n CancelableCloseEvent,\n CloseEvent,\n} from './utils/events'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\nconst kSend = Symbol('kSend')\n\nexport interface WebSocketServerEventMap {\n open: Event\n message: MessageEvent<WebSocketData>\n error: Event\n close: CloseEvent\n}\n\nexport abstract class WebSocketServerConnectionProtocol {\n public abstract connect(): void\n public abstract send(data: WebSocketData): void\n public abstract close(): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket server instance represents the actual production\n * WebSocket server connection. It's idle by default but you can\n * establish it by calling `server.connect()`.\n */\nexport class WebSocketServerConnection implements WebSocketServerConnectionProtocol {\n /**\n * A WebSocket instance connected to the original server.\n */\n private realWebSocket?: WebSocket\n private mockCloseController: AbortController\n private realCloseController: AbortController\n private [kEmitter]: EventTarget\n\n constructor(\n private readonly client: WebSocketOverride,\n private readonly transport: WebSocketClassTransport,\n private readonly createConnection: () => WebSocket\n ) {\n this[kEmitter] = new EventTarget()\n this.mockCloseController = new AbortController()\n this.realCloseController = new AbortController()\n\n // Automatically forward outgoing client events\n // to the actual server unless the outgoing message event\n // has been prevented. The \"outgoing\" transport event it\n // dispatched by the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // Ignore client messages if the server connection\n // hasn't been established yet. Nowhere to forward.\n if (typeof this.realWebSocket === 'undefined') {\n return\n }\n\n // Every outgoing client message can prevent this forwarding\n // by preventing the default of the outgoing message event.\n // This listener will be added before user-defined listeners,\n // so execute the logic on the next tick.\n queueMicrotask(() => {\n if (!event.defaultPrevented) {\n /**\n * @note Use the internal send mechanism so consumers can tell\n * apart direct user calls to `server.send()` and internal calls.\n * E.g. MSW has to ignore this internal call to log out messages correctly.\n */\n this[kSend](event.data)\n }\n })\n })\n\n this.transport.addEventListener(\n 'incoming',\n this.handleIncomingMessage.bind(this)\n )\n }\n\n /**\n * The `WebSocket` instance connected to the original server.\n * Accessing this before calling `server.connect()` will throw.\n */\n public get socket(): WebSocket {\n invariant(\n this.realWebSocket,\n 'Cannot access \"socket\" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?'\n )\n\n return this.realWebSocket\n }\n\n /**\n * Open connection to the original WebSocket server.\n */\n public connect(): void {\n invariant(\n !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN,\n 'Failed to call \"connect()\" on the original WebSocket instance: the connection already open'\n )\n\n const realWebSocket = this.createConnection()\n\n // Inherit the binary type from the mock WebSocket client.\n realWebSocket.binaryType = this.client.binaryType\n\n // Allow the interceptor to listen to when the server connection\n // has been established. This isn't necessary to operate with the connection\n // but may be beneficial in some cases (like conditionally adding logging).\n realWebSocket.addEventListener(\n 'open',\n (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket!, new Event('open', event))\n )\n },\n { once: true }\n )\n\n realWebSocket.addEventListener('message', (event) => {\n // Dispatch the \"incoming\" transport event instead of\n // invoking the internal handler directly. This way,\n // anyone can listen to the \"incoming\" event but this\n // class is the one resulting in it.\n this.transport.dispatchEvent(\n bindEvent(\n this.realWebSocket!,\n new MessageEvent('incoming', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n })\n\n // Close the original connection when the mock client closes.\n // E.g. \"client.close()\" was called. This is never forwarded anywhere.\n this.client.addEventListener(\n 'close',\n (event) => {\n this.handleMockClose(event)\n },\n {\n signal: this.mockCloseController.signal,\n }\n )\n\n // Forward the \"close\" event to let the interceptor handle\n // closures initiated by the original server.\n realWebSocket.addEventListener(\n 'close',\n (event) => {\n this.handleRealClose(event)\n },\n {\n signal: this.realCloseController.signal,\n }\n )\n\n realWebSocket.addEventListener('error', () => {\n const errorEvent = bindEvent(\n realWebSocket,\n new Event('error', { cancelable: true })\n )\n\n // Emit the \"error\" event on the `server` connection\n // to let the interceptor react to original server errors.\n this[kEmitter].dispatchEvent(errorEvent)\n\n // If the error event from the original server hasn't been prevented,\n // forward it to the underlying client.\n if (!errorEvent.defaultPrevented) {\n this.client.dispatchEvent(bindEvent(this.client, new Event('error')))\n }\n })\n\n this.realWebSocket = realWebSocket\n }\n\n /**\n * Listen for the incoming events from the original WebSocket server.\n */\n public addEventListener<EventType extends keyof WebSocketServerEventMap>(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.client)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Remove the listener for the given event.\n */\n public removeEventListener<EventType extends keyof WebSocketServerEventMap>(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the original WebSocket server.\n * @example\n * server.send('hello')\n * server.send(new Blob(['hello']))\n * server.send(new TextEncoder().encode('hello'))\n */\n public send(data: WebSocketData): void {\n this[kSend](data)\n }\n\n private [kSend](data: WebSocketData): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Silently ignore writes on the closed original WebSocket.\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Delegate the send to when the original connection is open.\n // Unlike the mock, connecting to the original server may take time\n // so we cannot call this on the next tick.\n if (realWebSocket.readyState === WebSocket.CONNECTING) {\n realWebSocket.addEventListener(\n 'open',\n () => {\n realWebSocket.send(data)\n },\n { once: true }\n )\n return\n }\n\n // Send the data to the original WebSocket server.\n realWebSocket.send(data)\n }\n\n /**\n * Close the actual server connection.\n */\n public close(): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Remove the \"close\" event listener from the server\n // so it doesn't close the underlying WebSocket client\n // when you call \"server.close()\". This also prevents the\n // `close` event on the `server` connection from being dispatched twice.\n this.realCloseController.abort()\n\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Close the actual client connection.\n realWebSocket.close()\n\n // Dispatch the \"close\" event on the `server` connection.\n queueMicrotask(() => {\n this[kEmitter].dispatchEvent(\n bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n /**\n * @note `server.close()` in the interceptor\n * always results in clean closures.\n */\n code: 1000,\n cancelable: true,\n })\n )\n )\n })\n }\n\n private handleIncomingMessage(event: MessageEvent<WebSocketData>): void {\n // Clone the event to dispatch it on this class\n // once again and prevent the \"already being dispatched\"\n // exception. Clone it here so we can observe this event\n // being prevented in the \"server.on()\" listeners.\n const messageEvent = bindEvent(\n event.target,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n /**\n * @note Emit \"message\" event on the server connection\n * instance to let the interceptor know about these\n * incoming events from the original server. In that listener,\n * the interceptor can modify or skip the event forwarding\n * to the mock WebSocket instance.\n */\n this[kEmitter].dispatchEvent(messageEvent)\n\n /**\n * @note Forward the incoming server events to the client.\n * Preventing the default on the message event stops this.\n */\n if (!messageEvent.defaultPrevented) {\n this.client.dispatchEvent(\n bindEvent(\n /**\n * @note Bind the forwarded original server events\n * to the mock WebSocket instance so it would\n * dispatch them straight away.\n */\n this.client,\n // Clone the message event again to prevent\n // the \"already being dispatched\" exception.\n new MessageEvent('message', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n }\n }\n\n private handleMockClose(_event: Event): void {\n // Close the original connection if the mock client closes.\n if (this.realWebSocket) {\n this.realWebSocket.close()\n }\n }\n\n private handleRealClose(event: CloseEvent): void {\n // For closures originating from the original server,\n // remove the \"close\" listener from the mock client.\n // original close -> (?) client[kClose]() --X--> \"close\" (again).\n this.mockCloseController.abort()\n\n const closeEvent = bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(closeEvent)\n\n // If the close event from the server hasn't been prevented,\n // forward the closure to the mock client.\n if (!closeEvent.defaultPrevented) {\n // Close the intercepted client forcefully to\n // allow non-configurable status codes from the server.\n // If the socket has been closed by now, no harm calling\n // this again—it will have no effect.\n this.client[kClose](event.code, event.reason)\n }\n }\n}\n","import { bindEvent } from './utils/bindEvent'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './WebSocketTransport'\nimport { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\n/**\n * Abstraction over the given mock `WebSocket` instance that allows\n * for controlling that instance (e.g. sending and receiving messages).\n */\nexport class WebSocketClassTransport\n extends EventTarget\n implements WebSocketTransport\n{\n constructor(protected readonly socket: WebSocketOverride) {\n super()\n\n // Emit the \"close\" event on the transport if the close\n // originates from the WebSocket client. E.g. the application\n // calls \"ws.close()\", not the interceptor.\n this.socket.addEventListener('close', (event) => {\n this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event)))\n })\n\n /**\n * Emit the \"outgoing\" event on the transport\n * whenever the WebSocket client sends data (\"ws.send()\").\n */\n this.socket[kOnSend] = (data) => {\n this.dispatchEvent(\n bindEvent(\n this.socket,\n // Dispatch this as cancelable because \"client\" connection\n // re-creates this message event (cannot dispatch the same event).\n new CancelableMessageEvent('outgoing', {\n data,\n origin: this.socket.url,\n cancelable: true,\n })\n )\n )\n }\n }\n\n public addEventListener<EventType extends keyof WebSocketTransportEventMap>(\n type: EventType,\n callback: StrictEventListenerOrEventListenerObject<\n WebSocketTransportEventMap[EventType]\n > | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n return super.addEventListener(type, callback as EventListener, options)\n }\n\n public dispatchEvent<EventType extends keyof WebSocketTransportEventMap>(\n event: WebSocketTransportEventMap[EventType]\n ): boolean {\n return super.dispatchEvent(event)\n }\n\n public send(data: WebSocketData): void {\n queueMicrotask(() => {\n if (\n this.socket.readyState === this.socket.CLOSING ||\n this.socket.readyState === this.socket.CLOSED\n ) {\n return\n }\n\n const dispatchEvent = () => {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Setting this event's \"target\" to the\n * WebSocket override instance is important.\n * This way it can tell apart original incoming events\n * (must be forwarded to the transport) from the\n * mocked message events like the one below\n * (must be dispatched on the client instance).\n */\n this.socket,\n new MessageEvent('message', {\n data,\n origin: this.socket.url,\n })\n )\n )\n }\n\n if (this.socket.readyState === this.socket.CONNECTING) {\n this.socket.addEventListener(\n 'open',\n () => {\n dispatchEvent()\n },\n { once: true }\n )\n } else {\n dispatchEvent()\n }\n })\n }\n\n public close(code: number, reason?: string): void {\n /**\n * @note Call the internal close method directly\n * to allow closing the connection with the status codes\n * that are non-configurable by the user (> 1000 <= 1015).\n */\n this.socket[kClose](code, reason)\n }\n}\n","import { Interceptor } from '../../Interceptor'\nimport {\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n type WebSocketClientEventMap,\n} from './WebSocketClientConnection'\nimport {\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n type WebSocketServerEventMap,\n} from './WebSocketServerConnection'\nimport { WebSocketClassTransport } from './WebSocketClassTransport'\nimport {\n kClose,\n kPassthroughPromise,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { emitAsync } from '../../utils/emitAsync'\n\nexport {\n type WebSocketData,\n type WebSocketTransport,\n} from './WebSocketTransport'\nexport {\n WebSocketClientEventMap,\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n WebSocketServerEventMap,\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n}\n\nexport {\n CloseEvent,\n CancelableCloseEvent,\n CancelableMessageEvent,\n} from './utils/events'\n\nexport type WebSocketEventMap = {\n connection: [args: WebSocketConnectionData]\n}\n\nexport type WebSocketConnectionData = {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection\n\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection\n\n /**\n * The connection information.\n */\n info: {\n /**\n * The protocols supported by the WebSocket client.\n */\n protocols: string | Array<string> | undefined\n }\n}\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor extends Interceptor<WebSocketEventMap> {\n static symbol = Symbol('websocket')\n\n constructor() {\n super(WebSocketInterceptor.symbol)\n }\n\n protected checkEnvironment(): boolean {\n return hasConfigurableGlobal('WebSocket')\n }\n\n protected setup(): void {\n const originalWebSocketDescriptor = Object.getOwnPropertyDescriptor(\n globalThis,\n 'WebSocket'\n )\n\n const WebSocketProxy = new Proxy(globalThis.WebSocket, {\n construct: (\n target,\n args: ConstructorParameters<typeof globalThis.WebSocket>,\n newTarget\n ) => {\n const [url, protocols] = args\n\n const createConnection = (): WebSocket => {\n return Reflect.construct(target, args, newTarget)\n }\n\n // All WebSocket instances are mocked and don't forward\n // any events to the original server (no connection established).\n // To forward the events, the user must use the \"server.send()\" API.\n const socket = new WebSocketOverride(url, protocols)\n const transport = new WebSocketClassTransport(socket)\n\n // Emit the \"connection\" event to the interceptor on the next tick\n // so the client can modify WebSocket options, like \"binaryType\"\n // while the connection is already pending.\n queueMicrotask(async () => {\n try {\n const server = new WebSocketServerConnection(\n socket,\n transport,\n createConnection\n )\n\n const hasConnectionListeners =\n this.emitter.listenerCount('connection') > 0\n\n // The \"globalThis.WebSocket\" class stands for\n // the client-side connection. Assume it's established\n // as soon as the WebSocket instance is constructed.\n await emitAsync(this.emitter, 'connection', {\n client: new WebSocketClientConnection(socket, transport),\n server,\n info: {\n protocols,\n },\n })\n\n if (hasConnectionListeners) {\n socket[kPassthroughPromise].resolve(false)\n } else {\n socket[kPassthroughPromise].resolve(true)\n\n server.connect()\n\n // Forward the \"open\" event from the original server\n // to the mock WebSocket client in the case of a passthrough connection.\n server.addEventListener('open', () => {\n socket.dispatchEvent(bindEvent(socket, new Event('open')))\n\n // Forward the original connection protocol to the\n // mock WebSocket client.\n if (server['realWebSocket']) {\n socket.protocol = server['realWebSocket'].protocol\n }\n })\n }\n } catch (error) {\n /**\n * @note Translate unhandled exceptions during the connection\n * handling (i.e. interceptor exceptions) as WebSocket connection\n * closures with error. This prevents from the exceptions occurring\n * in `queueMicrotask` from being process-wide and uncatchable.\n */\n if (error instanceof Error) {\n socket.dispatchEvent(new Event('error'))\n\n // No need to close the connection if it's already being closed.\n // E.g. the interceptor called `client.close()` and then threw an error.\n if (\n socket.readyState !== WebSocket.CLOSING &&\n socket.readyState !== WebSocket.CLOSED\n ) {\n socket[kClose](1011, error.message, false)\n }\n\n console.error(error)\n }\n }\n })\n\n return socket\n },\n })\n\n Object.defineProperty(globalThis, 'WebSocket', {\n value: WebSocketProxy,\n configurable: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(\n globalThis,\n 'WebSocket',\n originalWebSocketDescriptor!\n )\n })\n }\n}\n"],"mappings":";;;;;;;AAEA,SAAgB,UACd,QACA,OACuB;AACvB,QAAO,iBAAiB,OAAO;EAC7B,QAAQ;GACN,OAAO;GACP,YAAY;GACZ,UAAU;GACX;EACD,eAAe;GACb,OAAO;GACP,YAAY;GACZ,UAAU;GACX;EACF,CAAC;AAEF,QAAO;;;;;ACnBT,MAAM,cAAc,OAAO,cAAc;AACzC,MAAM,oBAA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AO,qBAAqB,QAAQ,KAAK;AAEzC,aAAO,SAAS;AAIhB,aAAO,iBAAiB,cAAc;AACpC,cAAO,cAAc,UAAU,QAAQ,IAAI,MAAM,OAAO,CAAC,CAAC;AAI1D,WAAI,OAAO,iBACT,QAAO,WAAW,OAAO,iBAAiB;QAE5C;;aAEG,OAAO;;;;;;;AAOd,SAAI,iBAAiB,OAAO;AAC1B,aAAO,cAAc,IAAI,MAAM,QAAQ,CAAC;AAIxC,UACE,OAAO,eAAe,UAAU,WAChC,OAAO,eAAe,UAAU,OAEhC,QAAO,QAAQ,MAAM,MAAM,SAAS,MAAM;AAG5C,cAAQ,MAAM,MAAM;;;KAGxB;AAEF,UAAO;KAEV,CAAC;AAEF,SAAO,eAAe,YAAY,aAAa;GAC7C,OAAO;GACP,cAAc;GACf,CAAC;AAEF,OAAK,cAAc,WAAW;AAC5B,UAAO,eACL,YACA,aACA,4BACD;IACD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["kEmitter","kBoundListener","socket: WebSocket","transport: WebSocketTransport","createRequestId","resolveWebSocketUrl","DeferredPromise","client: WebSocketOverride","transport: WebSocketClassTransport","createConnection: () => WebSocket","socket: WebSocketOverride","Interceptor","hasConfigurableGlobal","emitAsync","globalsRegistry"],"sources":["../../../../src/interceptors/WebSocket/utils/bindEvent.ts","../../../../src/interceptors/WebSocket/utils/events.ts","../../../../src/interceptors/WebSocket/WebSocketClientConnection.ts","../../../../src/interceptors/WebSocket/WebSocketOverride.ts","../../../../src/interceptors/WebSocket/WebSocketServerConnection.ts","../../../../src/interceptors/WebSocket/WebSocketClassTransport.ts","../../../../src/interceptors/WebSocket/index.ts"],"sourcesContent":["type EventWithTarget<E extends Event, T> = E & { target: T }\n\nexport function bindEvent<E extends Event, T>(\n target: T,\n event: E\n): EventWithTarget<E, T> {\n Object.defineProperties(event, {\n target: {\n value: target,\n enumerable: true,\n writable: true,\n },\n currentTarget: {\n value: target,\n enumerable: true,\n writable: true,\n },\n })\n\n return event as EventWithTarget<E, T>\n}\n","const kCancelable = Symbol('kCancelable')\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\n\n/**\n * A `MessageEvent` superset that supports event cancellation\n * in Node.js. It's rather non-intrusive so it can be safely\n * used in the browser as well.\n *\n * @see https://github.com/nodejs/node/issues/51767\n */\nexport class CancelableMessageEvent<T = any> extends MessageEvent<T> {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: MessageEventInit<T>) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number\n reason?: string\n wasClean?: boolean\n}\n\nexport class CloseEvent extends Event {\n public code: number\n public reason: string\n public wasClean: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this.code = init.code === undefined ? 0 : init.code\n this.reason = init.reason === undefined ? '' : init.reason\n this.wasClean = init.wasClean === undefined ? false : init.wasClean\n }\n}\n\nexport class CancelableCloseEvent extends CloseEvent {\n [kCancelable]: boolean;\n [kDefaultPrevented]: boolean\n\n constructor(type: string, init: CloseEventInit = {}) {\n super(type, init)\n this[kCancelable] = !!init.cancelable\n this[kDefaultPrevented] = false\n }\n\n get cancelable() {\n return this[kCancelable]\n }\n\n set cancelable(nextCancelable) {\n this[kCancelable] = nextCancelable\n }\n\n get defaultPrevented() {\n return this[kDefaultPrevented]\n }\n\n set defaultPrevented(nextDefaultPrevented) {\n this[kDefaultPrevented] = nextDefaultPrevented\n }\n\n public preventDefault(): void {\n if (this.cancelable && !this[kDefaultPrevented]) {\n this[kDefaultPrevented] = true\n }\n }\n}\n","import type { WebSocketData, WebSocketTransport } from './WebSocketTransport'\nimport type { WebSocketEventListener } from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../createRequestId'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\nexport interface WebSocketClientEventMap {\n message: MessageEvent<WebSocketData>\n close: CloseEvent\n}\n\nexport abstract class WebSocketClientConnectionProtocol {\n abstract id: string\n abstract url: URL\n public abstract send(data: WebSocketData): void\n public abstract close(code?: number, reason?: string): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n type: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketClientEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket client instance represents an incoming\n * client connection. The user can control the connection,\n * send and receive events.\n */\nexport class WebSocketClientConnection implements WebSocketClientConnectionProtocol {\n public readonly id: string\n public readonly url: URL\n\n private [kEmitter]: EventTarget\n\n constructor(\n public readonly socket: WebSocket,\n private readonly transport: WebSocketTransport\n ) {\n this.id = createRequestId()\n this.url = new URL(socket.url)\n this[kEmitter] = new EventTarget()\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n\n // This is a bit silly but forward the cancellation state\n // of the \"client\" message event to the \"outgoing\" transport event.\n // This way, other agens (like \"server\" connection) can know\n // whether the client listener has pervented the default.\n if (message.defaultPrevented) {\n event.preventDefault()\n }\n })\n\n /**\n * Emit the \"close\" event on the \"client\" connection\n * whenever the underlying transport is closed.\n * @note \"client.close()\" does NOT dispatch the \"close\"\n * event on the WebSocket because it uses non-configurable\n * close status code. Thus, we listen to the transport\n * instead of the WebSocket's \"close\" event.\n */\n this.transport.addEventListener('close', (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.socket, new CloseEvent('close', event))\n )\n })\n }\n\n /**\n * Listen for the outgoing events from the connected WebSocket client.\n */\n public addEventListener<EventType extends keyof WebSocketClientEventMap>(\n type: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.socket)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n configurable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n type,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Removes the listener for the given event.\n */\n public removeEventListener<EventType extends keyof WebSocketClientEventMap>(\n event: EventType,\n listener: WebSocketEventListener<WebSocketClientEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the connected client.\n */\n public send(data: WebSocketData): void {\n this.transport.send(data)\n }\n\n /**\n * Close the WebSocket connection.\n * @param {number} code A status code (see https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1).\n * @param {string} reason A custom connection close reason.\n */\n public close(code?: number, reason?: string): void {\n this.transport.close(code, reason)\n }\n}\n","import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport type { WebSocketData } from './WebSocketTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport { CloseEvent } from './utils/events'\nimport { resolveWebSocketUrl } from '../../utils/resolveWebSocketUrl'\n\nexport type WebSocketEventListener<\n EventType extends WebSocketEventMap[keyof WebSocketEventMap] = Event,\n> = (this: WebSocket, event: EventType) => void\n\nconst WEBSOCKET_CLOSE_CODE_RANGE_ERROR =\n 'InvalidAccessError: close code out of user configurable range'\n\nexport const kPassthroughPromise = Symbol('kPassthroughPromise')\nexport const kOnSend = Symbol('kOnSend')\nexport const kClose = Symbol('kClose')\n\nexport class WebSocketOverride extends EventTarget implements WebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n readonly CONNECTING = 0\n readonly OPEN = 1\n readonly CLOSING = 2\n readonly CLOSED = 3\n\n public url: string\n public protocol: string\n public extensions: string\n public binaryType: BinaryType\n public readyState: WebSocket['readyState']\n public bufferedAmount: number\n\n private _onopen: WebSocketEventListener | null = null\n private _onmessage: WebSocketEventListener<\n MessageEvent<WebSocketData>\n > | null = null\n private _onerror: WebSocketEventListener | null = null\n private _onclose: WebSocketEventListener<CloseEvent> | null = null\n\n private [kPassthroughPromise]: DeferredPromise<boolean>\n private [kOnSend]?: (data: WebSocketData) => void\n\n constructor(url: string | URL, protocols?: string | Array<string>) {\n super()\n this.url = resolveWebSocketUrl(url)\n this.protocol = ''\n this.extensions = ''\n this.binaryType = 'blob'\n this.readyState = this.CONNECTING\n this.bufferedAmount = 0\n\n this[kPassthroughPromise] = new DeferredPromise<boolean>()\n\n queueMicrotask(async () => {\n if (await this[kPassthroughPromise]) {\n return\n }\n\n this.protocol =\n typeof protocols === 'string'\n ? protocols\n : Array.isArray(protocols) && protocols.length > 0\n ? protocols[0]\n : ''\n\n /**\n * @note Check that nothing has prevented this connection\n * (e.g. called `client.close()` in the connection listener).\n * If the connection has been prevented, never dispatch the open event,.\n */\n if (this.readyState === this.CONNECTING) {\n this.readyState = this.OPEN\n this.dispatchEvent(bindEvent(this, new Event('open')))\n }\n })\n }\n\n set onopen(listener: WebSocketEventListener | null) {\n this.removeEventListener('open', this._onopen)\n this._onopen = listener\n if (listener !== null) {\n this.addEventListener('open', listener)\n }\n }\n get onopen(): WebSocketEventListener | null {\n return this._onopen\n }\n\n set onmessage(\n listener: WebSocketEventListener<MessageEvent<WebSocketData>> | null\n ) {\n this.removeEventListener(\n 'message',\n this._onmessage as WebSocketEventListener\n )\n this._onmessage = listener\n if (listener !== null) {\n this.addEventListener('message', listener)\n }\n }\n get onmessage(): WebSocketEventListener<MessageEvent<WebSocketData>> | null {\n return this._onmessage\n }\n\n set onerror(listener: WebSocketEventListener | null) {\n this.removeEventListener('error', this._onerror)\n this._onerror = listener\n if (listener !== null) {\n this.addEventListener('error', listener)\n }\n }\n get onerror(): WebSocketEventListener | null {\n return this._onerror\n }\n\n set onclose(listener: WebSocketEventListener<CloseEvent> | null) {\n this.removeEventListener('close', this._onclose as WebSocketEventListener)\n this._onclose = listener\n if (listener !== null) {\n this.addEventListener('close', listener)\n }\n }\n get onclose(): WebSocketEventListener<CloseEvent> | null {\n return this._onclose\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#ref-for-dom-websocket-send%E2%91%A0\n */\n public send(data: WebSocketData): void {\n if (this.readyState === this.CONNECTING) {\n this.close()\n throw new DOMException('InvalidStateError')\n }\n\n // Sending when the socket is about to close\n // discards the sent data.\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n // Buffer the data to send in this even loop\n // but send it in the next.\n this.bufferedAmount += getDataSize(data)\n\n queueMicrotask(() => {\n // This is a bit optimistic but since no actual data transfer\n // is involved, all the data will be \"sent\" on the next tick.\n this.bufferedAmount = 0\n\n /**\n * @note Notify the parent about outgoing data.\n * This notifies the transport and the connection\n * listens to the outgoing data to emit the \"message\" event.\n */\n this[kOnSend]?.(data)\n })\n }\n\n public close(code: number = 1000, reason?: string): void {\n invariant(code, WEBSOCKET_CLOSE_CODE_RANGE_ERROR)\n invariant(\n code === 1000 || (code >= 3000 && code <= 4999),\n WEBSOCKET_CLOSE_CODE_RANGE_ERROR\n )\n\n this[kClose](code, reason)\n }\n\n private [kClose](\n code: number = 1000,\n reason?: string,\n wasClean = true\n ): void {\n /**\n * @note Move this check here so that even internal closures,\n * like those triggered by the `server` connection, are not\n * performed twice.\n */\n if (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n return\n }\n\n this.readyState = this.CLOSING\n\n queueMicrotask(() => {\n this.readyState = this.CLOSED\n\n this.dispatchEvent(\n bindEvent(\n this,\n new CloseEvent('close', {\n code,\n reason,\n wasClean,\n })\n )\n )\n\n // Remove all event listeners once the socket is closed.\n this._onopen = null\n this._onmessage = null\n this._onerror = null\n this._onclose = null\n })\n }\n\n public addEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n listener: (this: WebSocket, event: WebSocketEventMap[K]) => void,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions\n ): void\n public addEventListener(\n type: unknown,\n listener: unknown,\n options?: unknown\n ): void {\n return super.addEventListener(\n type as string,\n listener as EventListener,\n options as AddEventListenerOptions\n )\n }\n\n removeEventListener<K extends keyof WebSocketEventMap>(\n type: K,\n callback: EventListenerOrEventListenerObject | null,\n options?: boolean | EventListenerOptions\n ): void {\n return super.removeEventListener(type, callback, options)\n }\n}\n\nfunction getDataSize(data: WebSocketData): number {\n if (typeof data === 'string') {\n return data.length\n }\n\n if (data instanceof Blob) {\n return data.size\n }\n\n return data.byteLength\n}\n","import { invariant } from 'outvariant'\nimport {\n kClose,\n WebSocketEventListener,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport type { WebSocketData } from './WebSocketTransport'\nimport type { WebSocketClassTransport } from './WebSocketClassTransport'\nimport { bindEvent } from './utils/bindEvent'\nimport {\n CancelableMessageEvent,\n CancelableCloseEvent,\n CloseEvent,\n} from './utils/events'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\nconst kSend = Symbol('kSend')\n\nexport interface WebSocketServerEventMap {\n open: Event\n message: MessageEvent<WebSocketData>\n error: Event\n close: CloseEvent\n}\n\nexport abstract class WebSocketServerConnectionProtocol {\n public abstract connect(): void\n public abstract send(data: WebSocketData): void\n public abstract close(): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketServerEventMap,\n >(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void\n}\n\n/**\n * The WebSocket server instance represents the actual production\n * WebSocket server connection. It's idle by default but you can\n * establish it by calling `server.connect()`.\n */\nexport class WebSocketServerConnection implements WebSocketServerConnectionProtocol {\n /**\n * A WebSocket instance connected to the original server.\n */\n private realWebSocket?: WebSocket\n private mockCloseController: AbortController\n private realCloseController: AbortController\n private [kEmitter]: EventTarget\n\n constructor(\n private readonly client: WebSocketOverride,\n private readonly transport: WebSocketClassTransport,\n private readonly createConnection: () => WebSocket\n ) {\n this[kEmitter] = new EventTarget()\n this.mockCloseController = new AbortController()\n this.realCloseController = new AbortController()\n\n // Automatically forward outgoing client events\n // to the actual server unless the outgoing message event\n // has been prevented. The \"outgoing\" transport event it\n // dispatched by the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // Ignore client messages if the server connection\n // hasn't been established yet. Nowhere to forward.\n if (typeof this.realWebSocket === 'undefined') {\n return\n }\n\n // Every outgoing client message can prevent this forwarding\n // by preventing the default of the outgoing message event.\n // This listener will be added before user-defined listeners,\n // so execute the logic on the next tick.\n queueMicrotask(() => {\n if (!event.defaultPrevented) {\n /**\n * @note Use the internal send mechanism so consumers can tell\n * apart direct user calls to `server.send()` and internal calls.\n * E.g. MSW has to ignore this internal call to log out messages correctly.\n */\n this[kSend](event.data)\n }\n })\n })\n\n this.transport.addEventListener(\n 'incoming',\n this.handleIncomingMessage.bind(this)\n )\n }\n\n /**\n * The `WebSocket` instance connected to the original server.\n * Accessing this before calling `server.connect()` will throw.\n */\n public get socket(): WebSocket {\n invariant(\n this.realWebSocket,\n 'Cannot access \"socket\" on the original WebSocket server object: the connection is not open. Did you forget to call `server.connect()`?'\n )\n\n return this.realWebSocket\n }\n\n /**\n * Open connection to the original WebSocket server.\n */\n public connect(): void {\n invariant(\n !this.realWebSocket || this.realWebSocket.readyState !== WebSocket.OPEN,\n 'Failed to call \"connect()\" on the original WebSocket instance: the connection already open'\n )\n\n const realWebSocket = this.createConnection()\n\n // Inherit the binary type from the mock WebSocket client.\n realWebSocket.binaryType = this.client.binaryType\n\n // Allow the interceptor to listen to when the server connection\n // has been established. This isn't necessary to operate with the connection\n // but may be beneficial in some cases (like conditionally adding logging).\n realWebSocket.addEventListener(\n 'open',\n (event) => {\n this[kEmitter].dispatchEvent(\n bindEvent(this.realWebSocket!, new Event('open', event))\n )\n },\n { once: true }\n )\n\n realWebSocket.addEventListener('message', (event) => {\n // Dispatch the \"incoming\" transport event instead of\n // invoking the internal handler directly. This way,\n // anyone can listen to the \"incoming\" event but this\n // class is the one resulting in it.\n this.transport.dispatchEvent(\n bindEvent(\n this.realWebSocket!,\n new MessageEvent('incoming', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n })\n\n // Close the original connection when the mock client closes.\n // E.g. \"client.close()\" was called. This is never forwarded anywhere.\n this.client.addEventListener(\n 'close',\n (event) => {\n this.handleMockClose(event)\n },\n {\n signal: this.mockCloseController.signal,\n }\n )\n\n // Forward the \"close\" event to let the interceptor handle\n // closures initiated by the original server.\n realWebSocket.addEventListener(\n 'close',\n (event) => {\n this.handleRealClose(event)\n },\n {\n signal: this.realCloseController.signal,\n }\n )\n\n realWebSocket.addEventListener('error', () => {\n const errorEvent = bindEvent(\n realWebSocket,\n new Event('error', { cancelable: true })\n )\n\n // Emit the \"error\" event on the `server` connection\n // to let the interceptor react to original server errors.\n this[kEmitter].dispatchEvent(errorEvent)\n\n // If the error event from the original server hasn't been prevented,\n // forward it to the underlying client.\n if (!errorEvent.defaultPrevented) {\n this.client.dispatchEvent(bindEvent(this.client, new Event('error')))\n }\n })\n\n this.realWebSocket = realWebSocket\n }\n\n /**\n * Listen for the incoming events from the original WebSocket server.\n */\n public addEventListener<EventType extends keyof WebSocketServerEventMap>(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (!Reflect.has(listener, kBoundListener)) {\n const boundListener = listener.bind(this.client)\n\n // Store the bound listener on the original listener\n // so the exact bound function can be accessed in \"removeEventListener()\".\n Object.defineProperty(listener, kBoundListener, {\n value: boundListener,\n enumerable: false,\n })\n }\n\n this[kEmitter].addEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Remove the listener for the given event.\n */\n public removeEventListener<EventType extends keyof WebSocketServerEventMap>(\n event: EventType,\n listener: WebSocketEventListener<WebSocketServerEventMap[EventType]>,\n options?: EventListenerOptions | boolean\n ): void {\n this[kEmitter].removeEventListener(\n event,\n Reflect.get(listener, kBoundListener) as EventListener,\n options\n )\n }\n\n /**\n * Send data to the original WebSocket server.\n * @example\n * server.send('hello')\n * server.send(new Blob(['hello']))\n * server.send(new TextEncoder().encode('hello'))\n */\n public send(data: WebSocketData): void {\n this[kSend](data)\n }\n\n private [kSend](data: WebSocketData): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to call \"server.send()\" for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Silently ignore writes on the closed original WebSocket.\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Delegate the send to when the original connection is open.\n // Unlike the mock, connecting to the original server may take time\n // so we cannot call this on the next tick.\n if (realWebSocket.readyState === WebSocket.CONNECTING) {\n realWebSocket.addEventListener(\n 'open',\n () => {\n realWebSocket.send(data)\n },\n { once: true }\n )\n return\n }\n\n // Send the data to the original WebSocket server.\n realWebSocket.send(data)\n }\n\n /**\n * Close the actual server connection.\n */\n public close(): void {\n const { realWebSocket } = this\n\n invariant(\n realWebSocket,\n 'Failed to close server connection for \"%s\": the connection is not open. Did you forget to call \"server.connect()\"?',\n this.client.url\n )\n\n // Remove the \"close\" event listener from the server\n // so it doesn't close the underlying WebSocket client\n // when you call \"server.close()\". This also prevents the\n // `close` event on the `server` connection from being dispatched twice.\n this.realCloseController.abort()\n\n if (\n realWebSocket.readyState === WebSocket.CLOSING ||\n realWebSocket.readyState === WebSocket.CLOSED\n ) {\n return\n }\n\n // Close the actual client connection.\n realWebSocket.close()\n\n // Dispatch the \"close\" event on the `server` connection.\n queueMicrotask(() => {\n this[kEmitter].dispatchEvent(\n bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n /**\n * @note `server.close()` in the interceptor\n * always results in clean closures.\n */\n code: 1000,\n cancelable: true,\n })\n )\n )\n })\n }\n\n private handleIncomingMessage(event: MessageEvent<WebSocketData>): void {\n // Clone the event to dispatch it on this class\n // once again and prevent the \"already being dispatched\"\n // exception. Clone it here so we can observe this event\n // being prevented in the \"server.on()\" listeners.\n const messageEvent = bindEvent(\n event.target,\n new CancelableMessageEvent('message', {\n data: event.data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n /**\n * @note Emit \"message\" event on the server connection\n * instance to let the interceptor know about these\n * incoming events from the original server. In that listener,\n * the interceptor can modify or skip the event forwarding\n * to the mock WebSocket instance.\n */\n this[kEmitter].dispatchEvent(messageEvent)\n\n /**\n * @note Forward the incoming server events to the client.\n * Preventing the default on the message event stops this.\n */\n if (!messageEvent.defaultPrevented) {\n this.client.dispatchEvent(\n bindEvent(\n /**\n * @note Bind the forwarded original server events\n * to the mock WebSocket instance so it would\n * dispatch them straight away.\n */\n this.client,\n // Clone the message event again to prevent\n // the \"already being dispatched\" exception.\n new MessageEvent('message', {\n data: event.data,\n origin: event.origin,\n })\n )\n )\n }\n }\n\n private handleMockClose(_event: Event): void {\n // Close the original connection if the mock client closes.\n if (this.realWebSocket) {\n this.realWebSocket.close()\n }\n }\n\n private handleRealClose(event: CloseEvent): void {\n // For closures originating from the original server,\n // remove the \"close\" listener from the mock client.\n // original close -> (?) client[kClose]() --X--> \"close\" (again).\n this.mockCloseController.abort()\n\n const closeEvent = bindEvent(\n this.realWebSocket,\n new CancelableCloseEvent('close', {\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(closeEvent)\n\n // If the close event from the server hasn't been prevented,\n // forward the closure to the mock client.\n if (!closeEvent.defaultPrevented) {\n // Close the intercepted client forcefully to\n // allow non-configurable status codes from the server.\n // If the socket has been closed by now, no harm calling\n // this again—it will have no effect.\n this.client[kClose](event.code, event.reason)\n }\n }\n}\n","import { bindEvent } from './utils/bindEvent'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './WebSocketTransport'\nimport { kOnSend, kClose, WebSocketOverride } from './WebSocketOverride'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\n\n/**\n * Abstraction over the given mock `WebSocket` instance that allows\n * for controlling that instance (e.g. sending and receiving messages).\n */\nexport class WebSocketClassTransport\n extends EventTarget\n implements WebSocketTransport\n{\n constructor(protected readonly socket: WebSocketOverride) {\n super()\n\n // Emit the \"close\" event on the transport if the close\n // originates from the WebSocket client. E.g. the application\n // calls \"ws.close()\", not the interceptor.\n this.socket.addEventListener('close', (event) => {\n this.dispatchEvent(bindEvent(this.socket, new CloseEvent('close', event)))\n })\n\n /**\n * Emit the \"outgoing\" event on the transport\n * whenever the WebSocket client sends data (\"ws.send()\").\n */\n this.socket[kOnSend] = (data) => {\n this.dispatchEvent(\n bindEvent(\n this.socket,\n // Dispatch this as cancelable because \"client\" connection\n // re-creates this message event (cannot dispatch the same event).\n new CancelableMessageEvent('outgoing', {\n data,\n origin: this.socket.url,\n cancelable: true,\n })\n )\n )\n }\n }\n\n public addEventListener<EventType extends keyof WebSocketTransportEventMap>(\n type: EventType,\n callback: StrictEventListenerOrEventListenerObject<\n WebSocketTransportEventMap[EventType]\n > | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n return super.addEventListener(type, callback as EventListener, options)\n }\n\n public dispatchEvent<EventType extends keyof WebSocketTransportEventMap>(\n event: WebSocketTransportEventMap[EventType]\n ): boolean {\n return super.dispatchEvent(event)\n }\n\n public send(data: WebSocketData): void {\n queueMicrotask(() => {\n if (\n this.socket.readyState === this.socket.CLOSING ||\n this.socket.readyState === this.socket.CLOSED\n ) {\n return\n }\n\n const dispatchEvent = () => {\n this.socket.dispatchEvent(\n bindEvent(\n /**\n * @note Setting this event's \"target\" to the\n * WebSocket override instance is important.\n * This way it can tell apart original incoming events\n * (must be forwarded to the transport) from the\n * mocked message events like the one below\n * (must be dispatched on the client instance).\n */\n this.socket,\n new MessageEvent('message', {\n data,\n origin: this.socket.url,\n })\n )\n )\n }\n\n if (this.socket.readyState === this.socket.CONNECTING) {\n this.socket.addEventListener(\n 'open',\n () => {\n dispatchEvent()\n },\n { once: true }\n )\n } else {\n dispatchEvent()\n }\n })\n }\n\n public close(code: number, reason?: string): void {\n /**\n * @note Call the internal close method directly\n * to allow closing the connection with the status codes\n * that are non-configurable by the user (> 1000 <= 1015).\n */\n this.socket[kClose](code, reason)\n }\n}\n","import { Interceptor } from '../../Interceptor'\nimport {\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n type WebSocketClientEventMap,\n} from './WebSocketClientConnection'\nimport {\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n type WebSocketServerEventMap,\n} from './WebSocketServerConnection'\nimport { WebSocketClassTransport } from './WebSocketClassTransport'\nimport {\n kClose,\n kPassthroughPromise,\n WebSocketOverride,\n} from './WebSocketOverride'\nimport { bindEvent } from './utils/bindEvent'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { globalsRegistry } from '../../utils/globalsRegistry'\n\nexport {\n type WebSocketData,\n type WebSocketTransport,\n} from './WebSocketTransport'\nexport {\n WebSocketClientEventMap,\n WebSocketClientConnectionProtocol,\n WebSocketClientConnection,\n WebSocketServerEventMap,\n WebSocketServerConnectionProtocol,\n WebSocketServerConnection,\n}\n\nexport {\n CloseEvent,\n CancelableCloseEvent,\n CancelableMessageEvent,\n} from './utils/events'\n\nexport type WebSocketEventMap = {\n connection: [args: WebSocketConnectionData]\n}\n\nexport type WebSocketConnectionData = {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection\n\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection\n\n /**\n * The connection information.\n */\n info: {\n /**\n * The protocols supported by the WebSocket client.\n */\n protocols: string | Array<string> | undefined\n }\n}\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor extends Interceptor<WebSocketEventMap> {\n static symbol = Symbol('websocket')\n\n constructor() {\n super(WebSocketInterceptor.symbol)\n }\n\n protected checkEnvironment(): boolean {\n return hasConfigurableGlobal('WebSocket')\n }\n\n protected setup(): void {\n const logger = this.logger.extend('setup')\n\n const WebSocketProxy = new Proxy(globalThis.WebSocket, {\n construct: (\n target,\n args: ConstructorParameters<typeof globalThis.WebSocket>,\n newTarget\n ) => {\n const [url, protocols] = args\n\n const createConnection = (): WebSocket => {\n return Reflect.construct(target, args, newTarget)\n }\n\n // All WebSocket instances are mocked and don't forward\n // any events to the original server (no connection established).\n // To forward the events, the user must use the \"server.send()\" API.\n const socket = new WebSocketOverride(url, protocols)\n const transport = new WebSocketClassTransport(socket)\n\n // Emit the \"connection\" event to the interceptor on the next tick\n // so the client can modify WebSocket options, like \"binaryType\"\n // while the connection is already pending.\n queueMicrotask(async () => {\n try {\n const server = new WebSocketServerConnection(\n socket,\n transport,\n createConnection\n )\n\n const hasConnectionListeners =\n this.emitter.listenerCount('connection') > 0\n\n // The \"globalThis.WebSocket\" class stands for\n // the client-side connection. Assume it's established\n // as soon as the WebSocket instance is constructed.\n await emitAsync(this.emitter, 'connection', {\n client: new WebSocketClientConnection(socket, transport),\n server,\n info: {\n protocols,\n },\n })\n\n if (hasConnectionListeners) {\n socket[kPassthroughPromise].resolve(false)\n } else {\n socket[kPassthroughPromise].resolve(true)\n\n server.connect()\n\n // Forward the \"open\" event from the original server\n // to the mock WebSocket client in the case of a passthrough connection.\n server.addEventListener('open', () => {\n socket.dispatchEvent(bindEvent(socket, new Event('open')))\n\n // Forward the original connection protocol to the\n // mock WebSocket client.\n if (server['realWebSocket']) {\n socket.protocol = server['realWebSocket'].protocol\n }\n })\n }\n } catch (error) {\n /**\n * @note Translate unhandled exceptions during the connection\n * handling (i.e. interceptor exceptions) as WebSocket connection\n * closures with error. This prevents from the exceptions occurring\n * in `queueMicrotask` from being process-wide and uncatchable.\n */\n if (error instanceof Error) {\n socket.dispatchEvent(new Event('error'))\n\n // No need to close the connection if it's already being closed.\n // E.g. the interceptor called `client.close()` and then threw an error.\n if (\n socket.readyState !== WebSocket.CLOSING &&\n socket.readyState !== WebSocket.CLOSED\n ) {\n socket[kClose](1011, error.message, false)\n }\n\n console.error(error)\n }\n }\n })\n\n return socket\n },\n })\n\n logger.info('patching global WebSocket...')\n\n this.subscriptions.push(\n globalsRegistry.replaceGlobal('WebSocket', WebSocketProxy)\n )\n\n logger.info('global WebSocket patched!', globalThis.WebSocket.name)\n }\n}\n"],"mappings":";;;;;;;AAEA,SAAgB,UACd,QACA,OACuB;AACvB,QAAO,iBAAiB,OAAO;EAC7B,QAAQ;GACN,OAAO;GACP,YAAY;GACZ,UAAU;GACX;EACD,eAAe;GACb,OAAO;GACP,YAAY;GACZ,UAAU;GACX;EACF,CAAC;AAEF,QAAO;;;;;ACnBT,MAAM,cAAc,OAAO,cAAc;AACzC,MAAM,oBAAoB,OAAO,oBAAoB;;;;;;;;AASrD,I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,aAAO,SAAS;AAIhB,aAAO,iBAAiB,cAAc;AACpC,cAAO,cAAc,UAAU,QAAQ,IAAI,MAAM,OAAO,CAAC,CAAC;AAI1D,WAAI,OAAO,iBACT,QAAO,WAAW,OAAO,iBAAiB;QAE5C;;aAEG,OAAO;;;;;;;AAOd,SAAI,iBAAiB,OAAO;AAC1B,aAAO,cAAc,IAAI,MAAM,QAAQ,CAAC;AAIxC,UACE,OAAO,eAAe,UAAU,WAChC,OAAO,eAAe,UAAU,OAEhC,QAAO,QAAQ,MAAM,MAAM,SAAS,MAAM;AAG5C,cAAQ,MAAM,MAAM;;;KAGxB;AAEF,UAAO;KAEV,CAAC;AAEF,SAAO,KAAK,+BAA+B;AAE3C,OAAK,cAAc,KACjBC,8CAAgB,cAAc,aAAa,eAAe,CAC3D;AAED,SAAO,KAAK,6BAA6B,WAAW,UAAU,KAAK"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { r as Interceptor, t as createRequestId } from "../../createRequestId-
|
|
1
|
+
import { r as Interceptor, t as createRequestId } from "../../createRequestId-DYCsFHOi.mjs";
|
|
2
2
|
import { t as resolveWebSocketUrl } from "../../resolveWebSocketUrl-C83-x9iE.mjs";
|
|
3
|
-
import { n as emitAsync, t as hasConfigurableGlobal } from "../../hasConfigurableGlobal-
|
|
3
|
+
import { n as globalsRegistry, r as emitAsync, t as hasConfigurableGlobal } from "../../hasConfigurableGlobal-B39W0thh.mjs";
|
|
4
4
|
import { DeferredPromise } from "@open-draft/deferred-promise";
|
|
5
5
|
import { invariant } from "outvariant";
|
|
6
6
|
|
|
@@ -558,7 +558,7 @@ var WebSocketInterceptor = class WebSocketInterceptor extends Interceptor {
|
|
|
558
558
|
return hasConfigurableGlobal("WebSocket");
|
|
559
559
|
}
|
|
560
560
|
setup() {
|
|
561
|
-
const
|
|
561
|
+
const logger = this.logger.extend("setup");
|
|
562
562
|
const WebSocketProxy = new Proxy(globalThis.WebSocket, { construct: (target, args, newTarget) => {
|
|
563
563
|
const [url, protocols] = args;
|
|
564
564
|
const createConnection = () => {
|
|
@@ -600,13 +600,9 @@ var WebSocketInterceptor = class WebSocketInterceptor extends Interceptor {
|
|
|
600
600
|
});
|
|
601
601
|
return socket;
|
|
602
602
|
} });
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
});
|
|
607
|
-
this.subscriptions.push(() => {
|
|
608
|
-
Object.defineProperty(globalThis, "WebSocket", originalWebSocketDescriptor);
|
|
609
|
-
});
|
|
603
|
+
logger.info("patching global WebSocket...");
|
|
604
|
+
this.subscriptions.push(globalsRegistry.replaceGlobal("WebSocket", WebSocketProxy));
|
|
605
|
+
logger.info("global WebSocket patched!", globalThis.WebSocket.name);
|
|
610
606
|
}
|
|
611
607
|
};
|
|
612
608
|
|