@depup/mswjs__interceptors 0.45.1-depup.0 → 0.45.3-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 CHANGED
@@ -13,10 +13,16 @@ 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.1 |
17
- | Processed | 2026-09-24 |
16
+ | Original | [@mswjs/interceptors](https://www.npmjs.com/package/@mswjs/interceptors) @ 0.45.3 |
17
+ | Processed | 2026-09-25 |
18
18
  | Smoke test | passed |
19
- | Deps updated | 0 |
19
+ | Deps updated | 1 |
20
+
21
+ ## Dependency Changes
22
+
23
+ | Dependency | From | To |
24
+ |------------|------|-----|
25
+ | rettime | ^0.11.11 | ^0.11.12 |
20
26
 
21
27
  ---
22
28
 
package/changes.json CHANGED
@@ -1,5 +1,10 @@
1
1
  {
2
- "bumped": {},
3
- "timestamp": "2026-09-24T16:10:45.805Z",
4
- "totalUpdated": 0
2
+ "bumped": {
3
+ "rettime": {
4
+ "from": "^0.11.11",
5
+ "to": "^0.11.12"
6
+ }
7
+ },
8
+ "timestamp": "2026-09-25T16:10:06.570Z",
9
+ "totalUpdated": 1
5
10
  }
@@ -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: WebSocketClientConnection<Message>;
25
+ client: WebSocketClientHandle<Message>;
18
26
  /**
19
27
  * The original WebSocket server connection.
20
28
  */
21
- server: WebSocketServerConnection<Message>;
29
+ server: WebSocketServerHandle<Message>;
22
30
  info: WebSocketConnectionInfo;
23
31
  }
24
- declare class WebSocketConnectionEvent<Message = WebSocketData> extends TypedEvent<WebSocketConnectionEventData<Message>, void, 'connection'> {
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: WebSocketConnectionEventData<Message>);
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: WebSocketClientConnection<Message>;
287
- server: WebSocketServerConnection<Message>;
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: WebSocketClientConnection<Message> | WebSocketServerConnection<Message>;
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: WebSocketClientConnection<Message>;
383
- server: WebSocketServerConnection<Message>;
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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AAO;KAExB,MAAM,yBACJ,KAAK,QAAQ,cAAc,YAAY,IAAI;;;;;;;KAW7C,MAAM,gBAAgC,CAAC,WAAW,SAAS,OAAO,CAAC;KAEnE,MAAM,KAAK,QAAQ,cACjB,OAAO,OACL,IAAI,yBAAyB;MAC3B;MACA;MACA,MAAM,QAAQ;KAChB,CAAC,GACD,GAAG,aACL,CACF;KAEA,IAAI,wBACF,OAAO,oBAAoB,CAAC,QAAQ,KAAK;UACpC;MACL,OAAO,oBAAoB,CAAC,QAAQ,IAAI;MAExC,OAAO,QAAQ;MAIf,OAAO,iBAAiB,cAAc;OACpC,OAAO,cAAc,UAAU,QAAQ,IAAI,MAAM,MAAM,CAAC,CAAC;OAIzD,IAAI,OAAO,kBACT,OAAO,WAAW,OAAO,gBAAgB,CAAC;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;E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AO,kBACT,OAAO,WAAW,OAAO,gBAAgB,CAAC;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,2 +1,2 @@
1
- import { t as FetchInterceptor } from "../../web-DUlFZEtz.js";
1
+ import { t as FetchInterceptor } from "../../web-DAjikHQM.js";
2
2
  export { FetchInterceptor };
@@ -1,4 +1,4 @@
1
- import { t as FetchInterceptor } from "../web-DUlFZEtz.js";
1
+ import { t as FetchInterceptor } from "../web-DAjikHQM.js";
2
2
  import { t as XMLHttpRequestInterceptor } from "../web-EzmPOkVl.js";
3
3
  //#region src/presets/browser.ts
4
4
  /**
@@ -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 Clone the request instance right before performing it.
196
- * This preserves any modifications made to the intercepted request
197
- * in the "request" listener. This also allows the user to read the
198
- * request body in the "response" listener (otherwise "unusable").
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 requestCloneForResponseEvent = request.clone();
201
- const [responseError, originalResponse] = await until(() => realFetch(request));
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: requestCloneForResponseEvent,
209
- request: requestCloneForResponseEvent,
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-DUlFZEtz.js.map
308
+ //# sourceMappingURL=web-DAjikHQM.js.map