@wix/create-headless-site 0.0.2

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