crossws 0.0.1 → 0.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.
Files changed (46) hide show
  1. package/README.md +155 -56
  2. package/adapters/bun.d.ts +1 -0
  3. package/adapters/cloudflare.d.ts +1 -0
  4. package/adapters/deno.d.ts +1 -0
  5. package/adapters/node.d.ts +1 -0
  6. package/dist/adapters/bun.cjs +44 -29
  7. package/dist/adapters/bun.d.cts +5 -35
  8. package/dist/adapters/bun.d.mts +5 -35
  9. package/dist/adapters/bun.d.ts +5 -35
  10. package/dist/adapters/bun.mjs +44 -26
  11. package/dist/adapters/cloudflare.cjs +52 -0
  12. package/dist/adapters/cloudflare.d.cts +12 -0
  13. package/dist/adapters/cloudflare.d.mts +12 -0
  14. package/dist/adapters/cloudflare.d.ts +12 -0
  15. package/dist/adapters/cloudflare.mjs +50 -0
  16. package/dist/adapters/deno.cjs +20 -29
  17. package/dist/adapters/deno.d.cts +2 -10
  18. package/dist/adapters/deno.d.mts +2 -10
  19. package/dist/adapters/deno.d.ts +2 -10
  20. package/dist/adapters/deno.mjs +20 -26
  21. package/dist/adapters/node.cjs +57 -3891
  22. package/dist/adapters/node.d.cts +36 -37
  23. package/dist/adapters/node.d.mts +36 -37
  24. package/dist/adapters/node.d.ts +36 -37
  25. package/dist/adapters/node.mjs +48 -3872
  26. package/dist/index.cjs +5 -5
  27. package/dist/index.d.cts +40 -10
  28. package/dist/index.d.mts +40 -10
  29. package/dist/index.d.ts +40 -10
  30. package/dist/index.mjs +4 -4
  31. package/dist/shared/{crossws.002417e5.cjs → crossws.21e14e0d.cjs} +7 -4
  32. package/dist/shared/crossws.2ed26345.cjs +3931 -0
  33. package/dist/shared/{crossws.08866fa6.mjs → crossws.9536f626.mjs} +7 -4
  34. package/dist/shared/crossws.a5db571c.mjs +3910 -0
  35. package/dist/websocket/index.cjs +5 -0
  36. package/dist/websocket/index.d.cts +10 -0
  37. package/dist/websocket/index.d.mts +10 -0
  38. package/dist/websocket/index.d.ts +10 -0
  39. package/dist/websocket/index.mjs +3 -0
  40. package/dist/websocket/node.cjs +17 -0
  41. package/dist/websocket/node.d.cts +10 -0
  42. package/dist/websocket/node.d.mts +10 -0
  43. package/dist/websocket/node.d.ts +10 -0
  44. package/dist/websocket/node.mjs +15 -0
  45. package/package.json +44 -17
  46. package/websocket.d.ts +1 -0
