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