kinetex - v1.0.0-rc.1
    Preparing search index...

    Class WSClient

    WebSocket client with reconnection, backoff, ping/pong, and buffering.

    Cross-runtime: Browser, Deno, Bun, Node.js, Cloudflare Workers, Vercel Edge.

    Architecture:

    • Manages WebSocket lifecycle: connect, reconnect on failure, graceful close
    • Exponential backoff with jitter for reconnection delays
    • Built-in ping/pong heartbeat with configurable intervals
    • Message buffering during disconnection with automatic drain on reconnect
    • Async iterator interface for receiving messages
    const ws = new WSClient({ url: "wss://example.com/socket" });

    // Send messages
    ws.send("hello");
    ws.send(JSON.stringify({ type: "ping" }));

    // Receive messages via async iterator
    for await (const msg of ws) {
    console.log("received:", msg);
    }

    // Or use callbacks
    ws.onMessage((msg) => console.log(msg));
    Index

    Constructors

    Accessors

    • get connected(): boolean

      True when the socket is in the OPEN state and ready for data.

      Returns boolean

    • get bufferedCount(): number

      Number of messages currently buffered in the outgoing queue.

      Returns number

    • get metrics(): WSMetrics

      Snapshot of lifetime metrics (bytes sent/received, reconnect count, uptime).

      Returns WSMetrics

    • get serverEndpoint(): string | null

      The server endpoint the client is currently (or was last) connected to. Populated after a successful handshake. Useful for verifying sticky-session routing in load-balanced deployments.

      Returns string | null

    Methods

    • Initiate the WebSocket connection. Resolves once the handshake completes. If already CONNECTING or RECONNECTING, queues the caller for resolution once OPEN is reached.

      Returns Promise<void>

      A promise that resolves when the socket is OPEN

    • Returns a Promise that resolves once the socket reaches OPEN. Safe to call while CONNECTING or RECONNECTING. Rejects with WSConnectTimeoutError if timeoutMs elapses (default 60s).

      Parameters

      • timeoutMs: number = 60_000

        Timeout in milliseconds. If 0, no timeout is applied and the promise will wait indefinitely until the socket opens or errors.

      Returns Promise<void>

      A promise that resolves when the socket is OPEN

    • Permanently close the connection. No reconnect will occur.

      Parameters

      • code: number = 1000
      • reason: string = "Client closed"

      Returns void

    • Destroy the client and clean up all resources. More aggressive than close() - clears all listeners and buffers.

      Returns void

    • Send a text message. Buffered when the socket is reconnecting or under backpressure.

      Parameters

      • data: string

        Text payload to send

      Returns void

    • Send a binary message. Buffered when the socket is reconnecting or under backpressure.

      Parameters

      • data: ArrayBuffer | Uint8Array<ArrayBufferLike>

        Binary payload (Uint8Array or ArrayBuffer)

      Returns void

    • Serialize and send a value as JSON text.

      Parameters

      • data: unknown

        Any JSON-serializable value

      Returns void

    • Send a message and await a correlated reply.

      Type Parameters

      • T = unknown

      Parameters

      • payload: unknown

        What to send (string → sent as-is; anything else → JSON-serialized).

      • replyMatcher: (msg: WSMessage) => boolean

        Predicate called for every incoming message until it returns true.

      • extract: (msg: WSMessage) => T = ...

        Transform the matching WSMessage into the return type. Default: msg.json ?? msg.data.

      • timeoutMs: number = 10_000

        How long to wait ms. Default: 10_000. 0 = no timeout.

      Returns Promise<T>

      A promise that resolves with the extracted reply value

    • Register a message listener.

      Parameters

      • fn: (msg: WSMessage) => void

        Callback invoked for every incoming message

      Returns () => void

      An eject function that removes this listener

    • Register a close listener.

      Parameters

      • fn: (evt: WSCloseEvent) => void

        Callback invoked with the close event (code + reason)

      Returns () => void

      An eject function that removes this listener

    • Return and clear the current outgoing message buffer.

      When reconnecting, any messages queued while disconnected are held in this buffer. On successful reconnect, buffered messages are automatically flushed to the new socket. Use this method to inspect or discard queued messages if needed.

      Returns (string | ArrayBuffer)[]

      Array of pending messages (strings or ArrayBuffers)

    • Subscribe to a room. Sends a room:join signal over the wire and tracks the subscription so it can be re-joined after a reconnect.

      Parameters

      • room: string

        Room name.

      • Optionalnamespace: string

        Optional namespace qualifier.

      Returns void

    • Unsubscribe from a room. Sends a room:leave signal.

      Parameters

      • room: string

        Room name to leave

      • Optionalnamespace: string

        Optional namespace qualifier

      Returns void

    • Returns a Promise that resolves when the outgoing buffer has drained below the low-water mark. Rejects immediately if already closed/aborted.

      Parameters

      • timeoutMs: number = 30_000

        Max ms to wait. 0 = no timeout. Default: 30_000.

      Returns Promise<void>

      A promise that resolves when the buffer is drained

    • Gracefully shut down: wait for the outgoing buffer to drain, then close the connection cleanly.

      Parameters

      • timeoutMs: number = 30_000

        Max ms to wait for drain before force-closing. Default: 30_000.

      Returns Promise<void>

      A promise that resolves after clean shutdown

    • Iterate over incoming messages. The iterator closes when the socket closes.

      Returns AsyncIterator<WSMessage>