@@ -1,3832 +1,15 @@
1
- import require$$0$2 from 'stream';
2
- import require$$0 from 'zlib';
3
- import require$$0$1 from 'buffer';
4
- import require$$1 from 'crypto';
5
- import require$$0$3 from 'events';
6
- import require$$1$1 from 'https';
7
- import require$$2 from 'http';
8
- import require$$3 from 'net';
9
- import require$$4 from 'tls';
10
- import require$$7 from 'url';
11
- import { d as defineWebSocketAdapter, a as WebSocketMessage, W as WebSocketError, b as WebSocketPeer } from '../shared/crossws.08866fa6.mjs';
12
-
13
- function getDefaultExportFromCjs (x) {
14
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
15
- }
16
-
17
- var bufferUtil$1 = {exports: {}};
18
-
19
- var constants = {
20
- BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],
21
- EMPTY_BUFFER: Buffer.alloc(0),
22
- GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
23
- kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
24
- kListener: Symbol('kListener'),
25
- kStatusCode: Symbol('status-code'),
26
- kWebSocket: Symbol('websocket'),
27
- NOOP: () => {}
28
- };
29
-
30
- var unmask$1;
31
- var mask;
32
-
33
- const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants;
34
-
35
- const FastBuffer$2 = Buffer[Symbol.species];
36
-
37
- /**
38
- * Merges an array of buffers into a new buffer.
39
- *
40
- * @param {Buffer[]} list The array of buffers to concat
41
- * @param {Number} totalLength The total length of buffers in the list
42
- * @return {Buffer} The resulting buffer
43
- * @public
44
- */
45
- function concat$1(list, totalLength) {
46
- if (list.length === 0) return EMPTY_BUFFER$3;
47
- if (list.length === 1) return list[0];
48
-
49
- const target = Buffer.allocUnsafe(totalLength);
50
- let offset = 0;
51
-
52
- for (let i = 0; i < list.length; i++) {
53
- const buf = list[i];
54
- target.set(buf, offset);
55
- offset += buf.length;
56
- }
57
-
58
- if (offset < totalLength) {
59
- return new FastBuffer$2(target.buffer, target.byteOffset, offset);
60
- }
61
-
62
- return target;
63
- }
64
-
65
- /**
66
- * Masks a buffer using the given mask.
67
- *
68
- * @param {Buffer} source The buffer to mask
69
- * @param {Buffer} mask The mask to use
70
- * @param {Buffer} output The buffer where to store the result
71
- * @param {Number} offset The offset at which to start writing
72
- * @param {Number} length The number of bytes to mask.
73
- * @public
74
- */
75
- function _mask(source, mask, output, offset, length) {
76
- for (let i = 0; i < length; i++) {
77
- output[offset + i] = source[i] ^ mask[i & 3];
78
- }
79
- }
80
-
81
- /**
82
- * Unmasks a buffer using the given mask.
83
- *
84
- * @param {Buffer} buffer The buffer to unmask
85
- * @param {Buffer} mask The mask to use
86
- * @public
87
- */
88
- function _unmask(buffer, mask) {
89
- for (let i = 0; i < buffer.length; i++) {
90
- buffer[i] ^= mask[i & 3];
91
- }
92
- }
93
-
94
- /**
95
- * Converts a buffer to an `ArrayBuffer`.
96
- *
97
- * @param {Buffer} buf The buffer to convert
98
- * @return {ArrayBuffer} Converted buffer
99
- * @public
100
- */
101
- function toArrayBuffer$1(buf) {
102
- if (buf.length === buf.buffer.byteLength) {
103
- return buf.buffer;
104
- }
105
-
106
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
107
- }
108
-
109
- /**
110
- * Converts `data` to a `Buffer`.
111
- *
112
- * @param {*} data The data to convert
113
- * @return {Buffer} The buffer
114
- * @throws {TypeError}
115
- * @public
116
- */
117
- function toBuffer$2(data) {
118
- toBuffer$2.readOnly = true;
119
-
120
- if (Buffer.isBuffer(data)) return data;
121
-
122
- let buf;
123
-
124
- if (data instanceof ArrayBuffer) {
125
- buf = new FastBuffer$2(data);
126
- } else if (ArrayBuffer.isView(data)) {
127
- buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength);
128
- } else {
129
- buf = Buffer.from(data);
130
- toBuffer$2.readOnly = false;
131
- }
132
-
133
- return buf;
134
- }
135
-
136
- bufferUtil$1.exports = {
137
- concat: concat$1,
138
- mask: _mask,
139
- toArrayBuffer: toArrayBuffer$1,
140
- toBuffer: toBuffer$2,
141
- unmask: _unmask
142
- };
143
-
144
- /* istanbul ignore else */
145
- if (!process.env.WS_NO_BUFFER_UTIL) {
146
- try {
147
- const bufferUtil = require('bufferutil');
148
-
149
- mask = bufferUtil$1.exports.mask = function (source, mask, output, offset, length) {
150
- if (length < 48) _mask(source, mask, output, offset, length);
151
- else bufferUtil.mask(source, mask, output, offset, length);
152
- };
153
-
154
- unmask$1 = bufferUtil$1.exports.unmask = function (buffer, mask) {
155
- if (buffer.length < 32) _unmask(buffer, mask);
156
- else bufferUtil.unmask(buffer, mask);
157
- };
158
- } catch (e) {
159
- // Continue regardless of the error.
160
- }
161
- }
162
-
163
- var bufferUtilExports = bufferUtil$1.exports;
164
-
165
- const kDone = Symbol('kDone');
166
- const kRun = Symbol('kRun');
167
-
168
- /**
169
- * A very simple job queue with adjustable concurrency. Adapted from
170
- * https://github.com/STRML/async-limiter
171
- */
172
- let Limiter$1 = class Limiter {
173
- /**
174
- * Creates a new `Limiter`.
175
- *
176
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
177
- * to run concurrently
178
- */
179
- constructor(concurrency) {
180
- this[kDone] = () => {
181
- this.pending--;
182
- this[kRun]();
183
- };
184
- this.concurrency = concurrency || Infinity;
185
- this.jobs = [];
186
- this.pending = 0;
187
- }
188
-
189
- /**
190
- * Adds a job to the queue.
191
- *
192
- * @param {Function} job The job to run
193
- * @public
194
- */
195
- add(job) {
196
- this.jobs.push(job);
197
- this[kRun]();
198
- }
199
-
200
- /**
201
- * Removes a job from the queue and runs it if possible.
202
- *
203
- * @private
204
- */
205
- [kRun]() {
206
- if (this.pending === this.concurrency) return;
207
-
208
- if (this.jobs.length) {
209
- const job = this.jobs.shift();
210
-
211
- this.pending++;
212
- job(this[kDone]);
213
- }
214
- }
215
- };
216
-
217
- var limiter = Limiter$1;
218
-
219
- const zlib = require$$0;
220
-
221
- const bufferUtil = bufferUtilExports;
222
- const Limiter = limiter;
223
- const { kStatusCode: kStatusCode$2 } = constants;
224
-
225
- const FastBuffer$1 = Buffer[Symbol.species];
226
- const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
227
- const kPerMessageDeflate = Symbol('permessage-deflate');
228
- const kTotalLength = Symbol('total-length');
229
- const kCallback = Symbol('callback');
230
- const kBuffers = Symbol('buffers');
231
- const kError$1 = Symbol('error');
232
-
233
- //
234
- // We limit zlib concurrency, which prevents severe memory fragmentation
235
- // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
236
- // and https://github.com/websockets/ws/issues/1202
237
- //
238
- // Intentionally global; it's the global thread pool that's an issue.
239
- //
240
- let zlibLimiter;
241
-
242
- /**
243
- * permessage-deflate implementation.
244
- */
245
- let PerMessageDeflate$4 = class PerMessageDeflate {
246
- /**
247
- * Creates a PerMessageDeflate instance.
248
- *
249
- * @param {Object} [options] Configuration options
250
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
251
- * for, or request, a custom client window size
252
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
253
- * acknowledge disabling of client context takeover
254
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
255
- * calls to zlib
256
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
257
- * use of a custom server window size
258
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
259
- * disabling of server context takeover
260
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
261
- * messages should not be compressed if context takeover is disabled
262
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
263
- * deflate
264
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
265
- * inflate
266
- * @param {Boolean} [isServer=false] Create the instance in either server or
267
- * client mode
268
- * @param {Number} [maxPayload=0] The maximum allowed message length
269
- */
270
- constructor(options, isServer, maxPayload) {
271
- this._maxPayload = maxPayload | 0;
272
- this._options = options || {};
273
- this._threshold =
274
- this._options.threshold !== undefined ? this._options.threshold : 1024;
275
- this._isServer = !!isServer;
276
- this._deflate = null;
277
- this._inflate = null;
278
-
279
- this.params = null;
280
-
281
- if (!zlibLimiter) {
282
- const concurrency =
283
- this._options.concurrencyLimit !== undefined
284
- ? this._options.concurrencyLimit
285
- : 10;
286
- zlibLimiter = new Limiter(concurrency);
287
- }
288
- }
289
-
290
- /**
291
- * @type {String}
292
- */
293
- static get extensionName() {
294
- return 'permessage-deflate';
295
- }
296
-
297
- /**
298
- * Create an extension negotiation offer.
299
- *
300
- * @return {Object} Extension parameters
301
- * @public
302
- */
303
- offer() {
304
- const params = {};
305
-
306
- if (this._options.serverNoContextTakeover) {
307
- params.server_no_context_takeover = true;
308
- }
309
- if (this._options.clientNoContextTakeover) {
310
- params.client_no_context_takeover = true;
311
- }
312
- if (this._options.serverMaxWindowBits) {
313
- params.server_max_window_bits = this._options.serverMaxWindowBits;
314
- }
315
- if (this._options.clientMaxWindowBits) {
316
- params.client_max_window_bits = this._options.clientMaxWindowBits;
317
- } else if (this._options.clientMaxWindowBits == null) {
318
- params.client_max_window_bits = true;
319
- }
320
-
321
- return params;
322
- }
323
-
324
- /**
325
- * Accept an extension negotiation offer/response.
326
- *
327
- * @param {Array} configurations The extension negotiation offers/reponse
328
- * @return {Object} Accepted configuration
329
- * @public
330
- */
331
- accept(configurations) {
332
- configurations = this.normalizeParams(configurations);
333
-
334
- this.params = this._isServer
335
- ? this.acceptAsServer(configurations)
336
- : this.acceptAsClient(configurations);
337
-
338
- return this.params;
339
- }
340
-
341
- /**
342
- * Releases all resources used by the extension.
343
- *
344
- * @public
345
- */
346
- cleanup() {
347
- if (this._inflate) {
348
- this._inflate.close();
349
- this._inflate = null;
350
- }
351
-
352
- if (this._deflate) {
353
- const callback = this._deflate[kCallback];
354
-
355
- this._deflate.close();
356
- this._deflate = null;
357
-
358
- if (callback) {
359
- callback(
360
- new Error(
361
- 'The deflate stream was closed while data was being processed'
362
- )
363
- );
364
- }
365
- }
366
- }
367
-
368
- /**
369
- * Accept an extension negotiation offer.
370
- *
371
- * @param {Array} offers The extension negotiation offers
372
- * @return {Object} Accepted configuration
373
- * @private
374
- */
375
- acceptAsServer(offers) {
376
- const opts = this._options;
377
- const accepted = offers.find((params) => {
378
- if (
379
- (opts.serverNoContextTakeover === false &&
380
- params.server_no_context_takeover) ||
381
- (params.server_max_window_bits &&
382
- (opts.serverMaxWindowBits === false ||
383
- (typeof opts.serverMaxWindowBits === 'number' &&
384
- opts.serverMaxWindowBits > params.server_max_window_bits))) ||
385
- (typeof opts.clientMaxWindowBits === 'number' &&
386
- !params.client_max_window_bits)
387
- ) {
388
- return false;
389
- }
390
-
391
- return true;
392
- });
393
-
394
- if (!accepted) {
395
- throw new Error('None of the extension offers can be accepted');
396
- }
397
-
398
- if (opts.serverNoContextTakeover) {
399
- accepted.server_no_context_takeover = true;
400
- }
401
- if (opts.clientNoContextTakeover) {
402
- accepted.client_no_context_takeover = true;
403
- }
404
- if (typeof opts.serverMaxWindowBits === 'number') {
405
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
406
- }
407
- if (typeof opts.clientMaxWindowBits === 'number') {
408
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
409
- } else if (
410
- accepted.client_max_window_bits === true ||
411
- opts.clientMaxWindowBits === false
412
- ) {
413
- delete accepted.client_max_window_bits;
414
- }
415
-
416
- return accepted;
417
- }
418
-
419
- /**
420
- * Accept the extension negotiation response.
421
- *
422
- * @param {Array} response The extension negotiation response
423
- * @return {Object} Accepted configuration
424
- * @private
425
- */
426
- acceptAsClient(response) {
427
- const params = response[0];
428
-
429
- if (
430
- this._options.clientNoContextTakeover === false &&
431
- params.client_no_context_takeover
432
- ) {
433
- throw new Error('Unexpected parameter "client_no_context_takeover"');
434
- }
435
-
436
- if (!params.client_max_window_bits) {
437
- if (typeof this._options.clientMaxWindowBits === 'number') {
438
- params.client_max_window_bits = this._options.clientMaxWindowBits;
439
- }
440
- } else if (
441
- this._options.clientMaxWindowBits === false ||
442
- (typeof this._options.clientMaxWindowBits === 'number' &&
443
- params.client_max_window_bits > this._options.clientMaxWindowBits)
444
- ) {
445
- throw new Error(
446
- 'Unexpected or invalid parameter "client_max_window_bits"'
447
- );
448
- }
449
-
450
- return params;
451
- }
452
-
453
- /**
454
- * Normalize parameters.
455
- *
456
- * @param {Array} configurations The extension negotiation offers/reponse
457
- * @return {Array} The offers/response with normalized parameters
458
- * @private
459
- */
460
- normalizeParams(configurations) {
461
- configurations.forEach((params) => {
462
- Object.keys(params).forEach((key) => {
463
- let value = params[key];
464
-
465
- if (value.length > 1) {
466
- throw new Error(`Parameter "${key}" must have only a single value`);
467
- }
468
-
469
- value = value[0];
470
-
471
- if (key === 'client_max_window_bits') {
472
- if (value !== true) {
473
- const num = +value;
474
- if (!Number.isInteger(num) || num < 8 || num > 15) {
475
- throw new TypeError(
476
- `Invalid value for parameter "${key}": ${value}`
477
- );
478
- }
479
- value = num;
480
- } else if (!this._isServer) {
481
- throw new TypeError(
482
- `Invalid value for parameter "${key}": ${value}`
483
- );
484
- }
485
- } else if (key === 'server_max_window_bits') {
486
- const num = +value;
487
- if (!Number.isInteger(num) || num < 8 || num > 15) {
488
- throw new TypeError(
489
- `Invalid value for parameter "${key}": ${value}`
490
- );
491
- }
492
- value = num;
493
- } else if (
494
- key === 'client_no_context_takeover' ||
495
- key === 'server_no_context_takeover'
496
- ) {
497
- if (value !== true) {
498
- throw new TypeError(
499
- `Invalid value for parameter "${key}": ${value}`
500
- );
501
- }
502
- } else {
503
- throw new Error(`Unknown parameter "${key}"`);
504
- }
505
-
506
- params[key] = value;
507
- });
508
- });
509
-
510
- return configurations;
511
- }
512
-
513
- /**
514
- * Decompress data. Concurrency limited.
515
- *
516
- * @param {Buffer} data Compressed data
517
- * @param {Boolean} fin Specifies whether or not this is the last fragment
518
- * @param {Function} callback Callback
519
- * @public
520
- */
521
- decompress(data, fin, callback) {
522
- zlibLimiter.add((done) => {
523
- this._decompress(data, fin, (err, result) => {
524
- done();
525
- callback(err, result);
526
- });
527
- });
528
- }
529
-
530
- /**
531
- * Compress data. Concurrency limited.
532
- *
533
- * @param {(Buffer|String)} data Data to compress
534
- * @param {Boolean} fin Specifies whether or not this is the last fragment
535
- * @param {Function} callback Callback
536
- * @public
537
- */
538
- compress(data, fin, callback) {
539
- zlibLimiter.add((done) => {
540
- this._compress(data, fin, (err, result) => {
541
- done();
542
- callback(err, result);
543
- });
544
- });
545
- }
546
-
547
- /**
548
- * Decompress data.
549
- *
550
- * @param {Buffer} data Compressed data
551
- * @param {Boolean} fin Specifies whether or not this is the last fragment
552
- * @param {Function} callback Callback
553
- * @private
554
- */
555
- _decompress(data, fin, callback) {
556
- const endpoint = this._isServer ? 'client' : 'server';
557
-
558
- if (!this._inflate) {
559
- const key = `${endpoint}_max_window_bits`;
560
- const windowBits =
561
- typeof this.params[key] !== 'number'
562
- ? zlib.Z_DEFAULT_WINDOWBITS
563
- : this.params[key];
564
-
565
- this._inflate = zlib.createInflateRaw({
566
- ...this._options.zlibInflateOptions,
567
- windowBits
568
- });
569
- this._inflate[kPerMessageDeflate] = this;
570
- this._inflate[kTotalLength] = 0;
571
- this._inflate[kBuffers] = [];
572
- this._inflate.on('error', inflateOnError);
573
- this._inflate.on('data', inflateOnData);
574
- }
575
-
576
- this._inflate[kCallback] = callback;
577
-
578
- this._inflate.write(data);
579
- if (fin) this._inflate.write(TRAILER);
580
-
581
- this._inflate.flush(() => {
582
- const err = this._inflate[kError$1];
583
-
584
- if (err) {
585
- this._inflate.close();
586
- this._inflate = null;
587
- callback(err);
588
- return;
589
- }
590
-
591
- const data = bufferUtil.concat(
592
- this._inflate[kBuffers],
593
- this._inflate[kTotalLength]
594
- );
595
-
596
- if (this._inflate._readableState.endEmitted) {
597
- this._inflate.close();
598
- this._inflate = null;
599
- } else {
600
- this._inflate[kTotalLength] = 0;
601
- this._inflate[kBuffers] = [];
602
-
603
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
604
- this._inflate.reset();
605
- }
606
- }
607
-
608
- callback(null, data);
609
- });
610
- }
611
-
612
- /**
613
- * Compress data.
614
- *
615
- * @param {(Buffer|String)} data Data to compress
616
- * @param {Boolean} fin Specifies whether or not this is the last fragment
617
- * @param {Function} callback Callback
618
- * @private
619
- */
620
- _compress(data, fin, callback) {
621
- const endpoint = this._isServer ? 'server' : 'client';
622
-
623
- if (!this._deflate) {
624
- const key = `${endpoint}_max_window_bits`;
625
- const windowBits =
626
- typeof this.params[key] !== 'number'
627
- ? zlib.Z_DEFAULT_WINDOWBITS
628
- : this.params[key];
629
-
630
- this._deflate = zlib.createDeflateRaw({
631
- ...this._options.zlibDeflateOptions,
632
- windowBits
633
- });
634
-
635
- this._deflate[kTotalLength] = 0;
636
- this._deflate[kBuffers] = [];
637
-
638
- this._deflate.on('data', deflateOnData);
639
- }
640
-
641
- this._deflate[kCallback] = callback;
642
-
643
- this._deflate.write(data);
644
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
645
- if (!this._deflate) {
646
- //
647
- // The deflate stream was closed while data was being processed.
648
- //
649
- return;
650
- }
651
-
652
- let data = bufferUtil.concat(
653
- this._deflate[kBuffers],
654
- this._deflate[kTotalLength]
655
- );
656
-
657
- if (fin) {
658
- data = new FastBuffer$1(data.buffer, data.byteOffset, data.length - 4);
659
- }
660
-
661
- //
662
- // Ensure that the callback will not be called again in
663
- // `PerMessageDeflate#cleanup()`.
664
- //
665
- this._deflate[kCallback] = null;
666
-
667
- this._deflate[kTotalLength] = 0;
668
- this._deflate[kBuffers] = [];
669
-
670
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
671
- this._deflate.reset();
672
- }
673
-
674
- callback(null, data);
675
- });
676
- }
677
- };
678
-
679
- var permessageDeflate = PerMessageDeflate$4;
680
-
681
- /**
682
- * The listener of the `zlib.DeflateRaw` stream `'data'` event.
683
- *
684
- * @param {Buffer} chunk A chunk of data
685
- * @private
686
- */
687
- function deflateOnData(chunk) {
688
- this[kBuffers].push(chunk);
689
- this[kTotalLength] += chunk.length;
690
- }
691
-
692
- /**
693
- * The listener of the `zlib.InflateRaw` stream `'data'` event.
694
- *
695
- * @param {Buffer} chunk A chunk of data
696
- * @private
697
- */
698
- function inflateOnData(chunk) {
699
- this[kTotalLength] += chunk.length;
700
-
701
- if (
702
- this[kPerMessageDeflate]._maxPayload < 1 ||
703
- this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
704
- ) {
705
- this[kBuffers].push(chunk);
706
- return;
707
- }
708
-
709
- this[kError$1] = new RangeError('Max payload size exceeded');
710
- this[kError$1].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
711
- this[kError$1][kStatusCode$2] = 1009;
712
- this.removeListener('data', inflateOnData);
713
- this.reset();
714
- }
715
-
716
- /**
717
- * The listener of the `zlib.InflateRaw` stream `'error'` event.
718
- *
719
- * @param {Error} err The emitted error
720
- * @private
721
- */
722
- function inflateOnError(err) {
723
- //
724
- // There is no need to call `Zlib#close()` as the handle is automatically
725
- // closed when an error is emitted.
726
- //
727
- this[kPerMessageDeflate]._inflate = null;
728
- err[kStatusCode$2] = 1007;
729
- this[kCallback](err);
730
- }
731
-
732
- var validation = {exports: {}};
733
-
734
- var isValidUTF8_1;
735
-
736
- const { isUtf8 } = require$$0$1;
737
-
738
- //
739
- // Allowed token characters:
740
- //
741
- // '!', '#', '$', '%', '&', ''', '*', '+', '-',
742
- // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
743
- //
744
- // tokenChars[32] === 0 // ' '
745
- // tokenChars[33] === 1 // '!'
746
- // tokenChars[34] === 0 // '"'
747
- // ...
748
- //
749
- // prettier-ignore
750
- const tokenChars$2 = [
751
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
752
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
753
- 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
754
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
755
- 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
756
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
757
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
758
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
759
- ];
760
-
761
- /**
762
- * Checks if a status code is allowed in a close frame.
763
- *
764
- * @param {Number} code The status code
765
- * @return {Boolean} `true` if the status code is valid, else `false`
766
- * @public
767
- */
768
- function isValidStatusCode$2(code) {
769
- return (
770
- (code >= 1000 &&
771
- code <= 1014 &&
772
- code !== 1004 &&
773
- code !== 1005 &&
774
- code !== 1006) ||
775
- (code >= 3000 && code <= 4999)
776
- );
777
- }
778
-
779
- /**
780
- * Checks if a given buffer contains only correct UTF-8.
781
- * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
782
- * Markus Kuhn.
783
- *
784
- * @param {Buffer} buf The buffer to check
785
- * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
786
- * @public
787
- */
788
- function _isValidUTF8(buf) {
789
- const len = buf.length;
790
- let i = 0;
791
-
792
- while (i < len) {
793
- if ((buf[i] & 0x80) === 0) {
794
- // 0xxxxxxx
795
- i++;
796
- } else if ((buf[i] & 0xe0) === 0xc0) {
797
- // 110xxxxx 10xxxxxx
798
- if (
799
- i + 1 === len ||
800
- (buf[i + 1] & 0xc0) !== 0x80 ||
801
- (buf[i] & 0xfe) === 0xc0 // Overlong
802
- ) {
803
- return false;
804
- }
805
-
806
- i += 2;
807
- } else if ((buf[i] & 0xf0) === 0xe0) {
808
- // 1110xxxx 10xxxxxx 10xxxxxx
809
- if (
810
- i + 2 >= len ||
811
- (buf[i + 1] & 0xc0) !== 0x80 ||
812
- (buf[i + 2] & 0xc0) !== 0x80 ||
813
- (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
814
- (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
815
- ) {
816
- return false;
817
- }
818
-
819
- i += 3;
820
- } else if ((buf[i] & 0xf8) === 0xf0) {
821
- // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
822
- if (
823
- i + 3 >= len ||
824
- (buf[i + 1] & 0xc0) !== 0x80 ||
825
- (buf[i + 2] & 0xc0) !== 0x80 ||
826
- (buf[i + 3] & 0xc0) !== 0x80 ||
827
- (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
828
- (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
829
- buf[i] > 0xf4 // > U+10FFFF
830
- ) {
831
- return false;
832
- }
833
-
834
- i += 4;
835
- } else {
836
- return false;
837
- }
838
- }
839
-
840
- return true;
841
- }
842
-
843
- validation.exports = {
844
- isValidStatusCode: isValidStatusCode$2,
845
- isValidUTF8: _isValidUTF8,
846
- tokenChars: tokenChars$2
847
- };
848
-
849
- if (isUtf8) {
850
- isValidUTF8_1 = validation.exports.isValidUTF8 = function (buf) {
851
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
852
- };
853
- } /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {
854
- try {
855
- const isValidUTF8 = require('utf-8-validate');
856
-
857
- isValidUTF8_1 = validation.exports.isValidUTF8 = function (buf) {
858
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
859
- };
860
- } catch (e) {
861
- // Continue regardless of the error.
862
- }
863
- }
864
-
865
- var validationExports = validation.exports;
866
-
867
- const { Writable } = require$$0$2;
868
-
869
- const PerMessageDeflate$3 = permessageDeflate;
870
- const {
871
- BINARY_TYPES: BINARY_TYPES$1,
872
- EMPTY_BUFFER: EMPTY_BUFFER$2,
873
- kStatusCode: kStatusCode$1,
874
- kWebSocket: kWebSocket$2
875
- } = constants;
876
- const { concat, toArrayBuffer, unmask } = bufferUtilExports;
877
- const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports;
878
-
879
- const FastBuffer = Buffer[Symbol.species];
880
- const promise = Promise.resolve();
881
-
882
- //
883
- // `queueMicrotask()` is not available in Node.js < 11.
884
- //
885
- const queueTask =
886
- typeof queueMicrotask === 'function' ? queueMicrotask : queueMicrotaskShim;
887
-
888
- const GET_INFO = 0;
889
- const GET_PAYLOAD_LENGTH_16 = 1;
890
- const GET_PAYLOAD_LENGTH_64 = 2;
891
- const GET_MASK = 3;
892
- const GET_DATA = 4;
893
- const INFLATING = 5;
894
- const WAIT_MICROTASK = 6;
895
-
896
- /**
897
- * HyBi Receiver implementation.
898
- *
899
- * @extends Writable
900
- */
901
- let Receiver$1 = class Receiver extends Writable {
902
- /**
903
- * Creates a Receiver instance.
904
- *
905
- * @param {Object} [options] Options object
906
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
907
- * @param {Object} [options.extensions] An object containing the negotiated
908
- * extensions
909
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
910
- * client or server mode
911
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
912
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
913
- * not to skip UTF-8 validation for text and close messages
914
- */
915
- constructor(options = {}) {
916
- super();
917
-
918
- this._binaryType = options.binaryType || BINARY_TYPES$1[0];
919
- this._extensions = options.extensions || {};
920
- this._isServer = !!options.isServer;
921
- this._maxPayload = options.maxPayload | 0;
922
- this._skipUTF8Validation = !!options.skipUTF8Validation;
923
- this[kWebSocket$2] = undefined;
924
-
925
- this._bufferedBytes = 0;
926
- this._buffers = [];
927
-
928
- this._compressed = false;
929
- this._payloadLength = 0;
930
- this._mask = undefined;
931
- this._fragmented = 0;
932
- this._masked = false;
933
- this._fin = false;
934
- this._opcode = 0;
935
-
936
- this._totalPayloadLength = 0;
937
- this._messageLength = 0;
938
- this._fragments = [];
939
-
940
- this._state = GET_INFO;
941
- this._loop = false;
942
- }
943
-
944
- /**
945
- * Implements `Writable.prototype._write()`.
946
- *
947
- * @param {Buffer} chunk The chunk of data to write
948
- * @param {String} encoding The character encoding of `chunk`
949
- * @param {Function} cb Callback
950
- * @private
951
- */
952
- _write(chunk, encoding, cb) {
953
- if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
954
-
955
- this._bufferedBytes += chunk.length;
956
- this._buffers.push(chunk);
957
- this.startLoop(cb);
958
- }
959
-
960
- /**
961
- * Consumes `n` bytes from the buffered data.
962
- *
963
- * @param {Number} n The number of bytes to consume
964
- * @return {Buffer} The consumed bytes
965
- * @private
966
- */
967
- consume(n) {
968
- this._bufferedBytes -= n;
969
-
970
- if (n === this._buffers[0].length) return this._buffers.shift();
971
-
972
- if (n < this._buffers[0].length) {
973
- const buf = this._buffers[0];
974
- this._buffers[0] = new FastBuffer(
975
- buf.buffer,
976
- buf.byteOffset + n,
977
- buf.length - n
978
- );
979
-
980
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
981
- }
982
-
983
- const dst = Buffer.allocUnsafe(n);
984
-
985
- do {
986
- const buf = this._buffers[0];
987
- const offset = dst.length - n;
988
-
989
- if (n >= buf.length) {
990
- dst.set(this._buffers.shift(), offset);
991
- } else {
992
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
993
- this._buffers[0] = new FastBuffer(
994
- buf.buffer,
995
- buf.byteOffset + n,
996
- buf.length - n
997
- );
998
- }
999
-
1000
- n -= buf.length;
1001
- } while (n > 0);
1002
-
1003
- return dst;
1004
- }
1005
-
1006
- /**
1007
- * Starts the parsing loop.
1008
- *
1009
- * @param {Function} cb Callback
1010
- * @private
1011
- */
1012
- startLoop(cb) {
1013
- let err;
1014
- this._loop = true;
1015
-
1016
- do {
1017
- switch (this._state) {
1018
- case GET_INFO:
1019
- err = this.getInfo();
1020
- break;
1021
- case GET_PAYLOAD_LENGTH_16:
1022
- err = this.getPayloadLength16();
1023
- break;
1024
- case GET_PAYLOAD_LENGTH_64:
1025
- err = this.getPayloadLength64();
1026
- break;
1027
- case GET_MASK:
1028
- this.getMask();
1029
- break;
1030
- case GET_DATA:
1031
- err = this.getData(cb);
1032
- break;
1033
- case INFLATING:
1034
- this._loop = false;
1035
- return;
1036
- default:
1037
- //
1038
- // `WAIT_MICROTASK`.
1039
- //
1040
- this._loop = false;
1041
-
1042
- queueTask(() => {
1043
- this._state = GET_INFO;
1044
- this.startLoop(cb);
1045
- });
1046
- return;
1047
- }
1048
- } while (this._loop);
1049
-
1050
- cb(err);
1051
- }
1052
-
1053
- /**
1054
- * Reads the first two bytes of a frame.
1055
- *
1056
- * @return {(RangeError|undefined)} A possible error
1057
- * @private
1058
- */
1059
- getInfo() {
1060
- if (this._bufferedBytes < 2) {
1061
- this._loop = false;
1062
- return;
1063
- }
1064
-
1065
- const buf = this.consume(2);
1066
-
1067
- if ((buf[0] & 0x30) !== 0x00) {
1068
- this._loop = false;
1069
- return error(
1070
- RangeError,
1071
- 'RSV2 and RSV3 must be clear',
1072
- true,
1073
- 1002,
1074
- 'WS_ERR_UNEXPECTED_RSV_2_3'
1075
- );
1076
- }
1077
-
1078
- const compressed = (buf[0] & 0x40) === 0x40;
1079
-
1080
- if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
1081
- this._loop = false;
1082
- return error(
1083
- RangeError,
1084
- 'RSV1 must be clear',
1085
- true,
1086
- 1002,
1087
- 'WS_ERR_UNEXPECTED_RSV_1'
1088
- );
1089
- }
1090
-
1091
- this._fin = (buf[0] & 0x80) === 0x80;
1092
- this._opcode = buf[0] & 0x0f;
1093
- this._payloadLength = buf[1] & 0x7f;
1094
-
1095
- if (this._opcode === 0x00) {
1096
- if (compressed) {
1097
- this._loop = false;
1098
- return error(
1099
- RangeError,
1100
- 'RSV1 must be clear',
1101
- true,
1102
- 1002,
1103
- 'WS_ERR_UNEXPECTED_RSV_1'
1104
- );
1105
- }
1106
-
1107
- if (!this._fragmented) {
1108
- this._loop = false;
1109
- return error(
1110
- RangeError,
1111
- 'invalid opcode 0',
1112
- true,
1113
- 1002,
1114
- 'WS_ERR_INVALID_OPCODE'
1115
- );
1116
- }
1117
-
1118
- this._opcode = this._fragmented;
1119
- } else if (this._opcode === 0x01 || this._opcode === 0x02) {
1120
- if (this._fragmented) {
1121
- this._loop = false;
1122
- return error(
1123
- RangeError,
1124
- `invalid opcode ${this._opcode}`,
1125
- true,
1126
- 1002,
1127
- 'WS_ERR_INVALID_OPCODE'
1128
- );
1129
- }
1130
-
1131
- this._compressed = compressed;
1132
- } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
1133
- if (!this._fin) {
1134
- this._loop = false;
1135
- return error(
1136
- RangeError,
1137
- 'FIN must be set',
1138
- true,
1139
- 1002,
1140
- 'WS_ERR_EXPECTED_FIN'
1141
- );
1142
- }
1143
-
1144
- if (compressed) {
1145
- this._loop = false;
1146
- return error(
1147
- RangeError,
1148
- 'RSV1 must be clear',
1149
- true,
1150
- 1002,
1151
- 'WS_ERR_UNEXPECTED_RSV_1'
1152
- );
1153
- }
1154
-
1155
- if (
1156
- this._payloadLength > 0x7d ||
1157
- (this._opcode === 0x08 && this._payloadLength === 1)
1158
- ) {
1159
- this._loop = false;
1160
- return error(
1161
- RangeError,
1162
- `invalid payload length ${this._payloadLength}`,
1163
- true,
1164
- 1002,
1165
- 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
1166
- );
1167
- }
1168
- } else {
1169
- this._loop = false;
1170
- return error(
1171
- RangeError,
1172
- `invalid opcode ${this._opcode}`,
1173
- true,
1174
- 1002,
1175
- 'WS_ERR_INVALID_OPCODE'
1176
- );
1177
- }
1178
-
1179
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1180
- this._masked = (buf[1] & 0x80) === 0x80;
1181
-
1182
- if (this._isServer) {
1183
- if (!this._masked) {
1184
- this._loop = false;
1185
- return error(
1186
- RangeError,
1187
- 'MASK must be set',
1188
- true,
1189
- 1002,
1190
- 'WS_ERR_EXPECTED_MASK'
1191
- );
1192
- }
1193
- } else if (this._masked) {
1194
- this._loop = false;
1195
- return error(
1196
- RangeError,
1197
- 'MASK must be clear',
1198
- true,
1199
- 1002,
1200
- 'WS_ERR_UNEXPECTED_MASK'
1201
- );
1202
- }
1203
-
1204
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1205
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1206
- else return this.haveLength();
1207
- }
1208
-
1209
- /**
1210
- * Gets extended payload length (7+16).
1211
- *
1212
- * @return {(RangeError|undefined)} A possible error
1213
- * @private
1214
- */
1215
- getPayloadLength16() {
1216
- if (this._bufferedBytes < 2) {
1217
- this._loop = false;
1218
- return;
1219
- }
1220
-
1221
- this._payloadLength = this.consume(2).readUInt16BE(0);
1222
- return this.haveLength();
1223
- }
1224
-
1225
- /**
1226
- * Gets extended payload length (7+64).
1227
- *
1228
- * @return {(RangeError|undefined)} A possible error
1229
- * @private
1230
- */
1231
- getPayloadLength64() {
1232
- if (this._bufferedBytes < 8) {
1233
- this._loop = false;
1234
- return;
1235
- }
1236
-
1237
- const buf = this.consume(8);
1238
- const num = buf.readUInt32BE(0);
1239
-
1240
- //
1241
- // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
1242
- // if payload length is greater than this number.
1243
- //
1244
- if (num > Math.pow(2, 53 - 32) - 1) {
1245
- this._loop = false;
1246
- return error(
1247
- RangeError,
1248
- 'Unsupported WebSocket frame: payload length > 2^53 - 1',
1249
- false,
1250
- 1009,
1251
- 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
1252
- );
1253
- }
1254
-
1255
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1256
- return this.haveLength();
1257
- }
1258
-
1259
- /**
1260
- * Payload length has been read.
1261
- *
1262
- * @return {(RangeError|undefined)} A possible error
1263
- * @private
1264
- */
1265
- haveLength() {
1266
- if (this._payloadLength && this._opcode < 0x08) {
1267
- this._totalPayloadLength += this._payloadLength;
1268
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1269
- this._loop = false;
1270
- return error(
1271
- RangeError,
1272
- 'Max payload size exceeded',
1273
- false,
1274
- 1009,
1275
- 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
1276
- );
1277
- }
1278
- }
1279
-
1280
- if (this._masked) this._state = GET_MASK;
1281
- else this._state = GET_DATA;
1282
- }
1283
-
1284
- /**
1285
- * Reads mask bytes.
1286
- *
1287
- * @private
1288
- */
1289
- getMask() {
1290
- if (this._bufferedBytes < 4) {
1291
- this._loop = false;
1292
- return;
1293
- }
1294
-
1295
- this._mask = this.consume(4);
1296
- this._state = GET_DATA;
1297
- }
1298
-
1299
- /**
1300
- * Reads data bytes.
1301
- *
1302
- * @param {Function} cb Callback
1303
- * @return {(Error|RangeError|undefined)} A possible error
1304
- * @private
1305
- */
1306
- getData(cb) {
1307
- let data = EMPTY_BUFFER$2;
1308
-
1309
- if (this._payloadLength) {
1310
- if (this._bufferedBytes < this._payloadLength) {
1311
- this._loop = false;
1312
- return;
1313
- }
1314
-
1315
- data = this.consume(this._payloadLength);
1316
-
1317
- if (
1318
- this._masked &&
1319
- (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
1320
- ) {
1321
- unmask(data, this._mask);
1322
- }
1323
- }
1324
-
1325
- if (this._opcode > 0x07) return this.controlMessage(data);
1326
-
1327
- if (this._compressed) {
1328
- this._state = INFLATING;
1329
- this.decompress(data, cb);
1330
- return;
1331
- }
1332
-
1333
- if (data.length) {
1334
- //
1335
- // This message is not compressed so its length is the sum of the payload
1336
- // length of all fragments.
1337
- //
1338
- this._messageLength = this._totalPayloadLength;
1339
- this._fragments.push(data);
1340
- }
1341
-
1342
- return this.dataMessage();
1343
- }
1344
-
1345
- /**
1346
- * Decompresses data.
1347
- *
1348
- * @param {Buffer} data Compressed data
1349
- * @param {Function} cb Callback
1350
- * @private
1351
- */
1352
- decompress(data, cb) {
1353
- const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName];
1354
-
1355
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1356
- if (err) return cb(err);
1357
-
1358
- if (buf.length) {
1359
- this._messageLength += buf.length;
1360
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1361
- return cb(
1362
- error(
1363
- RangeError,
1364
- 'Max payload size exceeded',
1365
- false,
1366
- 1009,
1367
- 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
1368
- )
1369
- );
1370
- }
1371
-
1372
- this._fragments.push(buf);
1373
- }
1374
-
1375
- const er = this.dataMessage();
1376
- if (er) return cb(er);
1377
-
1378
- this.startLoop(cb);
1379
- });
1380
- }
1381
-
1382
- /**
1383
- * Handles a data message.
1384
- *
1385
- * @return {(Error|undefined)} A possible error
1386
- * @private
1387
- */
1388
- dataMessage() {
1389
- if (this._fin) {
1390
- const messageLength = this._messageLength;
1391
- const fragments = this._fragments;
1392
-
1393
- this._totalPayloadLength = 0;
1394
- this._messageLength = 0;
1395
- this._fragmented = 0;
1396
- this._fragments = [];
1397
-
1398
- if (this._opcode === 2) {
1399
- let data;
1400
-
1401
- if (this._binaryType === 'nodebuffer') {
1402
- data = concat(fragments, messageLength);
1403
- } else if (this._binaryType === 'arraybuffer') {
1404
- data = toArrayBuffer(concat(fragments, messageLength));
1405
- } else {
1406
- data = fragments;
1407
- }
1408
-
1409
- this.emit('message', data, true);
1410
- } else {
1411
- const buf = concat(fragments, messageLength);
1412
-
1413
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1414
- this._loop = false;
1415
- return error(
1416
- Error,
1417
- 'invalid UTF-8 sequence',
1418
- true,
1419
- 1007,
1420
- 'WS_ERR_INVALID_UTF8'
1421
- );
1422
- }
1423
-
1424
- this.emit('message', buf, false);
1425
- }
1426
- }
1427
-
1428
- this._state = WAIT_MICROTASK;
1429
- }
1430
-
1431
- /**
1432
- * Handles a control message.
1433
- *
1434
- * @param {Buffer} data Data to handle
1435
- * @return {(Error|RangeError|undefined)} A possible error
1436
- * @private
1437
- */
1438
- controlMessage(data) {
1439
- if (this._opcode === 0x08) {
1440
- this._loop = false;
1441
-
1442
- if (data.length === 0) {
1443
- this.emit('conclude', 1005, EMPTY_BUFFER$2);
1444
- this.end();
1445
-
1446
- this._state = GET_INFO;
1447
- } else {
1448
- const code = data.readUInt16BE(0);
1449
-
1450
- if (!isValidStatusCode$1(code)) {
1451
- return error(
1452
- RangeError,
1453
- `invalid status code ${code}`,
1454
- true,
1455
- 1002,
1456
- 'WS_ERR_INVALID_CLOSE_CODE'
1457
- );
1458
- }
1459
-
1460
- const buf = new FastBuffer(
1461
- data.buffer,
1462
- data.byteOffset + 2,
1463
- data.length - 2
1464
- );
1465
-
1466
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1467
- return error(
1468
- Error,
1469
- 'invalid UTF-8 sequence',
1470
- true,
1471
- 1007,
1472
- 'WS_ERR_INVALID_UTF8'
1473
- );
1474
- }
1475
-
1476
- this.emit('conclude', code, buf);
1477
- this.end();
1478
-
1479
- this._state = GET_INFO;
1480
- }
1481
- } else if (this._opcode === 0x09) {
1482
- this.emit('ping', data);
1483
- this._state = WAIT_MICROTASK;
1484
- } else {
1485
- this.emit('pong', data);
1486
- this._state = WAIT_MICROTASK;
1487
- }
1488
- }
1489
- };
1490
-
1491
- var receiver = Receiver$1;
1492
-
1493
- /**
1494
- * Builds an error object.
1495
- *
1496
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1497
- * @param {String} message The error message
1498
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1499
- * `message`
1500
- * @param {Number} statusCode The status code
1501
- * @param {String} errorCode The exposed error code
1502
- * @return {(Error|RangeError)} The error
1503
- * @private
1504
- */
1505
- function error(ErrorCtor, message, prefix, statusCode, errorCode) {
1506
- const err = new ErrorCtor(
1507
- prefix ? `Invalid WebSocket frame: ${message}` : message
1508
- );
1509
-
1510
- Error.captureStackTrace(err, error);
1511
- err.code = errorCode;
1512
- err[kStatusCode$1] = statusCode;
1513
- return err;
1514
- }
1515
-
1516
- /**
1517
- * A shim for `queueMicrotask()`.
1518
- *
1519
- * @param {Function} cb Callback
1520
- */
1521
- function queueMicrotaskShim(cb) {
1522
- promise.then(cb).catch(throwErrorNextTick);
1523
- }
1524
-
1525
- /**
1526
- * Throws an error.
1527
- *
1528
- * @param {Error} err The error to throw
1529
- * @private
1530
- */
1531
- function throwError(err) {
1532
- throw err;
1533
- }
1534
-
1535
- /**
1536
- * Throws an error in the next tick.
1537
- *
1538
- * @param {Error} err The error to throw
1539
- * @private
1540
- */
1541
- function throwErrorNextTick(err) {
1542
- process.nextTick(throwError, err);
1543
- }
1544
-
1545
- /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */
1546
- const { randomFillSync } = require$$1;
1547
-
1548
- const PerMessageDeflate$2 = permessageDeflate;
1549
- const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants;
1550
- const { isValidStatusCode } = validationExports;
1551
- const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtilExports;
1552
-
1553
- const kByteLength = Symbol('kByteLength');
1554
- const maskBuffer = Buffer.alloc(4);
1555
-
1556
- /**
1557
- * HyBi Sender implementation.
1558
- */
1559
- let Sender$1 = class Sender {
1560
- /**
1561
- * Creates a Sender instance.
1562
- *
1563
- * @param {Duplex} socket The connection socket
1564
- * @param {Object} [extensions] An object containing the negotiated extensions
1565
- * @param {Function} [generateMask] The function used to generate the masking
1566
- * key
1567
- */
1568
- constructor(socket, extensions, generateMask) {
1569
- this._extensions = extensions || {};
1570
-
1571
- if (generateMask) {
1572
- this._generateMask = generateMask;
1573
- this._maskBuffer = Buffer.alloc(4);
1574
- }
1575
-
1576
- this._socket = socket;
1577
-
1578
- this._firstFragment = true;
1579
- this._compress = false;
1580
-
1581
- this._bufferedBytes = 0;
1582
- this._deflating = false;
1583
- this._queue = [];
1584
- }
1585
-
1586
- /**
1587
- * Frames a piece of data according to the HyBi WebSocket protocol.
1588
- *
1589
- * @param {(Buffer|String)} data The data to frame
1590
- * @param {Object} options Options object
1591
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1592
- * FIN bit
1593
- * @param {Function} [options.generateMask] The function used to generate the
1594
- * masking key
1595
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1596
- * `data`
1597
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1598
- * key
1599
- * @param {Number} options.opcode The opcode
1600
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1601
- * modified
1602
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1603
- * RSV1 bit
1604
- * @return {(Buffer|String)[]} The framed data
1605
- * @public
1606
- */
1607
- static frame(data, options) {
1608
- let mask;
1609
- let merge = false;
1610
- let offset = 2;
1611
- let skipMasking = false;
1612
-
1613
- if (options.mask) {
1614
- mask = options.maskBuffer || maskBuffer;
1615
-
1616
- if (options.generateMask) {
1617
- options.generateMask(mask);
1618
- } else {
1619
- randomFillSync(mask, 0, 4);
1620
- }
1621
-
1622
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1623
- offset = 6;
1624
- }
1625
-
1626
- let dataLength;
1627
-
1628
- if (typeof data === 'string') {
1629
- if (
1630
- (!options.mask || skipMasking) &&
1631
- options[kByteLength] !== undefined
1632
- ) {
1633
- dataLength = options[kByteLength];
1634
- } else {
1635
- data = Buffer.from(data);
1636
- dataLength = data.length;
1637
- }
1638
- } else {
1639
- dataLength = data.length;
1640
- merge = options.mask && options.readOnly && !skipMasking;
1641
- }
1642
-
1643
- let payloadLength = dataLength;
1644
-
1645
- if (dataLength >= 65536) {
1646
- offset += 8;
1647
- payloadLength = 127;
1648
- } else if (dataLength > 125) {
1649
- offset += 2;
1650
- payloadLength = 126;
1651
- }
1652
-
1653
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1654
-
1655
- target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
1656
- if (options.rsv1) target[0] |= 0x40;
1657
-
1658
- target[1] = payloadLength;
1659
-
1660
- if (payloadLength === 126) {
1661
- target.writeUInt16BE(dataLength, 2);
1662
- } else if (payloadLength === 127) {
1663
- target[2] = target[3] = 0;
1664
- target.writeUIntBE(dataLength, 4, 6);
1665
- }
1666
-
1667
- if (!options.mask) return [target, data];
1668
-
1669
- target[1] |= 0x80;
1670
- target[offset - 4] = mask[0];
1671
- target[offset - 3] = mask[1];
1672
- target[offset - 2] = mask[2];
1673
- target[offset - 1] = mask[3];
1674
-
1675
- if (skipMasking) return [target, data];
1676
-
1677
- if (merge) {
1678
- applyMask(data, mask, target, offset, dataLength);
1679
- return [target];
1680
- }
1681
-
1682
- applyMask(data, mask, data, 0, dataLength);
1683
- return [target, data];
1684
- }
1685
-
1686
- /**
1687
- * Sends a close message to the other peer.
1688
- *
1689
- * @param {Number} [code] The status code component of the body
1690
- * @param {(String|Buffer)} [data] The message component of the body
1691
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1692
- * @param {Function} [cb] Callback
1693
- * @public
1694
- */
1695
- close(code, data, mask, cb) {
1696
- let buf;
1697
-
1698
- if (code === undefined) {
1699
- buf = EMPTY_BUFFER$1;
1700
- } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
1701
- throw new TypeError('First argument must be a valid error code number');
1702
- } else if (data === undefined || !data.length) {
1703
- buf = Buffer.allocUnsafe(2);
1704
- buf.writeUInt16BE(code, 0);
1705
- } else {
1706
- const length = Buffer.byteLength(data);
1707
-
1708
- if (length > 123) {
1709
- throw new RangeError('The message must not be greater than 123 bytes');
1710
- }
1711
-
1712
- buf = Buffer.allocUnsafe(2 + length);
1713
- buf.writeUInt16BE(code, 0);
1714
-
1715
- if (typeof data === 'string') {
1716
- buf.write(data, 2);
1717
- } else {
1718
- buf.set(data, 2);
1719
- }
1720
- }
1721
-
1722
- const options = {
1723
- [kByteLength]: buf.length,
1724
- fin: true,
1725
- generateMask: this._generateMask,
1726
- mask,
1727
- maskBuffer: this._maskBuffer,
1728
- opcode: 0x08,
1729
- readOnly: false,
1730
- rsv1: false
1731
- };
1732
-
1733
- if (this._deflating) {
1734
- this.enqueue([this.dispatch, buf, false, options, cb]);
1735
- } else {
1736
- this.sendFrame(Sender.frame(buf, options), cb);
1737
- }
1738
- }
1739
-
1740
- /**
1741
- * Sends a ping message to the other peer.
1742
- *
1743
- * @param {*} data The message to send
1744
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1745
- * @param {Function} [cb] Callback
1746
- * @public
1747
- */
1748
- ping(data, mask, cb) {
1749
- let byteLength;
1750
- let readOnly;
1751
-
1752
- if (typeof data === 'string') {
1753
- byteLength = Buffer.byteLength(data);
1754
- readOnly = false;
1755
- } else {
1756
- data = toBuffer$1(data);
1757
- byteLength = data.length;
1758
- readOnly = toBuffer$1.readOnly;
1759
- }
1760
-
1761
- if (byteLength > 125) {
1762
- throw new RangeError('The data size must not be greater than 125 bytes');
1763
- }
1764
-
1765
- const options = {
1766
- [kByteLength]: byteLength,
1767
- fin: true,
1768
- generateMask: this._generateMask,
1769
- mask,
1770
- maskBuffer: this._maskBuffer,
1771
- opcode: 0x09,
1772
- readOnly,
1773
- rsv1: false
1774
- };
1775
-
1776
- if (this._deflating) {
1777
- this.enqueue([this.dispatch, data, false, options, cb]);
1778
- } else {
1779
- this.sendFrame(Sender.frame(data, options), cb);
1780
- }
1781
- }
1782
-
1783
- /**
1784
- * Sends a pong message to the other peer.
1785
- *
1786
- * @param {*} data The message to send
1787
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1788
- * @param {Function} [cb] Callback
1789
- * @public
1790
- */
1791
- pong(data, mask, cb) {
1792
- let byteLength;
1793
- let readOnly;
1794
-
1795
- if (typeof data === 'string') {
1796
- byteLength = Buffer.byteLength(data);
1797
- readOnly = false;
1798
- } else {
1799
- data = toBuffer$1(data);
1800
- byteLength = data.length;
1801
- readOnly = toBuffer$1.readOnly;
1802
- }
1803
-
1804
- if (byteLength > 125) {
1805
- throw new RangeError('The data size must not be greater than 125 bytes');
1806
- }
1807
-
1808
- const options = {
1809
- [kByteLength]: byteLength,
1810
- fin: true,
1811
- generateMask: this._generateMask,
1812
- mask,
1813
- maskBuffer: this._maskBuffer,
1814
- opcode: 0x0a,
1815
- readOnly,
1816
- rsv1: false
1817
- };
1818
-
1819
- if (this._deflating) {
1820
- this.enqueue([this.dispatch, data, false, options, cb]);
1821
- } else {
1822
- this.sendFrame(Sender.frame(data, options), cb);
1823
- }
1824
- }
1825
-
1826
- /**
1827
- * Sends a data message to the other peer.
1828
- *
1829
- * @param {*} data The message to send
1830
- * @param {Object} options Options object
1831
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1832
- * or text
1833
- * @param {Boolean} [options.compress=false] Specifies whether or not to
1834
- * compress `data`
1835
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1836
- * last one
1837
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1838
- * `data`
1839
- * @param {Function} [cb] Callback
1840
- * @public
1841
- */
1842
- send(data, options, cb) {
1843
- const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
1844
- let opcode = options.binary ? 2 : 1;
1845
- let rsv1 = options.compress;
1846
-
1847
- let byteLength;
1848
- let readOnly;
1849
-
1850
- if (typeof data === 'string') {
1851
- byteLength = Buffer.byteLength(data);
1852
- readOnly = false;
1853
- } else {
1854
- data = toBuffer$1(data);
1855
- byteLength = data.length;
1856
- readOnly = toBuffer$1.readOnly;
1857
- }
1858
-
1859
- if (this._firstFragment) {
1860
- this._firstFragment = false;
1861
- if (
1862
- rsv1 &&
1863
- perMessageDeflate &&
1864
- perMessageDeflate.params[
1865
- perMessageDeflate._isServer
1866
- ? 'server_no_context_takeover'
1867
- : 'client_no_context_takeover'
1868
- ]
1869
- ) {
1870
- rsv1 = byteLength >= perMessageDeflate._threshold;
1871
- }
1872
- this._compress = rsv1;
1873
- } else {
1874
- rsv1 = false;
1875
- opcode = 0;
1876
- }
1877
-
1878
- if (options.fin) this._firstFragment = true;
1879
-
1880
- if (perMessageDeflate) {
1881
- const opts = {
1882
- [kByteLength]: byteLength,
1883
- fin: options.fin,
1884
- generateMask: this._generateMask,
1885
- mask: options.mask,
1886
- maskBuffer: this._maskBuffer,
1887
- opcode,
1888
- readOnly,
1889
- rsv1
1890
- };
1891
-
1892
- if (this._deflating) {
1893
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1894
- } else {
1895
- this.dispatch(data, this._compress, opts, cb);
1896
- }
1897
- } else {
1898
- this.sendFrame(
1899
- Sender.frame(data, {
1900
- [kByteLength]: byteLength,
1901
- fin: options.fin,
1902
- generateMask: this._generateMask,
1903
- mask: options.mask,
1904
- maskBuffer: this._maskBuffer,
1905
- opcode,
1906
- readOnly,
1907
- rsv1: false
1908
- }),
1909
- cb
1910
- );
1911
- }
1912
- }
1913
-
1914
- /**
1915
- * Dispatches a message.
1916
- *
1917
- * @param {(Buffer|String)} data The message to send
1918
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1919
- * `data`
1920
- * @param {Object} options Options object
1921
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1922
- * FIN bit
1923
- * @param {Function} [options.generateMask] The function used to generate the
1924
- * masking key
1925
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1926
- * `data`
1927
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1928
- * key
1929
- * @param {Number} options.opcode The opcode
1930
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1931
- * modified
1932
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1933
- * RSV1 bit
1934
- * @param {Function} [cb] Callback
1935
- * @private
1936
- */
1937
- dispatch(data, compress, options, cb) {
1938
- if (!compress) {
1939
- this.sendFrame(Sender.frame(data, options), cb);
1940
- return;
1941
- }
1942
-
1943
- const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
1944
-
1945
- this._bufferedBytes += options[kByteLength];
1946
- this._deflating = true;
1947
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1948
- if (this._socket.destroyed) {
1949
- const err = new Error(
1950
- 'The socket was closed while data was being compressed'
1951
- );
1952
-
1953
- if (typeof cb === 'function') cb(err);
1954
-
1955
- for (let i = 0; i < this._queue.length; i++) {
1956
- const params = this._queue[i];
1957
- const callback = params[params.length - 1];
1958
-
1959
- if (typeof callback === 'function') callback(err);
1960
- }
1961
-
1962
- return;
1963
- }
1964
-
1965
- this._bufferedBytes -= options[kByteLength];
1966
- this._deflating = false;
1967
- options.readOnly = false;
1968
- this.sendFrame(Sender.frame(buf, options), cb);
1969
- this.dequeue();
1970
- });
1971
- }
1972
-
1973
- /**
1974
- * Executes queued send operations.
1975
- *
1976
- * @private
1977
- */
1978
- dequeue() {
1979
- while (!this._deflating && this._queue.length) {
1980
- const params = this._queue.shift();
1981
-
1982
- this._bufferedBytes -= params[3][kByteLength];
1983
- Reflect.apply(params[0], this, params.slice(1));
1984
- }
1985
- }
1986
-
1987
- /**
1988
- * Enqueues a send operation.
1989
- *
1990
- * @param {Array} params Send operation parameters.
1991
- * @private
1992
- */
1993
- enqueue(params) {
1994
- this._bufferedBytes += params[3][kByteLength];
1995
- this._queue.push(params);
1996
- }
1997
-
1998
- /**
1999
- * Sends a frame.
2000
- *
2001
- * @param {Buffer[]} list The frame to send
2002
- * @param {Function} [cb] Callback
2003
- * @private
2004
- */
2005
- sendFrame(list, cb) {
2006
- if (list.length === 2) {
2007
- this._socket.cork();
2008
- this._socket.write(list[0]);
2009
- this._socket.write(list[1], cb);
2010
- this._socket.uncork();
2011
- } else {
2012
- this._socket.write(list[0], cb);
2013
- }
2014
- }
2015
- };
2016
-
2017
- var sender = Sender$1;
2018
-
2019
- const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants;
2020
-
2021
- const kCode = Symbol('kCode');
2022
- const kData = Symbol('kData');
2023
- const kError = Symbol('kError');
2024
- const kMessage = Symbol('kMessage');
2025
- const kReason = Symbol('kReason');
2026
- const kTarget = Symbol('kTarget');
2027
- const kType = Symbol('kType');
2028
- const kWasClean = Symbol('kWasClean');
2029
-
2030
- /**
2031
- * Class representing an event.
2032
- */
2033
- class Event {
2034
- /**
2035
- * Create a new `Event`.
2036
- *
2037
- * @param {String} type The name of the event
2038
- * @throws {TypeError} If the `type` argument is not specified
2039
- */
2040
- constructor(type) {
2041
- this[kTarget] = null;
2042
- this[kType] = type;
2043
- }
2044
-
2045
- /**
2046
- * @type {*}
2047
- */
2048
- get target() {
2049
- return this[kTarget];
2050
- }
2051
-
2052
- /**
2053
- * @type {String}
2054
- */
2055
- get type() {
2056
- return this[kType];
2057
- }
2058
- }
2059
-
2060
- Object.defineProperty(Event.prototype, 'target', { enumerable: true });
2061
- Object.defineProperty(Event.prototype, 'type', { enumerable: true });
2062
-
2063
- /**
2064
- * Class representing a close event.
2065
- *
2066
- * @extends Event
2067
- */
2068
- class CloseEvent extends Event {
2069
- /**
2070
- * Create a new `CloseEvent`.
2071
- *
2072
- * @param {String} type The name of the event
2073
- * @param {Object} [options] A dictionary object that allows for setting
2074
- * attributes via object members of the same name
2075
- * @param {Number} [options.code=0] The status code explaining why the
2076
- * connection was closed
2077
- * @param {String} [options.reason=''] A human-readable string explaining why
2078
- * the connection was closed
2079
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
2080
- * connection was cleanly closed
2081
- */
2082
- constructor(type, options = {}) {
2083
- super(type);
2084
-
2085
- this[kCode] = options.code === undefined ? 0 : options.code;
2086
- this[kReason] = options.reason === undefined ? '' : options.reason;
2087
- this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
2088
- }
2089
-
2090
- /**
2091
- * @type {Number}
2092
- */
2093
- get code() {
2094
- return this[kCode];
2095
- }
2096
-
2097
- /**
2098
- * @type {String}
2099
- */
2100
- get reason() {
2101
- return this[kReason];
2102
- }
2103
-
2104
- /**
2105
- * @type {Boolean}
2106
- */
2107
- get wasClean() {
2108
- return this[kWasClean];
2109
- }
2110
- }
2111
-
2112
- Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
2113
- Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
2114
- Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
2115
-
2116
- /**
2117
- * Class representing an error event.
2118
- *
2119
- * @extends Event
2120
- */
2121
- class ErrorEvent extends Event {
2122
- /**
2123
- * Create a new `ErrorEvent`.
2124
- *
2125
- * @param {String} type The name of the event
2126
- * @param {Object} [options] A dictionary object that allows for setting
2127
- * attributes via object members of the same name
2128
- * @param {*} [options.error=null] The error that generated this event
2129
- * @param {String} [options.message=''] The error message
2130
- */
2131
- constructor(type, options = {}) {
2132
- super(type);
2133
-
2134
- this[kError] = options.error === undefined ? null : options.error;
2135
- this[kMessage] = options.message === undefined ? '' : options.message;
2136
- }
2137
-
2138
- /**
2139
- * @type {*}
2140
- */
2141
- get error() {
2142
- return this[kError];
2143
- }
2144
-
2145
- /**
2146
- * @type {String}
2147
- */
2148
- get message() {
2149
- return this[kMessage];
2150
- }
2151
- }
2152
-
2153
- Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
2154
- Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
2155
-
2156
- /**
2157
- * Class representing a message event.
2158
- *
2159
- * @extends Event
2160
- */
2161
- class MessageEvent extends Event {
2162
- /**
2163
- * Create a new `MessageEvent`.
2164
- *
2165
- * @param {String} type The name of the event
2166
- * @param {Object} [options] A dictionary object that allows for setting
2167
- * attributes via object members of the same name
2168
- * @param {*} [options.data=null] The message content
2169
- */
2170
- constructor(type, options = {}) {
2171
- super(type);
2172
-
2173
- this[kData] = options.data === undefined ? null : options.data;
2174
- }
2175
-
2176
- /**
2177
- * @type {*}
2178
- */
2179
- get data() {
2180
- return this[kData];
2181
- }
2182
- }
2183
-
2184
- Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
2185
-
2186
- /**
2187
- * This provides methods for emulating the `EventTarget` interface. It's not
2188
- * meant to be used directly.
2189
- *
2190
- * @mixin
2191
- */
2192
- const EventTarget = {
2193
- /**
2194
- * Register an event listener.
2195
- *
2196
- * @param {String} type A string representing the event type to listen for
2197
- * @param {(Function|Object)} handler The listener to add
2198
- * @param {Object} [options] An options object specifies characteristics about
2199
- * the event listener
2200
- * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2201
- * listener should be invoked at most once after being added. If `true`,
2202
- * the listener would be automatically removed when invoked.
2203
- * @public
2204
- */
2205
- addEventListener(type, handler, options = {}) {
2206
- for (const listener of this.listeners(type)) {
2207
- if (
2208
- !options[kForOnEventAttribute$1] &&
2209
- listener[kListener$1] === handler &&
2210
- !listener[kForOnEventAttribute$1]
2211
- ) {
2212
- return;
2213
- }
2214
- }
2215
-
2216
- let wrapper;
2217
-
2218
- if (type === 'message') {
2219
- wrapper = function onMessage(data, isBinary) {
2220
- const event = new MessageEvent('message', {
2221
- data: isBinary ? data : data.toString()
2222
- });
2223
-
2224
- event[kTarget] = this;
2225
- callListener(handler, this, event);
2226
- };
2227
- } else if (type === 'close') {
2228
- wrapper = function onClose(code, message) {
2229
- const event = new CloseEvent('close', {
2230
- code,
2231
- reason: message.toString(),
2232
- wasClean: this._closeFrameReceived && this._closeFrameSent
2233
- });
2234
-
2235
- event[kTarget] = this;
2236
- callListener(handler, this, event);
2237
- };
2238
- } else if (type === 'error') {
2239
- wrapper = function onError(error) {
2240
- const event = new ErrorEvent('error', {
2241
- error,
2242
- message: error.message
2243
- });
2244
-
2245
- event[kTarget] = this;
2246
- callListener(handler, this, event);
2247
- };
2248
- } else if (type === 'open') {
2249
- wrapper = function onOpen() {
2250
- const event = new Event('open');
2251
-
2252
- event[kTarget] = this;
2253
- callListener(handler, this, event);
2254
- };
2255
- } else {
2256
- return;
2257
- }
2258
-
2259
- wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1];
2260
- wrapper[kListener$1] = handler;
2261
-
2262
- if (options.once) {
2263
- this.once(type, wrapper);
2264
- } else {
2265
- this.on(type, wrapper);
2266
- }
2267
- },
2268
-
2269
- /**
2270
- * Remove an event listener.
2271
- *
2272
- * @param {String} type A string representing the event type to remove
2273
- * @param {(Function|Object)} handler The listener to remove
2274
- * @public
2275
- */
2276
- removeEventListener(type, handler) {
2277
- for (const listener of this.listeners(type)) {
2278
- if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) {
2279
- this.removeListener(type, listener);
2280
- break;
2281
- }
2282
- }
2283
- }
2284
- };
2285
-
2286
- var eventTarget = {
2287
- CloseEvent,
2288
- ErrorEvent,
2289
- Event,
2290
- EventTarget,
2291
- MessageEvent
2292
- };
2293
-
2294
- /**
2295
- * Call an event listener
2296
- *
2297
- * @param {(Function|Object)} listener The listener to call
2298
- * @param {*} thisArg The value to use as `this`` when calling the listener
2299
- * @param {Event} event The event to pass to the listener
2300
- * @private
2301
- */
2302
- function callListener(listener, thisArg, event) {
2303
- if (typeof listener === 'object' && listener.handleEvent) {
2304
- listener.handleEvent.call(listener, event);
2305
- } else {
2306
- listener.call(thisArg, event);
2307
- }
2308
- }
2309
-
2310
- const { tokenChars: tokenChars$1 } = validationExports;
2311
-
2312
- /**
2313
- * Adds an offer to the map of extension offers or a parameter to the map of
2314
- * parameters.
2315
- *
2316
- * @param {Object} dest The map of extension offers or parameters
2317
- * @param {String} name The extension or parameter name
2318
- * @param {(Object|Boolean|String)} elem The extension parameters or the
2319
- * parameter value
2320
- * @private
2321
- */
2322
- function push(dest, name, elem) {
2323
- if (dest[name] === undefined) dest[name] = [elem];
2324
- else dest[name].push(elem);
2325
- }
2326
-
2327
- /**
2328
- * Parses the `Sec-WebSocket-Extensions` header into an object.
2329
- *
2330
- * @param {String} header The field value of the header
2331
- * @return {Object} The parsed object
2332
- * @public
2333
- */
2334
- function parse$2(header) {
2335
- const offers = Object.create(null);
2336
- let params = Object.create(null);
2337
- let mustUnescape = false;
2338
- let isEscaping = false;
2339
- let inQuotes = false;
2340
- let extensionName;
2341
- let paramName;
2342
- let start = -1;
2343
- let code = -1;
2344
- let end = -1;
2345
- let i = 0;
2346
-
2347
- for (; i < header.length; i++) {
2348
- code = header.charCodeAt(i);
2349
-
2350
- if (extensionName === undefined) {
2351
- if (end === -1 && tokenChars$1[code] === 1) {
2352
- if (start === -1) start = i;
2353
- } else if (
2354
- i !== 0 &&
2355
- (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
2356
- ) {
2357
- if (end === -1 && start !== -1) end = i;
2358
- } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
2359
- if (start === -1) {
2360
- throw new SyntaxError(`Unexpected character at index ${i}`);
2361
- }
2362
-
2363
- if (end === -1) end = i;
2364
- const name = header.slice(start, end);
2365
- if (code === 0x2c) {
2366
- push(offers, name, params);
2367
- params = Object.create(null);
2368
- } else {
2369
- extensionName = name;
2370
- }
2371
-
2372
- start = end = -1;
2373
- } else {
2374
- throw new SyntaxError(`Unexpected character at index ${i}`);
2375
- }
2376
- } else if (paramName === undefined) {
2377
- if (end === -1 && tokenChars$1[code] === 1) {
2378
- if (start === -1) start = i;
2379
- } else if (code === 0x20 || code === 0x09) {
2380
- if (end === -1 && start !== -1) end = i;
2381
- } else if (code === 0x3b || code === 0x2c) {
2382
- if (start === -1) {
2383
- throw new SyntaxError(`Unexpected character at index ${i}`);
2384
- }
2385
-
2386
- if (end === -1) end = i;
2387
- push(params, header.slice(start, end), true);
2388
- if (code === 0x2c) {
2389
- push(offers, extensionName, params);
2390
- params = Object.create(null);
2391
- extensionName = undefined;
2392
- }
2393
-
2394
- start = end = -1;
2395
- } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
2396
- paramName = header.slice(start, i);
2397
- start = end = -1;
2398
- } else {
2399
- throw new SyntaxError(`Unexpected character at index ${i}`);
2400
- }
2401
- } else {
2402
- //
2403
- // The value of a quoted-string after unescaping must conform to the
2404
- // token ABNF, so only token characters are valid.
2405
- // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
2406
- //
2407
- if (isEscaping) {
2408
- if (tokenChars$1[code] !== 1) {
2409
- throw new SyntaxError(`Unexpected character at index ${i}`);
2410
- }
2411
- if (start === -1) start = i;
2412
- else if (!mustUnescape) mustUnescape = true;
2413
- isEscaping = false;
2414
- } else if (inQuotes) {
2415
- if (tokenChars$1[code] === 1) {
2416
- if (start === -1) start = i;
2417
- } else if (code === 0x22 /* '"' */ && start !== -1) {
2418
- inQuotes = false;
2419
- end = i;
2420
- } else if (code === 0x5c /* '\' */) {
2421
- isEscaping = true;
2422
- } else {
2423
- throw new SyntaxError(`Unexpected character at index ${i}`);
2424
- }
2425
- } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
2426
- inQuotes = true;
2427
- } else if (end === -1 && tokenChars$1[code] === 1) {
2428
- if (start === -1) start = i;
2429
- } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
2430
- if (end === -1) end = i;
2431
- } else if (code === 0x3b || code === 0x2c) {
2432
- if (start === -1) {
2433
- throw new SyntaxError(`Unexpected character at index ${i}`);
2434
- }
2435
-
2436
- if (end === -1) end = i;
2437
- let value = header.slice(start, end);
2438
- if (mustUnescape) {
2439
- value = value.replace(/\\/g, '');
2440
- mustUnescape = false;
2441
- }
2442
- push(params, paramName, value);
2443
- if (code === 0x2c) {
2444
- push(offers, extensionName, params);
2445
- params = Object.create(null);
2446
- extensionName = undefined;
2447
- }
2448
-
2449
- paramName = undefined;
2450
- start = end = -1;
2451
- } else {
2452
- throw new SyntaxError(`Unexpected character at index ${i}`);
2453
- }
2454
- }
2455
- }
2456
-
2457
- if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
2458
- throw new SyntaxError('Unexpected end of input');
2459
- }
2460
-
2461
- if (end === -1) end = i;
2462
- const token = header.slice(start, end);
2463
- if (extensionName === undefined) {
2464
- push(offers, token, params);
2465
- } else {
2466
- if (paramName === undefined) {
2467
- push(params, token, true);
2468
- } else if (mustUnescape) {
2469
- push(params, paramName, token.replace(/\\/g, ''));
2470
- } else {
2471
- push(params, paramName, token);
2472
- }
2473
- push(offers, extensionName, params);
2474
- }
2475
-
2476
- return offers;
2477
- }
2478
-
2479
- /**
2480
- * Builds the `Sec-WebSocket-Extensions` header field value.
2481
- *
2482
- * @param {Object} extensions The map of extensions and parameters to format
2483
- * @return {String} A string representing the given object
2484
- * @public
2485
- */
2486
- function format$1(extensions) {
2487
- return Object.keys(extensions)
2488
- .map((extension) => {
2489
- let configurations = extensions[extension];
2490
- if (!Array.isArray(configurations)) configurations = [configurations];
2491
- return configurations
2492
- .map((params) => {
2493
- return [extension]
2494
- .concat(
2495
- Object.keys(params).map((k) => {
2496
- let values = params[k];
2497
- if (!Array.isArray(values)) values = [values];
2498
- return values
2499
- .map((v) => (v === true ? k : `${k}=${v}`))
2500
- .join('; ');
2501
- })
2502
- )
2503
- .join('; ');
2504
- })
2505
- .join(', ');
2506
- })
2507
- .join(', ');
2508
- }
2509
-
2510
- var extension$1 = { format: format$1, parse: parse$2 };
2511
-
2512
- /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$" }] */
2513
-
2514
- const EventEmitter$1 = require$$0$3;
2515
- const https = require$$1$1;
2516
- const http$1 = require$$2;
2517
- const net = require$$3;
2518
- const tls = require$$4;
2519
- const { randomBytes, createHash: createHash$1 } = require$$1;
2520
- const { URL } = require$$7;
2521
-
2522
- const PerMessageDeflate$1 = permessageDeflate;
2523
- const Receiver = receiver;
2524
- const Sender = sender;
2525
- const {
2526
- BINARY_TYPES,
2527
- EMPTY_BUFFER,
2528
- GUID: GUID$1,
2529
- kForOnEventAttribute,
2530
- kListener,
2531
- kStatusCode,
2532
- kWebSocket: kWebSocket$1,
2533
- NOOP
2534
- } = constants;
2535
- const {
2536
- EventTarget: { addEventListener, removeEventListener }
2537
- } = eventTarget;
2538
- const { format, parse: parse$1 } = extension$1;
2539
- const { toBuffer } = bufferUtilExports;
2540
-
2541
- const closeTimeout = 30 * 1000;
2542
- const kAborted = Symbol('kAborted');
2543
- const protocolVersions = [8, 13];
2544
- const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
2545
- const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2546
-
2547
- /**
2548
- * Class representing a WebSocket.
2549
- *
2550
- * @extends EventEmitter
2551
- */
2552
- let WebSocket$2 = class WebSocket extends EventEmitter$1 {
2553
- /**
2554
- * Create a new `WebSocket`.
2555
- *
2556
- * @param {(String|URL)} address The URL to which to connect
2557
- * @param {(String|String[])} [protocols] The subprotocols
2558
- * @param {Object} [options] Connection options
2559
- */
2560
- constructor(address, protocols, options) {
2561
- super();
2562
-
2563
- this._binaryType = BINARY_TYPES[0];
2564
- this._closeCode = 1006;
2565
- this._closeFrameReceived = false;
2566
- this._closeFrameSent = false;
2567
- this._closeMessage = EMPTY_BUFFER;
2568
- this._closeTimer = null;
2569
- this._extensions = {};
2570
- this._paused = false;
2571
- this._protocol = '';
2572
- this._readyState = WebSocket.CONNECTING;
2573
- this._receiver = null;
2574
- this._sender = null;
2575
- this._socket = null;
2576
-
2577
- if (address !== null) {
2578
- this._bufferedAmount = 0;
2579
- this._isServer = false;
2580
- this._redirects = 0;
2581
-
2582
- if (protocols === undefined) {
2583
- protocols = [];
2584
- } else if (!Array.isArray(protocols)) {
2585
- if (typeof protocols === 'object' && protocols !== null) {
2586
- options = protocols;
2587
- protocols = [];
2588
- } else {
2589
- protocols = [protocols];
2590
- }
2591
- }
2592
-
2593
- initAsClient(this, address, protocols, options);
2594
- } else {
2595
- this._isServer = true;
2596
- }
2597
- }
2598
-
2599
- /**
2600
- * This deviates from the WHATWG interface since ws doesn't support the
2601
- * required default "blob" type (instead we define a custom "nodebuffer"
2602
- * type).
2603
- *
2604
- * @type {String}
2605
- */
2606
- get binaryType() {
2607
- return this._binaryType;
2608
- }
2609
-
2610
- set binaryType(type) {
2611
- if (!BINARY_TYPES.includes(type)) return;
2612
-
2613
- this._binaryType = type;
2614
-
2615
- //
2616
- // Allow to change `binaryType` on the fly.
2617
- //
2618
- if (this._receiver) this._receiver._binaryType = type;
2619
- }
2620
-
2621
- /**
2622
- * @type {Number}
2623
- */
2624
- get bufferedAmount() {
2625
- if (!this._socket) return this._bufferedAmount;
2626
-
2627
- return this._socket._writableState.length + this._sender._bufferedBytes;
2628
- }
2629
-
2630
- /**
2631
- * @type {String}
2632
- */
2633
- get extensions() {
2634
- return Object.keys(this._extensions).join();
2635
- }
2636
-
2637
- /**
2638
- * @type {Boolean}
2639
- */
2640
- get isPaused() {
2641
- return this._paused;
2642
- }
2643
-
2644
- /**
2645
- * @type {Function}
2646
- */
2647
- /* istanbul ignore next */
2648
- get onclose() {
2649
- return null;
2650
- }
2651
-
2652
- /**
2653
- * @type {Function}
2654
- */
2655
- /* istanbul ignore next */
2656
- get onerror() {
2657
- return null;
2658
- }
2659
-
2660
- /**
2661
- * @type {Function}
2662
- */
2663
- /* istanbul ignore next */
2664
- get onopen() {
2665
- return null;
2666
- }
2667
-
2668
- /**
2669
- * @type {Function}
2670
- */
2671
- /* istanbul ignore next */
2672
- get onmessage() {
2673
- return null;
2674
- }
2675
-
2676
- /**
2677
- * @type {String}
2678
- */
2679
- get protocol() {
2680
- return this._protocol;
2681
- }
2682
-
2683
- /**
2684
- * @type {Number}
2685
- */
2686
- get readyState() {
2687
- return this._readyState;
2688
- }
2689
-
2690
- /**
2691
- * @type {String}
2692
- */
2693
- get url() {
2694
- return this._url;
2695
- }
2696
-
2697
- /**
2698
- * Set up the socket and the internal resources.
2699
- *
2700
- * @param {Duplex} socket The network socket between the server and client
2701
- * @param {Buffer} head The first packet of the upgraded stream
2702
- * @param {Object} options Options object
2703
- * @param {Function} [options.generateMask] The function used to generate the
2704
- * masking key
2705
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
2706
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2707
- * not to skip UTF-8 validation for text and close messages
2708
- * @private
2709
- */
2710
- setSocket(socket, head, options) {
2711
- const receiver = new Receiver({
2712
- binaryType: this.binaryType,
2713
- extensions: this._extensions,
2714
- isServer: this._isServer,
2715
- maxPayload: options.maxPayload,
2716
- skipUTF8Validation: options.skipUTF8Validation
2717
- });
2718
-
2719
- this._sender = new Sender(socket, this._extensions, options.generateMask);
2720
- this._receiver = receiver;
2721
- this._socket = socket;
2722
-
2723
- receiver[kWebSocket$1] = this;
2724
- socket[kWebSocket$1] = this;
2725
-
2726
- receiver.on('conclude', receiverOnConclude);
2727
- receiver.on('drain', receiverOnDrain);
2728
- receiver.on('error', receiverOnError);
2729
- receiver.on('message', receiverOnMessage);
2730
- receiver.on('ping', receiverOnPing);
2731
- receiver.on('pong', receiverOnPong);
2732
-
2733
- //
2734
- // These methods may not be available if `socket` is just a `Duplex`.
2735
- //
2736
- if (socket.setTimeout) socket.setTimeout(0);
2737
- if (socket.setNoDelay) socket.setNoDelay();
2738
-
2739
- if (head.length > 0) socket.unshift(head);
2740
-
2741
- socket.on('close', socketOnClose);
2742
- socket.on('data', socketOnData);
2743
- socket.on('end', socketOnEnd);
2744
- socket.on('error', socketOnError$1);
2745
-
2746
- this._readyState = WebSocket.OPEN;
2747
- this.emit('open');
2748
- }
2749
-
2750
- /**
2751
- * Emit the `'close'` event.
2752
- *
2753
- * @private
2754
- */
2755
- emitClose() {
2756
- if (!this._socket) {
2757
- this._readyState = WebSocket.CLOSED;
2758
- this.emit('close', this._closeCode, this._closeMessage);
2759
- return;
2760
- }
2761
-
2762
- if (this._extensions[PerMessageDeflate$1.extensionName]) {
2763
- this._extensions[PerMessageDeflate$1.extensionName].cleanup();
2764
- }
2765
-
2766
- this._receiver.removeAllListeners();
2767
- this._readyState = WebSocket.CLOSED;
2768
- this.emit('close', this._closeCode, this._closeMessage);
2769
- }
2770
-
2771
- /**
2772
- * Start a closing handshake.
2773
- *
2774
- * +----------+ +-----------+ +----------+
2775
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2776
- * | +----------+ +-----------+ +----------+ |
2777
- * +----------+ +-----------+ |
2778
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2779
- * +----------+ +-----------+ |
2780
- * | | | +---+ |
2781
- * +------------------------+-->|fin| - - - -
2782
- * | +---+ | +---+
2783
- * - - - - -|fin|<---------------------+
2784
- * +---+
2785
- *
2786
- * @param {Number} [code] Status code explaining why the connection is closing
2787
- * @param {(String|Buffer)} [data] The reason why the connection is
2788
- * closing
2789
- * @public
2790
- */
2791
- close(code, data) {
2792
- if (this.readyState === WebSocket.CLOSED) return;
2793
- if (this.readyState === WebSocket.CONNECTING) {
2794
- const msg = 'WebSocket was closed before the connection was established';
2795
- abortHandshake$1(this, this._req, msg);
2796
- return;
2797
- }
2798
-
2799
- if (this.readyState === WebSocket.CLOSING) {
2800
- if (
2801
- this._closeFrameSent &&
2802
- (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
2803
- ) {
2804
- this._socket.end();
2805
- }
2806
-
2807
- return;
2808
- }
2809
-
2810
- this._readyState = WebSocket.CLOSING;
2811
- this._sender.close(code, data, !this._isServer, (err) => {
2812
- //
2813
- // This error is handled by the `'error'` listener on the socket. We only
2814
- // want to know if the close frame has been sent here.
2815
- //
2816
- if (err) return;
2817
-
2818
- this._closeFrameSent = true;
2819
-
2820
- if (
2821
- this._closeFrameReceived ||
2822
- this._receiver._writableState.errorEmitted
2823
- ) {
2824
- this._socket.end();
2825
- }
2826
- });
2827
-
2828
- //
2829
- // Specify a timeout for the closing handshake to complete.
2830
- //
2831
- this._closeTimer = setTimeout(
2832
- this._socket.destroy.bind(this._socket),
2833
- closeTimeout
2834
- );
2835
- }
2836
-
2837
- /**
2838
- * Pause the socket.
2839
- *
2840
- * @public
2841
- */
2842
- pause() {
2843
- if (
2844
- this.readyState === WebSocket.CONNECTING ||
2845
- this.readyState === WebSocket.CLOSED
2846
- ) {
2847
- return;
2848
- }
2849
-
2850
- this._paused = true;
2851
- this._socket.pause();
2852
- }
2853
-
2854
- /**
2855
- * Send a ping.
2856
- *
2857
- * @param {*} [data] The data to send
2858
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2859
- * @param {Function} [cb] Callback which is executed when the ping is sent
2860
- * @public
2861
- */
2862
- ping(data, mask, cb) {
2863
- if (this.readyState === WebSocket.CONNECTING) {
2864
- throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
2865
- }
2866
-
2867
- if (typeof data === 'function') {
2868
- cb = data;
2869
- data = mask = undefined;
2870
- } else if (typeof mask === 'function') {
2871
- cb = mask;
2872
- mask = undefined;
2873
- }
2874
-
2875
- if (typeof data === 'number') data = data.toString();
2876
-
2877
- if (this.readyState !== WebSocket.OPEN) {
2878
- sendAfterClose(this, data, cb);
2879
- return;
2880
- }
2881
-
2882
- if (mask === undefined) mask = !this._isServer;
2883
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2884
- }
2885
-
2886
- /**
2887
- * Send a pong.
2888
- *
2889
- * @param {*} [data] The data to send
2890
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2891
- * @param {Function} [cb] Callback which is executed when the pong is sent
2892
- * @public
2893
- */
2894
- pong(data, mask, cb) {
2895
- if (this.readyState === WebSocket.CONNECTING) {
2896
- throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
2897
- }
2898
-
2899
- if (typeof data === 'function') {
2900
- cb = data;
2901
- data = mask = undefined;
2902
- } else if (typeof mask === 'function') {
2903
- cb = mask;
2904
- mask = undefined;
2905
- }
2906
-
2907
- if (typeof data === 'number') data = data.toString();
2908
-
2909
- if (this.readyState !== WebSocket.OPEN) {
2910
- sendAfterClose(this, data, cb);
2911
- return;
2912
- }
2913
-
2914
- if (mask === undefined) mask = !this._isServer;
2915
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2916
- }
2917
-
2918
- /**
2919
- * Resume the socket.
2920
- *
2921
- * @public
2922
- */
2923
- resume() {
2924
- if (
2925
- this.readyState === WebSocket.CONNECTING ||
2926
- this.readyState === WebSocket.CLOSED
2927
- ) {
2928
- return;
2929
- }
2930
-
2931
- this._paused = false;
2932
- if (!this._receiver._writableState.needDrain) this._socket.resume();
2933
- }
2934
-
2935
- /**
2936
- * Send a data message.
2937
- *
2938
- * @param {*} data The message to send
2939
- * @param {Object} [options] Options object
2940
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2941
- * text
2942
- * @param {Boolean} [options.compress] Specifies whether or not to compress
2943
- * `data`
2944
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2945
- * last one
2946
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2947
- * @param {Function} [cb] Callback which is executed when data is written out
2948
- * @public
2949
- */
2950
- send(data, options, cb) {
2951
- if (this.readyState === WebSocket.CONNECTING) {
2952
- throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
2953
- }
2954
-
2955
- if (typeof options === 'function') {
2956
- cb = options;
2957
- options = {};
2958
- }
2959
-
2960
- if (typeof data === 'number') data = data.toString();
2961
-
2962
- if (this.readyState !== WebSocket.OPEN) {
2963
- sendAfterClose(this, data, cb);
2964
- return;
2965
- }
2966
-
2967
- const opts = {
2968
- binary: typeof data !== 'string',
2969
- mask: !this._isServer,
2970
- compress: true,
2971
- fin: true,
2972
- ...options
2973
- };
2974
-
2975
- if (!this._extensions[PerMessageDeflate$1.extensionName]) {
2976
- opts.compress = false;
2977
- }
2978
-
2979
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
2980
- }
2981
-
2982
- /**
2983
- * Forcibly close the connection.
2984
- *
2985
- * @public
2986
- */
2987
- terminate() {
2988
- if (this.readyState === WebSocket.CLOSED) return;
2989
- if (this.readyState === WebSocket.CONNECTING) {
2990
- const msg = 'WebSocket was closed before the connection was established';
2991
- abortHandshake$1(this, this._req, msg);
2992
- return;
2993
- }
2994
-
2995
- if (this._socket) {
2996
- this._readyState = WebSocket.CLOSING;
2997
- this._socket.destroy();
2998
- }
2999
- }
3000
- };
3001
-
3002
- /**
3003
- * @constant {Number} CONNECTING
3004
- * @memberof WebSocket
3005
- */
3006
- Object.defineProperty(WebSocket$2, 'CONNECTING', {
3007
- enumerable: true,
3008
- value: readyStates.indexOf('CONNECTING')
3009
- });
3010
-
3011
- /**
3012
- * @constant {Number} CONNECTING
3013
- * @memberof WebSocket.prototype
3014
- */
3015
- Object.defineProperty(WebSocket$2.prototype, 'CONNECTING', {
3016
- enumerable: true,
3017
- value: readyStates.indexOf('CONNECTING')
3018
- });
3019
-
3020
- /**
3021
- * @constant {Number} OPEN
3022
- * @memberof WebSocket
3023
- */
3024
- Object.defineProperty(WebSocket$2, 'OPEN', {
3025
- enumerable: true,
3026
- value: readyStates.indexOf('OPEN')
3027
- });
3028
-
3029
- /**
3030
- * @constant {Number} OPEN
3031
- * @memberof WebSocket.prototype
3032
- */
3033
- Object.defineProperty(WebSocket$2.prototype, 'OPEN', {
3034
- enumerable: true,
3035
- value: readyStates.indexOf('OPEN')
3036
- });
3037
-
3038
- /**
3039
- * @constant {Number} CLOSING
3040
- * @memberof WebSocket
3041
- */
3042
- Object.defineProperty(WebSocket$2, 'CLOSING', {
3043
- enumerable: true,
3044
- value: readyStates.indexOf('CLOSING')
3045
- });
3046
-
3047
- /**
3048
- * @constant {Number} CLOSING
3049
- * @memberof WebSocket.prototype
3050
- */
3051
- Object.defineProperty(WebSocket$2.prototype, 'CLOSING', {
3052
- enumerable: true,
3053
- value: readyStates.indexOf('CLOSING')
3054
- });
3055
-
3056
- /**
3057
- * @constant {Number} CLOSED
3058
- * @memberof WebSocket
3059
- */
3060
- Object.defineProperty(WebSocket$2, 'CLOSED', {
3061
- enumerable: true,
3062
- value: readyStates.indexOf('CLOSED')
3063
- });
3064
-
3065
- /**
3066
- * @constant {Number} CLOSED
3067
- * @memberof WebSocket.prototype
3068
- */
3069
- Object.defineProperty(WebSocket$2.prototype, 'CLOSED', {
3070
- enumerable: true,
3071
- value: readyStates.indexOf('CLOSED')
3072
- });
3073
-
3074
- [
3075
- 'binaryType',
3076
- 'bufferedAmount',
3077
- 'extensions',
3078
- 'isPaused',
3079
- 'protocol',
3080
- 'readyState',
3081
- 'url'
3082
- ].forEach((property) => {
3083
- Object.defineProperty(WebSocket$2.prototype, property, { enumerable: true });
3084
- });
3085
-
3086
- //
3087
- // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
3088
- // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
3089
- //
3090
- ['open', 'error', 'close', 'message'].forEach((method) => {
3091
- Object.defineProperty(WebSocket$2.prototype, `on${method}`, {
3092
- enumerable: true,
3093
- get() {
3094
- for (const listener of this.listeners(method)) {
3095
- if (listener[kForOnEventAttribute]) return listener[kListener];
3096
- }
3097
-
3098
- return null;
3099
- },
3100
- set(handler) {
3101
- for (const listener of this.listeners(method)) {
3102
- if (listener[kForOnEventAttribute]) {
3103
- this.removeListener(method, listener);
3104
- break;
3105
- }
3106
- }
3107
-
3108
- if (typeof handler !== 'function') return;
3109
-
3110
- this.addEventListener(method, handler, {
3111
- [kForOnEventAttribute]: true
3112
- });
3113
- }
3114
- });
3115
- });
3116
-
3117
- WebSocket$2.prototype.addEventListener = addEventListener;
3118
- WebSocket$2.prototype.removeEventListener = removeEventListener;
3119
-
3120
- var websocket = WebSocket$2;
3121
-
3122
- /**
3123
- * Initialize a WebSocket client.
3124
- *
3125
- * @param {WebSocket} websocket The client to initialize
3126
- * @param {(String|URL)} address The URL to which to connect
3127
- * @param {Array} protocols The subprotocols
3128
- * @param {Object} [options] Connection options
3129
- * @param {Boolean} [options.followRedirects=false] Whether or not to follow
3130
- * redirects
3131
- * @param {Function} [options.generateMask] The function used to generate the
3132
- * masking key
3133
- * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
3134
- * handshake request
3135
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3136
- * size
3137
- * @param {Number} [options.maxRedirects=10] The maximum number of redirects
3138
- * allowed
3139
- * @param {String} [options.origin] Value of the `Origin` or
3140
- * `Sec-WebSocket-Origin` header
3141
- * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
3142
- * permessage-deflate
3143
- * @param {Number} [options.protocolVersion=13] Value of the
3144
- * `Sec-WebSocket-Version` header
3145
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3146
- * not to skip UTF-8 validation for text and close messages
3147
- * @private
3148
- */
3149
- function initAsClient(websocket, address, protocols, options) {
3150
- const opts = {
3151
- protocolVersion: protocolVersions[1],
3152
- maxPayload: 100 * 1024 * 1024,
3153
- skipUTF8Validation: false,
3154
- perMessageDeflate: true,
3155
- followRedirects: false,
3156
- maxRedirects: 10,
3157
- ...options,
3158
- createConnection: undefined,
3159
- socketPath: undefined,
3160
- hostname: undefined,
3161
- protocol: undefined,
3162
- timeout: undefined,
3163
- method: 'GET',
3164
- host: undefined,
3165
- path: undefined,
3166
- port: undefined
3167
- };
3168
-
3169
- if (!protocolVersions.includes(opts.protocolVersion)) {
3170
- throw new RangeError(
3171
- `Unsupported protocol version: ${opts.protocolVersion} ` +
3172
- `(supported versions: ${protocolVersions.join(', ')})`
3173
- );
3174
- }
3175
-
3176
- let parsedUrl;
3177
-
3178
- if (address instanceof URL) {
3179
- parsedUrl = address;
3180
- } else {
3181
- try {
3182
- parsedUrl = new URL(address);
3183
- } catch (e) {
3184
- throw new SyntaxError(`Invalid URL: ${address}`);
3185
- }
3186
- }
3187
-
3188
- if (parsedUrl.protocol === 'http:') {
3189
- parsedUrl.protocol = 'ws:';
3190
- } else if (parsedUrl.protocol === 'https:') {
3191
- parsedUrl.protocol = 'wss:';
3192
- }
3193
-
3194
- websocket._url = parsedUrl.href;
3195
-
3196
- const isSecure = parsedUrl.protocol === 'wss:';
3197
- const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
3198
- let invalidUrlMessage;
3199
-
3200
- if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
3201
- invalidUrlMessage =
3202
- 'The URL\'s protocol must be one of "ws:", "wss:", ' +
3203
- '"http:", "https", or "ws+unix:"';
3204
- } else if (isIpcUrl && !parsedUrl.pathname) {
3205
- invalidUrlMessage = "The URL's pathname is empty";
3206
- } else if (parsedUrl.hash) {
3207
- invalidUrlMessage = 'The URL contains a fragment identifier';
3208
- }
3209
-
3210
- if (invalidUrlMessage) {
3211
- const err = new SyntaxError(invalidUrlMessage);
3212
-
3213
- if (websocket._redirects === 0) {
3214
- throw err;
3215
- } else {
3216
- emitErrorAndClose(websocket, err);
3217
- return;
3218
- }
3219
- }
3220
-
3221
- const defaultPort = isSecure ? 443 : 80;
3222
- const key = randomBytes(16).toString('base64');
3223
- const request = isSecure ? https.request : http$1.request;
3224
- const protocolSet = new Set();
3225
- let perMessageDeflate;
3226
-
3227
- opts.createConnection = isSecure ? tlsConnect : netConnect;
3228
- opts.defaultPort = opts.defaultPort || defaultPort;
3229
- opts.port = parsedUrl.port || defaultPort;
3230
- opts.host = parsedUrl.hostname.startsWith('[')
3231
- ? parsedUrl.hostname.slice(1, -1)
3232
- : parsedUrl.hostname;
3233
- opts.headers = {
3234
- ...opts.headers,
3235
- 'Sec-WebSocket-Version': opts.protocolVersion,
3236
- 'Sec-WebSocket-Key': key,
3237
- Connection: 'Upgrade',
3238
- Upgrade: 'websocket'
3239
- };
3240
- opts.path = parsedUrl.pathname + parsedUrl.search;
3241
- opts.timeout = opts.handshakeTimeout;
3242
-
3243
- if (opts.perMessageDeflate) {
3244
- perMessageDeflate = new PerMessageDeflate$1(
3245
- opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
3246
- false,
3247
- opts.maxPayload
3248
- );
3249
- opts.headers['Sec-WebSocket-Extensions'] = format({
3250
- [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer()
3251
- });
3252
- }
3253
- if (protocols.length) {
3254
- for (const protocol of protocols) {
3255
- if (
3256
- typeof protocol !== 'string' ||
3257
- !subprotocolRegex.test(protocol) ||
3258
- protocolSet.has(protocol)
3259
- ) {
3260
- throw new SyntaxError(
3261
- 'An invalid or duplicated subprotocol was specified'
3262
- );
3263
- }
3264
-
3265
- protocolSet.add(protocol);
3266
- }
3267
-
3268
- opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
3269
- }
3270
- if (opts.origin) {
3271
- if (opts.protocolVersion < 13) {
3272
- opts.headers['Sec-WebSocket-Origin'] = opts.origin;
3273
- } else {
3274
- opts.headers.Origin = opts.origin;
3275
- }
3276
- }
3277
- if (parsedUrl.username || parsedUrl.password) {
3278
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
3279
- }
3280
-
3281
- if (isIpcUrl) {
3282
- const parts = opts.path.split(':');
3283
-
3284
- opts.socketPath = parts[0];
3285
- opts.path = parts[1];
3286
- }
3287
-
3288
- let req;
3289
-
3290
- if (opts.followRedirects) {
3291
- if (websocket._redirects === 0) {
3292
- websocket._originalIpc = isIpcUrl;
3293
- websocket._originalSecure = isSecure;
3294
- websocket._originalHostOrSocketPath = isIpcUrl
3295
- ? opts.socketPath
3296
- : parsedUrl.host;
3297
-
3298
- const headers = options && options.headers;
3299
-
3300
- //
3301
- // Shallow copy the user provided options so that headers can be changed
3302
- // without mutating the original object.
3303
- //
3304
- options = { ...options, headers: {} };
3305
-
3306
- if (headers) {
3307
- for (const [key, value] of Object.entries(headers)) {
3308
- options.headers[key.toLowerCase()] = value;
3309
- }
3310
- }
3311
- } else if (websocket.listenerCount('redirect') === 0) {
3312
- const isSameHost = isIpcUrl
3313
- ? websocket._originalIpc
3314
- ? opts.socketPath === websocket._originalHostOrSocketPath
3315
- : false
3316
- : websocket._originalIpc
3317
- ? false
3318
- : parsedUrl.host === websocket._originalHostOrSocketPath;
3319
-
3320
- if (!isSameHost || (websocket._originalSecure && !isSecure)) {
3321
- //
3322
- // Match curl 7.77.0 behavior and drop the following headers. These
3323
- // headers are also dropped when following a redirect to a subdomain.
3324
- //
3325
- delete opts.headers.authorization;
3326
- delete opts.headers.cookie;
3327
-
3328
- if (!isSameHost) delete opts.headers.host;
3329
-
3330
- opts.auth = undefined;
3331
- }
3332
- }
3333
-
3334
- //
3335
- // Match curl 7.77.0 behavior and make the first `Authorization` header win.
3336
- // If the `Authorization` header is set, then there is nothing to do as it
3337
- // will take precedence.
3338
- //
3339
- if (opts.auth && !options.headers.authorization) {
3340
- options.headers.authorization =
3341
- 'Basic ' + Buffer.from(opts.auth).toString('base64');
3342
- }
3343
-
3344
- req = websocket._req = request(opts);
3345
-
3346
- if (websocket._redirects) {
3347
- //
3348
- // Unlike what is done for the `'upgrade'` event, no early exit is
3349
- // triggered here if the user calls `websocket.close()` or
3350
- // `websocket.terminate()` from a listener of the `'redirect'` event. This
3351
- // is because the user can also call `request.destroy()` with an error
3352
- // before calling `websocket.close()` or `websocket.terminate()` and this
3353
- // would result in an error being emitted on the `request` object with no
3354
- // `'error'` event listeners attached.
3355
- //
3356
- websocket.emit('redirect', websocket.url, req);
3357
- }
3358
- } else {
3359
- req = websocket._req = request(opts);
3360
- }
3361
-
3362
- if (opts.timeout) {
3363
- req.on('timeout', () => {
3364
- abortHandshake$1(websocket, req, 'Opening handshake has timed out');
3365
- });
3366
- }
3367
-
3368
- req.on('error', (err) => {
3369
- if (req === null || req[kAborted]) return;
3370
-
3371
- req = websocket._req = null;
3372
- emitErrorAndClose(websocket, err);
3373
- });
3374
-
3375
- req.on('response', (res) => {
3376
- const location = res.headers.location;
3377
- const statusCode = res.statusCode;
3378
-
3379
- if (
3380
- location &&
3381
- opts.followRedirects &&
3382
- statusCode >= 300 &&
3383
- statusCode < 400
3384
- ) {
3385
- if (++websocket._redirects > opts.maxRedirects) {
3386
- abortHandshake$1(websocket, req, 'Maximum redirects exceeded');
3387
- return;
3388
- }
3389
-
3390
- req.abort();
3391
-
3392
- let addr;
3393
-
3394
- try {
3395
- addr = new URL(location, address);
3396
- } catch (e) {
3397
- const err = new SyntaxError(`Invalid URL: ${location}`);
3398
- emitErrorAndClose(websocket, err);
3399
- return;
3400
- }
3401
-
3402
- initAsClient(websocket, addr, protocols, options);
3403
- } else if (!websocket.emit('unexpected-response', req, res)) {
3404
- abortHandshake$1(
3405
- websocket,
3406
- req,
3407
- `Unexpected server response: ${res.statusCode}`
3408
- );
3409
- }
3410
- });
3411
-
3412
- req.on('upgrade', (res, socket, head) => {
3413
- websocket.emit('upgrade', res);
3414
-
3415
- //
3416
- // The user may have closed the connection from a listener of the
3417
- // `'upgrade'` event.
3418
- //
3419
- if (websocket.readyState !== WebSocket$2.CONNECTING) return;
3420
-
3421
- req = websocket._req = null;
3422
-
3423
- if (res.headers.upgrade.toLowerCase() !== 'websocket') {
3424
- abortHandshake$1(websocket, socket, 'Invalid Upgrade header');
3425
- return;
3426
- }
3427
-
3428
- const digest = createHash$1('sha1')
3429
- .update(key + GUID$1)
3430
- .digest('base64');
3431
-
3432
- if (res.headers['sec-websocket-accept'] !== digest) {
3433
- abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
3434
- return;
3435
- }
3436
-
3437
- const serverProt = res.headers['sec-websocket-protocol'];
3438
- let protError;
3439
-
3440
- if (serverProt !== undefined) {
3441
- if (!protocolSet.size) {
3442
- protError = 'Server sent a subprotocol but none was requested';
3443
- } else if (!protocolSet.has(serverProt)) {
3444
- protError = 'Server sent an invalid subprotocol';
3445
- }
3446
- } else if (protocolSet.size) {
3447
- protError = 'Server sent no subprotocol';
3448
- }
3449
-
3450
- if (protError) {
3451
- abortHandshake$1(websocket, socket, protError);
3452
- return;
3453
- }
3454
-
3455
- if (serverProt) websocket._protocol = serverProt;
3456
-
3457
- const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
3458
-
3459
- if (secWebSocketExtensions !== undefined) {
3460
- if (!perMessageDeflate) {
3461
- const message =
3462
- 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
3463
- 'was requested';
3464
- abortHandshake$1(websocket, socket, message);
3465
- return;
3466
- }
3467
-
3468
- let extensions;
3469
-
3470
- try {
3471
- extensions = parse$1(secWebSocketExtensions);
3472
- } catch (err) {
3473
- const message = 'Invalid Sec-WebSocket-Extensions header';
3474
- abortHandshake$1(websocket, socket, message);
3475
- return;
3476
- }
3477
-
3478
- const extensionNames = Object.keys(extensions);
3479
-
3480
- if (
3481
- extensionNames.length !== 1 ||
3482
- extensionNames[0] !== PerMessageDeflate$1.extensionName
3483
- ) {
3484
- const message = 'Server indicated an extension that was not requested';
3485
- abortHandshake$1(websocket, socket, message);
3486
- return;
3487
- }
3488
-
3489
- try {
3490
- perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]);
3491
- } catch (err) {
3492
- const message = 'Invalid Sec-WebSocket-Extensions header';
3493
- abortHandshake$1(websocket, socket, message);
3494
- return;
3495
- }
3496
-
3497
- websocket._extensions[PerMessageDeflate$1.extensionName] =
3498
- perMessageDeflate;
3499
- }
3500
-
3501
- websocket.setSocket(socket, head, {
3502
- generateMask: opts.generateMask,
3503
- maxPayload: opts.maxPayload,
3504
- skipUTF8Validation: opts.skipUTF8Validation
3505
- });
3506
- });
3507
-
3508
- if (opts.finishRequest) {
3509
- opts.finishRequest(req, websocket);
3510
- } else {
3511
- req.end();
3512
- }
3513
- }
3514
-
3515
- /**
3516
- * Emit the `'error'` and `'close'` events.
3517
- *
3518
- * @param {WebSocket} websocket The WebSocket instance
3519
- * @param {Error} The error to emit
3520
- * @private
3521
- */
3522
- function emitErrorAndClose(websocket, err) {
3523
- websocket._readyState = WebSocket$2.CLOSING;
3524
- websocket.emit('error', err);
3525
- websocket.emitClose();
3526
- }
3527
-
3528
- /**
3529
- * Create a `net.Socket` and initiate a connection.
3530
- *
3531
- * @param {Object} options Connection options
3532
- * @return {net.Socket} The newly created socket used to start the connection
3533
- * @private
3534
- */
3535
- function netConnect(options) {
3536
- options.path = options.socketPath;
3537
- return net.connect(options);
3538
- }
3539
-
3540
- /**
3541
- * Create a `tls.TLSSocket` and initiate a connection.
3542
- *
3543
- * @param {Object} options Connection options
3544
- * @return {tls.TLSSocket} The newly created socket used to start the connection
3545
- * @private
3546
- */
3547
- function tlsConnect(options) {
3548
- options.path = undefined;
3549
-
3550
- if (!options.servername && options.servername !== '') {
3551
- options.servername = net.isIP(options.host) ? '' : options.host;
3552
- }
3553
-
3554
- return tls.connect(options);
3555
- }
3556
-
3557
- /**
3558
- * Abort the handshake and emit an error.
3559
- *
3560
- * @param {WebSocket} websocket The WebSocket instance
3561
- * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
3562
- * abort or the socket to destroy
3563
- * @param {String} message The error message
3564
- * @private
3565
- */
3566
- function abortHandshake$1(websocket, stream, message) {
3567
- websocket._readyState = WebSocket$2.CLOSING;
3568
-
3569
- const err = new Error(message);
3570
- Error.captureStackTrace(err, abortHandshake$1);
3571
-
3572
- if (stream.setHeader) {
3573
- stream[kAborted] = true;
3574
- stream.abort();
3575
-
3576
- if (stream.socket && !stream.socket.destroyed) {
3577
- //
3578
- // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
3579
- // called after the request completed. See
3580
- // https://github.com/websockets/ws/issues/1869.
3581
- //
3582
- stream.socket.destroy();
3583
- }
3584
-
3585
- process.nextTick(emitErrorAndClose, websocket, err);
3586
- } else {
3587
- stream.destroy(err);
3588
- stream.once('error', websocket.emit.bind(websocket, 'error'));
3589
- stream.once('close', websocket.emitClose.bind(websocket));
3590
- }
3591
- }
3592
-
3593
- /**
3594
- * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
3595
- * when the `readyState` attribute is `CLOSING` or `CLOSED`.
3596
- *
3597
- * @param {WebSocket} websocket The WebSocket instance
3598
- * @param {*} [data] The data to send
3599
- * @param {Function} [cb] Callback
3600
- * @private
3601
- */
3602
- function sendAfterClose(websocket, data, cb) {
3603
- if (data) {
3604
- const length = toBuffer(data).length;
3605
-
3606
- //
3607
- // The `_bufferedAmount` property is used only when the peer is a client and
3608
- // the opening handshake fails. Under these circumstances, in fact, the
3609
- // `setSocket()` method is not called, so the `_socket` and `_sender`
3610
- // properties are set to `null`.
3611
- //
3612
- if (websocket._socket) websocket._sender._bufferedBytes += length;
3613
- else websocket._bufferedAmount += length;
3614
- }
3615
-
3616
- if (cb) {
3617
- const err = new Error(
3618
- `WebSocket is not open: readyState ${websocket.readyState} ` +
3619
- `(${readyStates[websocket.readyState]})`
3620
- );
3621
- process.nextTick(cb, err);
3622
- }
3623
- }
3624
-
3625
- /**
3626
- * The listener of the `Receiver` `'conclude'` event.
3627
- *
3628
- * @param {Number} code The status code
3629
- * @param {Buffer} reason The reason for closing
3630
- * @private
3631
- */
3632
- function receiverOnConclude(code, reason) {
3633
- const websocket = this[kWebSocket$1];
3634
-
3635
- websocket._closeFrameReceived = true;
3636
- websocket._closeMessage = reason;
3637
- websocket._closeCode = code;
3638
-
3639
- if (websocket._socket[kWebSocket$1] === undefined) return;
3640
-
3641
- websocket._socket.removeListener('data', socketOnData);
3642
- process.nextTick(resume, websocket._socket);
3643
-
3644
- if (code === 1005) websocket.close();
3645
- else websocket.close(code, reason);
3646
- }
3647
-
3648
- /**
3649
- * The listener of the `Receiver` `'drain'` event.
3650
- *
3651
- * @private
3652
- */
3653
- function receiverOnDrain() {
3654
- const websocket = this[kWebSocket$1];
3655
-
3656
- if (!websocket.isPaused) websocket._socket.resume();
3657
- }
3658
-
3659
- /**
3660
- * The listener of the `Receiver` `'error'` event.
3661
- *
3662
- * @param {(RangeError|Error)} err The emitted error
3663
- * @private
3664
- */
3665
- function receiverOnError(err) {
3666
- const websocket = this[kWebSocket$1];
3667
-
3668
- if (websocket._socket[kWebSocket$1] !== undefined) {
3669
- websocket._socket.removeListener('data', socketOnData);
3670
-
3671
- //
3672
- // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
3673
- // https://github.com/websockets/ws/issues/1940.
3674
- //
3675
- process.nextTick(resume, websocket._socket);
3676
-
3677
- websocket.close(err[kStatusCode]);
3678
- }
3679
-
3680
- websocket.emit('error', err);
3681
- }
3682
-
3683
- /**
3684
- * The listener of the `Receiver` `'finish'` event.
3685
- *
3686
- * @private
3687
- */
3688
- function receiverOnFinish() {
3689
- this[kWebSocket$1].emitClose();
3690
- }
3691
-
3692
- /**
3693
- * The listener of the `Receiver` `'message'` event.
3694
- *
3695
- * @param {Buffer|ArrayBuffer|Buffer[])} data The message
3696
- * @param {Boolean} isBinary Specifies whether the message is binary or not
3697
- * @private
3698
- */
3699
- function receiverOnMessage(data, isBinary) {
3700
- this[kWebSocket$1].emit('message', data, isBinary);
3701
- }
3702
-
3703
- /**
3704
- * The listener of the `Receiver` `'ping'` event.
3705
- *
3706
- * @param {Buffer} data The data included in the ping frame
3707
- * @private
3708
- */
3709
- function receiverOnPing(data) {
3710
- const websocket = this[kWebSocket$1];
3711
-
3712
- websocket.pong(data, !websocket._isServer, NOOP);
3713
- websocket.emit('ping', data);
3714
- }
3715
-
3716
- /**
3717
- * The listener of the `Receiver` `'pong'` event.
3718
- *
3719
- * @param {Buffer} data The data included in the pong frame
3720
- * @private
3721
- */
3722
- function receiverOnPong(data) {
3723
- this[kWebSocket$1].emit('pong', data);
3724
- }
3725
-
3726
- /**
3727
- * Resume a readable stream
3728
- *
3729
- * @param {Readable} stream The readable stream
3730
- * @private
3731
- */
3732
- function resume(stream) {
3733
- stream.resume();
3734
- }
3735
-
3736
- /**
3737
- * The listener of the socket `'close'` event.
3738
- *
3739
- * @private
3740
- */
3741
- function socketOnClose() {
3742
- const websocket = this[kWebSocket$1];
3743
-
3744
- this.removeListener('close', socketOnClose);
3745
- this.removeListener('data', socketOnData);
3746
- this.removeListener('end', socketOnEnd);
3747
-
3748
- websocket._readyState = WebSocket$2.CLOSING;
3749
-
3750
- let chunk;
3751
-
3752
- //
3753
- // The close frame might not have been received or the `'end'` event emitted,
3754
- // for example, if the socket was destroyed due to an error. Ensure that the
3755
- // `receiver` stream is closed after writing any remaining buffered data to
3756
- // it. If the readable side of the socket is in flowing mode then there is no
3757
- // buffered data as everything has been already written and `readable.read()`
3758
- // will return `null`. If instead, the socket is paused, any possible buffered
3759
- // data will be read as a single chunk.
3760
- //
3761
- if (
3762
- !this._readableState.endEmitted &&
3763
- !websocket._closeFrameReceived &&
3764
- !websocket._receiver._writableState.errorEmitted &&
3765
- (chunk = websocket._socket.read()) !== null
3766
- ) {
3767
- websocket._receiver.write(chunk);
3768
- }
3769
-
3770
- websocket._receiver.end();
3771
-
3772
- this[kWebSocket$1] = undefined;
3773
-
3774
- clearTimeout(websocket._closeTimer);
3775
-
3776
- if (
3777
- websocket._receiver._writableState.finished ||
3778
- websocket._receiver._writableState.errorEmitted
3779
- ) {
3780
- websocket.emitClose();
3781
- } else {
3782
- websocket._receiver.on('error', receiverOnFinish);
3783
- websocket._receiver.on('finish', receiverOnFinish);
3784
- }
3785
- }
3786
-
3787
- /**
3788
- * The listener of the socket `'data'` event.
3789
- *
3790
- * @param {Buffer} chunk A chunk of data
3791
- * @private
3792
- */
3793
- function socketOnData(chunk) {
3794
- if (!this[kWebSocket$1]._receiver.write(chunk)) {
3795
- this.pause();
3796
- }
3797
- }
3798
-
3799
- /**
3800
- * The listener of the socket `'end'` event.
3801
- *
3802
- * @private
3803
- */
3804
- function socketOnEnd() {
3805
- const websocket = this[kWebSocket$1];
3806
-
3807
- websocket._readyState = WebSocket$2.CLOSING;
3808
- websocket._receiver.end();
3809
- this.end();
3810
- }
3811
-
3812
- /**
3813
- * The listener of the socket `'error'` event.
3814
- *
3815
- * @private
3816
- */
3817
- function socketOnError$1() {
3818
- const websocket = this[kWebSocket$1];
3819
-
3820
- this.removeListener('error', socketOnError$1);
3821
- this.on('error', NOOP);
3822
-
3823
- if (websocket) {
3824
- websocket._readyState = WebSocket$2.CLOSING;
3825
- this.destroy();
3826
- }
3827
- }
3828
-
3829
- const _WebSocket = /*@__PURE__*/getDefaultExportFromCjs(websocket);
1
+ import 'stream';
2
+ import { v as validationExports, g as getDefaultExportFromCjs, e as extension$1, p as permessageDeflate, w as websocket, c as constants } from '../shared/crossws.a5db571c.mjs';
3
+ import require$$0 from 'events';
4
+ import require$$2 from 'http';
5
+ import require$$1 from 'crypto';
6
+ import { d as defineWebSocketAdapter, a as WebSocketMessage, W as WebSocketError, b as WebSocketPeerBase } from '../shared/crossws.9536f626.mjs';
7
+ import 'https';
8
+ import 'net';
9
+ import 'tls';
10
+ import 'url';
11
+ import 'zlib';
12
+ import 'buffer';
3830
13
 
