vitest 0.8.2 → 0.8.5

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