Skip to content

@lunibee/ws

The @lunibee/ws package provides a low-level, high-performance WebSocket client engineered for Discord’s Gateway protocol.

Terminal window
bun add @lunibee/ws @lunibee/types

import { Gateway } from "@lunibee/ws";
import { IntentBits } from "@lunibee/types";
const gateway = new Gateway({
token: process.env.DISCORD_TOKEN!,
intents: [IntentBits.guilds, IntentBits.guildMessages],
shardId: 0,
shardCount: 1,
reconnect: true,
maxReconnectAttempts: 10,
});
gateway.on("open", () => console.log("WebSocket connection open."));
gateway.on("ready", (data) => console.log("Gateway ready:", (data as { user: { username: string } }).user.username));
// Every dispatch, with its event name: emitted as "RAW".
gateway.on("RAW", (raw) => console.log("Received event:", (raw as { event: string }).event));
// Or listen for one Discord event by name.
gateway.on("MESSAGE_CREATE", (message) => console.log((message as { content: string }).content));
await gateway.connect();
Option Type Default Description
token string Required Discord Bot Authentication Token.
intents GatewayIntentResolvable Required Array of intent bits or names, e.g. [IntentBits.guilds]. A single number or OR-ed bitfield throws.
shardId number 0 Zero-based shard ID.
shardCount number 1 Total number of shards.
reconnect boolean true Automatically reconnect on network drops.
maxReconnectAttempts number Infinity Maximum consecutive reconnection attempts.
connectTimeout number 30000 How long a socket may stay connecting before it is closed and retried.
reconnectBaseDelay number 1000 First reconnect delay, doubled per attempt.
reconnectMaxDelay number 30000 Ceiling for the reconnect backoff.
reconnectStormLimit number 5 Reconnects inside reconnectStormWindow after which unstable is emitted and the delay keeps doubling.
reconnectStormWindow number 60000 Span over which reconnects are counted for storm detection.
heartbeatAckTimeout number 10000 How long to wait for a heartbeat ACK before reconnecting.
zombieTimeout number 30000 Silence after which the connection is treated as dead. Must exceed heartbeatAckTimeout.
compress boolean false Enable zlib-stream transport compression.
properties GatewayProperties { os: process.platform, browser: "Lunibee", device: "Lunibee" } Identify properties (os, browser, device).
presence GatewayPresence online Initial presence sent with IDENTIFY.
createSocket SocketFactory global WebSocket Constructs the underlying socket (alternative transport or a test stub).

compress: true appends compress=zlib-stream to the Gateway URL and decodes frames with a persistent inflate stream, flushing on Discord’s Z_SYNC_FLUSH boundary (00 00 FF FF). Payloads split across several WebSocket frames are buffered until that boundary arrives, and frames are decoded strictly in arrival order.

const gateway = new Gateway({
token: process.env.DISCORD_TOKEN!,
intents: [IntentBits.guilds],
compress: true,
});

Gateway delegates session identity to a GatewaySession, which owns the session id, the last sequence number, the resume host, and the IDENTIFY-vs-RESUME decision. It is exported for inspection and testing:

import { GatewaySession } from "@lunibee/ws";
const session = new GatewaySession();
const token = session.beginConnection();
session.recordSequence(1, token);
session.activate({ session_id: "abc", resume_gateway_url: "wss://resume" }, token);
session.canResume; // true
session.handshake(); // { type: "resume", sessionId, sequence, resumeURL }

Each connection takes a generation token. Mutations must present it, so a socket the Gateway has replaced cannot advance the live session’s sequence or overwrite its session id — including a compressed frame that finishes decoding after the swap.

connect() is idempotent: calling it on an already-connected Gateway returns without opening a second socket, and it cancels any pending reconnect rather than racing it.

Reconnects that should resume close with 4900 (never 1000/1001), the heartbeat interval starts after the first jittered beat, and the sequence never moves backwards.