@gluwa/connect-kit 0.1.0-next.0

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