vitest 0.0.129 → 0.0.133

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 (40) hide show
  1. package/dist/_commonjsHelpers-c9e3b764.js +1 -0
  2. package/dist/cli.js +10 -9
  3. package/dist/constants-0211a379.js +34 -0
  4. package/dist/diff-18d4a7eb.js +4750 -0
  5. package/dist/entry.js +94 -33
  6. package/dist/externalize-2f63779d.js +1 -0
  7. package/dist/global-5d1fb309.js +21 -0
  8. package/dist/index-26cb6e63.js +1644 -0
  9. package/dist/index-354a6abd.js +40 -0
  10. package/dist/index-4cd25949.js +782 -0
  11. package/dist/index-720a83c6.js +396 -0
  12. package/dist/index-7975be53.js +331 -0
  13. package/dist/index-7f7acd60.js +8548 -0
  14. package/dist/index-e909c175.js +63 -0
  15. package/dist/index-fa899e66.js +5708 -0
  16. package/dist/index.d.ts +142 -27
  17. package/dist/index.js +4 -3
  18. package/dist/jest-mock-30625866.js +1 -0
  19. package/dist/magic-string.es-94000aea.js +1361 -0
  20. package/dist/node.d.ts +111 -4
  21. package/dist/node.js +9 -8
  22. package/dist/rpc-8c7cc374.js +1 -0
  23. package/dist/setup-5aaf533e.js +4365 -0
  24. package/dist/vi-aec007e7.js +3461 -0
  25. package/dist/worker.js +11 -7
  26. package/package.json +9 -9
  27. package/dist/constants-868b9a2e.js +0 -33
  28. package/dist/diff-be830986.js +0 -4751
  29. package/dist/global-0254dd68.js +0 -20
  30. package/dist/index-06712022.js +0 -39
  31. package/dist/index-42a3a132.js +0 -366
  32. package/dist/index-42d44ee5.js +0 -1643
  33. package/dist/index-93dcb598.js +0 -5707
  34. package/dist/index-a73f33e0.js +0 -62
  35. package/dist/index-cb02ee01.js +0 -330
  36. package/dist/index-cce5de77.js +0 -781
  37. package/dist/index-d30b5ed0.js +0 -8579
  38. package/dist/magic-string.es-98a8bfa0.js +0 -1360
  39. package/dist/setup-6e09a65a.js +0 -4364
  40. package/dist/vi-fe26a646.js +0 -3460