3831
14
  const { tokenChars } = validationExports;
3832
15
 
@@ -3891,14 +74,14 @@ var subprotocol$1 = { parse };
3891
74
 
3892
75
  /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$" }] */
3893
76
 
3894
- const EventEmitter = require$$0$3;
77
+ const EventEmitter = require$$0;
3895
78
  const http = require$$2;
3896
79
  const { createHash } = require$$1;
3897
80
 
3898
81
  const extension = extension$1;
3899
82
  const PerMessageDeflate = permessageDeflate;
3900
83
  const subprotocol = subprotocol$1;
3901
- const WebSocket$1 = websocket;
84
+ const WebSocket = websocket;
3902
85
  const { GUID, kWebSocket } = constants;
3903
86
 
3904
87
  const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
@@ -3917,6 +100,11 @@ class WebSocketServer extends EventEmitter {
3917
100
  * Create a `WebSocketServer` instance.
3918
101
  *
3919
102
  * @param {Object} options Configuration options
103
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
104
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
105
+ * multiple times in the same tick
106
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
107
+ * automatically send a pong in response to a ping
3920
108
  * @param {Number} [options.backlog=511] The maximum length of the queue of
3921
109
  * pending connections
3922
110
  * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
@@ -3943,6 +131,8 @@ class WebSocketServer extends EventEmitter {
3943
131
  super();
3944
132
 
3945
133
  options = {
134
+ allowSynchronousEvents: false,
135
+ autoPong: true,
3946
136
  maxPayload: 100 * 1024 * 1024,
3947
137
  skipUTF8Validation: false,
3948
138
  perMessageDeflate: false,
@@ -3955,7 +145,7 @@ class WebSocketServer extends EventEmitter {
3955
145
  host: null,
3956
146
  path: null,
3957
147
  port: null,
3958
- WebSocket: WebSocket$1,
148
+ WebSocket,
3959
149
  ...options
3960
150
  };
3961
151
 
@@ -4263,7 +453,7 @@ class WebSocketServer extends EventEmitter {
4263
453
  `Sec-WebSocket-Accept: ${digest}`
4264
454
  ];
4265
455
 
4266
- const ws = new this.options.WebSocket(null);
456
+ const ws = new this.options.WebSocket(null, undefined, this.options);
4267
457
 
4268
458
  if (protocols.size) {
4269
459
  //
@@ -4297,6 +487,7 @@ class WebSocketServer extends EventEmitter {
4297
487
  socket.removeListener('error', socketOnError);
4298
488
 
4299
489
  ws.setSocket(socket, head, {
490
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
4300
491
  maxPayload: this.options.maxPayload,
4301
492
  skipUTF8Validation: this.options.skipUTF8Validation
4302
493
  });
@@ -4420,60 +611,50 @@ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
4420
611
 
4421
612
  const _WebSocketServer = /*@__PURE__*/getDefaultExportFromCjs(websocketServer);
4422
613
 
4423
- const WebSocket = _WebSocket;
4424
614
  const node = defineWebSocketAdapter(
4425
- (handler, opts = {}) => {
615
+ (hooks, opts = {}) => {
4426
616
  const wss = opts.wss || new _WebSocketServer({
4427
617
  noServer: true,
4428
618
  ...opts.serverOptions
4429
619
  });
4430
- wss.on("error", (error) => {
4431
- handler.onEvent?.("node:server-error", error);
4432
- });
4433
- wss.on("headers", (headers, request) => {
4434
- handler.onEvent?.("node:server-headers", headers, request);
4435
- });
4436
- wss.on("listening", () => {
4437
- handler.onEvent?.("node:server-listening");
4438
- });
4439
- wss.on("close", () => {
4440
- handler.onEvent?.("node:server-close");
4441
- });
4442
620
  wss.on("connection", (ws, req) => {
4443
- const peer = new NodeWebSocketPeer(ws, req);
621
+ const peer = new NodeWebSocketPeer({ node: { ws, req, server: wss } });
622
+ hooks.open?.(peer);
4444
623
  ws.on("message", (data, isBinary) => {
4445
- handler.onEvent?.("node:message", ws, data, isBinary);
624
+ hooks["node:message"]?.(peer, data, isBinary);
4446
625
  if (Array.isArray(data)) {
4447
626
  data = Buffer.concat(data);
4448
627
  }
4449
- handler.onMessage?.(peer, new WebSocketMessage(data, isBinary));
628
+ hooks.message?.(peer, new WebSocketMessage(data, isBinary));
4450
629
  });
4451
630
  ws.on("error", (error) => {
4452
- handler.onEvent?.("node:error", ws, error);
4453
- handler.onError?.(peer, new WebSocketError(error));
631
+ hooks["node:error"]?.(peer, error);
632
+ hooks.error?.(peer, new WebSocketError(error));
4454
633
  });
4455
634
  ws.on("close", (code, reason) => {
4456
- handler.onEvent?.("node:close", ws, code, reason);
4457
- handler.onClose?.(peer, code, reason?.toString());
635
+ hooks["node:close"]?.(peer, code, reason);
636
+ hooks.close?.(peer, {
637
+ code,
638
+ reason: reason?.toString()
639
+ });
4458
640
  });
4459
641
  ws.on("open", () => {
4460
- handler.onEvent?.("node:open", ws);
4461
- handler.onOpen?.(peer);
642
+ hooks["node:open"]?.(peer);
4462
643
  });
4463
644
  ws.on("ping", (data) => {
4464
- handler.onEvent?.("node:ping", ws, data);
645
+ hooks["node:ping"]?.(peer, data);
4465
646
  });
4466
647
  ws.on("pong", (data) => {
4467
- handler.onEvent?.("node:pong", ws, data);
648
+ hooks["node:pong"]?.(peer, data);
4468
649
  });
4469
650
  ws.on(
4470
651
  "unexpected-response",
4471
- (request, response) => {
4472
- handler.onEvent?.("node:unexpected-response", ws, request, response);
652
+ (req2, res) => {
653
+ hooks["node:unexpected-response"]?.(peer, req2, res);
4473
654
  }
4474
655
  );
4475
- ws.on("upgrade", (request) => {
4476
- handler.onEvent?.("node:upgrade", ws, request);
656
+ ws.on("upgrade", (req2) => {
657
+ hooks["node:upgrade"]?.(peer, req2);
4477
658
  });
4478
659
  });
4479
660
  return {
@@ -4485,14 +666,9 @@ const node = defineWebSocketAdapter(
4485
666
  };
4486
667
  }
4487
668
  );
4488
- class NodeWebSocketPeer extends WebSocketPeer {
4489
- constructor(_ws, _req) {
4490
- super();
4491
- this._ws = _ws;
4492
- this._req = _req;
4493
- }
669
+ class NodeWebSocketPeer extends WebSocketPeerBase {
4494
670
  get id() {
4495
- const socket = this._req?.socket;
671
+ const socket = this.ctx.node.req.socket;
4496
672
  if (!socket) {
4497
673
  return void 0;
4498
674
  }
@@ -4500,12 +676,12 @@ class NodeWebSocketPeer extends WebSocketPeer {
4500
676
  return `${addr}:${socket.remotePort}`;
4501
677
  }
4502
678
  get readyState() {
4503
- return this._ws.readyState;
679
+ return this.ctx.node.ws.readyState;
4504
680
  }
4505
681
  send(message, compress) {
4506
- this._ws.send(message, { compress });
682
+ this.ctx.node.ws.send(message, { compress });
4507
683
  return 0;
4508
684
  }
4509
685
  }
4510
686
 
4511
- export { WebSocket, node as default };
687
+ export { node as default };