crossws 0.3.1 → 0.3.3

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