walter-ws 1.2.0 → 1.3.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.2.0",
3
+ "version": "1.3.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",
package/src/client.js CHANGED
@@ -6,6 +6,10 @@ const { EventEmitter } = require('node:events');
6
6
  const { READY_STATES, CLOSE_CODES } = require('./constants');
7
7
  const { WalterConnection } = require('./connection');
8
8
  const { CLIENT_KEY_POOL, ACCEPT_CACHE } = require('./server');
9
+ const { prepareClientFrame } = require('./frame');
10
+
11
+ // Global TLS 1.3 / 1.2 session ticket cache keyed by "hostname:port" for 1-RTT / 0-RTT reconnects
12
+ const TLS_SESSION_CACHE = new Map();
9
13
 
10
14
  let keyPoolIdx = 0;
11
15
 
@@ -66,8 +70,12 @@ class WalterClient extends EventEmitter {
66
70
  this.options = {
67
71
  headers: options.headers || null,
68
72
  protocols: options.protocols || null,
69
- maxPayload: options.maxPayload ?? 1024 * 1024,
73
+ maxPayload: options.maxPayload ?? 16 * 1024 * 1024,
70
74
  handshakeTimeout: options.handshakeTimeout ?? 10000,
75
+ skipUTF8Validation: options.skipUTF8Validation ?? false,
76
+ rawBuffer: options.rawBuffer ?? false,
77
+ tlsOptions: options.tlsOptions || null,
78
+ sessionReuse: options.sessionReuse ?? true,
71
79
  autoReconnect: options.autoReconnect ?? false,
72
80
  reconnectInterval: options.reconnectInterval ?? 1000,
73
81
  maxReconnectInterval: options.maxReconnectInterval ?? 30000,
@@ -131,17 +139,29 @@ class WalterClient extends EventEmitter {
131
139
 
132
140
  reqLines += '\r\n';
133
141
 
142
+ const sessionKey = `${this._hostname}:${this._port}`;
143
+ const cachedSession =
144
+ isSecure && this.options.sessionReuse ? TLS_SESSION_CACHE.get(sessionKey) : undefined;
145
+
134
146
  const socket = isSecure
135
147
  ? tls.connect({
136
- host: this._hostname,
137
- port: this._port,
138
- servername: this._hostname,
148
+ host: this.options.tlsOptions?.host || this._hostname,
149
+ port: this.options.tlsOptions?.port || this._port,
150
+ servername: this.options.tlsOptions?.servername || this._hostname,
151
+ ...(cachedSession ? { session: cachedSession } : {}),
152
+ ...(this.options.tlsOptions || {}),
139
153
  })
140
154
  : net.connect({
141
155
  host: this._hostname,
142
156
  port: this._port,
143
157
  });
144
158
 
159
+ if (isSecure && this.options.sessionReuse) {
160
+ socket.on('session', (session) => {
161
+ TLS_SESSION_CACHE.set(sessionKey, session);
162
+ });
163
+ }
164
+
145
165
  socket.setNoDelay(true);
146
166
  this._req = socket;
147
167
 
@@ -242,7 +262,11 @@ class WalterClient extends EventEmitter {
242
262
  this._connection = new WalterConnection(socket, {
243
263
  isServer: false,
244
264
  maxPayload: this.options.maxPayload,
265
+ skipUTF8Validation: this.options.skipUTF8Validation,
266
+ rawBuffer: this.options.rawBuffer,
245
267
  });
268
+ this._socket = socket;
269
+ this.socket = socket;
246
270
 
247
271
  this.readyState = READY_STATES.OPEN;
248
272
  this._reconnectAttempts = 0;
@@ -331,7 +355,11 @@ class WalterClient extends EventEmitter {
331
355
  this._sendQueue = [];
332
356
  for (const item of queue) {
333
357
  if (this.readyState === READY_STATES.OPEN && this._connection) {
334
- this._connection.send(item.data, item.options, item.callback);
358
+ if (item.frame) {
359
+ this._connection.socket.write(item.frame, item.callback);
360
+ } else {
361
+ this._connection.send(item.data, item.options, item.callback);
362
+ }
335
363
  }
336
364
  }
337
365
  }
@@ -355,6 +383,32 @@ class WalterClient extends EventEmitter {
355
383
  this._connection.send(data, options, callback);
356
384
  }
357
385
 
386
+ /**
387
+ * Sends a pre-compiled client frame Buffer directly to the socket with 0 CPU / 0 masking overhead.
388
+ * @param {Buffer} preMaskedFrame
389
+ * @param {Function} [callback]
390
+ */
391
+ sendFrame(preMaskedFrame, callback) {
392
+ if (!this._connection || this.readyState !== READY_STATES.OPEN) {
393
+ if (this.options.offlineQueue && !this._explicitClose) {
394
+ this._sendQueue.push({ frame: preMaskedFrame, callback });
395
+ return;
396
+ }
397
+ throw new Error(`WebSocket is not open: readyState ${this.readyState}`);
398
+ }
399
+ this._connection.socket.write(preMaskedFrame, callback);
400
+ }
401
+
402
+ /**
403
+ * Pre-encodes and pre-masks a static client message into a reusable Buffer.
404
+ * @param {string|Buffer|Uint8Array} data
405
+ * @param {object} [options]
406
+ * @returns {Buffer}
407
+ */
408
+ prepareFrame(data, options) {
409
+ return prepareClientFrame(data, options);
410
+ }
411
+
358
412
  /**
359
413
  * Sends an object serialized as JSON text.
360
414
  * @param {any} obj
package/src/connection.js CHANGED
@@ -65,6 +65,8 @@ class WalterConnection extends EventEmitter {
65
65
  this.socket = socket;
66
66
  this.isServer = options.isServer ?? true;
67
67
  this.maxPayload = options.maxPayload ?? 1024 * 1024;
68
+ this.skipUTF8Validation = options.skipUTF8Validation ?? false;
69
+ this.rawBuffer = options.rawBuffer ?? false;
68
70
  this.request = options.request || null;
69
71
  this.readyState = READY_STATES.OPEN;
70
72
  this.isAlive = true;
@@ -336,7 +338,13 @@ class WalterConnection extends EventEmitter {
336
338
  */
337
339
  _deliverDataMessage(opcode, payload) {
338
340
  if (opcode === OPCODES.TEXT) {
339
- const text = decodeUTF8Strict(payload);
341
+ if (this.rawBuffer) {
342
+ this.emit('message', payload, false);
343
+ return;
344
+ }
345
+ const text = this.skipUTF8Validation
346
+ ? payload.toString('utf8')
347
+ : decodeUTF8Strict(payload);
340
348
  this.emit('message', text, false);
341
349
  } else if (opcode === OPCODES.BINARY) {
342
350
  this.emit('message', payload, true);
package/src/frame.js CHANGED
@@ -21,6 +21,25 @@ function fillRandomMask(targetBuffer, targetOffset) {
21
21
  maskPoolOffset += 4;
22
22
  }
23
23
 
24
+ // Zero-GC 256KB Ring Buffer Pool for small frames (<= 256B) to eliminate V8 Garbage Collection pauses
25
+ const RING_POOL_SIZE = 256 * 1024;
26
+ const ringPool = Buffer.allocUnsafeSlow(RING_POOL_SIZE);
27
+ let ringOffset = 0;
28
+
29
+ function allocRingBuffer(size) {
30
+ if (size <= 256) {
31
+ // Keep 4-byte alignment for fast 32-bit Uint32Array operations
32
+ const alignedOffset = (ringOffset + 3) & ~3;
33
+ if (alignedOffset + size <= RING_POOL_SIZE) {
34
+ ringOffset = alignedOffset + size;
35
+ return ringPool.subarray(alignedOffset, ringOffset);
36
+ }
37
+ ringOffset = size;
38
+ return ringPool.subarray(0, size);
39
+ }
40
+ return Buffer.allocUnsafe(size);
41
+ }
42
+
24
43
  /**
25
44
  * Custom Error class for WebSocket protocol errors with corresponding close code.
26
45
  */
@@ -204,7 +223,7 @@ function encodeFrame(options) {
204
223
 
205
224
  const maskKeyLength = mask ? 4 : 0;
206
225
  const totalLen = headerLength + maskKeyLength + payloadLength;
207
- const frame = Buffer.allocUnsafe(totalLen);
226
+ const frame = options.usePool === false ? Buffer.allocUnsafe(totalLen) : allocRingBuffer(totalLen);
208
227
 
209
228
  // Byte 0: FIN (bit 7), RSV1-3 (bits 6-4 = 0), Opcode (bits 3-0)
210
229
  frame[0] = (fin ? 0x80 : 0x00) | (opcode & 0x0f);
@@ -454,13 +473,107 @@ function prepareMessage(data, options = {}) {
454
473
  fin: true,
455
474
  mask: false,
456
475
  returnParts: false,
476
+ usePool: false,
457
477
  });
458
478
  }
459
479
 
480
+ /**
481
+ * Pre-encodes and pre-masks a client-side (masked) WebSocket message into a dedicated reusable Buffer.
482
+ * Ideal for static client packets like IDENTIFY, HEARTBEAT (`{"op":1,"d":null}`), or SUBSCRIBE frames,
483
+ * allowing `ws.sendFrame(preMasked)` to write directly to the socket with 0 CPU, 0 allocation, and 0 XOR.
484
+ *
485
+ * @param {string|Buffer|Uint8Array} data
486
+ * @param {object} [options]
487
+ * @param {boolean} [options.binary]
488
+ * @returns {Buffer}
489
+ */
490
+ function prepareClientFrame(data, options = {}) {
491
+ const isBinary =
492
+ options.binary ?? (Buffer.isBuffer(data) || ArrayBuffer.isView(data));
493
+ const opcode = isBinary ? OPCODES.BINARY : OPCODES.TEXT;
494
+ const payload =
495
+ typeof data === 'string' || Buffer.isBuffer(data)
496
+ ? data
497
+ : ArrayBuffer.isView(data)
498
+ ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
499
+ : String(data);
500
+
501
+ return encodeFrame({
502
+ opcode,
503
+ payload,
504
+ fin: true,
505
+ mask: true,
506
+ returnParts: false,
507
+ usePool: false,
508
+ });
509
+ }
510
+
511
+ /**
512
+ * Ultra-fast zero-parse JSON string field extractor directly on a raw Buffer.
513
+ * Avoids `JSON.parse()` on massive payloads (e.g., 20KB GUILD_UPDATE) when only 1-2 fields are needed.
514
+ *
515
+ * Example:
516
+ * const idPrefix = Buffer.from('"id":"');
517
+ * const id = extractString(rawBuf, idPrefix);
518
+ *
519
+ * @param {Buffer} buf - Raw UTF-8 message Buffer
520
+ * @param {Buffer|string} prefix - Exact prefix before the string value (e.g., `"id":"` or `"vanity_url_code":"`)
521
+ * @param {number} [startOffset=0] - Optional byte offset to start searching from
522
+ * @returns {string|null}
523
+ */
524
+ function extractString(buf, prefix, startOffset = 0) {
525
+ const idx = buf.indexOf(prefix, startOffset);
526
+ if (idx === -1) return null;
527
+ const prefixLen = Buffer.isBuffer(prefix) ? prefix.length : Buffer.byteLength(prefix);
528
+ const valStart = idx + prefixLen;
529
+ const quoteEnd = buf.indexOf(0x22, valStart); // 0x22 = '"'
530
+ if (quoteEnd === -1) return null;
531
+ return buf.toString('utf8', valStart, quoteEnd);
532
+ }
533
+
534
+ /**
535
+ * Ultra-fast zero-parse JSON integer/float field extractor directly on a raw Buffer.
536
+ *
537
+ * Example:
538
+ * const interval = extractNumber(rawBuf, '"heartbeat_interval":');
539
+ *
540
+ * @param {Buffer} buf - Raw UTF-8 message Buffer
541
+ * @param {Buffer|string} prefix - Exact prefix before the numeric value (e.g., `"heartbeat_interval":`)
542
+ * @param {number} [startOffset=0] - Optional byte offset to start searching from
543
+ * @returns {number|null}
544
+ */
545
+ function extractNumber(buf, prefix, startOffset = 0) {
546
+ const idx = buf.indexOf(prefix, startOffset);
547
+ if (idx === -1) return null;
548
+ const prefixLen = Buffer.isBuffer(prefix) ? prefix.length : Buffer.byteLength(prefix);
549
+ let i = idx + prefixLen;
550
+ const len = buf.length;
551
+
552
+ // Skip optional whitespace
553
+ while (i < len && (buf[i] === 0x20 || buf[i] === 0x09)) i++;
554
+
555
+ let num = 0;
556
+ let hasDigits = false;
557
+ while (i < len) {
558
+ const c = buf[i];
559
+ if (c >= 0x30 && c <= 0x39) {
560
+ num = num * 10 + (c - 0x30);
561
+ hasDigits = true;
562
+ i++;
563
+ } else {
564
+ break;
565
+ }
566
+ }
567
+ return hasDigits ? num : null;
568
+ }
569
+
460
570
  module.exports = {
461
571
  WebSocketProtocolError,
462
572
  applyMask,
463
573
  encodeFrame,
464
574
  prepareMessage,
575
+ prepareClientFrame,
576
+ extractString,
577
+ extractNumber,
465
578
  FrameParser,
466
579
  };
package/src/index.d.ts CHANGED
@@ -40,6 +40,9 @@ export interface SendOptions {
40
40
  }
41
41
 
42
42
  export function prepareMessage(data: string | Buffer | Uint8Array, options?: { binary?: boolean }): Buffer;
43
+ export function prepareClientFrame(data: string | Buffer | Uint8Array, options?: { binary?: boolean }): Buffer;
44
+ export function extractString(buf: Buffer, prefix: Buffer | string, startOffset?: number): string | null;
45
+ export function extractNumber(buf: Buffer, prefix: Buffer | string, startOffset?: number): number | null;
43
46
 
44
47
  export class WalterConnection extends EventEmitter {
45
48
  id: number;
@@ -135,6 +138,10 @@ export interface WalterClientOptions {
135
138
  protocols?: string | string[];
136
139
  maxPayload?: number;
137
140
  handshakeTimeout?: number;
141
+ skipUTF8Validation?: boolean;
142
+ rawBuffer?: boolean;
143
+ tlsOptions?: Record<string, any>;
144
+ sessionReuse?: boolean;
138
145
  autoReconnect?: boolean;
139
146
  reconnectInterval?: number;
140
147
  maxReconnectInterval?: number;
@@ -150,14 +157,19 @@ export class WalterClient extends EventEmitter {
150
157
  static WalterClient: typeof WalterClient;
151
158
  static WalterConnection: typeof WalterConnection;
152
159
  static prepareMessage: typeof prepareMessage;
160
+ static prepareClientFrame: typeof prepareClientFrame;
161
+ static extractString: typeof extractString;
162
+ static extractNumber: typeof extractNumber;
153
163
  static CONNECTING: 0;
154
164
  static OPEN: 1;
155
165
  static CLOSING: 2;
156
166
  static CLOSED: 3;
157
167
 
158
- url: URL;
168
+ url: URL | string;
159
169
  readyState: 0 | 1 | 2 | 3;
160
170
  protocol: string | null;
171
+ _socket?: net.Socket;
172
+ socket?: net.Socket;
161
173
  onopen: ((event: { target: WalterClient }) => void) | null;
162
174
  onmessage: ((event: { data: string | Buffer; isBinary: boolean; target: WalterClient }) => void) | null;
163
175
  onclose: ((event: { code: number; reason: string; target: WalterClient }) => void) | null;
@@ -165,6 +177,8 @@ export class WalterClient extends EventEmitter {
165
177
 
166
178
  constructor(url: string | URL, options?: WalterClientOptions);
167
179
  send(data: string | Buffer | Uint8Array, options?: SendOptions | ((err?: Error) => void), callback?: (err?: Error) => void): void;
180
+ sendFrame(preMaskedFrame: Buffer, callback?: (err?: Error) => void): void;
181
+ prepareFrame(data: string | Buffer | Uint8Array, options?: { binary?: boolean }): Buffer;
168
182
  sendJSON(obj: unknown, callback?: (err?: Error) => void): void;
169
183
  ping(data?: Buffer | string, callback?: (err?: Error) => void): void;
170
184
  pong(data?: Buffer | string, callback?: (err?: Error) => void): void;
package/src/index.js CHANGED
@@ -3,7 +3,16 @@
3
3
  const { WalterServer, computeAcceptKey, isValidSecWebSocketKey } = require('./server');
4
4
  const { WalterClient } = require('./client');
5
5
  const { WalterConnection } = require('./connection');
6
- const { FrameParser, encodeFrame, prepareMessage, applyMask, WebSocketProtocolError } = require('./frame');
6
+ const {
7
+ FrameParser,
8
+ encodeFrame,
9
+ prepareMessage,
10
+ prepareClientFrame,
11
+ extractString,
12
+ extractNumber,
13
+ applyMask,
14
+ WebSocketProtocolError,
15
+ } = require('./frame');
7
16
  const { GUID, READY_STATES, OPCODES, CLOSE_CODES, isValidCloseCode } = require('./constants');
8
17
 
9
18
  // Drop-in compatibility with standard `ws` package (`const WebSocket = require('walter-ws')`)
@@ -16,6 +25,9 @@ WalterClient.WalterConnection = WalterConnection;
16
25
  WalterClient.FrameParser = FrameParser;
17
26
  WalterClient.encodeFrame = encodeFrame;
18
27
  WalterClient.prepareMessage = prepareMessage;
28
+ WalterClient.prepareClientFrame = prepareClientFrame;
29
+ WalterClient.extractString = extractString;
30
+ WalterClient.extractNumber = extractNumber;
19
31
  WalterClient.applyMask = applyMask;
20
32
  WalterClient.computeAcceptKey = computeAcceptKey;
21
33
  WalterClient.isValidSecWebSocketKey = isValidSecWebSocketKey;
package/src/index.mjs CHANGED
@@ -10,6 +10,9 @@ export const {
10
10
  FrameParser,
11
11
  encodeFrame,
12
12
  prepareMessage,
13
+ prepareClientFrame,
14
+ extractString,
15
+ extractNumber,
13
16
  applyMask,
14
17
  computeAcceptKey,
15
18
  isValidSecWebSocketKey,