@liangmi/mo 0.0.5 → 1.0.1

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