walter-ws 1.0.0 → 1.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "walter-ws",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Ultra-fast zero-dependency RFC 6455 WebSocket Server & Client implementation in pure Node.js",
5
5
  "main": "./src/index.js",
6
6
  "module": "./src/index.mjs",
@@ -24,6 +24,7 @@
24
24
  ],
25
25
  "scripts": {
26
26
  "start": "node examples/server.js",
27
+ "live": "node examples/live-crypto.js",
27
28
  "test": "node --test test/walter-ws.test.js",
28
29
  "bench": "node benchmark/vs.js"
29
30
  },
package/src/client.js CHANGED
@@ -34,6 +34,11 @@ class WalterClient extends EventEmitter {
34
34
  * @param {string|string[]} [options.protocols] - Optional subprotocol(s)
35
35
  * @param {number} [options.maxPayload=1048576] - Max allowed incoming frame/message payload size in bytes
36
36
  * @param {number} [options.handshakeTimeout=10000] - Handshake timeout in ms
37
+ * @param {boolean} [options.autoReconnect=false] - Automatically reconnect on unexpected disconnect
38
+ * @param {number} [options.reconnectInterval=1000] - Initial reconnect delay in ms
39
+ * @param {number} [options.maxReconnectInterval=30000] - Maximum backoff delay in ms
40
+ * @param {number} [options.maxReconnectAttempts=Infinity] - Max reconnect attempts
41
+ * @param {boolean} [options.offlineQueue=false] - Queue outgoing messages while connecting/reconnecting
37
42
  */
38
43
  constructor(url, options = {}) {
39
44
  super();
@@ -48,6 +53,11 @@ class WalterClient extends EventEmitter {
48
53
  protocols: options.protocols || null,
49
54
  maxPayload: options.maxPayload ?? 1024 * 1024,
50
55
  handshakeTimeout: options.handshakeTimeout ?? 10000,
56
+ autoReconnect: options.autoReconnect ?? false,
57
+ reconnectInterval: options.reconnectInterval ?? 1000,
58
+ maxReconnectInterval: options.maxReconnectInterval ?? 30000,
59
+ maxReconnectAttempts: options.maxReconnectAttempts ?? Infinity,
60
+ offlineQueue: options.offlineQueue ?? false,
51
61
  };
52
62
 
53
63
  this.readyState = READY_STATES.CONNECTING;
@@ -55,6 +65,18 @@ class WalterClient extends EventEmitter {
55
65
  this._connection = null;
56
66
  this._req = null;
57
67
 
68
+ this._explicitClose = false;
69
+ this._reconnectAttempts = 0;
70
+ this._reconnectTimer = null;
71
+ /** @type {Array<{ data: any, options: any, callback: any }>} */
72
+ this._sendQueue = [];
73
+
74
+ // W3C callback properties
75
+ this.onopen = null;
76
+ this.onmessage = null;
77
+ this.onclose = null;
78
+ this.onerror = null;
79
+
58
80
  this._connect();
59
81
  }
60
82
 
@@ -103,8 +125,13 @@ class WalterClient extends EventEmitter {
103
125
  req.on('error', (err) => {
104
126
  if (this.readyState !== READY_STATES.CLOSED) {
105
127
  this.readyState = READY_STATES.CLOSED;
106
- this.emit('error', err);
107
- this.emit('close', CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
128
+ if (this.listenerCount('error') > 0) {
129
+ this.emit('error', err);
130
+ }
131
+ if (typeof this.onerror === 'function') {
132
+ this.onerror({ error: err, message: err.message, target: this });
133
+ }
134
+ this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
108
135
  }
109
136
  });
110
137
 
@@ -112,8 +139,13 @@ class WalterClient extends EventEmitter {
112
139
  const err = new Error(`Unexpected server response: ${res.statusCode}`);
113
140
  this.readyState = READY_STATES.CLOSED;
114
141
  res.resume();
115
- this.emit('error', err);
116
- this.emit('close', CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
142
+ if (this.listenerCount('error') > 0) {
143
+ this.emit('error', err);
144
+ }
145
+ if (typeof this.onerror === 'function') {
146
+ this.onerror({ error: err, message: err.message, target: this });
147
+ }
148
+ this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
117
149
  });
118
150
 
119
151
  req.on('upgrade', (res, socket, head) => {
@@ -124,8 +156,13 @@ class WalterClient extends EventEmitter {
124
156
  `Invalid Sec-WebSocket-Accept header: expected ${expectedAccept}, got ${acceptHeader}`
125
157
  );
126
158
  this.readyState = READY_STATES.CLOSED;
127
- this.emit('error', err);
128
- this.emit('close', CLOSE_CODES.PROTOCOL_ERROR, err.message);
159
+ if (this.listenerCount('error') > 0) {
160
+ this.emit('error', err);
161
+ }
162
+ if (typeof this.onerror === 'function') {
163
+ this.onerror({ error: err, message: err.message, target: this });
164
+ }
165
+ this._handleDisconnect(CLOSE_CODES.PROTOCOL_ERROR, err.message);
129
166
  return;
130
167
  }
131
168
 
@@ -135,10 +172,14 @@ class WalterClient extends EventEmitter {
135
172
  });
136
173
 
137
174
  this.readyState = READY_STATES.OPEN;
175
+ this._reconnectAttempts = 0;
138
176
  this.protocol = res.headers['sec-websocket-protocol'] || null;
139
177
 
140
178
  this._connection.on('message', (data, isBinary) => {
141
179
  this.emit('message', data, isBinary);
180
+ if (typeof this.onmessage === 'function') {
181
+ this.onmessage({ data, isBinary, target: this });
182
+ }
142
183
  });
143
184
 
144
185
  this._connection.on('ping', (data) => {
@@ -150,15 +191,25 @@ class WalterClient extends EventEmitter {
150
191
  });
151
192
 
152
193
  this._connection.on('error', (err) => {
153
- this.emit('error', err);
194
+ if (this.listenerCount('error') > 0) {
195
+ this.emit('error', err);
196
+ }
197
+ if (typeof this.onerror === 'function') {
198
+ this.onerror({ error: err, message: err.message, target: this });
199
+ }
154
200
  });
155
201
 
156
202
  this._connection.on('close', (code, reason) => {
157
203
  this.readyState = READY_STATES.CLOSED;
158
- this.emit('close', code, reason);
204
+ this._handleDisconnect(code, reason);
159
205
  });
160
206
 
161
207
  this.emit('open');
208
+ if (typeof this.onopen === 'function') {
209
+ this.onopen({ target: this });
210
+ }
211
+
212
+ this._flushOfflineQueue();
162
213
 
163
214
  if (head && head.length > 0) {
164
215
  this._connection._onSocketData(head);
@@ -168,14 +219,64 @@ class WalterClient extends EventEmitter {
168
219
  req.end();
169
220
  }
170
221
 
222
+ /**
223
+ * Handles disconnection and schedules automatic reconnect if enabled.
224
+ * @param {number} code
225
+ * @param {string} reason
226
+ */
227
+ _handleDisconnect(code, reason) {
228
+ this.emit('close', code, reason);
229
+ if (typeof this.onclose === 'function') {
230
+ this.onclose({ code, reason, target: this });
231
+ }
232
+
233
+ if (
234
+ this.options.autoReconnect &&
235
+ !this._explicitClose &&
236
+ this._reconnectAttempts < this.options.maxReconnectAttempts
237
+ ) {
238
+ const attempt = this._reconnectAttempts++;
239
+ const delay = Math.min(
240
+ this.options.reconnectInterval * Math.pow(1.5, attempt),
241
+ this.options.maxReconnectInterval
242
+ );
243
+ this.emit('reconnecting', attempt + 1, delay);
244
+ this._reconnectTimer = setTimeout(() => {
245
+ this.readyState = READY_STATES.CONNECTING;
246
+ this._connect();
247
+ }, delay);
248
+ this._reconnectTimer.unref?.();
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Flushes any messages queued while the client was connecting/reconnecting.
254
+ */
255
+ _flushOfflineQueue() {
256
+ if (this._sendQueue.length === 0) return;
257
+ const queue = this._sendQueue;
258
+ this._sendQueue = [];
259
+ for (const item of queue) {
260
+ if (this.readyState === READY_STATES.OPEN && this._connection) {
261
+ this._connection.send(item.data, item.options, item.callback);
262
+ }
263
+ }
264
+ }
265
+
171
266
  /**
172
267
  * Sends a text or binary message to the server.
268
+ * If `offlineQueue` is true and the connection is not yet OPEN, queues the message automatically.
269
+ *
173
270
  * @param {string|Buffer|Uint8Array} data
174
271
  * @param {object} [options]
175
272
  * @param {Function} [callback]
176
273
  */
177
274
  send(data, options, callback) {
178
275
  if (!this._connection || this.readyState !== READY_STATES.OPEN) {
276
+ if (this.options.offlineQueue && !this._explicitClose) {
277
+ this._sendQueue.push({ data, options, callback });
278
+ return;
279
+ }
179
280
  throw new Error(`WebSocket is not open: readyState ${this.readyState}`);
180
281
  }
181
282
  this._connection.send(data, options, callback);
@@ -187,10 +288,7 @@ class WalterClient extends EventEmitter {
187
288
  * @param {Function} [callback]
188
289
  */
189
290
  sendJSON(obj, callback) {
190
- if (!this._connection || this.readyState !== READY_STATES.OPEN) {
191
- throw new Error(`WebSocket is not open: readyState ${this.readyState}`);
192
- }
193
- this._connection.sendJSON(obj, callback);
291
+ this.send(JSON.stringify(obj), { binary: false }, callback);
194
292
  }
195
293
 
196
294
  /**
@@ -214,11 +312,17 @@ class WalterClient extends EventEmitter {
214
312
  }
215
313
 
216
314
  /**
217
- * Initiates a clean closing handshake.
315
+ * Initiates a clean closing handshake and stops any auto-reconnect timer.
218
316
  * @param {number} [code=1000]
219
317
  * @param {string} [reason='']
220
318
  */
221
319
  close(code = CLOSE_CODES.NORMAL_CLOSURE, reason = '') {
320
+ this._explicitClose = true;
321
+ if (this._reconnectTimer) {
322
+ clearTimeout(this._reconnectTimer);
323
+ this._reconnectTimer = null;
324
+ }
325
+
222
326
  if (this.readyState === READY_STATES.CLOSED || this.readyState === READY_STATES.CLOSING) {
223
327
  return;
224
328
  }
@@ -230,10 +334,53 @@ class WalterClient extends EventEmitter {
230
334
  }
231
335
  }
232
336
 
337
+ /**
338
+ * W3C EventTarget compatibility: addEventListener
339
+ * @param {string} type
340
+ * @param {Function} listener
341
+ * @param {object|boolean} [options]
342
+ */
343
+ addEventListener(type, listener, options) {
344
+ if (typeof listener !== 'function') return;
345
+ const once = typeof options === 'object' && options !== null && options.once;
346
+ const wrapped = (arg1, arg2) => {
347
+ if (type === 'message') {
348
+ listener({ data: arg1, isBinary: arg2, target: this });
349
+ } else if (type === 'close') {
350
+ listener({ code: arg1, reason: arg2, target: this });
351
+ } else if (type === 'error') {
352
+ listener({ error: arg1, message: arg1?.message, target: this });
353
+ } else {
354
+ listener({ target: this });
355
+ }
356
+ };
357
+ listener._walterWrapped = wrapped;
358
+ if (once) {
359
+ this.once(type, wrapped);
360
+ } else {
361
+ this.on(type, wrapped);
362
+ }
363
+ }
364
+
365
+ /**
366
+ * W3C EventTarget compatibility: removeEventListener
367
+ * @param {string} type
368
+ * @param {Function} listener
369
+ */
370
+ removeEventListener(type, listener) {
371
+ if (!listener) return;
372
+ this.removeListener(type, listener._walterWrapped || listener);
373
+ }
374
+
233
375
  /**
234
376
  * Immediately terminates the underlying socket connection.
235
377
  */
236
378
  terminate() {
379
+ this._explicitClose = true;
380
+ if (this._reconnectTimer) {
381
+ clearTimeout(this._reconnectTimer);
382
+ this._reconnectTimer = null;
383
+ }
237
384
  this.readyState = READY_STATES.CLOSED;
238
385
  if (this._connection) {
239
386
  this._connection.terminate();
package/src/connection.js CHANGED
@@ -79,6 +79,11 @@ class WalterConnection extends EventEmitter {
79
79
  this._fragmentsLength = 0;
80
80
  this._fragmentOpcode = null;
81
81
 
82
+ // Room membership (O(1) Set) and fast corked batch queue
83
+ this.rooms = new Set();
84
+ this._server = options.server || null;
85
+ this._corkScheduled = false;
86
+
82
87
  this._parser = new FrameParser({
83
88
  maxPayload: this.maxPayload,
84
89
  requireMask: this.isServer, // Server requires client frames to be masked; Client requires unmasked frames
@@ -87,6 +92,80 @@ class WalterConnection extends EventEmitter {
87
92
  this._bindSocketEvents();
88
93
  }
89
94
 
95
+ /**
96
+ * Joins a named room on the server in O(1) time.
97
+ * @param {string} roomName
98
+ * @returns {this}
99
+ */
100
+ join(roomName) {
101
+ if (this._server) {
102
+ this._server.joinRoom(roomName, this);
103
+ } else {
104
+ this.rooms.add(roomName);
105
+ }
106
+ return this;
107
+ }
108
+
109
+ /**
110
+ * Leaves a named room on the server in O(1) time.
111
+ * @param {string} roomName
112
+ * @returns {this}
113
+ */
114
+ leave(roomName) {
115
+ if (this._server) {
116
+ this._server.leaveRoom(roomName, this);
117
+ } else {
118
+ this.rooms.delete(roomName);
119
+ }
120
+ return this;
121
+ }
122
+
123
+ /**
124
+ * Leaves all joined rooms.
125
+ */
126
+ leaveAllRooms() {
127
+ if (this._server) {
128
+ for (const room of this.rooms) {
129
+ this._server.leaveRoom(room, this);
130
+ }
131
+ }
132
+ this.rooms.clear();
133
+ }
134
+
135
+ /**
136
+ * Schedules a socket uncork on next microtask after batching multiple writes in the same tick.
137
+ */
138
+ _writeCorked(buffer, callback) {
139
+ if (!this._corkScheduled) {
140
+ this._corkScheduled = true;
141
+ this.socket.cork();
142
+ queueMicrotask(() => {
143
+ this._corkScheduled = false;
144
+ if (!this.socket.destroyed) {
145
+ this.socket.uncork();
146
+ }
147
+ });
148
+ }
149
+ this.socket.write(buffer, callback);
150
+ }
151
+
152
+ /**
153
+ * Returns true if the underlying TCP send buffer is full (backpressure guard).
154
+ * @param {number} [highWaterMark=65536]
155
+ * @returns {boolean}
156
+ */
157
+ isBackpressured(highWaterMark = 65536) {
158
+ return this.socket.writableLength > highWaterMark;
159
+ }
160
+
161
+ /**
162
+ * Returns current bytes queued in user-space socket buffer.
163
+ * @returns {number}
164
+ */
165
+ get bufferedAmount() {
166
+ return this.socket ? this.socket.writableLength : 0;
167
+ }
168
+
90
169
  /**
91
170
  * Attaches data, error, and close listeners to the underlying TCP socket.
92
171
  */
@@ -113,6 +192,7 @@ class WalterConnection extends EventEmitter {
113
192
  this._fragments = [];
114
193
  this._fragmentsLength = 0;
115
194
  this._fragmentOpcode = null;
195
+ this.leaveAllRooms();
116
196
 
117
197
  if (this.readyState !== READY_STATES.CLOSED) {
118
198
  this.readyState = READY_STATES.CLOSED;
@@ -352,11 +432,30 @@ class WalterConnection extends EventEmitter {
352
432
  this.socket.write(frame[0]);
353
433
  this.socket.write(frame[1], callback);
354
434
  this.socket.uncork();
435
+ } else if (options.batch) {
436
+ this._writeCorked(frame, callback);
355
437
  } else {
356
438
  this.socket.write(frame, callback);
357
439
  }
358
440
  }
359
441
 
442
+ /**
443
+ * Sends a pre-encoded WebSocket frame buffer directly to the TCP socket with zero encoding overhead.
444
+ * @param {Buffer|Buffer[]} preEncodedFrame
445
+ * @param {Function} [callback]
446
+ */
447
+ sendFrame(preEncodedFrame, callback) {
448
+ if (this.readyState !== READY_STATES.OPEN) return;
449
+ if (Array.isArray(preEncodedFrame)) {
450
+ this.socket.cork();
451
+ this.socket.write(preEncodedFrame[0]);
452
+ this.socket.write(preEncodedFrame[1], callback);
453
+ this.socket.uncork();
454
+ } else {
455
+ this.socket.write(preEncodedFrame, callback);
456
+ }
457
+ }
458
+
360
459
  /**
361
460
  * Helper to serialize and send an object as JSON text.
362
461
  * @param {any} obj
@@ -455,6 +554,44 @@ class WalterConnection extends EventEmitter {
455
554
  this.socket.write(frame, callback);
456
555
  }
457
556
 
557
+ /**
558
+ * W3C EventTarget compatibility: addEventListener
559
+ * @param {string} type
560
+ * @param {Function} listener
561
+ * @param {object|boolean} [options]
562
+ */
563
+ addEventListener(type, listener, options) {
564
+ if (typeof listener !== 'function') return;
565
+ const once = typeof options === 'object' && options !== null && options.once;
566
+ const wrapped = (arg1, arg2) => {
567
+ if (type === 'message') {
568
+ listener({ data: arg1, isBinary: arg2, target: this });
569
+ } else if (type === 'close') {
570
+ listener({ code: arg1, reason: arg2, target: this });
571
+ } else if (type === 'error') {
572
+ listener({ error: arg1, message: arg1?.message, target: this });
573
+ } else {
574
+ listener({ target: this });
575
+ }
576
+ };
577
+ listener._walterWrapped = wrapped;
578
+ if (once) {
579
+ this.once(type, wrapped);
580
+ } else {
581
+ this.on(type, wrapped);
582
+ }
583
+ }
584
+
585
+ /**
586
+ * W3C EventTarget compatibility: removeEventListener
587
+ * @param {string} type
588
+ * @param {Function} listener
589
+ */
590
+ removeEventListener(type, listener) {
591
+ if (!listener) return;
592
+ this.removeListener(type, listener._walterWrapped || listener);
593
+ }
594
+
458
595
  /**
459
596
  * Immediately destroys the underlying TCP connection without a closing handshake.
460
597
  */
package/src/frame.js CHANGED
@@ -391,9 +391,38 @@ class FrameParser {
391
391
  }
392
392
  }
393
393
 
394
+ /**
395
+ * Pre-encodes a server-side (unmasked) WebSocket message into a reusable RFC 6455 frame Buffer.
396
+ * Ideal for high-frequency broadcasting or sending the same static/cached payload to thousands of clients.
397
+ *
398
+ * @param {string|Buffer|Uint8Array} data
399
+ * @param {object} [options]
400
+ * @param {boolean} [options.binary]
401
+ * @returns {Buffer}
402
+ */
403
+ function prepareMessage(data, options = {}) {
404
+ const isBinary =
405
+ options.binary ?? (Buffer.isBuffer(data) || ArrayBuffer.isView(data));
406
+ const opcode = isBinary ? OPCODES.BINARY : OPCODES.TEXT;
407
+ const payload = Buffer.isBuffer(data)
408
+ ? data
409
+ : ArrayBuffer.isView(data)
410
+ ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
411
+ : Buffer.from(String(data), 'utf8');
412
+
413
+ return encodeFrame({
414
+ opcode,
415
+ payload,
416
+ fin: true,
417
+ mask: false,
418
+ returnParts: false,
419
+ });
420
+ }
421
+
394
422
  module.exports = {
395
423
  WebSocketProtocolError,
396
424
  applyMask,
397
425
  encodeFrame,
426
+ prepareMessage,
398
427
  FrameParser,
399
428
  };
package/src/index.d.ts CHANGED
@@ -36,8 +36,11 @@ export const CLOSE_CODES: Readonly<{
36
36
 
37
37
  export interface SendOptions {
38
38
  binary?: boolean;
39
+ batch?: boolean;
39
40
  }
40
41
 
42
+ export function prepareMessage(data: string | Buffer | Uint8Array, options?: { binary?: boolean }): Buffer;
43
+
41
44
  export class WalterConnection extends EventEmitter {
42
45
  id: number;
43
46
  socket: net.Socket;
@@ -47,6 +50,8 @@ export class WalterConnection extends EventEmitter {
47
50
  readyState: 0 | 1 | 2 | 3;
48
51
  isAlive: boolean;
49
52
  protocol?: string | null;
53
+ rooms: Set<string>;
54
+ readonly bufferedAmount: number;
50
55
 
51
56
  constructor(
52
57
  socket: net.Socket,
@@ -57,12 +62,19 @@ export class WalterConnection extends EventEmitter {
57
62
  }
58
63
  );
59
64
 
65
+ join(roomName: string): this;
66
+ leave(roomName: string): this;
67
+ leaveAllRooms(): void;
68
+ isBackpressured(highWaterMark?: number): boolean;
60
69
  send(data: string | Buffer | Uint8Array, options?: SendOptions | ((err?: Error) => void), callback?: (err?: Error) => void): void;
70
+ sendFrame(preEncodedFrame: Buffer | Buffer[], callback?: (err?: Error) => void): void;
61
71
  sendJSON(obj: unknown, callback?: (err?: Error) => void): void;
62
72
  ping(data?: Buffer | string, callback?: (err?: Error) => void): void;
63
73
  pong(data?: Buffer | string, callback?: (err?: Error) => void): void;
64
74
  close(code?: number, reason?: string): void;
65
75
  terminate(): void;
76
+ addEventListener(type: string, listener: (event: any) => void, options?: { once?: boolean } | boolean): void;
77
+ removeEventListener(type: string, listener: (event: any) => void): void;
66
78
 
67
79
  on(event: 'message', listener: (data: string | Buffer, isBinary: boolean) => void): this;
68
80
  on(event: 'ping' | 'pong', listener: (data: Buffer) => void): this;
@@ -86,14 +98,31 @@ export interface WalterServerOptions {
86
98
  heartbeatInterval?: number;
87
99
  }
88
100
 
101
+ export interface BroadcastOptions {
102
+ except?: WalterConnection;
103
+ binary?: boolean;
104
+ maxBackpressure?: number;
105
+ }
106
+
89
107
  export class WalterServer extends EventEmitter {
90
108
  clients: Set<WalterConnection>;
109
+ rooms: Map<string, Set<WalterConnection>>;
91
110
  options: WalterServerOptions;
92
111
 
93
112
  constructor(options: WalterServerOptions);
94
113
  address(): net.AddressInfo | string | null;
95
114
  handleUpgrade(req: http.IncomingMessage, socket: net.Socket, head: Buffer): Promise<void>;
96
- broadcast(data: string | Buffer | Uint8Array, options?: { except?: WalterConnection; binary?: boolean }): void;
115
+ joinRoom(roomName: string, ws: WalterConnection): void;
116
+ leaveRoom(roomName: string, ws: WalterConnection): void;
117
+ prepareMessage(data: string | Buffer | Uint8Array, options?: { binary?: boolean }): Buffer;
118
+ to(roomName: string): {
119
+ broadcast: (data: string | Buffer | Uint8Array, options?: BroadcastOptions) => void;
120
+ broadcastJSON: (obj: unknown, options?: BroadcastOptions) => void;
121
+ size: () => number;
122
+ };
123
+ broadcastToRoom(roomName: string, data: string | Buffer | Uint8Array, options?: BroadcastOptions): void;
124
+ broadcast(data: string | Buffer | Uint8Array, options?: BroadcastOptions): void;
125
+ broadcastJSON(obj: unknown, options?: BroadcastOptions): void;
97
126
  close(callback?: (err?: Error) => void): void;
98
127
 
99
128
  on(event: 'connection', listener: (ws: WalterConnection, req: http.IncomingMessage) => void): this;
@@ -106,6 +135,11 @@ export interface WalterClientOptions {
106
135
  protocols?: string | string[];
107
136
  maxPayload?: number;
108
137
  handshakeTimeout?: number;
138
+ autoReconnect?: boolean;
139
+ reconnectInterval?: number;
140
+ maxReconnectInterval?: number;
141
+ maxReconnectAttempts?: number;
142
+ offlineQueue?: boolean;
109
143
  }
110
144
 
111
145
  export class WalterClient extends EventEmitter {
@@ -115,6 +149,7 @@ export class WalterClient extends EventEmitter {
115
149
  static WalterServer: typeof WalterServer;
116
150
  static WalterClient: typeof WalterClient;
117
151
  static WalterConnection: typeof WalterConnection;
152
+ static prepareMessage: typeof prepareMessage;
118
153
  static CONNECTING: 0;
119
154
  static OPEN: 1;
120
155
  static CLOSING: 2;
@@ -123,6 +158,10 @@ export class WalterClient extends EventEmitter {
123
158
  url: URL;
124
159
  readyState: 0 | 1 | 2 | 3;
125
160
  protocol: string | null;
161
+ onopen: ((event: { target: WalterClient }) => void) | null;
162
+ onmessage: ((event: { data: string | Buffer; isBinary: boolean; target: WalterClient }) => void) | null;
163
+ onclose: ((event: { code: number; reason: string; target: WalterClient }) => void) | null;
164
+ onerror: ((event: { error: Error; message: string; target: WalterClient }) => void) | null;
126
165
 
127
166
  constructor(url: string | URL, options?: WalterClientOptions);
128
167
  send(data: string | Buffer | Uint8Array, options?: SendOptions | ((err?: Error) => void), callback?: (err?: Error) => void): void;
@@ -131,6 +170,8 @@ export class WalterClient extends EventEmitter {
131
170
  pong(data?: Buffer | string, callback?: (err?: Error) => void): void;
132
171
  close(code?: number, reason?: string): void;
133
172
  terminate(): void;
173
+ addEventListener(type: string, listener: (event: any) => void, options?: { once?: boolean } | boolean): void;
174
+ removeEventListener(type: string, listener: (event: any) => void): void;
134
175
 
135
176
  on(event: 'open', listener: () => void): this;
136
177
  on(event: 'message', listener: (data: string | Buffer, isBinary: boolean) => void): this;
package/src/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  const { WalterServer, computeAcceptKey, isValidSecWebSocketKey } = require('./server');
4
4
  const { WalterClient } = require('./client');
5
5
  const { WalterConnection } = require('./connection');
6
- const { FrameParser, encodeFrame, applyMask, WebSocketProtocolError } = require('./frame');
6
+ const { FrameParser, encodeFrame, prepareMessage, applyMask, WebSocketProtocolError } = require('./frame');
7
7
  const { GUID, READY_STATES, OPCODES, CLOSE_CODES, isValidCloseCode } = require('./constants');
8
8
 
9
9
  // Drop-in compatibility with standard `ws` package (`const WebSocket = require('walter-ws')`)
@@ -15,6 +15,7 @@ WalterClient.WalterClient = WalterClient;
15
15
  WalterClient.WalterConnection = WalterConnection;
16
16
  WalterClient.FrameParser = FrameParser;
17
17
  WalterClient.encodeFrame = encodeFrame;
18
+ WalterClient.prepareMessage = prepareMessage;
18
19
  WalterClient.applyMask = applyMask;
19
20
  WalterClient.computeAcceptKey = computeAcceptKey;
20
21
  WalterClient.isValidSecWebSocketKey = isValidSecWebSocketKey;
package/src/index.mjs CHANGED
@@ -9,6 +9,7 @@ export const {
9
9
  WebSocketServer,
10
10
  FrameParser,
11
11
  encodeFrame,
12
+ prepareMessage,
12
13
  applyMask,
13
14
  computeAcceptKey,
14
15
  isValidSecWebSocketKey,
package/src/server.js CHANGED
@@ -5,6 +5,7 @@ const crypto = require('node:crypto');
5
5
  const { EventEmitter } = require('node:events');
6
6
  const { GUID, READY_STATES } = require('./constants');
7
7
  const { WalterConnection } = require('./connection');
8
+ const { prepareMessage } = require('./frame');
8
9
 
9
10
  /**
10
11
  * Computes the RFC 6455 Sec-WebSocket-Accept header value from Sec-WebSocket-Key.
@@ -67,6 +68,8 @@ class WalterServer extends EventEmitter {
67
68
 
68
69
  /** @type {Set<WalterConnection>} */
69
70
  this.clients = new Set();
71
+ /** @type {Map<string, Set<WalterConnection>>} */
72
+ this.rooms = new Map();
70
73
  this._ownsHttpServer = false;
71
74
  this._heartbeatTimer = null;
72
75
 
@@ -217,6 +220,7 @@ class WalterServer extends EventEmitter {
217
220
  isServer: true,
218
221
  maxPayload: this.options.maxPayload,
219
222
  request: req,
223
+ server: this,
220
224
  });
221
225
  ws.protocol = selectedProtocol;
222
226
 
@@ -234,40 +238,128 @@ class WalterServer extends EventEmitter {
234
238
  }
235
239
 
236
240
  /**
237
- * Broadcasts a message to all currently OPEN clients.
241
+ * Adds a client connection to a named room in O(1) time.
242
+ * @param {string} roomName
243
+ * @param {WalterConnection} ws
244
+ */
245
+ joinRoom(roomName, ws) {
246
+ let roomSet = this.rooms.get(roomName);
247
+ if (!roomSet) {
248
+ roomSet = new Set();
249
+ this.rooms.set(roomName, roomSet);
250
+ }
251
+ roomSet.add(ws);
252
+ ws.rooms.add(roomName);
253
+ }
254
+
255
+ /**
256
+ * Removes a client connection from a named room in O(1) time.
257
+ * @param {string} roomName
258
+ * @param {WalterConnection} ws
259
+ */
260
+ leaveRoom(roomName, ws) {
261
+ const roomSet = this.rooms.get(roomName);
262
+ if (roomSet) {
263
+ roomSet.delete(ws);
264
+ if (roomSet.size === 0) {
265
+ this.rooms.delete(roomName);
266
+ }
267
+ }
268
+ ws.rooms.delete(roomName);
269
+ }
270
+
271
+ /**
272
+ * Pre-encodes a message once into an RFC 6455 frame Buffer for repeated zero-overhead sending.
273
+ * @param {string|Buffer|Uint8Array} data
274
+ * @param {object} [options]
275
+ * @returns {Buffer}
276
+ */
277
+ prepareMessage(data, options) {
278
+ return prepareMessage(data, options);
279
+ }
280
+
281
+ /**
282
+ * Targets a specific room for ultra-fast pre-encoded broadcasting.
283
+ * Example: `wss.to('vip').broadcast('Hello VIPs!', { except: sender })`
238
284
  *
239
- * @param {string|Buffer} data
285
+ * @param {string} roomName
286
+ */
287
+ to(roomName) {
288
+ return {
289
+ broadcast: (data, options = {}) => {
290
+ this.broadcastToRoom(roomName, data, options);
291
+ },
292
+ broadcastJSON: (obj, options = {}) => {
293
+ this.broadcastToRoom(roomName, JSON.stringify(obj), { ...options, binary: false });
294
+ },
295
+ size: () => {
296
+ const roomSet = this.rooms.get(roomName);
297
+ return roomSet ? roomSet.size : 0;
298
+ },
299
+ };
300
+ }
301
+
302
+ /**
303
+ * Pre-encodes a message once and broadcasts it only to members of `roomName`.
304
+ * If `options.maxBackpressure` is set, slow clients exceeding that buffer size are skipped.
305
+ *
306
+ * @param {string} roomName
307
+ * @param {string|Buffer|Uint8Array} data
308
+ * @param {object} [options]
309
+ * @param {WalterConnection} [options.except]
310
+ * @param {boolean} [options.binary]
311
+ * @param {number} [options.maxBackpressure=0]
312
+ */
313
+ broadcastToRoom(roomName, data, options = {}) {
314
+ const roomSet = this.rooms.get(roomName);
315
+ if (!roomSet || roomSet.size === 0) return;
316
+
317
+ const { except = null, binary, maxBackpressure = 0 } = options;
318
+ const preEncodedFrame = prepareMessage(data, { binary });
319
+
320
+ for (const client of roomSet) {
321
+ if (client !== except && client.readyState === READY_STATES.OPEN) {
322
+ if (maxBackpressure > 0 && client.socket.writableLength > maxBackpressure) {
323
+ continue;
324
+ }
325
+ client.socket.write(preEncodedFrame);
326
+ }
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Broadcasts a message to all currently OPEN clients using a single pre-encoded frame.
332
+ *
333
+ * @param {string|Buffer|Uint8Array} data
240
334
  * @param {object} [options]
241
335
  * @param {WalterConnection} [options.except] - Optional connection to exclude (e.g., sender)
242
336
  * @param {boolean} [options.binary]
337
+ * @param {number} [options.maxBackpressure=0] - Optional max writableLength before skipping slow client
243
338
  */
244
339
  broadcast(data, options = {}) {
245
- const { except = null, binary } = options;
246
- const isBinary =
247
- binary ?? (Buffer.isBuffer(data) || ArrayBuffer.isView(data));
248
- const opcode = isBinary ? 0x2 : 0x1;
249
- const payload = Buffer.isBuffer(data)
250
- ? data
251
- : ArrayBuffer.isView(data)
252
- ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
253
- : Buffer.from(String(data), 'utf8');
254
-
255
- const { encodeFrame } = require('./frame');
256
- // Pre-encode once and write the exact same frame buffer to all clients!
257
- const preEncodedFrame = encodeFrame({
258
- opcode,
259
- payload,
260
- fin: true,
261
- mask: false,
262
- });
340
+ if (this.clients.size === 0) return;
341
+ const { except = null, binary, maxBackpressure = 0 } = options;
342
+ const preEncodedFrame = prepareMessage(data, { binary });
263
343
 
264
344
  for (const client of this.clients) {
265
345
  if (client !== except && client.readyState === READY_STATES.OPEN) {
346
+ if (maxBackpressure > 0 && client.socket.writableLength > maxBackpressure) {
347
+ continue;
348
+ }
266
349
  client.socket.write(preEncodedFrame);
267
350
  }
268
351
  }
269
352
  }
270
353
 
354
+ /**
355
+ * Serializes an object to JSON once, encodes it into a single frame, and broadcasts to all clients.
356
+ * @param {any} obj
357
+ * @param {object} [options]
358
+ */
359
+ broadcastJSON(obj, options = {}) {
360
+ this.broadcast(JSON.stringify(obj), { ...options, binary: false });
361
+ }
362
+
271
363
  /**
272
364
  * Starts automatic ping/pong heartbeat check across all connected clients.
273
365
  * @param {number} intervalMs