@4pm/cli 0.8.2 → 0.8.3

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