@hyperlane-xyz/cli 26.0.0 → 27.1.0

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