@wix/create-app 0.0.80 → 0.0.82

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