nextclaw 0.19.16 → 0.19.21

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