@claw-fact-bus/openclaw-plugin 1.0.0

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