@depup/mswjs__interceptors 0.45.1-depup.0 → 0.45.4-depup.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/changes.json +1 -1
- package/lib/browser/interceptors/WebSocket/index.d.ts +26 -15
- package/lib/browser/interceptors/WebSocket/index.js +0 -5
- package/lib/browser/interceptors/WebSocket/index.js.map +1 -1
- package/lib/browser/interceptors/fetch/web.js +1 -1
- package/lib/browser/presets/browser.js +1 -1
- package/lib/browser/{web-DUlFZEtz.js → web-DAjikHQM.js} +14 -9
- package/lib/browser/web-DAjikHQM.js.map +1 -0
- package/lib/node/interceptors/WebSocket/index.d.ts +26 -15
- package/lib/node/interceptors/WebSocket/index.js +0 -5
- package/lib/node/interceptors/WebSocket/index.js.map +1 -1
- package/package.json +4 -4
- package/src/events/websocket.ts +31 -9
- package/src/interceptors/WebSocket/index.ts +3 -2
- package/src/interceptors/WebSocket/web-socket-extension.ts +8 -17
- package/src/interceptors/fetch/web.ts +13 -8
- package/lib/browser/web-DUlFZEtz.js.map +0 -1
package/README.md
CHANGED
|
@@ -13,8 +13,8 @@ npm install @depup/mswjs__interceptors
|
|
|
13
13
|
|
|
14
14
|
| Field | Value |
|
|
15
15
|
|-------|-------|
|
|
16
|
-
| Original | [@mswjs/interceptors](https://www.npmjs.com/package/@mswjs/interceptors) @ 0.45.
|
|
17
|
-
| Processed | 2026-09-
|
|
16
|
+
| Original | [@mswjs/interceptors](https://www.npmjs.com/package/@mswjs/interceptors) @ 0.45.4 |
|
|
17
|
+
| Processed | 2026-09-26 |
|
|
18
18
|
| Smoke test | passed |
|
|
19
19
|
| Deps updated | 0 |
|
|
20
20
|
|
package/changes.json
CHANGED
|
@@ -10,22 +10,38 @@ interface WebSocketConnectionInfo {
|
|
|
10
10
|
*/
|
|
11
11
|
protocols: string | Array<string> | undefined;
|
|
12
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* An intercepted WebSocket connection: the client and the server handles.
|
|
15
|
+
*
|
|
16
|
+
* @note Typed against the handles, not the connection classes,
|
|
17
|
+
* so that a connection living anywhere (in this process, in another
|
|
18
|
+
* runtime, or in a custom implementation) can be given to whoever
|
|
19
|
+
* consumes intercepted connections (e.g. a handler).
|
|
20
|
+
*/
|
|
13
21
|
interface WebSocketConnectionEventData<Message = WebSocketData> {
|
|
14
22
|
/**
|
|
15
23
|
* The incoming WebSocket client connection.
|
|
16
24
|
*/
|
|
17
|
-
client:
|
|
25
|
+
client: WebSocketClientHandle<Message>;
|
|
18
26
|
/**
|
|
19
27
|
* The original WebSocket server connection.
|
|
20
28
|
*/
|
|
21
|
-
server:
|
|
29
|
+
server: WebSocketServerHandle<Message>;
|
|
22
30
|
info: WebSocketConnectionInfo;
|
|
23
31
|
}
|
|
24
|
-
|
|
32
|
+
/**
|
|
33
|
+
* The connection intercepted by the `WebSocketInterceptor`:
|
|
34
|
+
* both the client and the server live in this process.
|
|
35
|
+
*/
|
|
36
|
+
interface WebSocketInterceptedConnection<Message = WebSocketData> extends WebSocketConnectionEventData<Message> {
|
|
37
|
+
client: WebSocketClientConnection<Message>;
|
|
38
|
+
server: WebSocketServerConnection<Message>;
|
|
39
|
+
}
|
|
40
|
+
declare class WebSocketConnectionEvent<Message = WebSocketData> extends TypedEvent<WebSocketInterceptedConnection<Message>, void, 'connection'> implements WebSocketInterceptedConnection<Message> {
|
|
25
41
|
client: WebSocketClientConnection<Message>;
|
|
26
42
|
server: WebSocketServerConnection<Message>;
|
|
27
43
|
info: WebSocketConnectionInfo;
|
|
28
|
-
constructor(data:
|
|
44
|
+
constructor(data: WebSocketInterceptedConnection<Message>);
|
|
29
45
|
}
|
|
30
46
|
type WebSocketEventMap$1<Message = WebSocketData, Extension = {}> = {
|
|
31
47
|
connection: WebSocketConnectionEvent<Message> & Extension;
|
|
@@ -283,8 +299,8 @@ type WebSocketExtensionResult<Value> = Value | Iterator<Value, Value | void> | u
|
|
|
283
299
|
* The intercepted connection an extension operates on.
|
|
284
300
|
*/
|
|
285
301
|
interface WebSocketExtensionContext<Message = WebSocketData> {
|
|
286
|
-
client:
|
|
287
|
-
server:
|
|
302
|
+
client: WebSocketClientHandle<Message>;
|
|
303
|
+
server: WebSocketServerHandle<Message>;
|
|
288
304
|
info: WebSocketConnectionInfo;
|
|
289
305
|
}
|
|
290
306
|
interface WebSocketExtensionMessageContext<Message = WebSocketData> extends WebSocketExtensionContext<Message> {
|
|
@@ -293,7 +309,7 @@ interface WebSocketExtensionMessageContext<Message = WebSocketData> extends WebS
|
|
|
293
309
|
* the `client` for data crossing the client connection,
|
|
294
310
|
* the `server` for data crossing the original server connection.
|
|
295
311
|
*/
|
|
296
|
-
connection:
|
|
312
|
+
connection: WebSocketClientHandle<Message> | WebSocketServerHandle<Message>;
|
|
297
313
|
}
|
|
298
314
|
/**
|
|
299
315
|
* A WebSocket extension: the server-side implementation of a protocol layered on top of
|
|
@@ -372,15 +388,10 @@ declare abstract class WebSocketExtension<Message = WebSocketData, Extension = {
|
|
|
372
388
|
* Apply this extension to the given connection.
|
|
373
389
|
* From then on, both the client and the server of that connection
|
|
374
390
|
* encode the data they send and decode the data they receive.
|
|
375
|
-
*
|
|
376
|
-
* @note Typed against the connection classes, not the handles:
|
|
377
|
-
* a connection is assignable across `Message` types only when
|
|
378
|
-
* compared as the same class, which is what lets an extension narrow
|
|
379
|
-
* the raw `WebSocketData` connections it is applied to.
|
|
380
391
|
*/
|
|
381
392
|
apply(connection: {
|
|
382
|
-
client:
|
|
383
|
-
server:
|
|
393
|
+
client: WebSocketClientHandle<Message>;
|
|
394
|
+
server: WebSocketServerHandle<Message>;
|
|
384
395
|
}): void;
|
|
385
396
|
}
|
|
386
397
|
//#endregion
|
|
@@ -488,5 +499,5 @@ declare class WebSocketInterceptor<const Extensions extends WebSocketExtensions
|
|
|
488
499
|
protected setup(): void;
|
|
489
500
|
}
|
|
490
501
|
//#endregion
|
|
491
|
-
export { CancelableCloseEvent, CancelableMessageEvent, CloseEvent, WebSocketClientConnection, type WebSocketClientEventMap, WebSocketClientHandle, WebSocketConnectionEvent, type WebSocketConnectionEventData, type WebSocketConnectionInfo, type WebSocketData, type WebSocketEventMap$1 as WebSocketEventMap, WebSocketExtension, type WebSocketExtensionApi, type WebSocketExtensionContext, type WebSocketExtensionMessage, type WebSocketExtensionMessageContext, type WebSocketExtensionResult, WebSocketInterceptor, WebSocketInterceptorApi, WebSocketInterceptorMessage, WebSocketInterceptorOptions, WebSocketServerConnection, type WebSocketServerEventMap, WebSocketServerHandle, type WebSocketTransport };
|
|
502
|
+
export { CancelableCloseEvent, CancelableMessageEvent, CloseEvent, WebSocketClientConnection, type WebSocketClientEventMap, WebSocketClientHandle, WebSocketConnectionEvent, type WebSocketConnectionEventData, type WebSocketConnectionInfo, type WebSocketData, type WebSocketEventMap$1 as WebSocketEventMap, WebSocketExtension, type WebSocketExtensionApi, type WebSocketExtensionContext, type WebSocketExtensionMessage, type WebSocketExtensionMessageContext, type WebSocketExtensionResult, type WebSocketInterceptedConnection, WebSocketInterceptor, WebSocketInterceptorApi, WebSocketInterceptorMessage, WebSocketInterceptorOptions, WebSocketServerConnection, type WebSocketServerEventMap, WebSocketServerHandle, type WebSocketTransport };
|
|
492
503
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -136,11 +136,6 @@ var WebSocketExtension = class {
|
|
|
136
136
|
* Apply this extension to the given connection.
|
|
137
137
|
* From then on, both the client and the server of that connection
|
|
138
138
|
* encode the data they send and decode the data they receive.
|
|
139
|
-
*
|
|
140
|
-
* @note Typed against the connection classes, not the handles:
|
|
141
|
-
* a connection is assignable across `Message` types only when
|
|
142
|
-
* compared as the same class, which is what lets an extension narrow
|
|
143
|
-
* the raw `WebSocketData` connections it is applied to.
|
|
144
139
|
*/
|
|
145
140
|
apply(connection) {
|
|
146
141
|
connection.client.extension = this;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["kEmitter","kBoundListener","#getMessageContext","#getMessageContext"],"sources":["../../../../src/events/websocket.ts","../../../../src/interceptors/WebSocket/utils/bind-event.ts","../../../../src/interceptors/WebSocket/utils/events.ts","../../../../src/interceptors/WebSocket/web-socket-extension.ts","../../../../src/interceptors/WebSocket/web-socket-client-connection.ts","../../../../src/interceptors/WebSocket/web-socket-override.ts","../../../../src/interceptors/WebSocket/web-socket-server-connection.ts","../../../../src/interceptors/WebSocket/web-socket-class-transport.ts","../../../../src/utils/internal-connection.ts","../../../../src/interceptors/WebSocket/index.ts"],"sourcesContent":["import { TypedEvent } from 'rettime'\nimport type {\n WebSocketData,\n WebSocketClientConnection,\n WebSocketServerConnection,\n} from '../interceptors/WebSocket'\n\n/**\n * The connection information.\n */\nexport interface WebSocketConnectionInfo {\n /**\n * The protocols supported by the WebSocket client.\n */\n protocols: string | Array<string> | undefined\n}\n\nexport interface WebSocketConnectionEventData<Message = WebSocketData> {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientConnection<Message>\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerConnection<Message>\n info: WebSocketConnectionInfo\n}\n\nexport class WebSocketConnectionEvent<\n Message = WebSocketData,\n> extends TypedEvent<\n WebSocketConnectionEventData<Message>,\n void,\n 'connection'\n> {\n public client: WebSocketClientConnection<Message>\n public server: WebSocketServerConnection<Message>\n public info: WebSocketConnectionInfo\n\n constructor(data: WebSocketConnectionEventData<Message>) {\n super('connection', { data })\n\n this.client = data.client\n this.server = data.server\n this.info = data.info\n }\n}\n\nexport type WebSocketEventMap<Message = WebSocketData, Extension = {}> = {\n connection: WebSocketConnectionEvent<Message> & Extension\n}\n","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 } from './web-socket-transport'\nimport type { WebSocketClientConnection } from './web-socket-client-connection'\nimport type { WebSocketServerConnection } from './web-socket-server-connection'\nimport type { WebSocketConnectionInfo } from '../../events/websocket'\n\nexport const kExtensionContext = Symbol('kExtensionContext')\n\n/**\n * The messages the given extension encodes and decodes.\n *\n * @note Inferred from the `encode()` parameter alone. Inferring from the\n * whole class would also consider the return type of `decode()`, where a\n * `Generator<Message>` (whose return type defaults to `any`) would widen\n * the messages to `any`.\n */\nexport type WebSocketExtensionMessage<Extension> = Extension extends {\n encode(message: infer Message, context: never): unknown\n}\n ? Message\n : never\n\n/**\n * The API the given extension adds to the connection event.\n */\nexport type WebSocketExtensionApi<Extension> =\n Extension extends WebSocketExtension<unknown, infer Api> ? Api : never\n\n/**\n * The result of an extension method: a single value, an iterator\n * over multiple values, or `undefined` for no values at all.\n *\n * @note Only iterators (objects with a `next()` method, like generators)\n * are unfolded. Iterables that are not iterators, like strings, arrays,\n * or typed arrays, are treated as a single value so array-shaped\n * messages remain unambiguous.\n */\nexport type WebSocketExtensionResult<Value> =\n | Value\n | Iterator<Value, Value | void>\n | undefined\n\n/**\n * The intercepted connection an extension operates on.\n */\nexport interface WebSocketExtensionContext<Message = WebSocketData> {\n client: WebSocketClientConnection<Message>\n server: WebSocketServerConnection<Message>\n info: WebSocketConnectionInfo\n}\n\nexport interface WebSocketExtensionMessageContext<\n Message = WebSocketData,\n> extends WebSocketExtensionContext<Message> {\n /**\n * The connection whose data is being encoded or decoded:\n * the `client` for data crossing the client connection,\n * the `server` for data crossing the original server connection.\n */\n connection:\n | WebSocketClientConnection<Message>\n | WebSocketServerConnection<Message>\n}\n\n/**\n * A WebSocket extension: the server-side implementation of a protocol layered on top of\n * WebSocket (e.g. Socket.IO): its message framing (`encode`/`decode`),\n * its session as spoken by a server endpoint (`connect`/`receive`),\n * and the server API it adds to every connection (`extend`).\n *\n * The interceptor decides *when* each part applies: `send()` encodes,\n * frames are decoded before being dispatched as `message` events,\n * `connect` and `receive` frames are sent while the mocked connection\n * plays the server, and the extension is exposed on the connection event.\n *\n * An extension is invisible to the connection consumer: `client.send()`,\n * `server.send()`, and the `message` events all operate on messages,\n * and the session frames never surface. Raw frames forwarded between\n * the client and the original server (passthrough) are never touched.\n *\n * A method returns a single value for a one-to-one mapping,\n * an iterator (e.g. a generator) to unfold one input into many,\n * or nothing to drop the input.\n *\n * @example\n * class SocketIo extends WebSocketExtension<SocketIoMessage, { rooms: Rooms }> {\n * match({ client }) {\n * return client.url.searchParams.has('EIO')\n * }\n * encode(message) { ... }\n * decode(data) { ... }\n * connect() { ... }\n * receive(data) { ... }\n * extend({ client }) {\n * return { rooms: new Rooms(client) }\n * }\n * }\n *\n * new WebSocketInterceptor({ extensions: [new SocketIo()] })\n */\nexport abstract class WebSocketExtension<\n Message = WebSocketData,\n Extension = {},\n> {\n /**\n * Whether this extension applies to the given connection.\n * Allows applying the extension to a subset of intercepted connections.\n */\n public match?(context: WebSocketExtensionContext<Message>): boolean\n\n /**\n * Encode the given message into the raw frame(s) to send to the peer.\n */\n public abstract encode(\n message: Message,\n context: WebSocketExtensionMessageContext<Message>\n ): WebSocketExtensionResult<WebSocketData>\n\n /**\n * Decode the given raw frame into the message(s) to dispatch\n * as `message` events. Return nothing to swallow the frame\n * (e.g. protocol control frames).\n */\n public abstract decode(\n data: WebSocketData,\n context: WebSocketExtensionMessageContext<Message>\n ): WebSocketExtensionResult<Message>\n\n /**\n * The raw frame(s) a server of this extension's protocol sends once the\n * connection is established (e.g. a session handshake).\n * Sent to the client by the interceptor when the mocked connection\n * opens, unless a connection to the original server was established,\n * in which case the original server speaks for itself.\n */\n public connect?(\n context: WebSocketExtensionContext<Message>\n ): WebSocketExtensionResult<WebSocketData>\n\n /**\n * The raw frame(s) a server of this extension's protocol sends back in response\n * to the given client frame (e.g. a control frame acknowledgement),\n * the way a WebSocket endpoint answers a ping with a pong.\n * Applied by the interceptor under the same condition as `connect`.\n */\n public receive?(\n data: WebSocketData,\n context: WebSocketExtensionContext<Message>\n ): WebSocketExtensionResult<WebSocketData>\n\n /**\n * The server API this extension adds to the given connection\n * (e.g. rooms). Exposed on the connection event alongside\n * the `client` and the `server`.\n */\n public extend?(context: WebSocketExtensionContext<Message>): Extension\n\n /**\n * Apply this extension to the given connection.\n * From then on, both the client and the server of that connection\n * encode the data they send and decode the data they receive.\n *\n * @note Typed against the connection classes, not the handles:\n * a connection is assignable across `Message` types only when\n * compared as the same class, which is what lets an extension narrow\n * the raw `WebSocketData` connections it is applied to.\n */\n public apply(connection: {\n client: WebSocketClientConnection<Message>\n server: WebSocketServerConnection<Message>\n }): void {\n connection.client.extension = this\n connection.server.extension = this\n }\n}\n\n/**\n * Assert that the given message is raw WebSocket data.\n * Without a protocol, a connection can only carry raw data.\n */\nexport function toWebSocketData(message: unknown): WebSocketData {\n if (\n typeof message === 'string' ||\n message instanceof ArrayBuffer ||\n message instanceof Blob\n ) {\n return message\n }\n\n if (ArrayBuffer.isView(message) && message.buffer instanceof ArrayBuffer) {\n return new Uint8Array(\n message.buffer,\n message.byteOffset,\n message.byteLength\n )\n }\n\n throw new TypeError(\n `Failed to send a message of type \"${typeof message}\": a connection without an extension can only send strings, Blob, ArrayBuffer, or ArrayBufferView`\n )\n}\n\n/**\n * Iterate over the values of the given protocol result.\n * A generator's return value, if any, counts as its last value.\n *\n * Delegating via `yield*` forwards early termination of this\n * generator (e.g. a `break` or an error in the consumer's loop)\n * to the underlying iterator so it can clean up after itself.\n */\nexport function* iterateWebSocketExtensionResult<Value>(\n result: WebSocketExtensionResult<Value>\n): Generator<Value, void, undefined> {\n if (result === undefined) {\n return\n }\n\n if (isIterator<Value>(result)) {\n const returnValue = yield* { [Symbol.iterator]: () => result }\n\n if (returnValue !== undefined) {\n yield returnValue\n }\n\n return\n }\n\n yield result\n}\n\n/**\n * @note Only objects with a `next()` method count as iterators.\n * Iterables that are not iterators (strings, arrays, typed arrays)\n * are intentionally excluded so array-shaped messages remain unambiguous.\n */\nfunction isIterator<Value>(\n value: unknown\n): value is Iterator<Value, Value | void> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof Reflect.get(value, 'next') === 'function'\n )\n}\n","import type { WebSocketData, WebSocketTransport } from './web-socket-transport'\nimport type { WebSocketEventListener } from './web-socket-override'\nimport { bindEvent } from './utils/bind-event'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../create-request-id'\nimport {\n kExtensionContext,\n iterateWebSocketExtensionResult,\n toWebSocketData,\n type WebSocketExtension,\n type WebSocketExtensionContext,\n type WebSocketExtensionMessageContext,\n} from './web-socket-extension'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\nexport interface WebSocketClientEventMap<Message = WebSocketData> {\n open: Event\n message: MessageEvent<Message>\n close: CloseEvent\n}\n\n/**\n * The handle to a WebSocket client connection: its identity and controls.\n * A handle is what a connection is regardless of where it lives.\n * A `WebSocketClientConnection` is a handle bound to a connection in this\n * process; a handle can also be revived from a serialized connection\n * in another process (e.g. a connection stored by a worker).\n *\n * `Message` is what crosses this connection: raw WebSocket data, or the\n * messages of the extension applied to it.\n */\nexport abstract class WebSocketClientHandle<Message = WebSocketData> {\n abstract id: string\n abstract url: URL\n public extension?: WebSocketExtension<unknown, unknown>\n public abstract send(data: Message): void\n public abstract close(code?: number, reason?: string): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketClientEventMap<Message>,\n >(\n type: EventType,\n listener: WebSocketEventListener<\n WebSocketClientEventMap<Message>[EventType]\n >,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketClientEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketClientEventMap<Message>[EventType]\n >,\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<\n Message = WebSocketData,\n> implements WebSocketClientHandle<Message> {\n public readonly id: string\n public readonly url: URL\n\n /**\n * An optional extension applied to the data crossing this connection:\n * `send()` encodes, outgoing client frames are decoded\n * before being dispatched as `message` events.\n */\n public extension?: WebSocketExtension<unknown, unknown>\n\n /**\n * The intercepted connection this client belongs to.\n * Provided by the interceptor once both connections exist.\n */\n public [kExtensionContext]?: WebSocketExtensionContext<unknown>\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 /**\n * Emit the \"open\" event on the \"client\" connection once the\n * client connection is open. This is either the mocked connection\n * opening or, for passthrough connections, the original server\n * connection opening (forwarded to the client by the interceptor).\n */\n this.socket.addEventListener(\n 'open',\n () => {\n this[kEmitter].dispatchEvent(bindEvent(this.socket, new Event('open')))\n },\n { once: true }\n )\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // A single frame may decode into any number of messages\n // (e.g. none for protocol control frames).\n const messages = this.extension\n ? iterateWebSocketExtensionResult(\n this.extension.decode(event.data, this.#getMessageContext())\n )\n : [event.data]\n let defaultPrevented = false\n\n for (const data of messages) {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n defaultPrevented ||= message.defaultPrevented\n }\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 (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<\n EventType extends keyof WebSocketClientEventMap<Message>,\n >(\n type: EventType,\n listener: WebSocketEventListener<\n WebSocketClientEventMap<Message>[EventType]\n >,\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<\n EventType extends keyof WebSocketClientEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketClientEventMap<Message>[EventType]\n >,\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: Message): void {\n if (!this.extension) {\n this.transport.send(toWebSocketData(data))\n return\n }\n\n for (const frame of iterateWebSocketExtensionResult(\n this.extension.encode(data, this.#getMessageContext())\n )) {\n this.transport.send(frame)\n }\n }\n\n #getMessageContext(): WebSocketExtensionMessageContext<unknown> {\n const context = this[kExtensionContext]\n\n if (!context) {\n throw new Error(\n `Failed to apply the extension to the client connection \"${this.url.href}\": the connection context is missing`\n )\n }\n\n return { ...context, connection: this }\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 type { WebSocketData } from './web-socket-transport'\nimport { bindEvent } from './utils/bind-event'\nimport { CloseEvent } from './utils/events'\nimport { resolveWebSocketUrl } from '../../utils/resolve-web-socket-url'\n\nexport type WebSocketEventListener<EventType extends Event = Event> = (\n this: WebSocket,\n event: EventType\n) => 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]: PromiseWithResolvers<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] = Promise.withResolvers<boolean>()\n\n queueMicrotask(async () => {\n if (await this[kPassthroughPromise].promise) {\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 './web-socket-override'\nimport type { WebSocketData } from './web-socket-transport'\nimport type { WebSocketClassTransport } from './web-socket-class-transport'\nimport { bindEvent } from './utils/bind-event'\nimport {\n CancelableMessageEvent,\n CancelableCloseEvent,\n CloseEvent,\n} from './utils/events'\nimport {\n kExtensionContext,\n iterateWebSocketExtensionResult,\n toWebSocketData,\n type WebSocketExtension,\n type WebSocketExtensionContext,\n type WebSocketExtensionMessageContext,\n} from './web-socket-extension'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\nconst kSend = Symbol('kSend')\n\nexport interface WebSocketServerEventMap<Message = WebSocketData> {\n open: Event\n message: MessageEvent<Message>\n error: Event\n close: CloseEvent\n}\n\n/**\n * The handle to the original WebSocket server connection: its controls.\n * A `WebSocketServerConnection` is a handle bound to a connection\n * in this process.\n */\nexport abstract class WebSocketServerHandle<Message = WebSocketData> {\n public extension?: WebSocketExtension<unknown, unknown>\n public abstract connect(): void\n public abstract send(data: Message): void\n public abstract close(): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketServerEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketServerEventMap<Message>[EventType]\n >,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketServerEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketServerEventMap<Message>[EventType]\n >,\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<\n Message = WebSocketData,\n> implements WebSocketServerHandle<Message> {\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 /**\n * An optional extension applied to the data crossing this connection:\n * `send()` encodes, incoming server frames are decoded\n * before being dispatched as `message` events.\n */\n public extension?: WebSocketExtension<unknown, unknown>\n\n /**\n * The intercepted connection this server belongs to.\n * Provided by the interceptor once both connections exist.\n */\n public [kExtensionContext]?: WebSocketExtensionContext<unknown>\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 * The ready state of the connection to the original WebSocket server.\n * Equals `WebSocket.CLOSED` until `server.connect()` is called.\n */\n public get readyState(): number {\n return this.realWebSocket?.readyState ?? WebSocket.CLOSED\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<\n EventType extends keyof WebSocketServerEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketServerEventMap<Message>[EventType]\n >,\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<\n EventType extends keyof WebSocketServerEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketServerEventMap<Message>[EventType]\n >,\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: Message): void {\n // Fail on a missing connection before encoding so the error\n // surfaces even if the extension drops the message or throws.\n this.assertConnected()\n\n if (!this.extension) {\n this[kSend](toWebSocketData(data))\n return\n }\n\n for (const frame of iterateWebSocketExtensionResult(\n this.extension.encode(data, this.#getMessageContext())\n )) {\n this[kSend](frame)\n }\n }\n\n #getMessageContext(): WebSocketExtensionMessageContext<unknown> {\n const context = this[kExtensionContext]\n\n if (!context) {\n throw new Error(\n `Failed to apply the extension to the server connection \"${this.client.url}\": the connection context is missing`\n )\n }\n\n return { ...context, connection: this }\n }\n\n /**\n * Return the original WebSocket, throwing if\n * the connection to the original server was not established.\n */\n private assertConnected(): WebSocket {\n invariant(\n this.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 return this.realWebSocket\n }\n\n private [kSend](data: WebSocketData): void {\n const realWebSocket = this.assertConnected()\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 // A single frame may decode into any number of messages\n // (e.g. none for protocol control frames).\n const messages = this.extension\n ? iterateWebSocketExtensionResult(\n this.extension.decode(event.data, this.#getMessageContext())\n )\n : [event.data]\n let defaultPrevented = false\n\n for (const data of messages) {\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,\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 defaultPrevented ||= messageEvent.defaultPrevented\n }\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 (!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/bind-event'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './web-socket-transport'\nimport { kOnSend, kClose, WebSocketOverride } from './web-socket-override'\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","interface InternalConnectionContext {\n run<T>(callback: () => T): T\n consume(): boolean\n}\n\ndeclare global {\n var __MSW_INTERNAL_CONNECTION_CONTEXT: InternalConnectionContext | undefined\n}\n\n/**\n * Share the Node-provided async context with the browser-built WebSocket\n * entry point without importing Node modules into the browser bundle.\n */\nexport function runAsInternalConnection<T>(callback: () => T): T {\n const context = globalThis.__MSW_INTERNAL_CONNECTION_CONTEXT\n\n if (context) {\n return context.run(callback)\n }\n\n return callback()\n}\n","import { Interceptor } from '../../interceptor'\nimport {\n WebSocketConnectionEvent,\n type WebSocketEventMap,\n type WebSocketConnectionInfo,\n type WebSocketConnectionEventData,\n} from '../../events/websocket'\nimport {\n WebSocketClientHandle,\n WebSocketClientConnection,\n type WebSocketClientEventMap,\n} from './web-socket-client-connection'\nimport {\n WebSocketServerHandle,\n WebSocketServerConnection,\n type WebSocketServerEventMap,\n} from './web-socket-server-connection'\nimport { WebSocketClassTransport } from './web-socket-class-transport'\nimport type { WebSocketData } from './web-socket-transport'\nimport {\n kClose,\n kPassthroughPromise,\n WebSocketOverride,\n} from './web-socket-override'\nimport { bindEvent } from './utils/bind-event'\nimport {\n kExtensionContext,\n iterateWebSocketExtensionResult,\n WebSocketExtension,\n type WebSocketExtensionContext,\n type WebSocketExtensionMessage,\n type WebSocketExtensionApi,\n} from './web-socket-extension'\nimport { hasConfigurableGlobal } from '../../utils/has-configurable-global'\nimport { patchesRegistry } from '../../utils/patches-registry'\nimport { createLogger } from '../../utils/logger'\nimport { runAsInternalConnection } from '../../utils/internal-connection'\n\nexport {\n type WebSocketData,\n type WebSocketTransport,\n} from './web-socket-transport'\nexport {\n WebSocketEventMap,\n WebSocketConnectionEvent,\n WebSocketConnectionInfo,\n WebSocketConnectionEventData,\n WebSocketClientEventMap,\n WebSocketClientHandle,\n WebSocketClientConnection,\n WebSocketServerEventMap,\n WebSocketServerHandle,\n WebSocketServerConnection,\n}\n\nexport {\n CloseEvent,\n CancelableCloseEvent,\n CancelableMessageEvent,\n} from './utils/events'\n\nexport {\n WebSocketExtension,\n type WebSocketExtensionContext,\n type WebSocketExtensionMessageContext,\n type WebSocketExtensionResult,\n type WebSocketExtensionMessage,\n type WebSocketExtensionApi,\n} from './web-socket-extension'\n\ntype WebSocketExtensions = ReadonlyArray<WebSocketExtension<unknown, unknown>>\n\n/**\n * The messages crossing the connections intercepted with the given\n * extensions: the messages of the extension applied to a connection,\n * or raw WebSocket data when there are no extensions.\n *\n * @note The types assume one of the extensions matches the connection.\n */\nexport type WebSocketInterceptorMessage<\n Extensions extends WebSocketExtensions,\n> = [Extensions] extends [readonly []]\n ? WebSocketData\n : WebSocketExtensionMessage<Extensions[number]>\n\n/**\n * The API the extension applied to a connection adds to the connection event.\n */\nexport type WebSocketInterceptorApi<Extensions extends WebSocketExtensions> = [\n Extensions,\n] extends [readonly []]\n ? {}\n : WebSocketExtensionApi<Extensions[number]>\n\nexport interface WebSocketInterceptorOptions<\n Extensions extends WebSocketExtensions = [],\n> {\n /**\n * Extensions to apply to the intercepted connections.\n * The first extension whose `match()` accepts a connection is applied\n * to it. An extension without `match()` accepts every connection.\n */\n extensions?: Extensions\n}\n\nconst logger = createLogger('websocket')\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor<\n const Extensions extends WebSocketExtensions = [],\n> extends Interceptor<\n WebSocketEventMap<\n WebSocketInterceptorMessage<Extensions>,\n WebSocketInterceptorApi<Extensions>\n >\n> {\n static symbol = Symbol.for('websocket-interceptor')\n\n private readonly extensions: WebSocketExtensions\n\n constructor(options: WebSocketInterceptorOptions<Extensions> = {}) {\n super()\n this.extensions = options.extensions ?? []\n }\n\n protected predicate(): boolean {\n return hasConfigurableGlobal('WebSocket')\n }\n\n protected setup(): void {\n logger.verbose('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 logger.info('connection intercepted %o', {\n url: url.toString(),\n protocols,\n })\n\n const createConnection = (): WebSocket => {\n return runAsInternalConnection(() => {\n return Reflect.construct(target, args, newTarget)\n })\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 /**\n * @note The mocked connection plays the server endpoint of the\n * protocol unless a connection to the original server was\n * created, in which case the original server speaks for itself.\n * Check the creation, not the ready state: the original connection\n * may have already closed by now (e.g. when the client is kept open\n * past the original server closing), and the client must not be\n * handshaked twice.\n */\n const isServerEndpoint = () => server['realWebSocket'] == null\n\n /**\n * @note Register these before the client connection so the\n * protocol frames precede anything sent from its listeners.\n */\n socket.addEventListener(\n 'open',\n () => {\n if (!isServerEndpoint()) {\n return\n }\n\n for (const frame of iterateWebSocketExtensionResult(\n client.extension?.connect?.(context)\n )) {\n transport.send(frame)\n }\n },\n { once: true }\n )\n\n transport.addEventListener('outgoing', (event) => {\n if (!isServerEndpoint()) {\n return\n }\n\n for (const frame of iterateWebSocketExtensionResult(\n client.extension?.receive?.(event.data, context)\n )) {\n transport.send(frame)\n }\n })\n\n const client = new WebSocketClientConnection(socket, transport)\n const context: WebSocketExtensionContext = {\n client,\n server,\n info: {\n protocols,\n },\n }\n client[kExtensionContext] = context\n server[kExtensionContext] = context\n\n const extension = this.extensions.find((extension) => {\n return extension.match?.(context) ?? true\n })\n extension?.apply(context)\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 /**\n * @note Expose the extension's own API (e.g. rooms) on the\n * connection event. The event map is inferred from the extensions\n * this interceptor was given; `Object.assign` with a spread of\n * sources is untyped, which is what lets the event take that type.\n */\n const extensionApis: Array<unknown> = [extension?.extend?.(context)]\n\n await this.emitter.emitAsPromise(\n Object.assign(\n new WebSocketConnectionEvent({\n client,\n server,\n info: context.info,\n }),\n ...extensionApis\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.verbose('patching global WebSocket...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'WebSocket', () => WebSocketProxy)\n )\n\n logger.verbose('global WebSocket patched: %s', globalThis.WebSocket.name)\n }\n}\n"],"mappings":";;;;;;AA6BA,IAAa,2BAAb,cAEU,WAIR;CAKA,YAAY,MAA6C;EACvD,MAAM,cAAc,EAAE,KAAK,CAAC;EAE5B,KAAK,SAAS,KAAK;EACnB,KAAK,SAAS,KAAK;EACnB,KAAK,OAAO,KAAK;CACnB;AACF;;;AC7CA,SAAgB,UACd,QACA,OACuB;CACvB,OAAO,iBAAiB,OAAO;EAC7B,QAAQ;GACN,OAAO;GACP,YAAY;GACZ,UAAU;EACZ;EACA,eAAe;GACb,OAAO;GACP,YAAY;GACZ,UAAU;EACZ;CACF,CAAC;CAED,OAAO;AACT;;;ACpBA,MAAM,cAAc,OAAO,aAAa;AACxC,MAAM,oBAAoB,OAAO,mBAAmB;;;;;;;;AASpD,IAAa,yBAAb,cAAqD,aAAgB;CAInE,YAAY,MAAc,MAA2B;EACnD,MAAM,MAAM,IAAI;EAChB,KAAK,eAAe,CA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AC;MAE9C,CAAC;KACH;IACF,SAAS,OAAO;;;;;;;KAOd,IAAI,iBAAiB,OAAO;MAC1B,OAAO,cAAc,IAAI,MAAM,OAAO,CAAC;MAIvC,IACE,OAAO,eAAe,UAAU,WAChC,OAAO,eAAe,UAAU,QAEhC,OAAO,OAAO,CAAC,MAAM,MAAM,SAAS,KAAK;MAG3C,QAAQ,MAAM,KAAK;KACrB;IACF;GACF,CAAC;GAED,OAAO;EACT,EACF,CAAC;EAED,OAAO,QAAQ,8BAA8B;EAE7C,KAAK,cAAc,KACjB,gBAAgB,WAAW,YAAY,mBAAmB,cAAc,CAC1E;EAEA,OAAO,QAAQ,gCAAgC,WAAW,UAAU,IAAI;CAC1E;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["kEmitter","kBoundListener","#getMessageContext","#getMessageContext"],"sources":["../../../../src/events/websocket.ts","../../../../src/interceptors/WebSocket/utils/bind-event.ts","../../../../src/interceptors/WebSocket/utils/events.ts","../../../../src/interceptors/WebSocket/web-socket-extension.ts","../../../../src/interceptors/WebSocket/web-socket-client-connection.ts","../../../../src/interceptors/WebSocket/web-socket-override.ts","../../../../src/interceptors/WebSocket/web-socket-server-connection.ts","../../../../src/interceptors/WebSocket/web-socket-class-transport.ts","../../../../src/utils/internal-connection.ts","../../../../src/interceptors/WebSocket/index.ts"],"sourcesContent":["import { TypedEvent } from 'rettime'\nimport type {\n WebSocketData,\n WebSocketClientHandle,\n WebSocketClientConnection,\n WebSocketServerHandle,\n WebSocketServerConnection,\n} from '../interceptors/WebSocket'\n\n/**\n * The connection information.\n */\nexport interface WebSocketConnectionInfo {\n /**\n * The protocols supported by the WebSocket client.\n */\n protocols: string | Array<string> | undefined\n}\n\n/**\n * An intercepted WebSocket connection: the client and the server handles.\n *\n * @note Typed against the handles, not the connection classes,\n * so that a connection living anywhere (in this process, in another\n * runtime, or in a custom implementation) can be given to whoever\n * consumes intercepted connections (e.g. a handler).\n */\nexport interface WebSocketConnectionEventData<Message = WebSocketData> {\n /**\n * The incoming WebSocket client connection.\n */\n client: WebSocketClientHandle<Message>\n /**\n * The original WebSocket server connection.\n */\n server: WebSocketServerHandle<Message>\n info: WebSocketConnectionInfo\n}\n\n/**\n * The connection intercepted by the `WebSocketInterceptor`:\n * both the client and the server live in this process.\n */\nexport interface WebSocketInterceptedConnection<\n Message = WebSocketData,\n> extends WebSocketConnectionEventData<Message> {\n client: WebSocketClientConnection<Message>\n server: WebSocketServerConnection<Message>\n}\n\nexport class WebSocketConnectionEvent<Message = WebSocketData>\n extends TypedEvent<\n WebSocketInterceptedConnection<Message>,\n void,\n 'connection'\n >\n implements WebSocketInterceptedConnection<Message>\n{\n public client: WebSocketClientConnection<Message>\n public server: WebSocketServerConnection<Message>\n public info: WebSocketConnectionInfo\n\n constructor(data: WebSocketInterceptedConnection<Message>) {\n super('connection', { data })\n\n this.client = data.client\n this.server = data.server\n this.info = data.info\n }\n}\n\nexport type WebSocketEventMap<Message = WebSocketData, Extension = {}> = {\n connection: WebSocketConnectionEvent<Message> & Extension\n}\n","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 } from './web-socket-transport'\nimport type { WebSocketClientHandle } from './web-socket-client-connection'\nimport type { WebSocketServerHandle } from './web-socket-server-connection'\nimport type { WebSocketConnectionInfo } from '../../events/websocket'\n\nexport const kExtensionContext = Symbol('kExtensionContext')\n\n/**\n * The messages the given extension encodes and decodes.\n *\n * @note Inferred from the `encode()` parameter alone. Inferring from the\n * whole class would also consider the return type of `decode()`, where a\n * `Generator<Message>` (whose return type defaults to `any`) would widen\n * the messages to `any`.\n */\nexport type WebSocketExtensionMessage<Extension> = Extension extends {\n encode(message: infer Message, context: never): unknown\n}\n ? Message\n : never\n\n/**\n * The API the given extension adds to the connection event.\n */\nexport type WebSocketExtensionApi<Extension> =\n Extension extends WebSocketExtension<unknown, infer Api> ? Api : never\n\n/**\n * The result of an extension method: a single value, an iterator\n * over multiple values, or `undefined` for no values at all.\n *\n * @note Only iterators (objects with a `next()` method, like generators)\n * are unfolded. Iterables that are not iterators, like strings, arrays,\n * or typed arrays, are treated as a single value so array-shaped\n * messages remain unambiguous.\n */\nexport type WebSocketExtensionResult<Value> =\n Value | Iterator<Value, Value | void> | undefined\n\n/**\n * The intercepted connection an extension operates on.\n */\nexport interface WebSocketExtensionContext<Message = WebSocketData> {\n client: WebSocketClientHandle<Message>\n server: WebSocketServerHandle<Message>\n info: WebSocketConnectionInfo\n}\n\nexport interface WebSocketExtensionMessageContext<\n Message = WebSocketData,\n> extends WebSocketExtensionContext<Message> {\n /**\n * The connection whose data is being encoded or decoded:\n * the `client` for data crossing the client connection,\n * the `server` for data crossing the original server connection.\n */\n connection: WebSocketClientHandle<Message> | WebSocketServerHandle<Message>\n}\n\n/**\n * A WebSocket extension: the server-side implementation of a protocol layered on top of\n * WebSocket (e.g. Socket.IO): its message framing (`encode`/`decode`),\n * its session as spoken by a server endpoint (`connect`/`receive`),\n * and the server API it adds to every connection (`extend`).\n *\n * The interceptor decides *when* each part applies: `send()` encodes,\n * frames are decoded before being dispatched as `message` events,\n * `connect` and `receive` frames are sent while the mocked connection\n * plays the server, and the extension is exposed on the connection event.\n *\n * An extension is invisible to the connection consumer: `client.send()`,\n * `server.send()`, and the `message` events all operate on messages,\n * and the session frames never surface. Raw frames forwarded between\n * the client and the original server (passthrough) are never touched.\n *\n * A method returns a single value for a one-to-one mapping,\n * an iterator (e.g. a generator) to unfold one input into many,\n * or nothing to drop the input.\n *\n * @example\n * class SocketIo extends WebSocketExtension<SocketIoMessage, { rooms: Rooms }> {\n * match({ client }) {\n * return client.url.searchParams.has('EIO')\n * }\n * encode(message) { ... }\n * decode(data) { ... }\n * connect() { ... }\n * receive(data) { ... }\n * extend({ client }) {\n * return { rooms: new Rooms(client) }\n * }\n * }\n *\n * new WebSocketInterceptor({ extensions: [new SocketIo()] })\n */\nexport abstract class WebSocketExtension<\n Message = WebSocketData,\n Extension = {},\n> {\n /**\n * Whether this extension applies to the given connection.\n * Allows applying the extension to a subset of intercepted connections.\n */\n public match?(context: WebSocketExtensionContext<Message>): boolean\n\n /**\n * Encode the given message into the raw frame(s) to send to the peer.\n */\n public abstract encode(\n message: Message,\n context: WebSocketExtensionMessageContext<Message>\n ): WebSocketExtensionResult<WebSocketData>\n\n /**\n * Decode the given raw frame into the message(s) to dispatch\n * as `message` events. Return nothing to swallow the frame\n * (e.g. protocol control frames).\n */\n public abstract decode(\n data: WebSocketData,\n context: WebSocketExtensionMessageContext<Message>\n ): WebSocketExtensionResult<Message>\n\n /**\n * The raw frame(s) a server of this extension's protocol sends once the\n * connection is established (e.g. a session handshake).\n * Sent to the client by the interceptor when the mocked connection\n * opens, unless a connection to the original server was established,\n * in which case the original server speaks for itself.\n */\n public connect?(\n context: WebSocketExtensionContext<Message>\n ): WebSocketExtensionResult<WebSocketData>\n\n /**\n * The raw frame(s) a server of this extension's protocol sends back in response\n * to the given client frame (e.g. a control frame acknowledgement),\n * the way a WebSocket endpoint answers a ping with a pong.\n * Applied by the interceptor under the same condition as `connect`.\n */\n public receive?(\n data: WebSocketData,\n context: WebSocketExtensionContext<Message>\n ): WebSocketExtensionResult<WebSocketData>\n\n /**\n * The server API this extension adds to the given connection\n * (e.g. rooms). Exposed on the connection event alongside\n * the `client` and the `server`.\n */\n public extend?(context: WebSocketExtensionContext<Message>): Extension\n\n /**\n * Apply this extension to the given connection.\n * From then on, both the client and the server of that connection\n * encode the data they send and decode the data they receive.\n */\n public apply(connection: {\n client: WebSocketClientHandle<Message>\n server: WebSocketServerHandle<Message>\n }): void {\n connection.client.extension = this\n connection.server.extension = this\n }\n}\n\n/**\n * Assert that the given message is raw WebSocket data.\n * Without a protocol, a connection can only carry raw data.\n */\nexport function toWebSocketData(message: unknown): WebSocketData {\n if (\n typeof message === 'string' ||\n message instanceof ArrayBuffer ||\n message instanceof Blob\n ) {\n return message\n }\n\n if (ArrayBuffer.isView(message) && message.buffer instanceof ArrayBuffer) {\n return new Uint8Array(\n message.buffer,\n message.byteOffset,\n message.byteLength\n )\n }\n\n throw new TypeError(\n `Failed to send a message of type \"${typeof message}\": a connection without an extension can only send strings, Blob, ArrayBuffer, or ArrayBufferView`\n )\n}\n\n/**\n * Iterate over the values of the given protocol result.\n * A generator's return value, if any, counts as its last value.\n *\n * Delegating via `yield*` forwards early termination of this\n * generator (e.g. a `break` or an error in the consumer's loop)\n * to the underlying iterator so it can clean up after itself.\n */\nexport function* iterateWebSocketExtensionResult<Value>(\n result: WebSocketExtensionResult<Value>\n): Generator<Value, void, undefined> {\n if (result === undefined) {\n return\n }\n\n if (isIterator<Value>(result)) {\n const returnValue = yield* { [Symbol.iterator]: () => result }\n\n if (returnValue !== undefined) {\n yield returnValue\n }\n\n return\n }\n\n yield result\n}\n\n/**\n * @note Only objects with a `next()` method count as iterators.\n * Iterables that are not iterators (strings, arrays, typed arrays)\n * are intentionally excluded so array-shaped messages remain unambiguous.\n */\nfunction isIterator<Value>(\n value: unknown\n): value is Iterator<Value, Value | void> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof Reflect.get(value, 'next') === 'function'\n )\n}\n","import type { WebSocketData, WebSocketTransport } from './web-socket-transport'\nimport type { WebSocketEventListener } from './web-socket-override'\nimport { bindEvent } from './utils/bind-event'\nimport { CancelableMessageEvent, CloseEvent } from './utils/events'\nimport { createRequestId } from '../../create-request-id'\nimport {\n kExtensionContext,\n iterateWebSocketExtensionResult,\n toWebSocketData,\n type WebSocketExtension,\n type WebSocketExtensionContext,\n type WebSocketExtensionMessageContext,\n} from './web-socket-extension'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\n\nexport interface WebSocketClientEventMap<Message = WebSocketData> {\n open: Event\n message: MessageEvent<Message>\n close: CloseEvent\n}\n\n/**\n * The handle to a WebSocket client connection: its identity and controls.\n * A handle is what a connection is regardless of where it lives.\n * A `WebSocketClientConnection` is a handle bound to a connection in this\n * process; a handle can also be revived from a serialized connection\n * in another process (e.g. a connection stored by a worker).\n *\n * `Message` is what crosses this connection: raw WebSocket data, or the\n * messages of the extension applied to it.\n */\nexport abstract class WebSocketClientHandle<Message = WebSocketData> {\n abstract id: string\n abstract url: URL\n public extension?: WebSocketExtension<unknown, unknown>\n public abstract send(data: Message): void\n public abstract close(code?: number, reason?: string): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketClientEventMap<Message>,\n >(\n type: EventType,\n listener: WebSocketEventListener<\n WebSocketClientEventMap<Message>[EventType]\n >,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketClientEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketClientEventMap<Message>[EventType]\n >,\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<\n Message = WebSocketData,\n> implements WebSocketClientHandle<Message> {\n public readonly id: string\n public readonly url: URL\n\n /**\n * An optional extension applied to the data crossing this connection:\n * `send()` encodes, outgoing client frames are decoded\n * before being dispatched as `message` events.\n */\n public extension?: WebSocketExtension<unknown, unknown>\n\n /**\n * The intercepted connection this client belongs to.\n * Provided by the interceptor once both connections exist.\n */\n public [kExtensionContext]?: WebSocketExtensionContext<unknown>\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 /**\n * Emit the \"open\" event on the \"client\" connection once the\n * client connection is open. This is either the mocked connection\n * opening or, for passthrough connections, the original server\n * connection opening (forwarded to the client by the interceptor).\n */\n this.socket.addEventListener(\n 'open',\n () => {\n this[kEmitter].dispatchEvent(bindEvent(this.socket, new Event('open')))\n },\n { once: true }\n )\n\n // Emit outgoing client data (\"ws.send()\") as \"message\"\n // events on the \"client\" connection.\n this.transport.addEventListener('outgoing', (event) => {\n // A single frame may decode into any number of messages\n // (e.g. none for protocol control frames).\n const messages = this.extension\n ? iterateWebSocketExtensionResult(\n this.extension.decode(event.data, this.#getMessageContext())\n )\n : [event.data]\n let defaultPrevented = false\n\n for (const data of messages) {\n const message = bindEvent(\n this.socket,\n new CancelableMessageEvent('message', {\n data,\n origin: event.origin,\n cancelable: true,\n })\n )\n\n this[kEmitter].dispatchEvent(message)\n defaultPrevented ||= message.defaultPrevented\n }\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 (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<\n EventType extends keyof WebSocketClientEventMap<Message>,\n >(\n type: EventType,\n listener: WebSocketEventListener<\n WebSocketClientEventMap<Message>[EventType]\n >,\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<\n EventType extends keyof WebSocketClientEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketClientEventMap<Message>[EventType]\n >,\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: Message): void {\n if (!this.extension) {\n this.transport.send(toWebSocketData(data))\n return\n }\n\n for (const frame of iterateWebSocketExtensionResult(\n this.extension.encode(data, this.#getMessageContext())\n )) {\n this.transport.send(frame)\n }\n }\n\n #getMessageContext(): WebSocketExtensionMessageContext<unknown> {\n const context = this[kExtensionContext]\n\n if (!context) {\n throw new Error(\n `Failed to apply the extension to the client connection \"${this.url.href}\": the connection context is missing`\n )\n }\n\n return { ...context, connection: this }\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 type { WebSocketData } from './web-socket-transport'\nimport { bindEvent } from './utils/bind-event'\nimport { CloseEvent } from './utils/events'\nimport { resolveWebSocketUrl } from '../../utils/resolve-web-socket-url'\n\nexport type WebSocketEventListener<EventType extends Event = Event> = (\n this: WebSocket,\n event: EventType\n) => 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]: PromiseWithResolvers<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] = Promise.withResolvers<boolean>()\n\n queueMicrotask(async () => {\n if (await this[kPassthroughPromise].promise) {\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 './web-socket-override'\nimport type { WebSocketData } from './web-socket-transport'\nimport type { WebSocketClassTransport } from './web-socket-class-transport'\nimport { bindEvent } from './utils/bind-event'\nimport {\n CancelableMessageEvent,\n CancelableCloseEvent,\n CloseEvent,\n} from './utils/events'\nimport {\n kExtensionContext,\n iterateWebSocketExtensionResult,\n toWebSocketData,\n type WebSocketExtension,\n type WebSocketExtensionContext,\n type WebSocketExtensionMessageContext,\n} from './web-socket-extension'\n\nconst kEmitter = Symbol('kEmitter')\nconst kBoundListener = Symbol('kBoundListener')\nconst kSend = Symbol('kSend')\n\nexport interface WebSocketServerEventMap<Message = WebSocketData> {\n open: Event\n message: MessageEvent<Message>\n error: Event\n close: CloseEvent\n}\n\n/**\n * The handle to the original WebSocket server connection: its controls.\n * A `WebSocketServerConnection` is a handle bound to a connection\n * in this process.\n */\nexport abstract class WebSocketServerHandle<Message = WebSocketData> {\n public extension?: WebSocketExtension<unknown, unknown>\n public abstract connect(): void\n public abstract send(data: Message): void\n public abstract close(): void\n\n public abstract addEventListener<\n EventType extends keyof WebSocketServerEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketServerEventMap<Message>[EventType]\n >,\n options?: AddEventListenerOptions | boolean\n ): void\n\n public abstract removeEventListener<\n EventType extends keyof WebSocketServerEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketServerEventMap<Message>[EventType]\n >,\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<\n Message = WebSocketData,\n> implements WebSocketServerHandle<Message> {\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 /**\n * An optional extension applied to the data crossing this connection:\n * `send()` encodes, incoming server frames are decoded\n * before being dispatched as `message` events.\n */\n public extension?: WebSocketExtension<unknown, unknown>\n\n /**\n * The intercepted connection this server belongs to.\n * Provided by the interceptor once both connections exist.\n */\n public [kExtensionContext]?: WebSocketExtensionContext<unknown>\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 * The ready state of the connection to the original WebSocket server.\n * Equals `WebSocket.CLOSED` until `server.connect()` is called.\n */\n public get readyState(): number {\n return this.realWebSocket?.readyState ?? WebSocket.CLOSED\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<\n EventType extends keyof WebSocketServerEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketServerEventMap<Message>[EventType]\n >,\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<\n EventType extends keyof WebSocketServerEventMap<Message>,\n >(\n event: EventType,\n listener: WebSocketEventListener<\n WebSocketServerEventMap<Message>[EventType]\n >,\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: Message): void {\n // Fail on a missing connection before encoding so the error\n // surfaces even if the extension drops the message or throws.\n this.assertConnected()\n\n if (!this.extension) {\n this[kSend](toWebSocketData(data))\n return\n }\n\n for (const frame of iterateWebSocketExtensionResult(\n this.extension.encode(data, this.#getMessageContext())\n )) {\n this[kSend](frame)\n }\n }\n\n #getMessageContext(): WebSocketExtensionMessageContext<unknown> {\n const context = this[kExtensionContext]\n\n if (!context) {\n throw new Error(\n `Failed to apply the extension to the server connection \"${this.client.url}\": the connection context is missing`\n )\n }\n\n return { ...context, connection: this }\n }\n\n /**\n * Return the original WebSocket, throwing if\n * the connection to the original server was not established.\n */\n private assertConnected(): WebSocket {\n invariant(\n this.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 return this.realWebSocket\n }\n\n private [kSend](data: WebSocketData): void {\n const realWebSocket = this.assertConnected()\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 // A single frame may decode into any number of messages\n // (e.g. none for protocol control frames).\n const messages = this.extension\n ? iterateWebSocketExtensionResult(\n this.extension.decode(event.data, this.#getMessageContext())\n )\n : [event.data]\n let defaultPrevented = false\n\n for (const data of messages) {\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,\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 defaultPrevented ||= messageEvent.defaultPrevented\n }\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 (!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/bind-event'\nimport {\n StrictEventListenerOrEventListenerObject,\n WebSocketData,\n WebSocketTransport,\n WebSocketTransportEventMap,\n} from './web-socket-transport'\nimport { kOnSend, kClose, WebSocketOverride } from './web-socket-override'\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","interface InternalConnectionContext {\n run<T>(callback: () => T): T\n consume(): boolean\n}\n\ndeclare global {\n var __MSW_INTERNAL_CONNECTION_CONTEXT: InternalConnectionContext | undefined\n}\n\n/**\n * Share the Node-provided async context with the browser-built WebSocket\n * entry point without importing Node modules into the browser bundle.\n */\nexport function runAsInternalConnection<T>(callback: () => T): T {\n const context = globalThis.__MSW_INTERNAL_CONNECTION_CONTEXT\n\n if (context) {\n return context.run(callback)\n }\n\n return callback()\n}\n","import { Interceptor } from '../../interceptor'\nimport {\n WebSocketConnectionEvent,\n type WebSocketEventMap,\n type WebSocketConnectionInfo,\n type WebSocketConnectionEventData,\n type WebSocketInterceptedConnection,\n} from '../../events/websocket'\nimport {\n WebSocketClientHandle,\n WebSocketClientConnection,\n type WebSocketClientEventMap,\n} from './web-socket-client-connection'\nimport {\n WebSocketServerHandle,\n WebSocketServerConnection,\n type WebSocketServerEventMap,\n} from './web-socket-server-connection'\nimport { WebSocketClassTransport } from './web-socket-class-transport'\nimport type { WebSocketData } from './web-socket-transport'\nimport {\n kClose,\n kPassthroughPromise,\n WebSocketOverride,\n} from './web-socket-override'\nimport { bindEvent } from './utils/bind-event'\nimport {\n kExtensionContext,\n iterateWebSocketExtensionResult,\n WebSocketExtension,\n type WebSocketExtensionMessage,\n type WebSocketExtensionApi,\n} from './web-socket-extension'\nimport { hasConfigurableGlobal } from '../../utils/has-configurable-global'\nimport { patchesRegistry } from '../../utils/patches-registry'\nimport { createLogger } from '../../utils/logger'\nimport { runAsInternalConnection } from '../../utils/internal-connection'\n\nexport {\n type WebSocketData,\n type WebSocketTransport,\n} from './web-socket-transport'\nexport {\n WebSocketEventMap,\n WebSocketConnectionEvent,\n WebSocketConnectionInfo,\n WebSocketConnectionEventData,\n WebSocketInterceptedConnection,\n WebSocketClientEventMap,\n WebSocketClientHandle,\n WebSocketClientConnection,\n WebSocketServerEventMap,\n WebSocketServerHandle,\n WebSocketServerConnection,\n}\n\nexport {\n CloseEvent,\n CancelableCloseEvent,\n CancelableMessageEvent,\n} from './utils/events'\n\nexport {\n WebSocketExtension,\n type WebSocketExtensionContext,\n type WebSocketExtensionMessageContext,\n type WebSocketExtensionResult,\n type WebSocketExtensionMessage,\n type WebSocketExtensionApi,\n} from './web-socket-extension'\n\ntype WebSocketExtensions = ReadonlyArray<WebSocketExtension<unknown, unknown>>\n\n/**\n * The messages crossing the connections intercepted with the given\n * extensions: the messages of the extension applied to a connection,\n * or raw WebSocket data when there are no extensions.\n *\n * @note The types assume one of the extensions matches the connection.\n */\nexport type WebSocketInterceptorMessage<\n Extensions extends WebSocketExtensions,\n> = [Extensions] extends [readonly []]\n ? WebSocketData\n : WebSocketExtensionMessage<Extensions[number]>\n\n/**\n * The API the extension applied to a connection adds to the connection event.\n */\nexport type WebSocketInterceptorApi<Extensions extends WebSocketExtensions> = [\n Extensions,\n] extends [readonly []]\n ? {}\n : WebSocketExtensionApi<Extensions[number]>\n\nexport interface WebSocketInterceptorOptions<\n Extensions extends WebSocketExtensions = [],\n> {\n /**\n * Extensions to apply to the intercepted connections.\n * The first extension whose `match()` accepts a connection is applied\n * to it. An extension without `match()` accepts every connection.\n */\n extensions?: Extensions\n}\n\nconst logger = createLogger('websocket')\n\n/**\n * Intercept the outgoing WebSocket connections created using\n * the global `WebSocket` class.\n */\nexport class WebSocketInterceptor<\n const Extensions extends WebSocketExtensions = [],\n> extends Interceptor<\n WebSocketEventMap<\n WebSocketInterceptorMessage<Extensions>,\n WebSocketInterceptorApi<Extensions>\n >\n> {\n static symbol = Symbol.for('websocket-interceptor')\n\n private readonly extensions: WebSocketExtensions\n\n constructor(options: WebSocketInterceptorOptions<Extensions> = {}) {\n super()\n this.extensions = options.extensions ?? []\n }\n\n protected predicate(): boolean {\n return hasConfigurableGlobal('WebSocket')\n }\n\n protected setup(): void {\n logger.verbose('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 logger.info('connection intercepted %o', {\n url: url.toString(),\n protocols,\n })\n\n const createConnection = (): WebSocket => {\n return runAsInternalConnection(() => {\n return Reflect.construct(target, args, newTarget)\n })\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 /**\n * @note The mocked connection plays the server endpoint of the\n * protocol unless a connection to the original server was\n * created, in which case the original server speaks for itself.\n * Check the creation, not the ready state: the original connection\n * may have already closed by now (e.g. when the client is kept open\n * past the original server closing), and the client must not be\n * handshaked twice.\n */\n const isServerEndpoint = () => server['realWebSocket'] == null\n\n /**\n * @note Register these before the client connection so the\n * protocol frames precede anything sent from its listeners.\n */\n socket.addEventListener(\n 'open',\n () => {\n if (!isServerEndpoint()) {\n return\n }\n\n for (const frame of iterateWebSocketExtensionResult(\n client.extension?.connect?.(context)\n )) {\n transport.send(frame)\n }\n },\n { once: true }\n )\n\n transport.addEventListener('outgoing', (event) => {\n if (!isServerEndpoint()) {\n return\n }\n\n for (const frame of iterateWebSocketExtensionResult(\n client.extension?.receive?.(event.data, context)\n )) {\n transport.send(frame)\n }\n })\n\n const client = new WebSocketClientConnection(socket, transport)\n const context: WebSocketInterceptedConnection = {\n client,\n server,\n info: {\n protocols,\n },\n }\n client[kExtensionContext] = context\n server[kExtensionContext] = context\n\n const extension = this.extensions.find((extension) => {\n return extension.match?.(context) ?? true\n })\n extension?.apply(context)\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 /**\n * @note Expose the extension's own API (e.g. rooms) on the\n * connection event. The event map is inferred from the extensions\n * this interceptor was given; `Object.assign` with a spread of\n * sources is untyped, which is what lets the event take that type.\n */\n const extensionApis: Array<unknown> = [extension?.extend?.(context)]\n\n await this.emitter.emitAsPromise(\n Object.assign(\n new WebSocketConnectionEvent({\n client,\n server,\n info: context.info,\n }),\n ...extensionApis\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.verbose('patching global WebSocket...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'WebSocket', () => WebSocketProxy)\n )\n\n logger.verbose('global WebSocket patched: %s', globalThis.WebSocket.name)\n }\n}\n"],"mappings":";;;;;;AAkDA,IAAa,2BAAb,cACU,WAMV;CAKE,YAAY,MAA+C;EACzD,MAAM,cAAc,EAAE,KAAK,CAAC;EAE5B,KAAK,SAAS,KAAK;EACnB,KAAK,SAAS,KAAK;EACnB,KAAK,OAAO,KAAK;CACnB;AACF;;;ACnEA,SAAgB,UACd,QACA,OACuB;CACvB,OAAO,iBAAiB,OAAO;EAC7B,QAAQ;GACN,OAAO;GACP,YAAY;GACZ,UAAU;EACZ;EACA,eAAe;GACb,OAAO;GACP,YAAY;GACZ,UAAU;EACZ;CACF,CAAC;CAED,OAAO;AACT;;;ACpBA,MAAM,cAAc,OAAO,aAAa;AACxC,MAAM,oBAAoB,OAAO,mBAAmB;;;;;;;;AASpD,IAAa,yBAAb,cAAqD,aAAgB;CAInE,YAAY,MAAc,MAA2B;EACnD,MAAM,MAAM,IAAI;EAChB,KAAK,eAAe,CAAC,CAAC,KAAK;EAC3B,KAAK,qBAAqB;CAC5B;CAEA,IAAI,aAAa;EACf,OAAO,KAAK;CACd;CAEA,IAAI,WAAW,gBAAgB;EAC7B,KAAK,eAAe;CACtB;CAEA,IAAI,mBAAmB;EACrB,OAAO,KAAK;CACd;CAEA,IAAI,iBAAiB,sBAAsB;EACzC,KAAK,qBAAqB;CAC5B;CAEA,iBAA8B;EAC5B,IAAI,KAAK,cAAc,CAAC,KAAK,oBAC3B,KAAK,qBAAqB;CAE9B;AACF;AAQA,IAAa,aAAb,cAAgC,MAAM;CAKpC,YAAY,MAAc,OAAuB,CAAC,GAAG;EACnD,MAAM,MAAM,IAAI;EAChB,KAAK,OAAO,KAAK,S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
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as FetchInterceptor } from "../../web-
|
|
1
|
+
import { t as FetchInterceptor } from "../../web-DAjikHQM.js";
|
|
2
2
|
export { FetchInterceptor };
|
|
@@ -192,21 +192,26 @@ var FetchInterceptor = class extends Interceptor {
|
|
|
192
192
|
passthrough: async () => {
|
|
193
193
|
logger.verbose("performing request as-is");
|
|
194
194
|
/**
|
|
195
|
-
* @note
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
* request
|
|
195
|
+
* @note Perform a clone of the request instance, not the instance itself.
|
|
196
|
+
* Performing a request consumes its body, and the "response" listener
|
|
197
|
+
* must still be able to read it. The clone is created right before
|
|
198
|
+
* the request is performed, so it preserves any modifications made
|
|
199
|
+
* to the intercepted request in the "request" listener.
|
|
200
|
+
*
|
|
201
|
+
* This also keeps the request instance emitted on the "response" event
|
|
202
|
+
* referentially equal to the one emitted on the "request" event
|
|
203
|
+
* so the consumer can associate the two by identity.
|
|
199
204
|
*/
|
|
200
|
-
const
|
|
201
|
-
const [responseError, originalResponse] = await until(() => realFetch(
|
|
205
|
+
const requestClone = request.clone();
|
|
206
|
+
const [responseError, originalResponse] = await until(() => realFetch(requestClone));
|
|
202
207
|
if (responseError) return responsePromise.reject(responseError);
|
|
203
208
|
logger.verbose("original fetch performed %o", originalResponse);
|
|
204
209
|
if (this.emitter.listenerCount("response") > 0) {
|
|
205
210
|
logger.verbose("emitting the \"response\" event");
|
|
206
211
|
const [response, responseClone] = cloneResponse(originalResponse);
|
|
207
212
|
await this.emitter.emitAsPromise(new HttpResponseEvent({
|
|
208
|
-
initiator:
|
|
209
|
-
request
|
|
213
|
+
initiator: request,
|
|
214
|
+
request,
|
|
210
215
|
requestId,
|
|
211
216
|
response: responseClone,
|
|
212
217
|
responseType: "original"
|
|
@@ -300,4 +305,4 @@ var FetchInterceptor = class extends Interceptor {
|
|
|
300
305
|
//#endregion
|
|
301
306
|
export { FetchInterceptor as t };
|
|
302
307
|
|
|
303
|
-
//# sourceMappingURL=web-
|
|
308
|
+
//# sourceMappingURL=web-DAjikHQM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"web-DAjikHQM.js","names":[],"sources":["../../src/interceptors/fetch/utils/create-network-error.ts","../../src/interceptors/fetch/utils/follow-redirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts","../../src/utils/clone-response.ts","../../src/interceptors/fetch/web.ts"],"sourcesContent":["export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './create-network-error'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n const finalResponse = await fetch(new Request(locationUrl, requestInit))\n Object.defineProperty(finalResponse, 'redirected', {\n value: true,\n configurable: true,\n })\n\n return finalResponse\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n","import { FetchResponse } from './fetch-utils'\nimport { copyRawHeaders } from '../interceptors/ClientRequest/utils/record-raw-headers'\n\n/** Clone for observers without letting their unread body block caller cancellation. */\nexport function cloneResponse(response: Response): [Response, Response] {\n const clone = FetchResponse.clone(response)\n\n if (!response.body || !clone.body) {\n return [response, clone]\n }\n\n const observer = wrapResponse(clone)\n const caller = wrapResponse(response, observer.cancel)\n\n return [caller.response, observer.response]\n}\n\nfunction wrapResponse(\n response: Response,\n onCancel?: (reason: unknown) => Promise<void>\n) {\n const body = response.body!\n const reader = body.getReader()\n const cancel = (reason: unknown) => {\n return body.locked ? reader.cancel(reason) : body.cancel(reason)\n }\n const stream = new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const { done, value } = await reader.read()\n\n if (done) {\n controller.close()\n reader.releaseLock()\n return\n }\n\n controller.enqueue(value)\n } catch (error) {\n controller.error(error)\n reader.releaseLock()\n }\n },\n async cancel(reason) {\n try {\n const cancellation = cancel(reason)\n\n if (onCancel) {\n // Caller cancellation owns both branches.\n await Promise.all([cancellation, onCancel(reason)])\n } else {\n // An observer must not wait for the caller to consume its branch:\n // Response delivery is still waiting for this listener to finish.\n void cancellation.catch(() => {})\n }\n } finally {\n reader.releaseLock()\n }\n },\n },\n { highWaterMark: 0 }\n )\n const wrappedResponse = new FetchResponse(stream, response)\n copyRawHeaders(response.headers, wrappedResponse.headers)\n Object.defineProperties(wrappedResponse, {\n type: { value: response.type },\n redirected: { value: response.redirected },\n })\n\n return { response: wrappedResponse, cancel }\n}\n","import { until } from '@open-draft/until'\nimport { HttpResponseEvent, type HttpRequestEventMap } from '../../events/http'\nimport { RequestController } from '../../request-controller'\nimport { handleRequest } from '../../utils/handle-request'\nimport { createRequestId } from '../../create-request-id'\nimport { createNetworkError } from './utils/create-network-error'\nimport { followFetchRedirect } from './utils/follow-redirect'\nimport { decompressResponse } from './utils/decompression'\nimport { cloneResponse } from '../../utils/clone-response'\nimport { hasConfigurableGlobal } from '../../utils/has-configurable-global'\nimport { FetchResponse } from '../../utils/fetch-utils'\nimport { isResponseError } from '../../utils/response-utils'\nimport { patchesRegistry } from '../../utils/patches-registry'\nimport { copyRawHeaders } from '../ClientRequest/utils/record-raw-headers'\nimport { Interceptor } from '../../interceptor'\nimport { createLogger } from '../../utils/logger'\n\nconst logger = createLogger('fetch')\n\n/**\n * Interceptor for `fetch` requests in the browser.\n */\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol.for('fetch-interceptor')\n\n protected predicate() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n logger.verbose('patching global fetch...')\n\n this.subscriptions.push(\n patchesRegistry.applyPatch(globalThis, 'fetch', (realFetch) => {\n return async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !URL.canParse(input)\n ? new URL(input, location.href)\n : input\n\n const request = new Request(resolvedInput, init)\n\n const responsePromise = Promise.withResolvers<Response>()\n\n const controller = new RequestController(\n request,\n {\n passthrough: async () => {\n logger.verbose('performing request as-is')\n\n /**\n * @note Perform a clone of the request instance, not the instance itself.\n * Performing a request consumes its body, and the \"response\" listener\n * must still be able to read it. The clone is created right before\n * the request is performed, so it preserves any modifications made\n * to the intercepted request in the \"request\" listener.\n *\n * This also keeps the request instance emitted on the \"response\" event\n * referentially equal to the one emitted on the \"request\" event\n * so the consumer can associate the two by identity.\n */\n const requestClone = request.clone()\n\n // Perform the intercepted request as-is.\n const [responseError, originalResponse] = await until(() =>\n realFetch(requestClone)\n )\n\n if (responseError) {\n return responsePromise.reject(responseError)\n }\n\n logger.verbose('original fetch performed %o', originalResponse)\n\n if (this.emitter.listenerCount('response') > 0) {\n logger.verbose('emitting the \"response\" event')\n\n const [response, responseClone] = cloneResponse(originalResponse)\n await this.emitter.emitAsPromise(\n new HttpResponseEvent({\n initiator: request,\n request,\n requestId,\n response: responseClone,\n responseType: 'original',\n })\n )\n\n responsePromise.resolve(response)\n return\n }\n\n // Resolve the response promise with the original response\n // since the `fetch()` return this internal promise.\n responsePromise.resolve(originalResponse)\n },\n respondWith: async (rawResponse) => {\n // Handle mocked `Response.error()` (i.e. request errors).\n if (isResponseError(rawResponse)) {\n logger.verbose('request errored %o', {\n response: rawResponse,\n })\n responsePromise.reject(createNetworkError(rawResponse))\n return\n }\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response = new FetchResponse(\n decompressedStream || rawResponse.body,\n {\n url: request.url,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: rawResponse.headers,\n }\n )\n\n copyRawHeaders(rawResponse.headers, response.headers)\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(\n createNetworkError('unexpected redirect')\n )\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n logger.verbose('emitting the \"response\" event')\n\n const [callerResponse, responseClone] = cloneResponse(response)\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await this.emitter.emitAsPromise(\n new HttpResponseEvent({\n initiator: request,\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: responseClone,\n responseType: 'mock',\n request,\n requestId,\n })\n )\n\n responsePromise.resolve(callerResponse)\n return\n }\n\n responsePromise.resolve(response)\n },\n errorWith: (reason) => {\n logger.verbose('request aborted %o', { reason })\n responsePromise.reject(reason)\n },\n },\n {\n logger,\n requestId,\n }\n )\n\n logger.verbose('awaiting request resolution')\n\n logger.verbose(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n /**\n * @note Give the consumer a chance to abort the request before\n * it is dispatched. Fetch queues the request processing as a\n * task, so a signal aborted synchronously after `fetch()` must\n * prevent the request from ever reaching the \"request\" listeners.\n * Without this, the first listener is invoked synchronously\n * within the `fetch()` call itself.\n */\n await Promise.resolve()\n\n await handleRequest({\n initiator: request,\n request,\n requestId,\n emitter: this.emitter,\n controller,\n logger,\n })\n\n return responsePromise.prom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