@alfe.ai/openclaw 0.0.22 → 0.0.24

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