@mentaproject/client 0.1.35 → 0.1.36

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