crossws 0.0.1 → 0.1.0

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