@@ -1,4364 +0,0 @@
1
- import { promises } from 'fs';
2
- import { c as createBirpc } from './index-a73f33e0.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 require$$7 from 'url';
12
- import { A as API_PATH } from './constants-868b9a2e.js';
13
- import { s as shouldExternalize } from './externalize-2f63779d.js';
14
- import { o as interpretSourcePos, n as parseStacktrace } from './diff-be830986.js';
15
- import './index-42a3a132.js';
16
- import 'tty';
17
- import 'local-pkg';
18
- import 'path';
19
- import 'module';
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} 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} 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 maskBuffer = Buffer.alloc(4);
1568
-
1569
- /**
1570
- * HyBi Sender implementation.
1571
- */
1572
- class Sender$1 {
1573
- /**
1574
- * Creates a Sender instance.
1575
- *
1576
- * @param {(net.Socket|tls.Socket)} socket The connection socket
1577
- * @param {Object} [extensions] An object containing the negotiated extensions
1578
- * @param {Function} [generateMask] The function used to generate the masking
1579
- * key
1580
- */
1581
- constructor(socket, extensions, generateMask) {
1582
- this._extensions = extensions || {};
1583
-
1584
- if (generateMask) {
1585
- this._generateMask = generateMask;
1586
- this._maskBuffer = Buffer.alloc(4);
1587
- }
1588
-
1589
- this._socket = socket;
1590
-
1591
- this._firstFragment = true;
1592
- this._compress = false;
1593
-
1594
- this._bufferedBytes = 0;
1595
- this._deflating = false;
1596
- this._queue = [];
1597
- }
1598
-
1599
- /**
1600
- * Frames a piece of data according to the HyBi WebSocket protocol.
1601
- *
1602
- * @param {Buffer} data The data to frame
1603
- * @param {Object} options Options object
1604
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1605
- * FIN bit
1606
- * @param {Function} [options.generateMask] The function used to generate the
1607
- * masking key
1608
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1609
- * `data`
1610
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1611
- * key
1612
- * @param {Number} options.opcode The opcode
1613
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1614
- * modified
1615
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1616
- * RSV1 bit
1617
- * @return {Buffer[]} The framed data as a list of `Buffer` instances
1618
- * @public
1619
- */
1620
- static frame(data, options) {
1621
- let mask;
1622
- let merge = false;
1623
- let offset = 2;
1624
- let skipMasking = false;
1625
-
1626
- if (options.mask) {
1627
- mask = options.maskBuffer || maskBuffer;
1628
-
1629
- if (options.generateMask) {
1630
- options.generateMask(mask);
1631
- } else {
1632
- randomFillSync(mask, 0, 4);
1633
- }
1634
-
1635
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1636
- if (options.readOnly && !skipMasking) merge = true;
1637
-
1638
- offset = 6;
1639
- }
1640
-
1641
- let payloadLength = data.length;
1642
-
1643
- if (data.length >= 65536) {
1644
- offset += 8;
1645
- payloadLength = 127;
1646
- } else if (data.length > 125) {
1647
- offset += 2;
1648
- payloadLength = 126;
1649
- }
1650
-
1651
- const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);
1652
-
1653
- target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
1654
- if (options.rsv1) target[0] |= 0x40;
1655
-
1656
- target[1] = payloadLength;
1657
-
1658
- if (payloadLength === 126) {
1659
- target.writeUInt16BE(data.length, 2);
1660
- } else if (payloadLength === 127) {
1661
- target[2] = target[3] = 0;
1662
- target.writeUIntBE(data.length, 4, 6);
1663
- }
1664
-
1665
- if (!options.mask) return [target, data];
1666
-
1667
- target[1] |= 0x80;
1668
- target[offset - 4] = mask[0];
1669
- target[offset - 3] = mask[1];
1670
- target[offset - 2] = mask[2];
1671
- target[offset - 1] = mask[3];
1672
-
1673
- if (skipMasking) return [target, data];
1674
-
1675
- if (merge) {
1676
- applyMask(data, mask, target, offset, data.length);
1677
- return [target];
1678
- }
1679
-
1680
- applyMask(data, mask, data, 0, data.length);
1681
- return [target, data];
1682
- }
1683
-
1684
- /**
1685
- * Sends a close message to the other peer.
1686
- *
1687
- * @param {Number} [code] The status code component of the body
1688
- * @param {(String|Buffer)} [data] The message component of the body
1689
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1690
- * @param {Function} [cb] Callback
1691
- * @public
1692
- */
1693
- close(code, data, mask, cb) {
1694
- let buf;
1695
-
1696
- if (code === undefined) {
1697
- buf = EMPTY_BUFFER$1;
1698
- } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
1699
- throw new TypeError('First argument must be a valid error code number');
1700
- } else if (data === undefined || !data.length) {
1701
- buf = Buffer.allocUnsafe(2);
1702
- buf.writeUInt16BE(code, 0);
1703
- } else {
1704
- const length = Buffer.byteLength(data);
1705
-
1706
- if (length > 123) {
1707
- throw new RangeError('The message must not be greater than 123 bytes');
1708
- }
1709
-
1710
- buf = Buffer.allocUnsafe(2 + length);
1711
- buf.writeUInt16BE(code, 0);
1712
-
1713
- if (typeof data === 'string') {
1714
- buf.write(data, 2);
1715
- } else {
1716
- buf.set(data, 2);
1717
- }
1718
- }
1719
-
1720
- if (this._deflating) {
1721
- this.enqueue([this.doClose, buf, mask, cb]);
1722
- } else {
1723
- this.doClose(buf, mask, cb);
1724
- }
1725
- }
1726
-
1727
- /**
1728
- * Frames and sends a close message.
1729
- *
1730
- * @param {Buffer} data The message to send
1731
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1732
- * @param {Function} [cb] Callback
1733
- * @private
1734
- */
1735
- doClose(data, mask, cb) {
1736
- this.sendFrame(
1737
- Sender$1.frame(data, {
1738
- fin: true,
1739
- rsv1: false,
1740
- opcode: 0x08,
1741
- mask,
1742
- maskBuffer: this._maskBuffer,
1743
- generateMask: this._generateMask,
1744
- readOnly: false
1745
- }),
1746
- cb
1747
- );
1748
- }
1749
-
1750
- /**
1751
- * Sends a ping message to the other peer.
1752
- *
1753
- * @param {*} data The message to send
1754
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1755
- * @param {Function} [cb] Callback
1756
- * @public
1757
- */
1758
- ping(data, mask, cb) {
1759
- const buf = toBuffer$1(data);
1760
-
1761
- if (buf.length > 125) {
1762
- throw new RangeError('The data size must not be greater than 125 bytes');
1763
- }
1764
-
1765
- if (this._deflating) {
1766
- this.enqueue([this.doPing, buf, mask, toBuffer$1.readOnly, cb]);
1767
- } else {
1768
- this.doPing(buf, mask, toBuffer$1.readOnly, cb);
1769
- }
1770
- }
1771
-
1772
- /**
1773
- * Frames and sends a ping message.
1774
- *
1775
- * @param {Buffer} data The message to send
1776
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1777
- * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified
1778
- * @param {Function} [cb] Callback
1779
- * @private
1780
- */
1781
- doPing(data, mask, readOnly, cb) {
1782
- this.sendFrame(
1783
- Sender$1.frame(data, {
1784
- fin: true,
1785
- rsv1: false,
1786
- opcode: 0x09,
1787
- mask,
1788
- maskBuffer: this._maskBuffer,
1789
- generateMask: this._generateMask,
1790
- readOnly
1791
- }),
1792
- cb
1793
- );
1794
- }
1795
-
1796
- /**
1797
- * Sends a pong message to the other peer.
1798
- *
1799
- * @param {*} data The message to send
1800
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1801
- * @param {Function} [cb] Callback
1802
- * @public
1803
- */
1804
- pong(data, mask, cb) {
1805
- const buf = toBuffer$1(data);
1806
-
1807
- if (buf.length > 125) {
1808
- throw new RangeError('The data size must not be greater than 125 bytes');
1809
- }
1810
-
1811
- if (this._deflating) {
1812
- this.enqueue([this.doPong, buf, mask, toBuffer$1.readOnly, cb]);
1813
- } else {
1814
- this.doPong(buf, mask, toBuffer$1.readOnly, cb);
1815
- }
1816
- }
1817
-
1818
- /**
1819
- * Frames and sends a pong message.
1820
- *
1821
- * @param {Buffer} data The message to send
1822
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1823
- * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified
1824
- * @param {Function} [cb] Callback
1825
- * @private
1826
- */
1827
- doPong(data, mask, readOnly, cb) {
1828
- this.sendFrame(
1829
- Sender$1.frame(data, {
1830
- fin: true,
1831
- rsv1: false,
1832
- opcode: 0x0a,
1833
- mask,
1834
- maskBuffer: this._maskBuffer,
1835
- generateMask: this._generateMask,
1836
- readOnly
1837
- }),
1838
- cb
1839
- );
1840
- }
1841
-
1842
- /**
1843
- * Sends a data message to the other peer.
1844
- *
1845
- * @param {*} data The message to send
1846
- * @param {Object} options Options object
1847
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1848
- * or text
1849
- * @param {Boolean} [options.compress=false] Specifies whether or not to
1850
- * compress `data`
1851
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1852
- * last one
1853
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1854
- * `data`
1855
- * @param {Function} [cb] Callback
1856
- * @public
1857
- */
1858
- send(data, options, cb) {
1859
- const buf = toBuffer$1(data);
1860
- const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
1861
- let opcode = options.binary ? 2 : 1;
1862
- let rsv1 = options.compress;
1863
-
1864
- if (this._firstFragment) {
1865
- this._firstFragment = false;
1866
- if (
1867
- rsv1 &&
1868
- perMessageDeflate &&
1869
- perMessageDeflate.params[
1870
- perMessageDeflate._isServer
1871
- ? 'server_no_context_takeover'
1872
- : 'client_no_context_takeover'
1873
- ]
1874
- ) {
1875
- rsv1 = buf.length >= perMessageDeflate._threshold;
1876
- }
1877
- this._compress = rsv1;
1878
- } else {
1879
- rsv1 = false;
1880
- opcode = 0;
1881
- }
1882
-
1883
- if (options.fin) this._firstFragment = true;
1884
-
1885
- if (perMessageDeflate) {
1886
- const opts = {
1887
- fin: options.fin,
1888
- rsv1,
1889
- opcode,
1890
- mask: options.mask,
1891
- maskBuffer: this._maskBuffer,
1892
- generateMask: this._generateMask,
1893
- readOnly: toBuffer$1.readOnly
1894
- };
1895
-
1896
- if (this._deflating) {
1897
- this.enqueue([this.dispatch, buf, this._compress, opts, cb]);
1898
- } else {
1899
- this.dispatch(buf, this._compress, opts, cb);
1900
- }
1901
- } else {
1902
- this.sendFrame(
1903
- Sender$1.frame(buf, {
1904
- fin: options.fin,
1905
- rsv1: false,
1906
- opcode,
1907
- mask: options.mask,
1908
- maskBuffer: this._maskBuffer,
1909
- generateMask: this._generateMask,
1910
- readOnly: toBuffer$1.readOnly
1911
- }),
1912
- cb
1913
- );
1914
- }
1915
- }
1916
-
1917
- /**
1918
- * Dispatches a data message.
1919
- *
1920
- * @param {Buffer} data The message to send
1921
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1922
- * `data`
1923
- * @param {Object} options Options object
1924
- * @param {Number} options.opcode The opcode
1925
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1926
- * FIN bit
1927
- * @param {Function} [options.generateMask] The function used to generate the
1928
- * masking key
1929
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1930
- * `data`
1931
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1932
- * key
1933
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1934
- * modified
1935
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1936
- * RSV1 bit
1937
- * @param {Function} [cb] Callback
1938
- * @private
1939
- */
1940
- dispatch(data, compress, options, cb) {
1941
- if (!compress) {
1942
- this.sendFrame(Sender$1.frame(data, options), cb);
1943
- return;
1944
- }
1945
-
1946
- const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
1947
-
1948
- this._bufferedBytes += data.length;
1949
- this._deflating = true;
1950
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1951
- if (this._socket.destroyed) {
1952
- const err = new Error(
1953
- 'The socket was closed while data was being compressed'
1954
- );
1955
-
1956
- if (typeof cb === 'function') cb(err);
1957
-
1958
- for (let i = 0; i < this._queue.length; i++) {
1959
- const callback = this._queue[i][4];
1960
-
1961
- if (typeof callback === 'function') callback(err);
1962
- }
1963
-
1964
- return;
1965
- }
1966
-
1967
- this._bufferedBytes -= data.length;
1968
- this._deflating = false;
1969
- options.readOnly = false;
1970
- this.sendFrame(Sender$1.frame(buf, options), cb);
1971
- this.dequeue();
1972
- });
1973
- }
1974
-
1975
- /**
1976
- * Executes queued send operations.
1977
- *
1978
- * @private
1979
- */
1980
- dequeue() {
1981
- while (!this._deflating && this._queue.length) {
1982
- const params = this._queue.shift();
1983
-
1984
- this._bufferedBytes -= params[1].length;
1985
- Reflect.apply(params[0], this, params.slice(1));
1986
- }
1987
- }
1988
-
1989
- /**
1990
- * Enqueues a send operation.
1991
- *
1992
- * @param {Array} params Send operation parameters.
1993
- * @private
1994
- */
1995
- enqueue(params) {
1996
- this._bufferedBytes += params[1].length;
1997
- this._queue.push(params);
1998
- }
1999
-
2000
- /**
2001
- * Sends a frame.
2002
- *
2003
- * @param {Buffer[]} list The frame to send
2004
- * @param {Function} [cb] Callback
2005
- * @private
2006
- */
2007
- sendFrame(list, cb) {
2008
- if (list.length === 2) {
2009
- this._socket.cork();
2010
- this._socket.write(list[0]);
2011
- this._socket.write(list[1], cb);
2012
- this._socket.uncork();
2013
- } else {
2014
- this._socket.write(list[0], cb);
2015
- }
2016
- }
2017
- }
2018
-
2019
- var sender = Sender$1;
2020
-
2021
- const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants;
2022
-
2023
- const kCode = Symbol('kCode');
2024
- const kData = Symbol('kData');
2025
- const kError = Symbol('kError');
2026
- const kMessage = Symbol('kMessage');
2027
- const kReason = Symbol('kReason');
2028
- const kTarget = Symbol('kTarget');
2029
- const kType = Symbol('kType');
2030
- const kWasClean = Symbol('kWasClean');
2031
-
2032
- /**
2033
- * Class representing an event.
2034
- */
2035
- class Event {
2036
- /**
2037
- * Create a new `Event`.
2038
- *
2039
- * @param {String} type The name of the event
2040
- * @throws {TypeError} If the `type` argument is not specified
2041
- */
2042
- constructor(type) {
2043
- this[kTarget] = null;
2044
- this[kType] = type;
2045
- }
2046
-
2047
- /**
2048
- * @type {*}
2049
- */
2050
- get target() {
2051
- return this[kTarget];
2052
- }
2053
-
2054
- /**
2055
- * @type {String}
2056
- */
2057
- get type() {
2058
- return this[kType];
2059
- }
2060
- }
2061
-
2062
- Object.defineProperty(Event.prototype, 'target', { enumerable: true });
2063
- Object.defineProperty(Event.prototype, 'type', { enumerable: true });
2064
-
2065
- /**
2066
- * Class representing a close event.
2067
- *
2068
- * @extends Event
2069
- */
2070
- class CloseEvent extends Event {
2071
- /**
2072
- * Create a new `CloseEvent`.
2073
- *
2074
- * @param {String} type The name of the event
2075
- * @param {Object} [options] A dictionary object that allows for setting
2076
- * attributes via object members of the same name
2077
- * @param {Number} [options.code=0] The status code explaining why the
2078
- * connection was closed
2079
- * @param {String} [options.reason=''] A human-readable string explaining why
2080
- * the connection was closed
2081
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
2082
- * connection was cleanly closed
2083
- */
2084
- constructor(type, options = {}) {
2085
- super(type);
2086
-
2087
- this[kCode] = options.code === undefined ? 0 : options.code;
2088
- this[kReason] = options.reason === undefined ? '' : options.reason;
2089
- this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
2090
- }
2091
-
2092
- /**
2093
- * @type {Number}
2094
- */
2095
- get code() {
2096
- return this[kCode];
2097
- }
2098
-
2099
- /**
2100
- * @type {String}
2101
- */
2102
- get reason() {
2103
- return this[kReason];
2104
- }
2105
-
2106
- /**
2107
- * @type {Boolean}
2108
- */
2109
- get wasClean() {
2110
- return this[kWasClean];
2111
- }
2112
- }
2113
-
2114
- Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
2115
- Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
2116
- Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
2117
-
2118
- /**
2119
- * Class representing an error event.
2120
- *
2121
- * @extends Event
2122
- */
2123
- class ErrorEvent extends Event {
2124
- /**
2125
- * Create a new `ErrorEvent`.
2126
- *
2127
- * @param {String} type The name of the event
2128
- * @param {Object} [options] A dictionary object that allows for setting
2129
- * attributes via object members of the same name
2130
- * @param {*} [options.error=null] The error that generated this event
2131
- * @param {String} [options.message=''] The error message
2132
- */
2133
- constructor(type, options = {}) {
2134
- super(type);
2135
-
2136
- this[kError] = options.error === undefined ? null : options.error;
2137
- this[kMessage] = options.message === undefined ? '' : options.message;
2138
- }
2139
-
2140
- /**
2141
- * @type {*}
2142
- */
2143
- get error() {
2144
- return this[kError];
2145
- }
2146
-
2147
- /**
2148
- * @type {String}
2149
- */
2150
- get message() {
2151
- return this[kMessage];
2152
- }
2153
- }
2154
-
2155
- Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
2156
- Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
2157
-
2158
- /**
2159
- * Class representing a message event.
2160
- *
2161
- * @extends Event
2162
- */
2163
- class MessageEvent extends Event {
2164
- /**
2165
- * Create a new `MessageEvent`.
2166
- *
2167
- * @param {String} type The name of the event
2168
- * @param {Object} [options] A dictionary object that allows for setting
2169
- * attributes via object members of the same name
2170
- * @param {*} [options.data=null] The message content
2171
- */
2172
- constructor(type, options = {}) {
2173
- super(type);
2174
-
2175
- this[kData] = options.data === undefined ? null : options.data;
2176
- }
2177
-
2178
- /**
2179
- * @type {*}
2180
- */
2181
- get data() {
2182
- return this[kData];
2183
- }
2184
- }
2185
-
2186
- Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
2187
-
2188
- /**
2189
- * This provides methods for emulating the `EventTarget` interface. It's not
2190
- * meant to be used directly.
2191
- *
2192
- * @mixin
2193
- */
2194
- const EventTarget = {
2195
- /**
2196
- * Register an event listener.
2197
- *
2198
- * @param {String} type A string representing the event type to listen for
2199
- * @param {Function} listener The listener to add
2200
- * @param {Object} [options] An options object specifies characteristics about
2201
- * the event listener
2202
- * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2203
- * listener should be invoked at most once after being added. If `true`,
2204
- * the listener would be automatically removed when invoked.
2205
- * @public
2206
- */
2207
- addEventListener(type, listener, options = {}) {
2208
- let wrapper;
2209
-
2210
- if (type === 'message') {
2211
- wrapper = function onMessage(data, isBinary) {
2212
- const event = new MessageEvent('message', {
2213
- data: isBinary ? data : data.toString()
2214
- });
2215
-
2216
- event[kTarget] = this;
2217
- listener.call(this, event);
2218
- };
2219
- } else if (type === 'close') {
2220
- wrapper = function onClose(code, message) {
2221
- const event = new CloseEvent('close', {
2222
- code,
2223
- reason: message.toString(),
2224
- wasClean: this._closeFrameReceived && this._closeFrameSent
2225
- });
2226
-
2227
- event[kTarget] = this;
2228
- listener.call(this, event);
2229
- };
2230
- } else if (type === 'error') {
2231
- wrapper = function onError(error) {
2232
- const event = new ErrorEvent('error', {
2233
- error,
2234
- message: error.message
2235
- });
2236
-
2237
- event[kTarget] = this;
2238
- listener.call(this, event);
2239
- };
2240
- } else if (type === 'open') {
2241
- wrapper = function onOpen() {
2242
- const event = new Event('open');
2243
-
2244
- event[kTarget] = this;
2245
- listener.call(this, event);
2246
- };
2247
- } else {
2248
- return;
2249
- }
2250
-
2251
- wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1];
2252
- wrapper[kListener$1] = listener;
2253
-
2254
- if (options.once) {
2255
- this.once(type, wrapper);
2256
- } else {
2257
- this.on(type, wrapper);
2258
- }
2259
- },
2260
-
2261
- /**
2262
- * Remove an event listener.
2263
- *
2264
- * @param {String} type A string representing the event type to remove
2265
- * @param {Function} handler The listener to remove
2266
- * @public
2267
- */
2268
- removeEventListener(type, handler) {
2269
- for (const listener of this.listeners(type)) {
2270
- if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) {
2271
- this.removeListener(type, listener);
2272
- break;
2273
- }
2274
- }
2275
- }
2276
- };
2277
-
2278
- var eventTarget = {
2279
- CloseEvent,
2280
- ErrorEvent,
2281
- Event,
2282
- EventTarget,
2283
- MessageEvent
2284
- };
2285
-
2286
- const { tokenChars: tokenChars$1 } = validation.exports;
2287
-
2288
- /**
2289
- * Adds an offer to the map of extension offers or a parameter to the map of
2290
- * parameters.
2291
- *
2292
- * @param {Object} dest The map of extension offers or parameters
2293
- * @param {String} name The extension or parameter name
2294
- * @param {(Object|Boolean|String)} elem The extension parameters or the
2295
- * parameter value
2296
- * @private
2297
- */
2298
- function push(dest, name, elem) {
2299
- if (dest[name] === undefined) dest[name] = [elem];
2300
- else dest[name].push(elem);
2301
- }
2302
-
2303
- /**
2304
- * Parses the `Sec-WebSocket-Extensions` header into an object.
2305
- *
2306
- * @param {String} header The field value of the header
2307
- * @return {Object} The parsed object
2308
- * @public
2309
- */
2310
- function parse$2(header) {
2311
- const offers = Object.create(null);
2312
- let params = Object.create(null);
2313
- let mustUnescape = false;
2314
- let isEscaping = false;
2315
- let inQuotes = false;
2316
- let extensionName;
2317
- let paramName;
2318
- let start = -1;
2319
- let code = -1;
2320
- let end = -1;
2321
- let i = 0;
2322
-
2323
- for (; i < header.length; i++) {
2324
- code = header.charCodeAt(i);
2325
-
2326
- if (extensionName === undefined) {
2327
- if (end === -1 && tokenChars$1[code] === 1) {
2328
- if (start === -1) start = i;
2329
- } else if (
2330
- i !== 0 &&
2331
- (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
2332
- ) {
2333
- if (end === -1 && start !== -1) end = i;
2334
- } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
2335
- if (start === -1) {
2336
- throw new SyntaxError(`Unexpected character at index ${i}`);
2337
- }
2338
-
2339
- if (end === -1) end = i;
2340
- const name = header.slice(start, end);
2341
- if (code === 0x2c) {
2342
- push(offers, name, params);
2343
- params = Object.create(null);
2344
- } else {
2345
- extensionName = name;
2346
- }
2347
-
2348
- start = end = -1;
2349
- } else {
2350
- throw new SyntaxError(`Unexpected character at index ${i}`);
2351
- }
2352
- } else if (paramName === undefined) {
2353
- if (end === -1 && tokenChars$1[code] === 1) {
2354
- if (start === -1) start = i;
2355
- } else if (code === 0x20 || code === 0x09) {
2356
- if (end === -1 && start !== -1) end = i;
2357
- } else if (code === 0x3b || code === 0x2c) {
2358
- if (start === -1) {
2359
- throw new SyntaxError(`Unexpected character at index ${i}`);
2360
- }
2361
-
2362
- if (end === -1) end = i;
2363
- push(params, header.slice(start, end), true);
2364
- if (code === 0x2c) {
2365
- push(offers, extensionName, params);
2366
- params = Object.create(null);
2367
- extensionName = undefined;
2368
- }
2369
-
2370
- start = end = -1;
2371
- } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
2372
- paramName = header.slice(start, i);
2373
- start = end = -1;
2374
- } else {
2375
- throw new SyntaxError(`Unexpected character at index ${i}`);
2376
- }
2377
- } else {
2378
- //
2379
- // The value of a quoted-string after unescaping must conform to the
2380
- // token ABNF, so only token characters are valid.
2381
- // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
2382
- //
2383
- if (isEscaping) {
2384
- if (tokenChars$1[code] !== 1) {
2385
- throw new SyntaxError(`Unexpected character at index ${i}`);
2386
- }
2387
- if (start === -1) start = i;
2388
- else if (!mustUnescape) mustUnescape = true;
2389
- isEscaping = false;
2390
- } else if (inQuotes) {
2391
- if (tokenChars$1[code] === 1) {
2392
- if (start === -1) start = i;
2393
- } else if (code === 0x22 /* '"' */ && start !== -1) {
2394
- inQuotes = false;
2395
- end = i;
2396
- } else if (code === 0x5c /* '\' */) {
2397
- isEscaping = true;
2398
- } else {
2399
- throw new SyntaxError(`Unexpected character at index ${i}`);
2400
- }
2401
- } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
2402
- inQuotes = true;
2403
- } else if (end === -1 && tokenChars$1[code] === 1) {
2404
- if (start === -1) start = i;
2405
- } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
2406
- if (end === -1) end = i;
2407
- } else if (code === 0x3b || code === 0x2c) {
2408
- if (start === -1) {
2409
- throw new SyntaxError(`Unexpected character at index ${i}`);
2410
- }
2411
-
2412
- if (end === -1) end = i;
2413
- let value = header.slice(start, end);
2414
- if (mustUnescape) {
2415
- value = value.replace(/\\/g, '');
2416
- mustUnescape = false;
2417
- }
2418
- push(params, paramName, value);
2419
- if (code === 0x2c) {
2420
- push(offers, extensionName, params);
2421
- params = Object.create(null);
2422
- extensionName = undefined;
2423
- }
2424
-
2425
- paramName = undefined;
2426
- start = end = -1;
2427
- } else {
2428
- throw new SyntaxError(`Unexpected character at index ${i}`);
2429
- }
2430
- }
2431
- }
2432
-
2433
- if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
2434
- throw new SyntaxError('Unexpected end of input');
2435
- }
2436
-
2437
- if (end === -1) end = i;
2438
- const token = header.slice(start, end);
2439
- if (extensionName === undefined) {
2440
- push(offers, token, params);
2441
- } else {
2442
- if (paramName === undefined) {
2443
- push(params, token, true);
2444
- } else if (mustUnescape) {
2445
- push(params, paramName, token.replace(/\\/g, ''));
2446
- } else {
2447
- push(params, paramName, token);
2448
- }
2449
- push(offers, extensionName, params);
2450
- }
2451
-
2452
- return offers;
2453
- }
2454
-
2455
- /**
2456
- * Builds the `Sec-WebSocket-Extensions` header field value.
2457
- *
2458
- * @param {Object} extensions The map of extensions and parameters to format
2459
- * @return {String} A string representing the given object
2460
- * @public
2461
- */
2462
- function format$1(extensions) {
2463
- return Object.keys(extensions)
2464
- .map((extension) => {
2465
- let configurations = extensions[extension];
2466
- if (!Array.isArray(configurations)) configurations = [configurations];
2467
- return configurations
2468
- .map((params) => {
2469
- return [extension]
2470
- .concat(
2471
- Object.keys(params).map((k) => {
2472
- let values = params[k];
2473
- if (!Array.isArray(values)) values = [values];
2474
- return values
2475
- .map((v) => (v === true ? k : `${k}=${v}`))
2476
- .join('; ');
2477
- })
2478
- )
2479
- .join('; ');
2480
- })
2481
- .join(', ');
2482
- })
2483
- .join(', ');
2484
- }
2485
-
2486
- var extension$1 = { format: format$1, parse: parse$2 };
2487
-
2488
- /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */
2489
-
2490
- const EventEmitter$1 = require$$2;
2491
- const https = require$$1;
2492
- const http$1 = require$$2$1;
2493
- const net = require$$3;
2494
- const tls = require$$4;
2495
- const { randomBytes, createHash: createHash$1 } = require$$5;
2496
- const { URL: URL$1 } = require$$7;
2497
-
2498
- const PerMessageDeflate$1 = permessageDeflate;
2499
- const Receiver = receiver;
2500
- const Sender = sender;
2501
- const {
2502
- BINARY_TYPES,
2503
- EMPTY_BUFFER,
2504
- GUID: GUID$1,
2505
- kForOnEventAttribute,
2506
- kListener,
2507
- kStatusCode,
2508
- kWebSocket: kWebSocket$1,
2509
- NOOP
2510
- } = constants;
2511
- const {
2512
- EventTarget: { addEventListener, removeEventListener }
2513
- } = eventTarget;
2514
- const { format, parse: parse$1 } = extension$1;
2515
- const { toBuffer } = bufferUtil$1.exports;
2516
-
2517
- const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
2518
- const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2519
- const protocolVersions = [8, 13];
2520
- const closeTimeout = 30 * 1000;
2521
-
2522
- /**
2523
- * Class representing a WebSocket.
2524
- *
2525
- * @extends EventEmitter
2526
- */
2527
- class WebSocket$1 extends EventEmitter$1 {
2528
- /**
2529
- * Create a new `WebSocket`.
2530
- *
2531
- * @param {(String|URL)} address The URL to which to connect
2532
- * @param {(String|String[])} [protocols] The subprotocols
2533
- * @param {Object} [options] Connection options
2534
- */
2535
- constructor(address, protocols, options) {
2536
- super();
2537
-
2538
- this._binaryType = BINARY_TYPES[0];
2539
- this._closeCode = 1006;
2540
- this._closeFrameReceived = false;
2541
- this._closeFrameSent = false;
2542
- this._closeMessage = EMPTY_BUFFER;
2543
- this._closeTimer = null;
2544
- this._extensions = {};
2545
- this._paused = false;
2546
- this._protocol = '';
2547
- this._readyState = WebSocket$1.CONNECTING;
2548
- this._receiver = null;
2549
- this._sender = null;
2550
- this._socket = null;
2551
-
2552
- if (address !== null) {
2553
- this._bufferedAmount = 0;
2554
- this._isServer = false;
2555
- this._redirects = 0;
2556
-
2557
- if (protocols === undefined) {
2558
- protocols = [];
2559
- } else if (!Array.isArray(protocols)) {
2560
- if (typeof protocols === 'object' && protocols !== null) {
2561
- options = protocols;
2562
- protocols = [];
2563
- } else {
2564
- protocols = [protocols];
2565
- }
2566
- }
2567
-
2568
- initAsClient(this, address, protocols, options);
2569
- } else {
2570
- this._isServer = true;
2571
- }
2572
- }
2573
-
2574
- /**
2575
- * This deviates from the WHATWG interface since ws doesn't support the
2576
- * required default "blob" type (instead we define a custom "nodebuffer"
2577
- * type).
2578
- *
2579
- * @type {String}
2580
- */
2581
- get binaryType() {
2582
- return this._binaryType;
2583
- }
2584
-
2585
- set binaryType(type) {
2586
- if (!BINARY_TYPES.includes(type)) return;
2587
-
2588
- this._binaryType = type;
2589
-
2590
- //
2591
- // Allow to change `binaryType` on the fly.
2592
- //
2593
- if (this._receiver) this._receiver._binaryType = type;
2594
- }
2595
-
2596
- /**
2597
- * @type {Number}
2598
- */
2599
- get bufferedAmount() {
2600
- if (!this._socket) return this._bufferedAmount;
2601
-
2602
- return this._socket._writableState.length + this._sender._bufferedBytes;
2603
- }
2604
-
2605
- /**
2606
- * @type {String}
2607
- */
2608
- get extensions() {
2609
- return Object.keys(this._extensions).join();
2610
- }
2611
-
2612
- /**
2613
- * @type {Boolean}
2614
- */
2615
- get isPaused() {
2616
- return this._paused;
2617
- }
2618
-
2619
- /**
2620
- * @type {Function}
2621
- */
2622
- /* istanbul ignore next */
2623
- get onclose() {
2624
- return null;
2625
- }
2626
-
2627
- /**
2628
- * @type {Function}
2629
- */
2630
- /* istanbul ignore next */
2631
- get onerror() {
2632
- return null;
2633
- }
2634
-
2635
- /**
2636
- * @type {Function}
2637
- */
2638
- /* istanbul ignore next */
2639
- get onopen() {
2640
- return null;
2641
- }
2642
-
2643
- /**
2644
- * @type {Function}
2645
- */
2646
- /* istanbul ignore next */
2647
- get onmessage() {
2648
- return null;
2649
- }
2650
-
2651
- /**
2652
- * @type {String}
2653
- */
2654
- get protocol() {
2655
- return this._protocol;
2656
- }
2657
-
2658
- /**
2659
- * @type {Number}
2660
- */
2661
- get readyState() {
2662
- return this._readyState;
2663
- }
2664
-
2665
- /**
2666
- * @type {String}
2667
- */
2668
- get url() {
2669
- return this._url;
2670
- }
2671
-
2672
- /**
2673
- * Set up the socket and the internal resources.
2674
- *
2675
- * @param {(net.Socket|tls.Socket)} socket The network socket between the
2676
- * server and client
2677
- * @param {Buffer} head The first packet of the upgraded stream
2678
- * @param {Object} options Options object
2679
- * @param {Function} [options.generateMask] The function used to generate the
2680
- * masking key
2681
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
2682
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2683
- * not to skip UTF-8 validation for text and close messages
2684
- * @private
2685
- */
2686
- setSocket(socket, head, options) {
2687
- const receiver = new Receiver({
2688
- binaryType: this.binaryType,
2689
- extensions: this._extensions,
2690
- isServer: this._isServer,
2691
- maxPayload: options.maxPayload,
2692
- skipUTF8Validation: options.skipUTF8Validation
2693
- });
2694
-
2695
- this._sender = new Sender(socket, this._extensions, options.generateMask);
2696
- this._receiver = receiver;
2697
- this._socket = socket;
2698
-
2699
- receiver[kWebSocket$1] = this;
2700
- socket[kWebSocket$1] = this;
2701
-
2702
- receiver.on('conclude', receiverOnConclude);
2703
- receiver.on('drain', receiverOnDrain);
2704
- receiver.on('error', receiverOnError);
2705
- receiver.on('message', receiverOnMessage);
2706
- receiver.on('ping', receiverOnPing);
2707
- receiver.on('pong', receiverOnPong);
2708
-
2709
- socket.setTimeout(0);
2710
- socket.setNoDelay();
2711
-
2712
- if (head.length > 0) socket.unshift(head);
2713
-
2714
- socket.on('close', socketOnClose);
2715
- socket.on('data', socketOnData);
2716
- socket.on('end', socketOnEnd);
2717
- socket.on('error', socketOnError$1);
2718
-
2719
- this._readyState = WebSocket$1.OPEN;
2720
- this.emit('open');
2721
- }
2722
-
2723
- /**
2724
- * Emit the `'close'` event.
2725
- *
2726
- * @private
2727
- */
2728
- emitClose() {
2729
- if (!this._socket) {
2730
- this._readyState = WebSocket$1.CLOSED;
2731
- this.emit('close', this._closeCode, this._closeMessage);
2732
- return;
2733
- }
2734
-
2735
- if (this._extensions[PerMessageDeflate$1.extensionName]) {
2736
- this._extensions[PerMessageDeflate$1.extensionName].cleanup();
2737
- }
2738
-
2739
- this._receiver.removeAllListeners();
2740
- this._readyState = WebSocket$1.CLOSED;
2741
- this.emit('close', this._closeCode, this._closeMessage);
2742
- }
2743
-
2744
- /**
2745
- * Start a closing handshake.
2746
- *
2747
- * +----------+ +-----------+ +----------+
2748
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2749
- * | +----------+ +-----------+ +----------+ |
2750
- * +----------+ +-----------+ |
2751
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2752
- * +----------+ +-----------+ |
2753
- * | | | +---+ |
2754
- * +------------------------+-->|fin| - - - -
2755
- * | +---+ | +---+
2756
- * - - - - -|fin|<---------------------+
2757
- * +---+
2758
- *
2759
- * @param {Number} [code] Status code explaining why the connection is closing
2760
- * @param {(String|Buffer)} [data] The reason why the connection is
2761
- * closing
2762
- * @public
2763
- */
2764
- close(code, data) {
2765
- if (this.readyState === WebSocket$1.CLOSED) return;
2766
- if (this.readyState === WebSocket$1.CONNECTING) {
2767
- const msg = 'WebSocket was closed before the connection was established';
2768
- return abortHandshake$1(this, this._req, msg);
2769
- }
2770
-
2771
- if (this.readyState === WebSocket$1.CLOSING) {
2772
- if (
2773
- this._closeFrameSent &&
2774
- (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
2775
- ) {
2776
- this._socket.end();
2777
- }
2778
-
2779
- return;
2780
- }
2781
-
2782
- this._readyState = WebSocket$1.CLOSING;
2783
- this._sender.close(code, data, !this._isServer, (err) => {
2784
- //
2785
- // This error is handled by the `'error'` listener on the socket. We only
2786
- // want to know if the close frame has been sent here.
2787
- //
2788
- if (err) return;
2789
-
2790
- this._closeFrameSent = true;
2791
-
2792
- if (
2793
- this._closeFrameReceived ||
2794
- this._receiver._writableState.errorEmitted
2795
- ) {
2796
- this._socket.end();
2797
- }
2798
- });
2799
-
2800
- //
2801
- // Specify a timeout for the closing handshake to complete.
2802
- //
2803
- this._closeTimer = setTimeout(
2804
- this._socket.destroy.bind(this._socket),
2805
- closeTimeout
2806
- );
2807
- }
2808
-
2809
- /**
2810
- * Pause the socket.
2811
- *
2812
- * @public
2813
- */
2814
- pause() {
2815
- if (
2816
- this.readyState === WebSocket$1.CONNECTING ||
2817
- this.readyState === WebSocket$1.CLOSED
2818
- ) {
2819
- return;
2820
- }
2821
-
2822
- this._paused = true;
2823
- this._socket.pause();
2824
- }
2825
-
2826
- /**
2827
- * Send a ping.
2828
- *
2829
- * @param {*} [data] The data to send
2830
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2831
- * @param {Function} [cb] Callback which is executed when the ping is sent
2832
- * @public
2833
- */
2834
- ping(data, mask, cb) {
2835
- if (this.readyState === WebSocket$1.CONNECTING) {
2836
- throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
2837
- }
2838
-
2839
- if (typeof data === 'function') {
2840
- cb = data;
2841
- data = mask = undefined;
2842
- } else if (typeof mask === 'function') {
2843
- cb = mask;
2844
- mask = undefined;
2845
- }
2846
-
2847
- if (typeof data === 'number') data = data.toString();
2848
-
2849
- if (this.readyState !== WebSocket$1.OPEN) {
2850
- sendAfterClose(this, data, cb);
2851
- return;
2852
- }
2853
-
2854
- if (mask === undefined) mask = !this._isServer;
2855
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2856
- }
2857
-
2858
- /**
2859
- * Send a pong.
2860
- *
2861
- * @param {*} [data] The data to send
2862
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2863
- * @param {Function} [cb] Callback which is executed when the pong is sent
2864
- * @public
2865
- */
2866
- pong(data, mask, cb) {
2867
- if (this.readyState === WebSocket$1.CONNECTING) {
2868
- throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
2869
- }
2870
-
2871
- if (typeof data === 'function') {
2872
- cb = data;
2873
- data = mask = undefined;
2874
- } else if (typeof mask === 'function') {
2875
- cb = mask;
2876
- mask = undefined;
2877
- }
2878
-
2879
- if (typeof data === 'number') data = data.toString();
2880
-
2881
- if (this.readyState !== WebSocket$1.OPEN) {
2882
- sendAfterClose(this, data, cb);
2883
- return;
2884
- }
2885
-
2886
- if (mask === undefined) mask = !this._isServer;
2887
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2888
- }
2889
-
2890
- /**
2891
- * Resume the socket.
2892
- *
2893
- * @public
2894
- */
2895
- resume() {
2896
- if (
2897
- this.readyState === WebSocket$1.CONNECTING ||
2898
- this.readyState === WebSocket$1.CLOSED
2899
- ) {
2900
- return;
2901
- }
2902
-
2903
- this._paused = false;
2904
- if (!this._receiver._writableState.needDrain) this._socket.resume();
2905
- }
2906
-
2907
- /**
2908
- * Send a data message.
2909
- *
2910
- * @param {*} data The message to send
2911
- * @param {Object} [options] Options object
2912
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2913
- * text
2914
- * @param {Boolean} [options.compress] Specifies whether or not to compress
2915
- * `data`
2916
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2917
- * last one
2918
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2919
- * @param {Function} [cb] Callback which is executed when data is written out
2920
- * @public
2921
- */
2922
- send(data, options, cb) {
2923
- if (this.readyState === WebSocket$1.CONNECTING) {
2924
- throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
2925
- }
2926
-
2927
- if (typeof options === 'function') {
2928
- cb = options;
2929
- options = {};
2930
- }
2931
-
2932
- if (typeof data === 'number') data = data.toString();
2933
-
2934
- if (this.readyState !== WebSocket$1.OPEN) {
2935
- sendAfterClose(this, data, cb);
2936
- return;
2937
- }
2938
-
2939
- const opts = {
2940
- binary: typeof data !== 'string',
2941
- mask: !this._isServer,
2942
- compress: true,
2943
- fin: true,
2944
- ...options
2945
- };
2946
-
2947
- if (!this._extensions[PerMessageDeflate$1.extensionName]) {
2948
- opts.compress = false;
2949
- }
2950
-
2951
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
2952
- }
2953
-
2954
- /**
2955
- * Forcibly close the connection.
2956
- *
2957
- * @public
2958
- */
2959
- terminate() {
2960
- if (this.readyState === WebSocket$1.CLOSED) return;
2961
- if (this.readyState === WebSocket$1.CONNECTING) {
2962
- const msg = 'WebSocket was closed before the connection was established';
2963
- return abortHandshake$1(this, this._req, msg);
2964
- }
2965
-
2966
- if (this._socket) {
2967
- this._readyState = WebSocket$1.CLOSING;
2968
- this._socket.destroy();
2969
- }
2970
- }
2971
- }
2972
-
2973
- /**
2974
- * @constant {Number} CONNECTING
2975
- * @memberof WebSocket
2976
- */
2977
- Object.defineProperty(WebSocket$1, 'CONNECTING', {
2978
- enumerable: true,
2979
- value: readyStates.indexOf('CONNECTING')
2980
- });
2981
-
2982
- /**
2983
- * @constant {Number} CONNECTING
2984
- * @memberof WebSocket.prototype
2985
- */
2986
- Object.defineProperty(WebSocket$1.prototype, 'CONNECTING', {
2987
- enumerable: true,
2988
- value: readyStates.indexOf('CONNECTING')
2989
- });
2990
-
2991
- /**
2992
- * @constant {Number} OPEN
2993
- * @memberof WebSocket
2994
- */
2995
- Object.defineProperty(WebSocket$1, 'OPEN', {
2996
- enumerable: true,
2997
- value: readyStates.indexOf('OPEN')
2998
- });
2999
-
3000
- /**
3001
- * @constant {Number} OPEN
3002
- * @memberof WebSocket.prototype
3003
- */
3004
- Object.defineProperty(WebSocket$1.prototype, 'OPEN', {
3005
- enumerable: true,
3006
- value: readyStates.indexOf('OPEN')
3007
- });
3008
-
3009
- /**
3010
- * @constant {Number} CLOSING
3011
- * @memberof WebSocket
3012
- */
3013
- Object.defineProperty(WebSocket$1, 'CLOSING', {
3014
- enumerable: true,
3015
- value: readyStates.indexOf('CLOSING')
3016
- });
3017
-
3018
- /**
3019
- * @constant {Number} CLOSING
3020
- * @memberof WebSocket.prototype
3021
- */
3022
- Object.defineProperty(WebSocket$1.prototype, 'CLOSING', {
3023
- enumerable: true,
3024
- value: readyStates.indexOf('CLOSING')
3025
- });
3026
-
3027
- /**
3028
- * @constant {Number} CLOSED
3029
- * @memberof WebSocket
3030
- */
3031
- Object.defineProperty(WebSocket$1, 'CLOSED', {
3032
- enumerable: true,
3033
- value: readyStates.indexOf('CLOSED')
3034
- });
3035
-
3036
- /**
3037
- * @constant {Number} CLOSED
3038
- * @memberof WebSocket.prototype
3039
- */
3040
- Object.defineProperty(WebSocket$1.prototype, 'CLOSED', {
3041
- enumerable: true,
3042
- value: readyStates.indexOf('CLOSED')
3043
- });
3044
-
3045
- [
3046
- 'binaryType',
3047
- 'bufferedAmount',
3048
- 'extensions',
3049
- 'isPaused',
3050
- 'protocol',
3051
- 'readyState',
3052
- 'url'
3053
- ].forEach((property) => {
3054
- Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true });
3055
- });
3056
-
3057
- //
3058
- // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
3059
- // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
3060
- //
3061
- ['open', 'error', 'close', 'message'].forEach((method) => {
3062
- Object.defineProperty(WebSocket$1.prototype, `on${method}`, {
3063
- enumerable: true,
3064
- get() {
3065
- for (const listener of this.listeners(method)) {
3066
- if (listener[kForOnEventAttribute]) return listener[kListener];
3067
- }
3068
-
3069
- return null;
3070
- },
3071
- set(handler) {
3072
- for (const listener of this.listeners(method)) {
3073
- if (listener[kForOnEventAttribute]) {
3074
- this.removeListener(method, listener);
3075
- break;
3076
- }
3077
- }
3078
-
3079
- if (typeof handler !== 'function') return;
3080
-
3081
- this.addEventListener(method, handler, {
3082
- [kForOnEventAttribute]: true
3083
- });
3084
- }
3085
- });
3086
- });
3087
-
3088
- WebSocket$1.prototype.addEventListener = addEventListener;
3089
- WebSocket$1.prototype.removeEventListener = removeEventListener;
3090
-
3091
- var websocket = WebSocket$1;
3092
-
3093
- /**
3094
- * Initialize a WebSocket client.
3095
- *
3096
- * @param {WebSocket} websocket The client to initialize
3097
- * @param {(String|URL)} address The URL to which to connect
3098
- * @param {Array} protocols The subprotocols
3099
- * @param {Object} [options] Connection options
3100
- * @param {Boolean} [options.followRedirects=false] Whether or not to follow
3101
- * redirects
3102
- * @param {Function} [options.generateMask] The function used to generate the
3103
- * masking key
3104
- * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
3105
- * handshake request
3106
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3107
- * size
3108
- * @param {Number} [options.maxRedirects=10] The maximum number of redirects
3109
- * allowed
3110
- * @param {String} [options.origin] Value of the `Origin` or
3111
- * `Sec-WebSocket-Origin` header
3112
- * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
3113
- * permessage-deflate
3114
- * @param {Number} [options.protocolVersion=13] Value of the
3115
- * `Sec-WebSocket-Version` header
3116
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3117
- * not to skip UTF-8 validation for text and close messages
3118
- * @private
3119
- */
3120
- function initAsClient(websocket, address, protocols, options) {
3121
- const opts = {
3122
- protocolVersion: protocolVersions[1],
3123
- maxPayload: 100 * 1024 * 1024,
3124
- skipUTF8Validation: false,
3125
- perMessageDeflate: true,
3126
- followRedirects: false,
3127
- maxRedirects: 10,
3128
- ...options,
3129
- createConnection: undefined,
3130
- socketPath: undefined,
3131
- hostname: undefined,
3132
- protocol: undefined,
3133
- timeout: undefined,
3134
- method: undefined,
3135
- host: undefined,
3136
- path: undefined,
3137
- port: undefined
3138
- };
3139
-
3140
- if (!protocolVersions.includes(opts.protocolVersion)) {
3141
- throw new RangeError(
3142
- `Unsupported protocol version: ${opts.protocolVersion} ` +
3143
- `(supported versions: ${protocolVersions.join(', ')})`
3144
- );
3145
- }
3146
-
3147
- let parsedUrl;
3148
-
3149
- if (address instanceof URL$1) {
3150
- parsedUrl = address;
3151
- websocket._url = address.href;
3152
- } else {
3153
- try {
3154
- parsedUrl = new URL$1(address);
3155
- } catch (e) {
3156
- throw new SyntaxError(`Invalid URL: ${address}`);
3157
- }
3158
-
3159
- websocket._url = address;
3160
- }
3161
-
3162
- const isSecure = parsedUrl.protocol === 'wss:';
3163
- const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
3164
- let invalidURLMessage;
3165
-
3166
- if (parsedUrl.protocol !== 'ws:' && !isSecure && !isUnixSocket) {
3167
- invalidURLMessage =
3168
- 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"';
3169
- } else if (isUnixSocket && !parsedUrl.pathname) {
3170
- invalidURLMessage = "The URL's pathname is empty";
3171
- } else if (parsedUrl.hash) {
3172
- invalidURLMessage = 'The URL contains a fragment identifier';
3173
- }
3174
-
3175
- if (invalidURLMessage) {
3176
- const err = new SyntaxError(invalidURLMessage);
3177
-
3178
- if (websocket._redirects === 0) {
3179
- throw err;
3180
- } else {
3181
- emitErrorAndClose(websocket, err);
3182
- return;
3183
- }
3184
- }
3185
-
3186
- const defaultPort = isSecure ? 443 : 80;
3187
- const key = randomBytes(16).toString('base64');
3188
- const get = isSecure ? https.get : http$1.get;
3189
- const protocolSet = new Set();
3190
- let perMessageDeflate;
3191
-
3192
- opts.createConnection = isSecure ? tlsConnect : netConnect;
3193
- opts.defaultPort = opts.defaultPort || defaultPort;
3194
- opts.port = parsedUrl.port || defaultPort;
3195
- opts.host = parsedUrl.hostname.startsWith('[')
3196
- ? parsedUrl.hostname.slice(1, -1)
3197
- : parsedUrl.hostname;
3198
- opts.headers = {
3199
- 'Sec-WebSocket-Version': opts.protocolVersion,
3200
- 'Sec-WebSocket-Key': key,
3201
- Connection: 'Upgrade',
3202
- Upgrade: 'websocket',
3203
- ...opts.headers
3204
- };
3205
- opts.path = parsedUrl.pathname + parsedUrl.search;
3206
- opts.timeout = opts.handshakeTimeout;
3207
-
3208
- if (opts.perMessageDeflate) {
3209
- perMessageDeflate = new PerMessageDeflate$1(
3210
- opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
3211
- false,
3212
- opts.maxPayload
3213
- );
3214
- opts.headers['Sec-WebSocket-Extensions'] = format({
3215
- [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer()
3216
- });
3217
- }
3218
- if (protocols.length) {
3219
- for (const protocol of protocols) {
3220
- if (
3221
- typeof protocol !== 'string' ||
3222
- !subprotocolRegex.test(protocol) ||
3223
- protocolSet.has(protocol)
3224
- ) {
3225
- throw new SyntaxError(
3226
- 'An invalid or duplicated subprotocol was specified'
3227
- );
3228
- }
3229
-
3230
- protocolSet.add(protocol);
3231
- }
3232
-
3233
- opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
3234
- }
3235
- if (opts.origin) {
3236
- if (opts.protocolVersion < 13) {
3237
- opts.headers['Sec-WebSocket-Origin'] = opts.origin;
3238
- } else {
3239
- opts.headers.Origin = opts.origin;
3240
- }
3241
- }
3242
- if (parsedUrl.username || parsedUrl.password) {
3243
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
3244
- }
3245
-
3246
- if (isUnixSocket) {
3247
- const parts = opts.path.split(':');
3248
-
3249
- opts.socketPath = parts[0];
3250
- opts.path = parts[1];
3251
- }
3252
-
3253
- let req = (websocket._req = get(opts));
3254
-
3255
- if (opts.timeout) {
3256
- req.on('timeout', () => {
3257
- abortHandshake$1(websocket, req, 'Opening handshake has timed out');
3258
- });
3259
- }
3260
-
3261
- req.on('error', (err) => {
3262
- if (req === null || req.aborted) return;
3263
-
3264
- req = websocket._req = null;
3265
- emitErrorAndClose(websocket, err);
3266
- });
3267
-
3268
- req.on('response', (res) => {
3269
- const location = res.headers.location;
3270
- const statusCode = res.statusCode;
3271
-
3272
- if (
3273
- location &&
3274
- opts.followRedirects &&
3275
- statusCode >= 300 &&
3276
- statusCode < 400
3277
- ) {
3278
- if (++websocket._redirects > opts.maxRedirects) {
3279
- abortHandshake$1(websocket, req, 'Maximum redirects exceeded');
3280
- return;
3281
- }
3282
-
3283
- req.abort();
3284
-
3285
- let addr;
3286
-
3287
- try {
3288
- addr = new URL$1(location, address);
3289
- } catch (e) {
3290
- const err = new SyntaxError(`Invalid URL: ${location}`);
3291
- emitErrorAndClose(websocket, err);
3292
- return;
3293
- }
3294
-
3295
- initAsClient(websocket, addr, protocols, options);
3296
- } else if (!websocket.emit('unexpected-response', req, res)) {
3297
- abortHandshake$1(
3298
- websocket,
3299
- req,
3300
- `Unexpected server response: ${res.statusCode}`
3301
- );
3302
- }
3303
- });
3304
-
3305
- req.on('upgrade', (res, socket, head) => {
3306
- websocket.emit('upgrade', res);
3307
-
3308
- //
3309
- // The user may have closed the connection from a listener of the `upgrade`
3310
- // event.
3311
- //
3312
- if (websocket.readyState !== WebSocket$1.CONNECTING) return;
3313
-
3314
- req = websocket._req = null;
3315
-
3316
- const digest = createHash$1('sha1')
3317
- .update(key + GUID$1)
3318
- .digest('base64');
3319
-
3320
- if (res.headers['sec-websocket-accept'] !== digest) {
3321
- abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
3322
- return;
3323
- }
3324
-
3325
- const serverProt = res.headers['sec-websocket-protocol'];
3326
- let protError;
3327
-
3328
- if (serverProt !== undefined) {
3329
- if (!protocolSet.size) {
3330
- protError = 'Server sent a subprotocol but none was requested';
3331
- } else if (!protocolSet.has(serverProt)) {
3332
- protError = 'Server sent an invalid subprotocol';
3333
- }
3334
- } else if (protocolSet.size) {
3335
- protError = 'Server sent no subprotocol';
3336
- }
3337
-
3338
- if (protError) {
3339
- abortHandshake$1(websocket, socket, protError);
3340
- return;
3341
- }
3342
-
3343
- if (serverProt) websocket._protocol = serverProt;
3344
-
3345
- const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
3346
-
3347
- if (secWebSocketExtensions !== undefined) {
3348
- if (!perMessageDeflate) {
3349
- const message =
3350
- 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
3351
- 'was requested';
3352
- abortHandshake$1(websocket, socket, message);
3353
- return;
3354
- }
3355
-
3356
- let extensions;
3357
-
3358
- try {
3359
- extensions = parse$1(secWebSocketExtensions);
3360
- } catch (err) {
3361
- const message = 'Invalid Sec-WebSocket-Extensions header';
3362
- abortHandshake$1(websocket, socket, message);
3363
- return;
3364
- }
3365
-
3366
- const extensionNames = Object.keys(extensions);
3367
-
3368
- if (
3369
- extensionNames.length !== 1 ||
3370
- extensionNames[0] !== PerMessageDeflate$1.extensionName
3371
- ) {
3372
- const message = 'Server indicated an extension that was not requested';
3373
- abortHandshake$1(websocket, socket, message);
3374
- return;
3375
- }
3376
-
3377
- try {
3378
- perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]);
3379
- } catch (err) {
3380
- const message = 'Invalid Sec-WebSocket-Extensions header';
3381
- abortHandshake$1(websocket, socket, message);
3382
- return;
3383
- }
3384
-
3385
- websocket._extensions[PerMessageDeflate$1.extensionName] =
3386
- perMessageDeflate;
3387
- }
3388
-
3389
- websocket.setSocket(socket, head, {
3390
- generateMask: opts.generateMask,
3391
- maxPayload: opts.maxPayload,
3392
- skipUTF8Validation: opts.skipUTF8Validation
3393
- });
3394
- });
3395
- }
3396
-
3397
- /**
3398
- * Emit the `'error'` and `'close'` event.
3399
- *
3400
- * @param {WebSocket} websocket The WebSocket instance
3401
- * @param {Error} The error to emit
3402
- * @private
3403
- */
3404
- function emitErrorAndClose(websocket, err) {
3405
- websocket._readyState = WebSocket$1.CLOSING;
3406
- websocket.emit('error', err);
3407
- websocket.emitClose();
3408
- }
3409
-
3410
- /**
3411
- * Create a `net.Socket` and initiate a connection.
3412
- *
3413
- * @param {Object} options Connection options
3414
- * @return {net.Socket} The newly created socket used to start the connection
3415
- * @private
3416
- */
3417
- function netConnect(options) {
3418
- options.path = options.socketPath;
3419
- return net.connect(options);
3420
- }
3421
-
3422
- /**
3423
- * Create a `tls.TLSSocket` and initiate a connection.
3424
- *
3425
- * @param {Object} options Connection options
3426
- * @return {tls.TLSSocket} The newly created socket used to start the connection
3427
- * @private
3428
- */
3429
- function tlsConnect(options) {
3430
- options.path = undefined;
3431
-
3432
- if (!options.servername && options.servername !== '') {
3433
- options.servername = net.isIP(options.host) ? '' : options.host;
3434
- }
3435
-
3436
- return tls.connect(options);
3437
- }
3438
-
3439
- /**
3440
- * Abort the handshake and emit an error.
3441
- *
3442
- * @param {WebSocket} websocket The WebSocket instance
3443
- * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
3444
- * abort or the socket to destroy
3445
- * @param {String} message The error message
3446
- * @private
3447
- */
3448
- function abortHandshake$1(websocket, stream, message) {
3449
- websocket._readyState = WebSocket$1.CLOSING;
3450
-
3451
- const err = new Error(message);
3452
- Error.captureStackTrace(err, abortHandshake$1);
3453
-
3454
- if (stream.setHeader) {
3455
- stream.abort();
3456
-
3457
- if (stream.socket && !stream.socket.destroyed) {
3458
- //
3459
- // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
3460
- // called after the request completed. See
3461
- // https://github.com/websockets/ws/issues/1869.
3462
- //
3463
- stream.socket.destroy();
3464
- }
3465
-
3466
- stream.once('abort', websocket.emitClose.bind(websocket));
3467
- websocket.emit('error', err);
3468
- } else {
3469
- stream.destroy(err);
3470
- stream.once('error', websocket.emit.bind(websocket, 'error'));
3471
- stream.once('close', websocket.emitClose.bind(websocket));
3472
- }
3473
- }
3474
-
3475
- /**
3476
- * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
3477
- * when the `readyState` attribute is `CLOSING` or `CLOSED`.
3478
- *
3479
- * @param {WebSocket} websocket The WebSocket instance
3480
- * @param {*} [data] The data to send
3481
- * @param {Function} [cb] Callback
3482
- * @private
3483
- */
3484
- function sendAfterClose(websocket, data, cb) {
3485
- if (data) {
3486
- const length = toBuffer(data).length;
3487
-
3488
- //
3489
- // The `_bufferedAmount` property is used only when the peer is a client and
3490
- // the opening handshake fails. Under these circumstances, in fact, the
3491
- // `setSocket()` method is not called, so the `_socket` and `_sender`
3492
- // properties are set to `null`.
3493
- //
3494
- if (websocket._socket) websocket._sender._bufferedBytes += length;
3495
- else websocket._bufferedAmount += length;
3496
- }
3497
-
3498
- if (cb) {
3499
- const err = new Error(
3500
- `WebSocket is not open: readyState ${websocket.readyState} ` +
3501
- `(${readyStates[websocket.readyState]})`
3502
- );
3503
- cb(err);
3504
- }
3505
- }
3506
-
3507
- /**
3508
- * The listener of the `Receiver` `'conclude'` event.
3509
- *
3510
- * @param {Number} code The status code
3511
- * @param {Buffer} reason The reason for closing
3512
- * @private
3513
- */
3514
- function receiverOnConclude(code, reason) {
3515
- const websocket = this[kWebSocket$1];
3516
-
3517
- websocket._closeFrameReceived = true;
3518
- websocket._closeMessage = reason;
3519
- websocket._closeCode = code;
3520
-
3521
- if (websocket._socket[kWebSocket$1] === undefined) return;
3522
-
3523
- websocket._socket.removeListener('data', socketOnData);
3524
- process.nextTick(resume, websocket._socket);
3525
-
3526
- if (code === 1005) websocket.close();
3527
- else websocket.close(code, reason);
3528
- }
3529
-
3530
- /**
3531
- * The listener of the `Receiver` `'drain'` event.
3532
- *
3533
- * @private
3534
- */
3535
- function receiverOnDrain() {
3536
- const websocket = this[kWebSocket$1];
3537
-
3538
- if (!websocket.isPaused) websocket._socket.resume();
3539
- }
3540
-
3541
- /**
3542
- * The listener of the `Receiver` `'error'` event.
3543
- *
3544
- * @param {(RangeError|Error)} err The emitted error
3545
- * @private
3546
- */
3547
- function receiverOnError(err) {
3548
- const websocket = this[kWebSocket$1];
3549
-
3550
- if (websocket._socket[kWebSocket$1] !== undefined) {
3551
- websocket._socket.removeListener('data', socketOnData);
3552
-
3553
- //
3554
- // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
3555
- // https://github.com/websockets/ws/issues/1940.
3556
- //
3557
- process.nextTick(resume, websocket._socket);
3558
-
3559
- websocket.close(err[kStatusCode]);
3560
- }
3561
-
3562
- websocket.emit('error', err);
3563
- }
3564
-
3565
- /**
3566
- * The listener of the `Receiver` `'finish'` event.
3567
- *
3568
- * @private
3569
- */
3570
- function receiverOnFinish() {
3571
- this[kWebSocket$1].emitClose();
3572
- }
3573
-
3574
- /**
3575
- * The listener of the `Receiver` `'message'` event.
3576
- *
3577
- * @param {Buffer|ArrayBuffer|Buffer[])} data The message
3578
- * @param {Boolean} isBinary Specifies whether the message is binary or not
3579
- * @private
3580
- */
3581
- function receiverOnMessage(data, isBinary) {
3582
- this[kWebSocket$1].emit('message', data, isBinary);
3583
- }
3584
-
3585
- /**
3586
- * The listener of the `Receiver` `'ping'` event.
3587
- *
3588
- * @param {Buffer} data The data included in the ping frame
3589
- * @private
3590
- */
3591
- function receiverOnPing(data) {
3592
- const websocket = this[kWebSocket$1];
3593
-
3594
- websocket.pong(data, !websocket._isServer, NOOP);
3595
- websocket.emit('ping', data);
3596
- }
3597
-
3598
- /**
3599
- * The listener of the `Receiver` `'pong'` event.
3600
- *
3601
- * @param {Buffer} data The data included in the pong frame
3602
- * @private
3603
- */
3604
- function receiverOnPong(data) {
3605
- this[kWebSocket$1].emit('pong', data);
3606
- }
3607
-
3608
- /**
3609
- * Resume a readable stream
3610
- *
3611
- * @param {Readable} stream The readable stream
3612
- * @private
3613
- */
3614
- function resume(stream) {
3615
- stream.resume();
3616
- }
3617
-
3618
- /**
3619
- * The listener of the `net.Socket` `'close'` event.
3620
- *
3621
- * @private
3622
- */
3623
- function socketOnClose() {
3624
- const websocket = this[kWebSocket$1];
3625
-
3626
- this.removeListener('close', socketOnClose);
3627
- this.removeListener('data', socketOnData);
3628
- this.removeListener('end', socketOnEnd);
3629
-
3630
- websocket._readyState = WebSocket$1.CLOSING;
3631
-
3632
- let chunk;
3633
-
3634
- //
3635
- // The close frame might not have been received or the `'end'` event emitted,
3636
- // for example, if the socket was destroyed due to an error. Ensure that the
3637
- // `receiver` stream is closed after writing any remaining buffered data to
3638
- // it. If the readable side of the socket is in flowing mode then there is no
3639
- // buffered data as everything has been already written and `readable.read()`
3640
- // will return `null`. If instead, the socket is paused, any possible buffered
3641
- // data will be read as a single chunk.
3642
- //
3643
- if (
3644
- !this._readableState.endEmitted &&
3645
- !websocket._closeFrameReceived &&
3646
- !websocket._receiver._writableState.errorEmitted &&
3647
- (chunk = websocket._socket.read()) !== null
3648
- ) {
3649
- websocket._receiver.write(chunk);
3650
- }
3651
-
3652
- websocket._receiver.end();
3653
-
3654
- this[kWebSocket$1] = undefined;
3655
-
3656
- clearTimeout(websocket._closeTimer);
3657
-
3658
- if (
3659
- websocket._receiver._writableState.finished ||
3660
- websocket._receiver._writableState.errorEmitted
3661
- ) {
3662
- websocket.emitClose();
3663
- } else {
3664
- websocket._receiver.on('error', receiverOnFinish);
3665
- websocket._receiver.on('finish', receiverOnFinish);
3666
- }
3667
- }
3668
-
3669
- /**
3670
- * The listener of the `net.Socket` `'data'` event.
3671
- *
3672
- * @param {Buffer} chunk A chunk of data
3673
- * @private
3674
- */
3675
- function socketOnData(chunk) {
3676
- if (!this[kWebSocket$1]._receiver.write(chunk)) {
3677
- this.pause();
3678
- }
3679
- }
3680
-
3681
- /**
3682
- * The listener of the `net.Socket` `'end'` event.
3683
- *
3684
- * @private
3685
- */
3686
- function socketOnEnd() {
3687
- const websocket = this[kWebSocket$1];
3688
-
3689
- websocket._readyState = WebSocket$1.CLOSING;
3690
- websocket._receiver.end();
3691
- this.end();
3692
- }
3693
-
3694
- /**
3695
- * The listener of the `net.Socket` `'error'` event.
3696
- *
3697
- * @private
3698
- */
3699
- function socketOnError$1() {
3700
- const websocket = this[kWebSocket$1];
3701
-
3702
- this.removeListener('error', socketOnError$1);
3703
- this.on('error', NOOP);
3704
-
3705
- if (websocket) {
3706
- websocket._readyState = WebSocket$1.CLOSING;
3707
- this.destroy();
3708
- }
3709
- }
3710
-
3711
- const { tokenChars } = validation.exports;
3712
-
3713
- /**
3714
- * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
3715
- *
3716
- * @param {String} header The field value of the header
3717
- * @return {Set} The subprotocol names
3718
- * @public
3719
- */
3720
- function parse(header) {
3721
- const protocols = new Set();
3722
- let start = -1;
3723
- let end = -1;
3724
- let i = 0;
3725
-
3726
- for (i; i < header.length; i++) {
3727
- const code = header.charCodeAt(i);
3728
-
3729
- if (end === -1 && tokenChars[code] === 1) {
3730
- if (start === -1) start = i;
3731
- } else if (
3732
- i !== 0 &&
3733
- (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
3734
- ) {
3735
- if (end === -1 && start !== -1) end = i;
3736
- } else if (code === 0x2c /* ',' */) {
3737
- if (start === -1) {
3738
- throw new SyntaxError(`Unexpected character at index ${i}`);
3739
- }
3740
-
3741
- if (end === -1) end = i;
3742
-
3743
- const protocol = header.slice(start, end);
3744
-
3745
- if (protocols.has(protocol)) {
3746
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3747
- }
3748
-
3749
- protocols.add(protocol);
3750
- start = end = -1;
3751
- } else {
3752
- throw new SyntaxError(`Unexpected character at index ${i}`);
3753
- }
3754
- }
3755
-
3756
- if (start === -1 || end !== -1) {
3757
- throw new SyntaxError('Unexpected end of input');
3758
- }
3759
-
3760
- const protocol = header.slice(start, i);
3761
-
3762
- if (protocols.has(protocol)) {
3763
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3764
- }
3765
-
3766
- protocols.add(protocol);
3767
- return protocols;
3768
- }
3769
-
3770
- var subprotocol$1 = { parse };
3771
-
3772
- /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */
3773
-
3774
- const EventEmitter = require$$2;
3775
- const http = require$$2$1;
3776
- const { createHash } = require$$5;
3777
-
3778
- const extension = extension$1;
3779
- const PerMessageDeflate = permessageDeflate;
3780
- const subprotocol = subprotocol$1;
3781
- const WebSocket = websocket;
3782
- const { GUID, kWebSocket } = constants;
3783
-
3784
- const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3785
-
3786
- const RUNNING = 0;
3787
- const CLOSING = 1;
3788
- const CLOSED = 2;
3789
-
3790
- /**
3791
- * Class representing a WebSocket server.
3792
- *
3793
- * @extends EventEmitter
3794
- */
3795
- class WebSocketServer extends EventEmitter {
3796
- /**
3797
- * Create a `WebSocketServer` instance.
3798
- *
3799
- * @param {Object} options Configuration options
3800
- * @param {Number} [options.backlog=511] The maximum length of the queue of
3801
- * pending connections
3802
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3803
- * track clients
3804
- * @param {Function} [options.handleProtocols] A hook to handle protocols
3805
- * @param {String} [options.host] The hostname where to bind the server
3806
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3807
- * size
3808
- * @param {Boolean} [options.noServer=false] Enable no server mode
3809
- * @param {String} [options.path] Accept only connections matching this path
3810
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3811
- * permessage-deflate
3812
- * @param {Number} [options.port] The port where to bind the server
3813
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3814
- * server to use
3815
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3816
- * not to skip UTF-8 validation for text and close messages
3817
- * @param {Function} [options.verifyClient] A hook to reject connections
3818
- * @param {Function} [callback] A listener for the `listening` event
3819
- */
3820
- constructor(options, callback) {
3821
- super();
3822
-
3823
- options = {
3824
- maxPayload: 100 * 1024 * 1024,
3825
- skipUTF8Validation: false,
3826
- perMessageDeflate: false,
3827
- handleProtocols: null,
3828
- clientTracking: true,
3829
- verifyClient: null,
3830
- noServer: false,
3831
- backlog: null, // use default (511 as implemented in net.js)
3832
- server: null,
3833
- host: null,
3834
- path: null,
3835
- port: null,
3836
- ...options
3837
- };
3838
-
3839
- if (
3840
- (options.port == null && !options.server && !options.noServer) ||
3841
- (options.port != null && (options.server || options.noServer)) ||
3842
- (options.server && options.noServer)
3843
- ) {
3844
- throw new TypeError(
3845
- 'One and only one of the "port", "server", or "noServer" options ' +
3846
- 'must be specified'
3847
- );
3848
- }
3849
-
3850
- if (options.port != null) {
3851
- this._server = http.createServer((req, res) => {
3852
- const body = http.STATUS_CODES[426];
3853
-
3854
- res.writeHead(426, {
3855
- 'Content-Length': body.length,
3856
- 'Content-Type': 'text/plain'
3857
- });
3858
- res.end(body);
3859
- });
3860
- this._server.listen(
3861
- options.port,
3862
- options.host,
3863
- options.backlog,
3864
- callback
3865
- );
3866
- } else if (options.server) {
3867
- this._server = options.server;
3868
- }
3869
-
3870
- if (this._server) {
3871
- const emitConnection = this.emit.bind(this, 'connection');
3872
-
3873
- this._removeListeners = addListeners(this._server, {
3874
- listening: this.emit.bind(this, 'listening'),
3875
- error: this.emit.bind(this, 'error'),
3876
- upgrade: (req, socket, head) => {
3877
- this.handleUpgrade(req, socket, head, emitConnection);
3878
- }
3879
- });
3880
- }
3881
-
3882
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3883
- if (options.clientTracking) {
3884
- this.clients = new Set();
3885
- this._shouldEmitClose = false;
3886
- }
3887
-
3888
- this.options = options;
3889
- this._state = RUNNING;
3890
- }
3891
-
3892
- /**
3893
- * Returns the bound address, the address family name, and port of the server
3894
- * as reported by the operating system if listening on an IP socket.
3895
- * If the server is listening on a pipe or UNIX domain socket, the name is
3896
- * returned as a string.
3897
- *
3898
- * @return {(Object|String|null)} The address of the server
3899
- * @public
3900
- */
3901
- address() {
3902
- if (this.options.noServer) {
3903
- throw new Error('The server is operating in "noServer" mode');
3904
- }
3905
-
3906
- if (!this._server) return null;
3907
- return this._server.address();
3908
- }
3909
-
3910
- /**
3911
- * Stop the server from accepting new connections and emit the `'close'` event
3912
- * when all existing connections are closed.
3913
- *
3914
- * @param {Function} [cb] A one-time listener for the `'close'` event
3915
- * @public
3916
- */
3917
- close(cb) {
3918
- if (this._state === CLOSED) {
3919
- if (cb) {
3920
- this.once('close', () => {
3921
- cb(new Error('The server is not running'));
3922
- });
3923
- }
3924
-
3925
- process.nextTick(emitClose, this);
3926
- return;
3927
- }
3928
-
3929
- if (cb) this.once('close', cb);
3930
-
3931
- if (this._state === CLOSING) return;
3932
- this._state = CLOSING;
3933
-
3934
- if (this.options.noServer || this.options.server) {
3935
- if (this._server) {
3936
- this._removeListeners();
3937
- this._removeListeners = this._server = null;
3938
- }
3939
-
3940
- if (this.clients) {
3941
- if (!this.clients.size) {
3942
- process.nextTick(emitClose, this);
3943
- } else {
3944
- this._shouldEmitClose = true;
3945
- }
3946
- } else {
3947
- process.nextTick(emitClose, this);
3948
- }
3949
- } else {
3950
- const server = this._server;
3951
-
3952
- this._removeListeners();
3953
- this._removeListeners = this._server = null;
3954
-
3955
- //
3956
- // The HTTP/S server was created internally. Close it, and rely on its
3957
- // `'close'` event.
3958
- //
3959
- server.close(() => {
3960
- emitClose(this);
3961
- });
3962
- }
3963
- }
3964
-
3965
- /**
3966
- * See if a given request should be handled by this server instance.
3967
- *
3968
- * @param {http.IncomingMessage} req Request object to inspect
3969
- * @return {Boolean} `true` if the request is valid, else `false`
3970
- * @public
3971
- */
3972
- shouldHandle(req) {
3973
- if (this.options.path) {
3974
- const index = req.url.indexOf('?');
3975
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3976
-
3977
- if (pathname !== this.options.path) return false;
3978
- }
3979
-
3980
- return true;
3981
- }
3982
-
3983
- /**
3984
- * Handle a HTTP Upgrade request.
3985
- *
3986
- * @param {http.IncomingMessage} req The request object
3987
- * @param {(net.Socket|tls.Socket)} socket The network socket between the
3988
- * server and client
3989
- * @param {Buffer} head The first packet of the upgraded stream
3990
- * @param {Function} cb Callback
3991
- * @public
3992
- */
3993
- handleUpgrade(req, socket, head, cb) {
3994
- socket.on('error', socketOnError);
3995
-
3996
- const key =
3997
- req.headers['sec-websocket-key'] !== undefined
3998
- ? req.headers['sec-websocket-key']
3999
- : false;
4000
- const version = +req.headers['sec-websocket-version'];
4001
-
4002
- if (
4003
- req.method !== 'GET' ||
4004
- req.headers.upgrade.toLowerCase() !== 'websocket' ||
4005
- !key ||
4006
- !keyRegex.test(key) ||
4007
- (version !== 8 && version !== 13) ||
4008
- !this.shouldHandle(req)
4009
- ) {
4010
- return abortHandshake(socket, 400);
4011
- }
4012
-
4013
- const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
4014
- let protocols = new Set();
4015
-
4016
- if (secWebSocketProtocol !== undefined) {
4017
- try {
4018
- protocols = subprotocol.parse(secWebSocketProtocol);
4019
- } catch (err) {
4020
- return abortHandshake(socket, 400);
4021
- }
4022
- }
4023
-
4024
- const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
4025
- const extensions = {};
4026
-
4027
- if (
4028
- this.options.perMessageDeflate &&
4029
- secWebSocketExtensions !== undefined
4030
- ) {
4031
- const perMessageDeflate = new PerMessageDeflate(
4032
- this.options.perMessageDeflate,
4033
- true,
4034
- this.options.maxPayload
4035
- );
4036
-
4037
- try {
4038
- const offers = extension.parse(secWebSocketExtensions);
4039
-
4040
- if (offers[PerMessageDeflate.extensionName]) {
4041
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
4042
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
4043
- }
4044
- } catch (err) {
4045
- return abortHandshake(socket, 400);
4046
- }
4047
- }
4048
-
4049
- //
4050
- // Optionally call external client verification handler.
4051
- //
4052
- if (this.options.verifyClient) {
4053
- const info = {
4054
- origin:
4055
- req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
4056
- secure: !!(req.socket.authorized || req.socket.encrypted),
4057
- req
4058
- };
4059
-
4060
- if (this.options.verifyClient.length === 2) {
4061
- this.options.verifyClient(info, (verified, code, message, headers) => {
4062
- if (!verified) {
4063
- return abortHandshake(socket, code || 401, message, headers);
4064
- }
4065
-
4066
- this.completeUpgrade(
4067
- extensions,
4068
- key,
4069
- protocols,
4070
- req,
4071
- socket,
4072
- head,
4073
- cb
4074
- );
4075
- });
4076
- return;
4077
- }
4078
-
4079
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
4080
- }
4081
-
4082
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
4083
- }
4084
-
4085
- /**
4086
- * Upgrade the connection to WebSocket.
4087
- *
4088
- * @param {Object} extensions The accepted extensions
4089
- * @param {String} key The value of the `Sec-WebSocket-Key` header
4090
- * @param {Set} protocols The subprotocols
4091
- * @param {http.IncomingMessage} req The request object
4092
- * @param {(net.Socket|tls.Socket)} socket The network socket between the
4093
- * server and client
4094
- * @param {Buffer} head The first packet of the upgraded stream
4095
- * @param {Function} cb Callback
4096
- * @throws {Error} If called more than once with the same socket
4097
- * @private
4098
- */
4099
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
4100
- //
4101
- // Destroy the socket if the client has already sent a FIN packet.
4102
- //
4103
- if (!socket.readable || !socket.writable) return socket.destroy();
4104
-
4105
- if (socket[kWebSocket]) {
4106
- throw new Error(
4107
- 'server.handleUpgrade() was called more than once with the same ' +
4108
- 'socket, possibly due to a misconfiguration'
4109
- );
4110
- }
4111
-
4112
- if (this._state > RUNNING) return abortHandshake(socket, 503);
4113
-
4114
- const digest = createHash('sha1')
4115
- .update(key + GUID)
4116
- .digest('base64');
4117
-
4118
- const headers = [
4119
- 'HTTP/1.1 101 Switching Protocols',
4120
- 'Upgrade: websocket',
4121
- 'Connection: Upgrade',
4122
- `Sec-WebSocket-Accept: ${digest}`
4123
- ];
4124
-
4125
- const ws = new WebSocket(null);
4126
-
4127
- if (protocols.size) {
4128
- //
4129
- // Optionally call external protocol selection handler.
4130
- //
4131
- const protocol = this.options.handleProtocols
4132
- ? this.options.handleProtocols(protocols, req)
4133
- : protocols.values().next().value;
4134
-
4135
- if (protocol) {
4136
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
4137
- ws._protocol = protocol;
4138
- }
4139
- }
4140
-
4141
- if (extensions[PerMessageDeflate.extensionName]) {
4142
- const params = extensions[PerMessageDeflate.extensionName].params;
4143
- const value = extension.format({
4144
- [PerMessageDeflate.extensionName]: [params]
4145
- });
4146
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
4147
- ws._extensions = extensions;
4148
- }
4149
-
4150
- //
4151
- // Allow external modification/inspection of handshake headers.
4152
- //
4153
- this.emit('headers', headers, req);
4154
-
4155
- socket.write(headers.concat('\r\n').join('\r\n'));
4156
- socket.removeListener('error', socketOnError);
4157
-
4158
- ws.setSocket(socket, head, {
4159
- maxPayload: this.options.maxPayload,
4160
- skipUTF8Validation: this.options.skipUTF8Validation
4161
- });
4162
-
4163
- if (this.clients) {
4164
- this.clients.add(ws);
4165
- ws.on('close', () => {
4166
- this.clients.delete(ws);
4167
-
4168
- if (this._shouldEmitClose && !this.clients.size) {
4169
- process.nextTick(emitClose, this);
4170
- }
4171
- });
4172
- }
4173
-
4174
- cb(ws, req);
4175
- }
4176
- }
4177
-
4178
- var websocketServer = WebSocketServer;
4179
-
4180
- /**
4181
- * Add event listeners on an `EventEmitter` using a map of <event, listener>
4182
- * pairs.
4183
- *
4184
- * @param {EventEmitter} server The event emitter
4185
- * @param {Object.<String, Function>} map The listeners to add
4186
- * @return {Function} A function that will remove the added listeners when
4187
- * called
4188
- * @private
4189
- */
4190
- function addListeners(server, map) {
4191
- for (const event of Object.keys(map)) server.on(event, map[event]);
4192
-
4193
- return function removeListeners() {
4194
- for (const event of Object.keys(map)) {
4195
- server.removeListener(event, map[event]);
4196
- }
4197
- };
4198
- }
4199
-
4200
- /**
4201
- * Emit a `'close'` event on an `EventEmitter`.
4202
- *
4203
- * @param {EventEmitter} server The event emitter
4204
- * @private
4205
- */
4206
- function emitClose(server) {
4207
- server._state = CLOSED;
4208
- server.emit('close');
4209
- }
4210
-
4211
- /**
4212
- * Handle premature socket errors.
4213
- *
4214
- * @private
4215
- */
4216
- function socketOnError() {
4217
- this.destroy();
4218
- }
4219
-
4220
- /**
4221
- * Close the connection when preconditions are not fulfilled.
4222
- *
4223
- * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
4224
- * @param {Number} code The HTTP response status code
4225
- * @param {String} [message] The HTTP response body
4226
- * @param {Object} [headers] Additional HTTP response headers
4227
- * @private
4228
- */
4229
- function abortHandshake(socket, code, message, headers) {
4230
- if (socket.writable) {
4231
- message = message || http.STATUS_CODES[code];
4232
- headers = {
4233
- Connection: 'close',
4234
- 'Content-Type': 'text/html',
4235
- 'Content-Length': Buffer.byteLength(message),
4236
- ...headers
4237
- };
4238
-
4239
- socket.write(
4240
- `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
4241
- Object.keys(headers)
4242
- .map((h) => `${h}: ${headers[h]}`)
4243
- .join('\r\n') +
4244
- '\r\n\r\n' +
4245
- message
4246
- );
4247
- }
4248
-
4249
- socket.removeListener('error', socketOnError);
4250
- socket.destroy();
4251
- }
4252
-
4253
- function setup(ctx) {
4254
- var _a;
4255
- const wss = new websocketServer({ noServer: true });
4256
- const clients = new Map();
4257
- (_a = ctx.server.httpServer) == null ? void 0 : _a.on("upgrade", (request, socket, head) => {
4258
- if (!request.url)
4259
- return;
4260
- const { pathname } = new URL(request.url, "http://localhost");
4261
- if (pathname !== API_PATH)
4262
- return;
4263
- wss.handleUpgrade(request, socket, head, (ws) => {
4264
- wss.emit("connection", ws, request);
4265
- setupClient(ws);
4266
- });
4267
- });
4268
- function setupClient(ws) {
4269
- const rpc = createBirpc({
4270
- functions: {
4271
- getFiles() {
4272
- return ctx.state.getFiles();
4273
- },
4274
- readFile(id) {
4275
- return promises.readFile(id, "utf-8");
4276
- },
4277
- writeFile(id, content) {
4278
- return promises.writeFile(id, content, "utf-8");
4279
- },
4280
- async rerun(files) {
4281
- await ctx.report("onWatcherRerun", files);
4282
- await ctx.runFiles(files);
4283
- await ctx.report("onWatcherStart");
4284
- },
4285
- getConfig() {
4286
- return ctx.config;
4287
- },
4288
- async getModuleGraph(id) {
4289
- const graph = {};
4290
- function clearId(id2) {
4291
- return (id2 == null ? void 0 : id2.replace(/\?v=\w+$/, "")) || "";
4292
- }
4293
- function get(mod, seen = new Set()) {
4294
- if (!mod || !mod.id || seen.has(mod))
4295
- return;
4296
- seen.add(mod);
4297
- const mods = Array.from(mod.importedModules).filter((i) => i.id && !i.id.includes("/vitest/dist/"));
4298
- graph[clearId(mod.id)] = mods.map((i) => clearId(i.id));
4299
- mods.forEach((m) => get(m, seen));
4300
- }
4301
- get(ctx.server.moduleGraph.getModuleById(id));
4302
- const externalized = [];
4303
- const inlined = [];
4304
- await Promise.all(Object.keys(graph).map(async (i) => {
4305
- const rewrote = await shouldExternalize(i, ctx.config);
4306
- if (rewrote)
4307
- externalized.push(rewrote);
4308
- else
4309
- inlined.push(i);
4310
- }));
4311
- return {
4312
- graph,
4313
- externalized,
4314
- inlined
4315
- };
4316
- }
4317
- },
4318
- post(msg) {
4319
- ws.send(msg);
4320
- },
4321
- on(fn) {
4322
- ws.on("message", fn);
4323
- },
4324
- eventNames: ["onCollected"],
4325
- serialize: stringify,
4326
- deserialize: parse$3
4327
- });
4328
- clients.set(ws, rpc);
4329
- ws.on("close", () => {
4330
- clients.delete(ws);
4331
- });
4332
- }
4333
- ctx.reporters.push(new WebSocketReporter(ctx, wss, clients));
4334
- }
4335
- class WebSocketReporter {
4336
- constructor(ctx, wss, clients) {
4337
- this.ctx = ctx;
4338
- this.wss = wss;
4339
- this.clients = clients;
4340
- }
4341
- onCollected(files) {
4342
- if (this.clients.size === 0)
4343
- return;
4344
- this.clients.forEach((client) => {
4345
- var _a;
4346
- (_a = client.onCollected) == null ? void 0 : _a.call(client, files);
4347
- });
4348
- }
4349
- async onTaskUpdate(packs) {
4350
- if (this.clients.size === 0)
4351
- return;
4352
- await Promise.all(packs.map(async (i) => {
4353
- var _a;
4354
- if ((_a = i[1]) == null ? void 0 : _a.error)
4355
- await interpretSourcePos(parseStacktrace(i[1].error), this.ctx);
4356
- }));
4357
- this.clients.forEach((client) => {
4358
- var _a;
4359
- (_a = client.onTaskUpdate) == null ? void 0 : _a.call(client, packs);
4360
- });
4361
- }
4362
- }
4363
-
4364
- export { setup };