@vesper85/strategy-sdk 0.1.7 → 0.1.8

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