/** * A scriptable fake WebSocket for the connection tests. It records outbound * frames and lets tests drive `open` / `message` / `close` from either side. */ import type { Transport } from '$lib/protocol/connection'; export class FakeSocket implements Transport { onopen: ((ev?: unknown) => void) | null = null; onclose: ((ev?: unknown) => void) | null = null; onerror: ((ev?: unknown) => void) | null = null; onmessage: ((ev: { data: unknown }) => void) | null = null; // Real WebSocket readyState: 0 CONNECTING, 1 OPEN, 2 CLOSING, 3 CLOSED. readyState = 0; // CONNECTING readonly sent: string[] = []; closed = false; send(data: string): void { if (this.readyState !== 1) throw new Error('not open'); this.sent.push(data); } close(): void { if (this.closed) return; this.closed = true; this.readyState = 3; this.onclose?.(); } // test drivers -------------------------------------------------------- open(): void { this.readyState = 1; // OPEN this.onopen?.(); } /** Deliver a raw server frame. */ serverSend(obj: object | string): void { const data = typeof obj === 'string' ? obj : JSON.stringify(obj); this.onmessage?.({ data }); } /** The socket drops (server-side close). */ serverClose(): void { if (this.closed) return; this.closed = true; this.readyState = 3; this.onclose?.(); } lastJson(): Record | null { if (this.sent.length === 0) return null; return JSON.parse(this.sent[this.sent.length - 1]); } } /** Creates and tracks a sequence of fake sockets handed to a connection. */ export class SocketSequence { readonly sockets: FakeSocket[] = []; // Arrow field so `this` survives being passed as a bare transport factory. factory = (_url: string): Transport => { const socket = new FakeSocket(); this.sockets.push(socket); return socket; }; get current(): FakeSocket { return this.sockets[this.sockets.length - 1]; } }