@naeemo/capnp 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,35 @@
1
1
  import { C as QuestionTable, S as ImportTable, _ as QueuedCallManager, a as serializeGetSchemaParams, b as AnswerTable, c as serializeSchemaRequest, d as parseSchemaNodes, f as SchemaFormat, g as PipelineResolutionTracker, h as PipelineOpTracker, i as deserializeSchemaResponse, l as serializeSchemaResponse, m as PIPELINE_CLIENT_SYMBOL, n as SCHEMA_MESSAGE_TYPES, o as serializeGetSchemaResults, p as SchemaNodeType, r as deserializeSchemaRequest, s as serializeListSchemasResults, t as RpcConnection, u as createSchemaRegistry, v as createPipelineClient, x as ExportTable, y as isPipelineClient } from "./rpc-connection-C3-uEtpd.js";
2
2
  import { createRequire } from "node:module";
3
- import * as net from "node:net";
3
+ import * as net$1 from "node:net";
4
+ import { createConnection } from "node:net";
5
+ import { EventEmitter } from "node:events";
4
6
 
5
7
  //#region \0rolldown/runtime.js
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
18
+ key = keys[i];
19
+ if (!__hasOwnProp.call(to, key) && key !== except) {
20
+ __defProp(to, key, {
21
+ get: ((k) => from[k]).bind(null, key),
22
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
23
+ });
24
+ }
25
+ }
26
+ }
27
+ return to;
28
+ };
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
30
+ value: mod,
31
+ enumerable: true
32
+ }) : target, mod));
6
33
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
7
34
 
8
35
  //#endregion
@@ -1794,7 +1821,7 @@ var TcpTransport = class TcpTransport {
1794
1821
  this.socket?.destroy();
1795
1822
  reject(/* @__PURE__ */ new Error("Connection timeout"));
1796
1823
  }, this.options.connectTimeoutMs ?? 1e4);
1797
- this.socket = new net.Socket();
1824
+ this.socket = new net$1.Socket();
1798
1825
  this.socket.on("connect", () => {
1799
1826
  clearTimeout(timeout);
1800
1827
  this._connected = true;
@@ -1951,7 +1978,7 @@ var EzRpcTransport = class EzRpcTransport {
1951
1978
  this.socket?.destroy();
1952
1979
  reject(/* @__PURE__ */ new Error(`Connection timeout: failed to connect to ${this.host}:${this.port}`));
1953
1980
  }, this.options.connectTimeoutMs ?? 1e4);
1954
- this.socket = new net.Socket();
1981
+ this.socket = new net$1.Socket();
1955
1982
  this.socket.on("connect", () => {
1956
1983
  clearTimeout(timeout);
1957
1984
  this._connected = true;
@@ -6192,5 +6219,3756 @@ var SchemaCapabilityClient = class {
6192
6219
  };
6193
6220
 
6194
6221
  //#endregion
6195
- export { AnswerTable, BaseCapabilityClient, BulkTransfer, BulkTransferManager, ConnectionManager, DEFAULT_BULK_CONFIG, DEFAULT_ESCROW_CONFIG, DEFAULT_FLOW_CONTROL, DEFAULT_JOIN_OPTIONS, DEFAULT_JOIN_SECURITY_POLICY, DEFAULT_REALTIME_CONFIG, DEFAULT_STREAMING_CAPABILITIES, DropPolicy, ElementSize, ExportTable, EzRpcTransport, ImportTable, Level3Handlers, Level4Handlers, ListBuilder, ListReader, MemoryPool, MessageBuilder, MessageReader, MultiSegmentMessageBuilder, OptimizedRpcMessageBuilder, PIPELINE_CLIENT_SYMBOL, PipelineOpTracker, PipelineResolutionTracker, PointerTag, QuestionTable, QueuedCallManager, RealtimeStream, RealtimeStreamManager, RestoreHandler, RpcConnection, SCHEMA_MESSAGE_TYPES, SchemaCapabilityClient, SchemaCapabilityServer, SchemaFormat, Segment, Stream, StreamManager, StreamPriority, StreamType, StreamingRpcConnection, StructBuilder, StructReader, SturdyRefManager, TcpTransport, UnionBuilder, UnionReader, WORD_SIZE, WebSocketTransport, configureGlobalMemoryPool, createBulkTransferManager, createDynamicReader, createDynamicReaderByTypeId, createDynamicReaderFromStruct, createDynamicWriter, createDynamicWriterByTypeId, createNestedDynamicWriter, createPipelineClient, createProvisionId, createRealtimeStreamManager, createRecipientId, createSchemaRegistry, createStream, createStreamManager, createStreamingConnection, createSturdyRef, createThirdPartyCapId, createUnionBuilder, createUnionReader, createZeroCopyView, decodePointer, deserializeRpcMessage, deserializeSchemaRequest, deserializeSchemaResponse, deserializeSturdyRef, dumpDynamicReader, encodeListPointer, encodeStructPointer, fastCopy, generateProvisionId, generateVatId, getGlobalMemoryPool, isPipelineClient, isSameBuffer, isStream, isSturdyRefValid, parseSchemaNodes, serializeDynamic, serializeDynamicByTypeId, serializeGetSchemaParams, serializeGetSchemaResults, serializeListSchemasResults, serializeRpcMessage, serializeSchemaRequest, serializeSchemaResponse, serializeSturdyRef, supportsStreaming };
6222
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/constants.js
6223
+ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6224
+ const BINARY_TYPES = [
6225
+ "nodebuffer",
6226
+ "arraybuffer",
6227
+ "fragments"
6228
+ ];
6229
+ const hasBlob = typeof Blob !== "undefined";
6230
+ if (hasBlob) BINARY_TYPES.push("blob");
6231
+ module.exports = {
6232
+ BINARY_TYPES,
6233
+ CLOSE_TIMEOUT: 3e4,
6234
+ EMPTY_BUFFER: Buffer.alloc(0),
6235
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
6236
+ hasBlob,
6237
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
6238
+ kListener: Symbol("kListener"),
6239
+ kStatusCode: Symbol("status-code"),
6240
+ kWebSocket: Symbol("websocket"),
6241
+ NOOP: () => {}
6242
+ };
6243
+ }));
6244
+
6245
+ //#endregion
6246
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/buffer-util.js
6247
+ var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6248
+ const { EMPTY_BUFFER } = require_constants();
6249
+ const FastBuffer = Buffer[Symbol.species];
6250
+ /**
6251
+ * Merges an array of buffers into a new buffer.
6252
+ *
6253
+ * @param {Buffer[]} list The array of buffers to concat
6254
+ * @param {Number} totalLength The total length of buffers in the list
6255
+ * @return {Buffer} The resulting buffer
6256
+ * @public
6257
+ */
6258
+ function concat(list, totalLength) {
6259
+ if (list.length === 0) return EMPTY_BUFFER;
6260
+ if (list.length === 1) return list[0];
6261
+ const target = Buffer.allocUnsafe(totalLength);
6262
+ let offset = 0;
6263
+ for (let i = 0; i < list.length; i++) {
6264
+ const buf = list[i];
6265
+ target.set(buf, offset);
6266
+ offset += buf.length;
6267
+ }
6268
+ if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
6269
+ return target;
6270
+ }
6271
+ /**
6272
+ * Masks a buffer using the given mask.
6273
+ *
6274
+ * @param {Buffer} source The buffer to mask
6275
+ * @param {Buffer} mask The mask to use
6276
+ * @param {Buffer} output The buffer where to store the result
6277
+ * @param {Number} offset The offset at which to start writing
6278
+ * @param {Number} length The number of bytes to mask.
6279
+ * @public
6280
+ */
6281
+ function _mask(source, mask, output, offset, length) {
6282
+ for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
6283
+ }
6284
+ /**
6285
+ * Unmasks a buffer using the given mask.
6286
+ *
6287
+ * @param {Buffer} buffer The buffer to unmask
6288
+ * @param {Buffer} mask The mask to use
6289
+ * @public
6290
+ */
6291
+ function _unmask(buffer, mask) {
6292
+ for (let i = 0; i < buffer.length; i++) buffer[i] ^= mask[i & 3];
6293
+ }
6294
+ /**
6295
+ * Converts a buffer to an `ArrayBuffer`.
6296
+ *
6297
+ * @param {Buffer} buf The buffer to convert
6298
+ * @return {ArrayBuffer} Converted buffer
6299
+ * @public
6300
+ */
6301
+ function toArrayBuffer(buf) {
6302
+ if (buf.length === buf.buffer.byteLength) return buf.buffer;
6303
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
6304
+ }
6305
+ /**
6306
+ * Converts `data` to a `Buffer`.
6307
+ *
6308
+ * @param {*} data The data to convert
6309
+ * @return {Buffer} The buffer
6310
+ * @throws {TypeError}
6311
+ * @public
6312
+ */
6313
+ function toBuffer(data) {
6314
+ toBuffer.readOnly = true;
6315
+ if (Buffer.isBuffer(data)) return data;
6316
+ let buf;
6317
+ if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
6318
+ else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
6319
+ else {
6320
+ buf = Buffer.from(data);
6321
+ toBuffer.readOnly = false;
6322
+ }
6323
+ return buf;
6324
+ }
6325
+ module.exports = {
6326
+ concat,
6327
+ mask: _mask,
6328
+ toArrayBuffer,
6329
+ toBuffer,
6330
+ unmask: _unmask
6331
+ };
6332
+ /* istanbul ignore else */
6333
+ if (!process.env.WS_NO_BUFFER_UTIL) try {
6334
+ const bufferUtil = __require("bufferutil");
6335
+ module.exports.mask = function(source, mask, output, offset, length) {
6336
+ if (length < 48) _mask(source, mask, output, offset, length);
6337
+ else bufferUtil.mask(source, mask, output, offset, length);
6338
+ };
6339
+ module.exports.unmask = function(buffer, mask) {
6340
+ if (buffer.length < 32) _unmask(buffer, mask);
6341
+ else bufferUtil.unmask(buffer, mask);
6342
+ };
6343
+ } catch (e) {}
6344
+ }));
6345
+
6346
+ //#endregion
6347
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/limiter.js
6348
+ var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6349
+ const kDone = Symbol("kDone");
6350
+ const kRun = Symbol("kRun");
6351
+ /**
6352
+ * A very simple job queue with adjustable concurrency. Adapted from
6353
+ * https://github.com/STRML/async-limiter
6354
+ */
6355
+ var Limiter = class {
6356
+ /**
6357
+ * Creates a new `Limiter`.
6358
+ *
6359
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
6360
+ * to run concurrently
6361
+ */
6362
+ constructor(concurrency) {
6363
+ this[kDone] = () => {
6364
+ this.pending--;
6365
+ this[kRun]();
6366
+ };
6367
+ this.concurrency = concurrency || Infinity;
6368
+ this.jobs = [];
6369
+ this.pending = 0;
6370
+ }
6371
+ /**
6372
+ * Adds a job to the queue.
6373
+ *
6374
+ * @param {Function} job The job to run
6375
+ * @public
6376
+ */
6377
+ add(job) {
6378
+ this.jobs.push(job);
6379
+ this[kRun]();
6380
+ }
6381
+ /**
6382
+ * Removes a job from the queue and runs it if possible.
6383
+ *
6384
+ * @private
6385
+ */
6386
+ [kRun]() {
6387
+ if (this.pending === this.concurrency) return;
6388
+ if (this.jobs.length) {
6389
+ const job = this.jobs.shift();
6390
+ this.pending++;
6391
+ job(this[kDone]);
6392
+ }
6393
+ }
6394
+ };
6395
+ module.exports = Limiter;
6396
+ }));
6397
+
6398
+ //#endregion
6399
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/permessage-deflate.js
6400
+ var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6401
+ const zlib = __require("zlib");
6402
+ const bufferUtil = require_buffer_util();
6403
+ const Limiter = require_limiter();
6404
+ const { kStatusCode } = require_constants();
6405
+ const FastBuffer = Buffer[Symbol.species];
6406
+ const TRAILER = Buffer.from([
6407
+ 0,
6408
+ 0,
6409
+ 255,
6410
+ 255
6411
+ ]);
6412
+ const kPerMessageDeflate = Symbol("permessage-deflate");
6413
+ const kTotalLength = Symbol("total-length");
6414
+ const kCallback = Symbol("callback");
6415
+ const kBuffers = Symbol("buffers");
6416
+ const kError = Symbol("error");
6417
+ let zlibLimiter;
6418
+ /**
6419
+ * permessage-deflate implementation.
6420
+ */
6421
+ var PerMessageDeflate = class {
6422
+ /**
6423
+ * Creates a PerMessageDeflate instance.
6424
+ *
6425
+ * @param {Object} [options] Configuration options
6426
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
6427
+ * for, or request, a custom client window size
6428
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
6429
+ * acknowledge disabling of client context takeover
6430
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
6431
+ * calls to zlib
6432
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
6433
+ * use of a custom server window size
6434
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
6435
+ * disabling of server context takeover
6436
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
6437
+ * messages should not be compressed if context takeover is disabled
6438
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
6439
+ * deflate
6440
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
6441
+ * inflate
6442
+ * @param {Boolean} [isServer=false] Create the instance in either server or
6443
+ * client mode
6444
+ * @param {Number} [maxPayload=0] The maximum allowed message length
6445
+ */
6446
+ constructor(options, isServer, maxPayload) {
6447
+ this._maxPayload = maxPayload | 0;
6448
+ this._options = options || {};
6449
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
6450
+ this._isServer = !!isServer;
6451
+ this._deflate = null;
6452
+ this._inflate = null;
6453
+ this.params = null;
6454
+ if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
6455
+ }
6456
+ /**
6457
+ * @type {String}
6458
+ */
6459
+ static get extensionName() {
6460
+ return "permessage-deflate";
6461
+ }
6462
+ /**
6463
+ * Create an extension negotiation offer.
6464
+ *
6465
+ * @return {Object} Extension parameters
6466
+ * @public
6467
+ */
6468
+ offer() {
6469
+ const params = {};
6470
+ if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
6471
+ if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
6472
+ if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
6473
+ if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
6474
+ else if (this._options.clientMaxWindowBits == null) params.client_max_window_bits = true;
6475
+ return params;
6476
+ }
6477
+ /**
6478
+ * Accept an extension negotiation offer/response.
6479
+ *
6480
+ * @param {Array} configurations The extension negotiation offers/reponse
6481
+ * @return {Object} Accepted configuration
6482
+ * @public
6483
+ */
6484
+ accept(configurations) {
6485
+ configurations = this.normalizeParams(configurations);
6486
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
6487
+ return this.params;
6488
+ }
6489
+ /**
6490
+ * Releases all resources used by the extension.
6491
+ *
6492
+ * @public
6493
+ */
6494
+ cleanup() {
6495
+ if (this._inflate) {
6496
+ this._inflate.close();
6497
+ this._inflate = null;
6498
+ }
6499
+ if (this._deflate) {
6500
+ const callback = this._deflate[kCallback];
6501
+ this._deflate.close();
6502
+ this._deflate = null;
6503
+ if (callback) callback(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
6504
+ }
6505
+ }
6506
+ /**
6507
+ * Accept an extension negotiation offer.
6508
+ *
6509
+ * @param {Array} offers The extension negotiation offers
6510
+ * @return {Object} Accepted configuration
6511
+ * @private
6512
+ */
6513
+ acceptAsServer(offers) {
6514
+ const opts = this._options;
6515
+ const accepted = offers.find((params) => {
6516
+ 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;
6517
+ return true;
6518
+ });
6519
+ if (!accepted) throw new Error("None of the extension offers can be accepted");
6520
+ if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
6521
+ if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
6522
+ if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
6523
+ if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
6524
+ else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
6525
+ return accepted;
6526
+ }
6527
+ /**
6528
+ * Accept the extension negotiation response.
6529
+ *
6530
+ * @param {Array} response The extension negotiation response
6531
+ * @return {Object} Accepted configuration
6532
+ * @private
6533
+ */
6534
+ acceptAsClient(response) {
6535
+ const params = response[0];
6536
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
6537
+ if (!params.client_max_window_bits) {
6538
+ if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
6539
+ } 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\"");
6540
+ return params;
6541
+ }
6542
+ /**
6543
+ * Normalize parameters.
6544
+ *
6545
+ * @param {Array} configurations The extension negotiation offers/reponse
6546
+ * @return {Array} The offers/response with normalized parameters
6547
+ * @private
6548
+ */
6549
+ normalizeParams(configurations) {
6550
+ configurations.forEach((params) => {
6551
+ Object.keys(params).forEach((key) => {
6552
+ let value = params[key];
6553
+ if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
6554
+ value = value[0];
6555
+ if (key === "client_max_window_bits") {
6556
+ if (value !== true) {
6557
+ const num = +value;
6558
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6559
+ value = num;
6560
+ } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6561
+ } else if (key === "server_max_window_bits") {
6562
+ const num = +value;
6563
+ if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6564
+ value = num;
6565
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
6566
+ if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
6567
+ } else throw new Error(`Unknown parameter "${key}"`);
6568
+ params[key] = value;
6569
+ });
6570
+ });
6571
+ return configurations;
6572
+ }
6573
+ /**
6574
+ * Decompress data. Concurrency limited.
6575
+ *
6576
+ * @param {Buffer} data Compressed data
6577
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
6578
+ * @param {Function} callback Callback
6579
+ * @public
6580
+ */
6581
+ decompress(data, fin, callback) {
6582
+ zlibLimiter.add((done) => {
6583
+ this._decompress(data, fin, (err, result) => {
6584
+ done();
6585
+ callback(err, result);
6586
+ });
6587
+ });
6588
+ }
6589
+ /**
6590
+ * Compress data. Concurrency limited.
6591
+ *
6592
+ * @param {(Buffer|String)} data Data to compress
6593
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
6594
+ * @param {Function} callback Callback
6595
+ * @public
6596
+ */
6597
+ compress(data, fin, callback) {
6598
+ zlibLimiter.add((done) => {
6599
+ this._compress(data, fin, (err, result) => {
6600
+ done();
6601
+ callback(err, result);
6602
+ });
6603
+ });
6604
+ }
6605
+ /**
6606
+ * Decompress data.
6607
+ *
6608
+ * @param {Buffer} data Compressed data
6609
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
6610
+ * @param {Function} callback Callback
6611
+ * @private
6612
+ */
6613
+ _decompress(data, fin, callback) {
6614
+ const endpoint = this._isServer ? "client" : "server";
6615
+ if (!this._inflate) {
6616
+ const key = `${endpoint}_max_window_bits`;
6617
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
6618
+ this._inflate = zlib.createInflateRaw({
6619
+ ...this._options.zlibInflateOptions,
6620
+ windowBits
6621
+ });
6622
+ this._inflate[kPerMessageDeflate] = this;
6623
+ this._inflate[kTotalLength] = 0;
6624
+ this._inflate[kBuffers] = [];
6625
+ this._inflate.on("error", inflateOnError);
6626
+ this._inflate.on("data", inflateOnData);
6627
+ }
6628
+ this._inflate[kCallback] = callback;
6629
+ this._inflate.write(data);
6630
+ if (fin) this._inflate.write(TRAILER);
6631
+ this._inflate.flush(() => {
6632
+ const err = this._inflate[kError];
6633
+ if (err) {
6634
+ this._inflate.close();
6635
+ this._inflate = null;
6636
+ callback(err);
6637
+ return;
6638
+ }
6639
+ const data = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
6640
+ if (this._inflate._readableState.endEmitted) {
6641
+ this._inflate.close();
6642
+ this._inflate = null;
6643
+ } else {
6644
+ this._inflate[kTotalLength] = 0;
6645
+ this._inflate[kBuffers] = [];
6646
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
6647
+ }
6648
+ callback(null, data);
6649
+ });
6650
+ }
6651
+ /**
6652
+ * Compress data.
6653
+ *
6654
+ * @param {(Buffer|String)} data Data to compress
6655
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
6656
+ * @param {Function} callback Callback
6657
+ * @private
6658
+ */
6659
+ _compress(data, fin, callback) {
6660
+ const endpoint = this._isServer ? "server" : "client";
6661
+ if (!this._deflate) {
6662
+ const key = `${endpoint}_max_window_bits`;
6663
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
6664
+ this._deflate = zlib.createDeflateRaw({
6665
+ ...this._options.zlibDeflateOptions,
6666
+ windowBits
6667
+ });
6668
+ this._deflate[kTotalLength] = 0;
6669
+ this._deflate[kBuffers] = [];
6670
+ this._deflate.on("data", deflateOnData);
6671
+ }
6672
+ this._deflate[kCallback] = callback;
6673
+ this._deflate.write(data);
6674
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
6675
+ if (!this._deflate) return;
6676
+ let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
6677
+ if (fin) data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
6678
+ this._deflate[kCallback] = null;
6679
+ this._deflate[kTotalLength] = 0;
6680
+ this._deflate[kBuffers] = [];
6681
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
6682
+ callback(null, data);
6683
+ });
6684
+ }
6685
+ };
6686
+ module.exports = PerMessageDeflate;
6687
+ /**
6688
+ * The listener of the `zlib.DeflateRaw` stream `'data'` event.
6689
+ *
6690
+ * @param {Buffer} chunk A chunk of data
6691
+ * @private
6692
+ */
6693
+ function deflateOnData(chunk) {
6694
+ this[kBuffers].push(chunk);
6695
+ this[kTotalLength] += chunk.length;
6696
+ }
6697
+ /**
6698
+ * The listener of the `zlib.InflateRaw` stream `'data'` event.
6699
+ *
6700
+ * @param {Buffer} chunk A chunk of data
6701
+ * @private
6702
+ */
6703
+ function inflateOnData(chunk) {
6704
+ this[kTotalLength] += chunk.length;
6705
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
6706
+ this[kBuffers].push(chunk);
6707
+ return;
6708
+ }
6709
+ this[kError] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
6710
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
6711
+ this[kError][kStatusCode] = 1009;
6712
+ this.removeListener("data", inflateOnData);
6713
+ this.reset();
6714
+ }
6715
+ /**
6716
+ * The listener of the `zlib.InflateRaw` stream `'error'` event.
6717
+ *
6718
+ * @param {Error} err The emitted error
6719
+ * @private
6720
+ */
6721
+ function inflateOnError(err) {
6722
+ this[kPerMessageDeflate]._inflate = null;
6723
+ if (this[kError]) {
6724
+ this[kCallback](this[kError]);
6725
+ return;
6726
+ }
6727
+ err[kStatusCode] = 1007;
6728
+ this[kCallback](err);
6729
+ }
6730
+ }));
6731
+
6732
+ //#endregion
6733
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/validation.js
6734
+ var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6735
+ const { isUtf8 } = __require("buffer");
6736
+ const { hasBlob } = require_constants();
6737
+ const tokenChars = [
6738
+ 0,
6739
+ 0,
6740
+ 0,
6741
+ 0,
6742
+ 0,
6743
+ 0,
6744
+ 0,
6745
+ 0,
6746
+ 0,
6747
+ 0,
6748
+ 0,
6749
+ 0,
6750
+ 0,
6751
+ 0,
6752
+ 0,
6753
+ 0,
6754
+ 0,
6755
+ 0,
6756
+ 0,
6757
+ 0,
6758
+ 0,
6759
+ 0,
6760
+ 0,
6761
+ 0,
6762
+ 0,
6763
+ 0,
6764
+ 0,
6765
+ 0,
6766
+ 0,
6767
+ 0,
6768
+ 0,
6769
+ 0,
6770
+ 0,
6771
+ 1,
6772
+ 0,
6773
+ 1,
6774
+ 1,
6775
+ 1,
6776
+ 1,
6777
+ 1,
6778
+ 0,
6779
+ 0,
6780
+ 1,
6781
+ 1,
6782
+ 0,
6783
+ 1,
6784
+ 1,
6785
+ 0,
6786
+ 1,
6787
+ 1,
6788
+ 1,
6789
+ 1,
6790
+ 1,
6791
+ 1,
6792
+ 1,
6793
+ 1,
6794
+ 1,
6795
+ 1,
6796
+ 0,
6797
+ 0,
6798
+ 0,
6799
+ 0,
6800
+ 0,
6801
+ 0,
6802
+ 0,
6803
+ 1,
6804
+ 1,
6805
+ 1,
6806
+ 1,
6807
+ 1,
6808
+ 1,
6809
+ 1,
6810
+ 1,
6811
+ 1,
6812
+ 1,
6813
+ 1,
6814
+ 1,
6815
+ 1,
6816
+ 1,
6817
+ 1,
6818
+ 1,
6819
+ 1,
6820
+ 1,
6821
+ 1,
6822
+ 1,
6823
+ 1,
6824
+ 1,
6825
+ 1,
6826
+ 1,
6827
+ 1,
6828
+ 1,
6829
+ 0,
6830
+ 0,
6831
+ 0,
6832
+ 1,
6833
+ 1,
6834
+ 1,
6835
+ 1,
6836
+ 1,
6837
+ 1,
6838
+ 1,
6839
+ 1,
6840
+ 1,
6841
+ 1,
6842
+ 1,
6843
+ 1,
6844
+ 1,
6845
+ 1,
6846
+ 1,
6847
+ 1,
6848
+ 1,
6849
+ 1,
6850
+ 1,
6851
+ 1,
6852
+ 1,
6853
+ 1,
6854
+ 1,
6855
+ 1,
6856
+ 1,
6857
+ 1,
6858
+ 1,
6859
+ 1,
6860
+ 1,
6861
+ 0,
6862
+ 1,
6863
+ 0,
6864
+ 1,
6865
+ 0
6866
+ ];
6867
+ /**
6868
+ * Checks if a status code is allowed in a close frame.
6869
+ *
6870
+ * @param {Number} code The status code
6871
+ * @return {Boolean} `true` if the status code is valid, else `false`
6872
+ * @public
6873
+ */
6874
+ function isValidStatusCode(code) {
6875
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
6876
+ }
6877
+ /**
6878
+ * Checks if a given buffer contains only correct UTF-8.
6879
+ * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
6880
+ * Markus Kuhn.
6881
+ *
6882
+ * @param {Buffer} buf The buffer to check
6883
+ * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
6884
+ * @public
6885
+ */
6886
+ function _isValidUTF8(buf) {
6887
+ const len = buf.length;
6888
+ let i = 0;
6889
+ while (i < len) if ((buf[i] & 128) === 0) i++;
6890
+ else if ((buf[i] & 224) === 192) {
6891
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) return false;
6892
+ i += 2;
6893
+ } else if ((buf[i] & 240) === 224) {
6894
+ 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;
6895
+ i += 3;
6896
+ } else if ((buf[i] & 248) === 240) {
6897
+ 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;
6898
+ i += 4;
6899
+ } else return false;
6900
+ return true;
6901
+ }
6902
+ /**
6903
+ * Determines whether a value is a `Blob`.
6904
+ *
6905
+ * @param {*} value The value to be tested
6906
+ * @return {Boolean} `true` if `value` is a `Blob`, else `false`
6907
+ * @private
6908
+ */
6909
+ function isBlob(value) {
6910
+ 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");
6911
+ }
6912
+ module.exports = {
6913
+ isBlob,
6914
+ isValidStatusCode,
6915
+ isValidUTF8: _isValidUTF8,
6916
+ tokenChars
6917
+ };
6918
+ if (isUtf8) module.exports.isValidUTF8 = function(buf) {
6919
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
6920
+ };
6921
+ else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
6922
+ const isValidUTF8 = __require("utf-8-validate");
6923
+ module.exports.isValidUTF8 = function(buf) {
6924
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
6925
+ };
6926
+ } catch (e) {}
6927
+ }));
6928
+
6929
+ //#endregion
6930
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/receiver.js
6931
+ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6932
+ const { Writable } = __require("stream");
6933
+ const PerMessageDeflate = require_permessage_deflate();
6934
+ const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants();
6935
+ const { concat, toArrayBuffer, unmask } = require_buffer_util();
6936
+ const { isValidStatusCode, isValidUTF8 } = require_validation();
6937
+ const FastBuffer = Buffer[Symbol.species];
6938
+ const GET_INFO = 0;
6939
+ const GET_PAYLOAD_LENGTH_16 = 1;
6940
+ const GET_PAYLOAD_LENGTH_64 = 2;
6941
+ const GET_MASK = 3;
6942
+ const GET_DATA = 4;
6943
+ const INFLATING = 5;
6944
+ const DEFER_EVENT = 6;
6945
+ /**
6946
+ * HyBi Receiver implementation.
6947
+ *
6948
+ * @extends Writable
6949
+ */
6950
+ var Receiver = class extends Writable {
6951
+ /**
6952
+ * Creates a Receiver instance.
6953
+ *
6954
+ * @param {Object} [options] Options object
6955
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
6956
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
6957
+ * multiple times in the same tick
6958
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
6959
+ * @param {Object} [options.extensions] An object containing the negotiated
6960
+ * extensions
6961
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
6962
+ * client or server mode
6963
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
6964
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
6965
+ * not to skip UTF-8 validation for text and close messages
6966
+ */
6967
+ constructor(options = {}) {
6968
+ super();
6969
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
6970
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
6971
+ this._extensions = options.extensions || {};
6972
+ this._isServer = !!options.isServer;
6973
+ this._maxPayload = options.maxPayload | 0;
6974
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
6975
+ this[kWebSocket] = void 0;
6976
+ this._bufferedBytes = 0;
6977
+ this._buffers = [];
6978
+ this._compressed = false;
6979
+ this._payloadLength = 0;
6980
+ this._mask = void 0;
6981
+ this._fragmented = 0;
6982
+ this._masked = false;
6983
+ this._fin = false;
6984
+ this._opcode = 0;
6985
+ this._totalPayloadLength = 0;
6986
+ this._messageLength = 0;
6987
+ this._fragments = [];
6988
+ this._errored = false;
6989
+ this._loop = false;
6990
+ this._state = GET_INFO;
6991
+ }
6992
+ /**
6993
+ * Implements `Writable.prototype._write()`.
6994
+ *
6995
+ * @param {Buffer} chunk The chunk of data to write
6996
+ * @param {String} encoding The character encoding of `chunk`
6997
+ * @param {Function} cb Callback
6998
+ * @private
6999
+ */
7000
+ _write(chunk, encoding, cb) {
7001
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
7002
+ this._bufferedBytes += chunk.length;
7003
+ this._buffers.push(chunk);
7004
+ this.startLoop(cb);
7005
+ }
7006
+ /**
7007
+ * Consumes `n` bytes from the buffered data.
7008
+ *
7009
+ * @param {Number} n The number of bytes to consume
7010
+ * @return {Buffer} The consumed bytes
7011
+ * @private
7012
+ */
7013
+ consume(n) {
7014
+ this._bufferedBytes -= n;
7015
+ if (n === this._buffers[0].length) return this._buffers.shift();
7016
+ if (n < this._buffers[0].length) {
7017
+ const buf = this._buffers[0];
7018
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
7019
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
7020
+ }
7021
+ const dst = Buffer.allocUnsafe(n);
7022
+ do {
7023
+ const buf = this._buffers[0];
7024
+ const offset = dst.length - n;
7025
+ if (n >= buf.length) dst.set(this._buffers.shift(), offset);
7026
+ else {
7027
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
7028
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
7029
+ }
7030
+ n -= buf.length;
7031
+ } while (n > 0);
7032
+ return dst;
7033
+ }
7034
+ /**
7035
+ * Starts the parsing loop.
7036
+ *
7037
+ * @param {Function} cb Callback
7038
+ * @private
7039
+ */
7040
+ startLoop(cb) {
7041
+ this._loop = true;
7042
+ do
7043
+ switch (this._state) {
7044
+ case GET_INFO:
7045
+ this.getInfo(cb);
7046
+ break;
7047
+ case GET_PAYLOAD_LENGTH_16:
7048
+ this.getPayloadLength16(cb);
7049
+ break;
7050
+ case GET_PAYLOAD_LENGTH_64:
7051
+ this.getPayloadLength64(cb);
7052
+ break;
7053
+ case GET_MASK:
7054
+ this.getMask();
7055
+ break;
7056
+ case GET_DATA:
7057
+ this.getData(cb);
7058
+ break;
7059
+ case INFLATING:
7060
+ case DEFER_EVENT:
7061
+ this._loop = false;
7062
+ return;
7063
+ }
7064
+ while (this._loop);
7065
+ if (!this._errored) cb();
7066
+ }
7067
+ /**
7068
+ * Reads the first two bytes of a frame.
7069
+ *
7070
+ * @param {Function} cb Callback
7071
+ * @private
7072
+ */
7073
+ getInfo(cb) {
7074
+ if (this._bufferedBytes < 2) {
7075
+ this._loop = false;
7076
+ return;
7077
+ }
7078
+ const buf = this.consume(2);
7079
+ if ((buf[0] & 48) !== 0) {
7080
+ cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
7081
+ return;
7082
+ }
7083
+ const compressed = (buf[0] & 64) === 64;
7084
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
7085
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
7086
+ return;
7087
+ }
7088
+ this._fin = (buf[0] & 128) === 128;
7089
+ this._opcode = buf[0] & 15;
7090
+ this._payloadLength = buf[1] & 127;
7091
+ if (this._opcode === 0) {
7092
+ if (compressed) {
7093
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
7094
+ return;
7095
+ }
7096
+ if (!this._fragmented) {
7097
+ cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
7098
+ return;
7099
+ }
7100
+ this._opcode = this._fragmented;
7101
+ } else if (this._opcode === 1 || this._opcode === 2) {
7102
+ if (this._fragmented) {
7103
+ cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
7104
+ return;
7105
+ }
7106
+ this._compressed = compressed;
7107
+ } else if (this._opcode > 7 && this._opcode < 11) {
7108
+ if (!this._fin) {
7109
+ cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
7110
+ return;
7111
+ }
7112
+ if (compressed) {
7113
+ cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
7114
+ return;
7115
+ }
7116
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
7117
+ cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
7118
+ return;
7119
+ }
7120
+ } else {
7121
+ cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
7122
+ return;
7123
+ }
7124
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
7125
+ this._masked = (buf[1] & 128) === 128;
7126
+ if (this._isServer) {
7127
+ if (!this._masked) {
7128
+ cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
7129
+ return;
7130
+ }
7131
+ } else if (this._masked) {
7132
+ cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
7133
+ return;
7134
+ }
7135
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
7136
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
7137
+ else this.haveLength(cb);
7138
+ }
7139
+ /**
7140
+ * Gets extended payload length (7+16).
7141
+ *
7142
+ * @param {Function} cb Callback
7143
+ * @private
7144
+ */
7145
+ getPayloadLength16(cb) {
7146
+ if (this._bufferedBytes < 2) {
7147
+ this._loop = false;
7148
+ return;
7149
+ }
7150
+ this._payloadLength = this.consume(2).readUInt16BE(0);
7151
+ this.haveLength(cb);
7152
+ }
7153
+ /**
7154
+ * Gets extended payload length (7+64).
7155
+ *
7156
+ * @param {Function} cb Callback
7157
+ * @private
7158
+ */
7159
+ getPayloadLength64(cb) {
7160
+ if (this._bufferedBytes < 8) {
7161
+ this._loop = false;
7162
+ return;
7163
+ }
7164
+ const buf = this.consume(8);
7165
+ const num = buf.readUInt32BE(0);
7166
+ if (num > Math.pow(2, 21) - 1) {
7167
+ cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
7168
+ return;
7169
+ }
7170
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
7171
+ this.haveLength(cb);
7172
+ }
7173
+ /**
7174
+ * Payload length has been read.
7175
+ *
7176
+ * @param {Function} cb Callback
7177
+ * @private
7178
+ */
7179
+ haveLength(cb) {
7180
+ if (this._payloadLength && this._opcode < 8) {
7181
+ this._totalPayloadLength += this._payloadLength;
7182
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
7183
+ cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
7184
+ return;
7185
+ }
7186
+ }
7187
+ if (this._masked) this._state = GET_MASK;
7188
+ else this._state = GET_DATA;
7189
+ }
7190
+ /**
7191
+ * Reads mask bytes.
7192
+ *
7193
+ * @private
7194
+ */
7195
+ getMask() {
7196
+ if (this._bufferedBytes < 4) {
7197
+ this._loop = false;
7198
+ return;
7199
+ }
7200
+ this._mask = this.consume(4);
7201
+ this._state = GET_DATA;
7202
+ }
7203
+ /**
7204
+ * Reads data bytes.
7205
+ *
7206
+ * @param {Function} cb Callback
7207
+ * @private
7208
+ */
7209
+ getData(cb) {
7210
+ let data = EMPTY_BUFFER;
7211
+ if (this._payloadLength) {
7212
+ if (this._bufferedBytes < this._payloadLength) {
7213
+ this._loop = false;
7214
+ return;
7215
+ }
7216
+ data = this.consume(this._payloadLength);
7217
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
7218
+ }
7219
+ if (this._opcode > 7) {
7220
+ this.controlMessage(data, cb);
7221
+ return;
7222
+ }
7223
+ if (this._compressed) {
7224
+ this._state = INFLATING;
7225
+ this.decompress(data, cb);
7226
+ return;
7227
+ }
7228
+ if (data.length) {
7229
+ this._messageLength = this._totalPayloadLength;
7230
+ this._fragments.push(data);
7231
+ }
7232
+ this.dataMessage(cb);
7233
+ }
7234
+ /**
7235
+ * Decompresses data.
7236
+ *
7237
+ * @param {Buffer} data Compressed data
7238
+ * @param {Function} cb Callback
7239
+ * @private
7240
+ */
7241
+ decompress(data, cb) {
7242
+ this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
7243
+ if (err) return cb(err);
7244
+ if (buf.length) {
7245
+ this._messageLength += buf.length;
7246
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
7247
+ cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
7248
+ return;
7249
+ }
7250
+ this._fragments.push(buf);
7251
+ }
7252
+ this.dataMessage(cb);
7253
+ if (this._state === GET_INFO) this.startLoop(cb);
7254
+ });
7255
+ }
7256
+ /**
7257
+ * Handles a data message.
7258
+ *
7259
+ * @param {Function} cb Callback
7260
+ * @private
7261
+ */
7262
+ dataMessage(cb) {
7263
+ if (!this._fin) {
7264
+ this._state = GET_INFO;
7265
+ return;
7266
+ }
7267
+ const messageLength = this._messageLength;
7268
+ const fragments = this._fragments;
7269
+ this._totalPayloadLength = 0;
7270
+ this._messageLength = 0;
7271
+ this._fragmented = 0;
7272
+ this._fragments = [];
7273
+ if (this._opcode === 2) {
7274
+ let data;
7275
+ if (this._binaryType === "nodebuffer") data = concat(fragments, messageLength);
7276
+ else if (this._binaryType === "arraybuffer") data = toArrayBuffer(concat(fragments, messageLength));
7277
+ else if (this._binaryType === "blob") data = new Blob(fragments);
7278
+ else data = fragments;
7279
+ if (this._allowSynchronousEvents) {
7280
+ this.emit("message", data, true);
7281
+ this._state = GET_INFO;
7282
+ } else {
7283
+ this._state = DEFER_EVENT;
7284
+ setImmediate(() => {
7285
+ this.emit("message", data, true);
7286
+ this._state = GET_INFO;
7287
+ this.startLoop(cb);
7288
+ });
7289
+ }
7290
+ } else {
7291
+ const buf = concat(fragments, messageLength);
7292
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
7293
+ cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
7294
+ return;
7295
+ }
7296
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
7297
+ this.emit("message", buf, false);
7298
+ this._state = GET_INFO;
7299
+ } else {
7300
+ this._state = DEFER_EVENT;
7301
+ setImmediate(() => {
7302
+ this.emit("message", buf, false);
7303
+ this._state = GET_INFO;
7304
+ this.startLoop(cb);
7305
+ });
7306
+ }
7307
+ }
7308
+ }
7309
+ /**
7310
+ * Handles a control message.
7311
+ *
7312
+ * @param {Buffer} data Data to handle
7313
+ * @return {(Error|RangeError|undefined)} A possible error
7314
+ * @private
7315
+ */
7316
+ controlMessage(data, cb) {
7317
+ if (this._opcode === 8) {
7318
+ if (data.length === 0) {
7319
+ this._loop = false;
7320
+ this.emit("conclude", 1005, EMPTY_BUFFER);
7321
+ this.end();
7322
+ } else {
7323
+ const code = data.readUInt16BE(0);
7324
+ if (!isValidStatusCode(code)) {
7325
+ cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
7326
+ return;
7327
+ }
7328
+ const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
7329
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
7330
+ cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
7331
+ return;
7332
+ }
7333
+ this._loop = false;
7334
+ this.emit("conclude", code, buf);
7335
+ this.end();
7336
+ }
7337
+ this._state = GET_INFO;
7338
+ return;
7339
+ }
7340
+ if (this._allowSynchronousEvents) {
7341
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
7342
+ this._state = GET_INFO;
7343
+ } else {
7344
+ this._state = DEFER_EVENT;
7345
+ setImmediate(() => {
7346
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
7347
+ this._state = GET_INFO;
7348
+ this.startLoop(cb);
7349
+ });
7350
+ }
7351
+ }
7352
+ /**
7353
+ * Builds an error object.
7354
+ *
7355
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
7356
+ * @param {String} message The error message
7357
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
7358
+ * `message`
7359
+ * @param {Number} statusCode The status code
7360
+ * @param {String} errorCode The exposed error code
7361
+ * @return {(Error|RangeError)} The error
7362
+ * @private
7363
+ */
7364
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
7365
+ this._loop = false;
7366
+ this._errored = true;
7367
+ const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
7368
+ Error.captureStackTrace(err, this.createError);
7369
+ err.code = errorCode;
7370
+ err[kStatusCode] = statusCode;
7371
+ return err;
7372
+ }
7373
+ };
7374
+ module.exports = Receiver;
7375
+ }));
7376
+
7377
+ //#endregion
7378
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/sender.js
7379
+ var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7380
+ const { Duplex: Duplex$3 } = __require("stream");
7381
+ const { randomFillSync } = __require("crypto");
7382
+ const PerMessageDeflate = require_permessage_deflate();
7383
+ const { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
7384
+ const { isBlob, isValidStatusCode } = require_validation();
7385
+ const { mask: applyMask, toBuffer } = require_buffer_util();
7386
+ const kByteLength = Symbol("kByteLength");
7387
+ const maskBuffer = Buffer.alloc(4);
7388
+ const RANDOM_POOL_SIZE = 8 * 1024;
7389
+ let randomPool;
7390
+ let randomPoolPointer = RANDOM_POOL_SIZE;
7391
+ const DEFAULT = 0;
7392
+ const DEFLATING = 1;
7393
+ const GET_BLOB_DATA = 2;
7394
+ /**
7395
+ * HyBi Sender implementation.
7396
+ */
7397
+ var Sender = class Sender {
7398
+ /**
7399
+ * Creates a Sender instance.
7400
+ *
7401
+ * @param {Duplex} socket The connection socket
7402
+ * @param {Object} [extensions] An object containing the negotiated extensions
7403
+ * @param {Function} [generateMask] The function used to generate the masking
7404
+ * key
7405
+ */
7406
+ constructor(socket, extensions, generateMask) {
7407
+ this._extensions = extensions || {};
7408
+ if (generateMask) {
7409
+ this._generateMask = generateMask;
7410
+ this._maskBuffer = Buffer.alloc(4);
7411
+ }
7412
+ this._socket = socket;
7413
+ this._firstFragment = true;
7414
+ this._compress = false;
7415
+ this._bufferedBytes = 0;
7416
+ this._queue = [];
7417
+ this._state = DEFAULT;
7418
+ this.onerror = NOOP;
7419
+ this[kWebSocket] = void 0;
7420
+ }
7421
+ /**
7422
+ * Frames a piece of data according to the HyBi WebSocket protocol.
7423
+ *
7424
+ * @param {(Buffer|String)} data The data to frame
7425
+ * @param {Object} options Options object
7426
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
7427
+ * FIN bit
7428
+ * @param {Function} [options.generateMask] The function used to generate the
7429
+ * masking key
7430
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
7431
+ * `data`
7432
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
7433
+ * key
7434
+ * @param {Number} options.opcode The opcode
7435
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
7436
+ * modified
7437
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
7438
+ * RSV1 bit
7439
+ * @return {(Buffer|String)[]} The framed data
7440
+ * @public
7441
+ */
7442
+ static frame(data, options) {
7443
+ let mask;
7444
+ let merge = false;
7445
+ let offset = 2;
7446
+ let skipMasking = false;
7447
+ if (options.mask) {
7448
+ mask = options.maskBuffer || maskBuffer;
7449
+ if (options.generateMask) options.generateMask(mask);
7450
+ else {
7451
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
7452
+ /* istanbul ignore else */
7453
+ if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
7454
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
7455
+ randomPoolPointer = 0;
7456
+ }
7457
+ mask[0] = randomPool[randomPoolPointer++];
7458
+ mask[1] = randomPool[randomPoolPointer++];
7459
+ mask[2] = randomPool[randomPoolPointer++];
7460
+ mask[3] = randomPool[randomPoolPointer++];
7461
+ }
7462
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
7463
+ offset = 6;
7464
+ }
7465
+ let dataLength;
7466
+ if (typeof data === "string") if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) dataLength = options[kByteLength];
7467
+ else {
7468
+ data = Buffer.from(data);
7469
+ dataLength = data.length;
7470
+ }
7471
+ else {
7472
+ dataLength = data.length;
7473
+ merge = options.mask && options.readOnly && !skipMasking;
7474
+ }
7475
+ let payloadLength = dataLength;
7476
+ if (dataLength >= 65536) {
7477
+ offset += 8;
7478
+ payloadLength = 127;
7479
+ } else if (dataLength > 125) {
7480
+ offset += 2;
7481
+ payloadLength = 126;
7482
+ }
7483
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
7484
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
7485
+ if (options.rsv1) target[0] |= 64;
7486
+ target[1] = payloadLength;
7487
+ if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
7488
+ else if (payloadLength === 127) {
7489
+ target[2] = target[3] = 0;
7490
+ target.writeUIntBE(dataLength, 4, 6);
7491
+ }
7492
+ if (!options.mask) return [target, data];
7493
+ target[1] |= 128;
7494
+ target[offset - 4] = mask[0];
7495
+ target[offset - 3] = mask[1];
7496
+ target[offset - 2] = mask[2];
7497
+ target[offset - 1] = mask[3];
7498
+ if (skipMasking) return [target, data];
7499
+ if (merge) {
7500
+ applyMask(data, mask, target, offset, dataLength);
7501
+ return [target];
7502
+ }
7503
+ applyMask(data, mask, data, 0, dataLength);
7504
+ return [target, data];
7505
+ }
7506
+ /**
7507
+ * Sends a close message to the other peer.
7508
+ *
7509
+ * @param {Number} [code] The status code component of the body
7510
+ * @param {(String|Buffer)} [data] The message component of the body
7511
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
7512
+ * @param {Function} [cb] Callback
7513
+ * @public
7514
+ */
7515
+ close(code, data, mask, cb) {
7516
+ let buf;
7517
+ if (code === void 0) buf = EMPTY_BUFFER;
7518
+ else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
7519
+ else if (data === void 0 || !data.length) {
7520
+ buf = Buffer.allocUnsafe(2);
7521
+ buf.writeUInt16BE(code, 0);
7522
+ } else {
7523
+ const length = Buffer.byteLength(data);
7524
+ if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
7525
+ buf = Buffer.allocUnsafe(2 + length);
7526
+ buf.writeUInt16BE(code, 0);
7527
+ if (typeof data === "string") buf.write(data, 2);
7528
+ else buf.set(data, 2);
7529
+ }
7530
+ const options = {
7531
+ [kByteLength]: buf.length,
7532
+ fin: true,
7533
+ generateMask: this._generateMask,
7534
+ mask,
7535
+ maskBuffer: this._maskBuffer,
7536
+ opcode: 8,
7537
+ readOnly: false,
7538
+ rsv1: false
7539
+ };
7540
+ if (this._state !== DEFAULT) this.enqueue([
7541
+ this.dispatch,
7542
+ buf,
7543
+ false,
7544
+ options,
7545
+ cb
7546
+ ]);
7547
+ else this.sendFrame(Sender.frame(buf, options), cb);
7548
+ }
7549
+ /**
7550
+ * Sends a ping message to the other peer.
7551
+ *
7552
+ * @param {*} data The message to send
7553
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
7554
+ * @param {Function} [cb] Callback
7555
+ * @public
7556
+ */
7557
+ ping(data, mask, cb) {
7558
+ let byteLength;
7559
+ let readOnly;
7560
+ if (typeof data === "string") {
7561
+ byteLength = Buffer.byteLength(data);
7562
+ readOnly = false;
7563
+ } else if (isBlob(data)) {
7564
+ byteLength = data.size;
7565
+ readOnly = false;
7566
+ } else {
7567
+ data = toBuffer(data);
7568
+ byteLength = data.length;
7569
+ readOnly = toBuffer.readOnly;
7570
+ }
7571
+ if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
7572
+ const options = {
7573
+ [kByteLength]: byteLength,
7574
+ fin: true,
7575
+ generateMask: this._generateMask,
7576
+ mask,
7577
+ maskBuffer: this._maskBuffer,
7578
+ opcode: 9,
7579
+ readOnly,
7580
+ rsv1: false
7581
+ };
7582
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
7583
+ this.getBlobData,
7584
+ data,
7585
+ false,
7586
+ options,
7587
+ cb
7588
+ ]);
7589
+ else this.getBlobData(data, false, options, cb);
7590
+ else if (this._state !== DEFAULT) this.enqueue([
7591
+ this.dispatch,
7592
+ data,
7593
+ false,
7594
+ options,
7595
+ cb
7596
+ ]);
7597
+ else this.sendFrame(Sender.frame(data, options), cb);
7598
+ }
7599
+ /**
7600
+ * Sends a pong message to the other peer.
7601
+ *
7602
+ * @param {*} data The message to send
7603
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
7604
+ * @param {Function} [cb] Callback
7605
+ * @public
7606
+ */
7607
+ pong(data, mask, cb) {
7608
+ let byteLength;
7609
+ let readOnly;
7610
+ if (typeof data === "string") {
7611
+ byteLength = Buffer.byteLength(data);
7612
+ readOnly = false;
7613
+ } else if (isBlob(data)) {
7614
+ byteLength = data.size;
7615
+ readOnly = false;
7616
+ } else {
7617
+ data = toBuffer(data);
7618
+ byteLength = data.length;
7619
+ readOnly = toBuffer.readOnly;
7620
+ }
7621
+ if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
7622
+ const options = {
7623
+ [kByteLength]: byteLength,
7624
+ fin: true,
7625
+ generateMask: this._generateMask,
7626
+ mask,
7627
+ maskBuffer: this._maskBuffer,
7628
+ opcode: 10,
7629
+ readOnly,
7630
+ rsv1: false
7631
+ };
7632
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
7633
+ this.getBlobData,
7634
+ data,
7635
+ false,
7636
+ options,
7637
+ cb
7638
+ ]);
7639
+ else this.getBlobData(data, false, options, cb);
7640
+ else if (this._state !== DEFAULT) this.enqueue([
7641
+ this.dispatch,
7642
+ data,
7643
+ false,
7644
+ options,
7645
+ cb
7646
+ ]);
7647
+ else this.sendFrame(Sender.frame(data, options), cb);
7648
+ }
7649
+ /**
7650
+ * Sends a data message to the other peer.
7651
+ *
7652
+ * @param {*} data The message to send
7653
+ * @param {Object} options Options object
7654
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
7655
+ * or text
7656
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
7657
+ * compress `data`
7658
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
7659
+ * last one
7660
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
7661
+ * `data`
7662
+ * @param {Function} [cb] Callback
7663
+ * @public
7664
+ */
7665
+ send(data, options, cb) {
7666
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
7667
+ let opcode = options.binary ? 2 : 1;
7668
+ let rsv1 = options.compress;
7669
+ let byteLength;
7670
+ let readOnly;
7671
+ if (typeof data === "string") {
7672
+ byteLength = Buffer.byteLength(data);
7673
+ readOnly = false;
7674
+ } else if (isBlob(data)) {
7675
+ byteLength = data.size;
7676
+ readOnly = false;
7677
+ } else {
7678
+ data = toBuffer(data);
7679
+ byteLength = data.length;
7680
+ readOnly = toBuffer.readOnly;
7681
+ }
7682
+ if (this._firstFragment) {
7683
+ this._firstFragment = false;
7684
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
7685
+ this._compress = rsv1;
7686
+ } else {
7687
+ rsv1 = false;
7688
+ opcode = 0;
7689
+ }
7690
+ if (options.fin) this._firstFragment = true;
7691
+ const opts = {
7692
+ [kByteLength]: byteLength,
7693
+ fin: options.fin,
7694
+ generateMask: this._generateMask,
7695
+ mask: options.mask,
7696
+ maskBuffer: this._maskBuffer,
7697
+ opcode,
7698
+ readOnly,
7699
+ rsv1
7700
+ };
7701
+ if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
7702
+ this.getBlobData,
7703
+ data,
7704
+ this._compress,
7705
+ opts,
7706
+ cb
7707
+ ]);
7708
+ else this.getBlobData(data, this._compress, opts, cb);
7709
+ else if (this._state !== DEFAULT) this.enqueue([
7710
+ this.dispatch,
7711
+ data,
7712
+ this._compress,
7713
+ opts,
7714
+ cb
7715
+ ]);
7716
+ else this.dispatch(data, this._compress, opts, cb);
7717
+ }
7718
+ /**
7719
+ * Gets the contents of a blob as binary data.
7720
+ *
7721
+ * @param {Blob} blob The blob
7722
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
7723
+ * the data
7724
+ * @param {Object} options Options object
7725
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
7726
+ * FIN bit
7727
+ * @param {Function} [options.generateMask] The function used to generate the
7728
+ * masking key
7729
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
7730
+ * `data`
7731
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
7732
+ * key
7733
+ * @param {Number} options.opcode The opcode
7734
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
7735
+ * modified
7736
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
7737
+ * RSV1 bit
7738
+ * @param {Function} [cb] Callback
7739
+ * @private
7740
+ */
7741
+ getBlobData(blob, compress, options, cb) {
7742
+ this._bufferedBytes += options[kByteLength];
7743
+ this._state = GET_BLOB_DATA;
7744
+ blob.arrayBuffer().then((arrayBuffer) => {
7745
+ if (this._socket.destroyed) {
7746
+ const err = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
7747
+ process.nextTick(callCallbacks, this, err, cb);
7748
+ return;
7749
+ }
7750
+ this._bufferedBytes -= options[kByteLength];
7751
+ const data = toBuffer(arrayBuffer);
7752
+ if (!compress) {
7753
+ this._state = DEFAULT;
7754
+ this.sendFrame(Sender.frame(data, options), cb);
7755
+ this.dequeue();
7756
+ } else this.dispatch(data, compress, options, cb);
7757
+ }).catch((err) => {
7758
+ process.nextTick(onError, this, err, cb);
7759
+ });
7760
+ }
7761
+ /**
7762
+ * Dispatches a message.
7763
+ *
7764
+ * @param {(Buffer|String)} data The message to send
7765
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
7766
+ * `data`
7767
+ * @param {Object} options Options object
7768
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
7769
+ * FIN bit
7770
+ * @param {Function} [options.generateMask] The function used to generate the
7771
+ * masking key
7772
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
7773
+ * `data`
7774
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
7775
+ * key
7776
+ * @param {Number} options.opcode The opcode
7777
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
7778
+ * modified
7779
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
7780
+ * RSV1 bit
7781
+ * @param {Function} [cb] Callback
7782
+ * @private
7783
+ */
7784
+ dispatch(data, compress, options, cb) {
7785
+ if (!compress) {
7786
+ this.sendFrame(Sender.frame(data, options), cb);
7787
+ return;
7788
+ }
7789
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
7790
+ this._bufferedBytes += options[kByteLength];
7791
+ this._state = DEFLATING;
7792
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
7793
+ if (this._socket.destroyed) {
7794
+ callCallbacks(this, /* @__PURE__ */ new Error("The socket was closed while data was being compressed"), cb);
7795
+ return;
7796
+ }
7797
+ this._bufferedBytes -= options[kByteLength];
7798
+ this._state = DEFAULT;
7799
+ options.readOnly = false;
7800
+ this.sendFrame(Sender.frame(buf, options), cb);
7801
+ this.dequeue();
7802
+ });
7803
+ }
7804
+ /**
7805
+ * Executes queued send operations.
7806
+ *
7807
+ * @private
7808
+ */
7809
+ dequeue() {
7810
+ while (this._state === DEFAULT && this._queue.length) {
7811
+ const params = this._queue.shift();
7812
+ this._bufferedBytes -= params[3][kByteLength];
7813
+ Reflect.apply(params[0], this, params.slice(1));
7814
+ }
7815
+ }
7816
+ /**
7817
+ * Enqueues a send operation.
7818
+ *
7819
+ * @param {Array} params Send operation parameters.
7820
+ * @private
7821
+ */
7822
+ enqueue(params) {
7823
+ this._bufferedBytes += params[3][kByteLength];
7824
+ this._queue.push(params);
7825
+ }
7826
+ /**
7827
+ * Sends a frame.
7828
+ *
7829
+ * @param {(Buffer | String)[]} list The frame to send
7830
+ * @param {Function} [cb] Callback
7831
+ * @private
7832
+ */
7833
+ sendFrame(list, cb) {
7834
+ if (list.length === 2) {
7835
+ this._socket.cork();
7836
+ this._socket.write(list[0]);
7837
+ this._socket.write(list[1], cb);
7838
+ this._socket.uncork();
7839
+ } else this._socket.write(list[0], cb);
7840
+ }
7841
+ };
7842
+ module.exports = Sender;
7843
+ /**
7844
+ * Calls queued callbacks with an error.
7845
+ *
7846
+ * @param {Sender} sender The `Sender` instance
7847
+ * @param {Error} err The error to call the callbacks with
7848
+ * @param {Function} [cb] The first callback
7849
+ * @private
7850
+ */
7851
+ function callCallbacks(sender, err, cb) {
7852
+ if (typeof cb === "function") cb(err);
7853
+ for (let i = 0; i < sender._queue.length; i++) {
7854
+ const params = sender._queue[i];
7855
+ const callback = params[params.length - 1];
7856
+ if (typeof callback === "function") callback(err);
7857
+ }
7858
+ }
7859
+ /**
7860
+ * Handles a `Sender` error.
7861
+ *
7862
+ * @param {Sender} sender The `Sender` instance
7863
+ * @param {Error} err The error
7864
+ * @param {Function} [cb] The first pending callback
7865
+ * @private
7866
+ */
7867
+ function onError(sender, err, cb) {
7868
+ callCallbacks(sender, err, cb);
7869
+ sender.onerror(err);
7870
+ }
7871
+ }));
7872
+
7873
+ //#endregion
7874
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/event-target.js
7875
+ var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7876
+ const { kForOnEventAttribute, kListener } = require_constants();
7877
+ const kCode = Symbol("kCode");
7878
+ const kData = Symbol("kData");
7879
+ const kError = Symbol("kError");
7880
+ const kMessage = Symbol("kMessage");
7881
+ const kReason = Symbol("kReason");
7882
+ const kTarget = Symbol("kTarget");
7883
+ const kType = Symbol("kType");
7884
+ const kWasClean = Symbol("kWasClean");
7885
+ /**
7886
+ * Class representing an event.
7887
+ */
7888
+ var Event = class {
7889
+ /**
7890
+ * Create a new `Event`.
7891
+ *
7892
+ * @param {String} type The name of the event
7893
+ * @throws {TypeError} If the `type` argument is not specified
7894
+ */
7895
+ constructor(type) {
7896
+ this[kTarget] = null;
7897
+ this[kType] = type;
7898
+ }
7899
+ /**
7900
+ * @type {*}
7901
+ */
7902
+ get target() {
7903
+ return this[kTarget];
7904
+ }
7905
+ /**
7906
+ * @type {String}
7907
+ */
7908
+ get type() {
7909
+ return this[kType];
7910
+ }
7911
+ };
7912
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
7913
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
7914
+ /**
7915
+ * Class representing a close event.
7916
+ *
7917
+ * @extends Event
7918
+ */
7919
+ var CloseEvent = class extends Event {
7920
+ /**
7921
+ * Create a new `CloseEvent`.
7922
+ *
7923
+ * @param {String} type The name of the event
7924
+ * @param {Object} [options] A dictionary object that allows for setting
7925
+ * attributes via object members of the same name
7926
+ * @param {Number} [options.code=0] The status code explaining why the
7927
+ * connection was closed
7928
+ * @param {String} [options.reason=''] A human-readable string explaining why
7929
+ * the connection was closed
7930
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
7931
+ * connection was cleanly closed
7932
+ */
7933
+ constructor(type, options = {}) {
7934
+ super(type);
7935
+ this[kCode] = options.code === void 0 ? 0 : options.code;
7936
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
7937
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
7938
+ }
7939
+ /**
7940
+ * @type {Number}
7941
+ */
7942
+ get code() {
7943
+ return this[kCode];
7944
+ }
7945
+ /**
7946
+ * @type {String}
7947
+ */
7948
+ get reason() {
7949
+ return this[kReason];
7950
+ }
7951
+ /**
7952
+ * @type {Boolean}
7953
+ */
7954
+ get wasClean() {
7955
+ return this[kWasClean];
7956
+ }
7957
+ };
7958
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
7959
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
7960
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
7961
+ /**
7962
+ * Class representing an error event.
7963
+ *
7964
+ * @extends Event
7965
+ */
7966
+ var ErrorEvent = class extends Event {
7967
+ /**
7968
+ * Create a new `ErrorEvent`.
7969
+ *
7970
+ * @param {String} type The name of the event
7971
+ * @param {Object} [options] A dictionary object that allows for setting
7972
+ * attributes via object members of the same name
7973
+ * @param {*} [options.error=null] The error that generated this event
7974
+ * @param {String} [options.message=''] The error message
7975
+ */
7976
+ constructor(type, options = {}) {
7977
+ super(type);
7978
+ this[kError] = options.error === void 0 ? null : options.error;
7979
+ this[kMessage] = options.message === void 0 ? "" : options.message;
7980
+ }
7981
+ /**
7982
+ * @type {*}
7983
+ */
7984
+ get error() {
7985
+ return this[kError];
7986
+ }
7987
+ /**
7988
+ * @type {String}
7989
+ */
7990
+ get message() {
7991
+ return this[kMessage];
7992
+ }
7993
+ };
7994
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
7995
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
7996
+ /**
7997
+ * Class representing a message event.
7998
+ *
7999
+ * @extends Event
8000
+ */
8001
+ var MessageEvent = class extends Event {
8002
+ /**
8003
+ * Create a new `MessageEvent`.
8004
+ *
8005
+ * @param {String} type The name of the event
8006
+ * @param {Object} [options] A dictionary object that allows for setting
8007
+ * attributes via object members of the same name
8008
+ * @param {*} [options.data=null] The message content
8009
+ */
8010
+ constructor(type, options = {}) {
8011
+ super(type);
8012
+ this[kData] = options.data === void 0 ? null : options.data;
8013
+ }
8014
+ /**
8015
+ * @type {*}
8016
+ */
8017
+ get data() {
8018
+ return this[kData];
8019
+ }
8020
+ };
8021
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
8022
+ /**
8023
+ * This provides methods for emulating the `EventTarget` interface. It's not
8024
+ * meant to be used directly.
8025
+ *
8026
+ * @mixin
8027
+ */
8028
+ const EventTarget = {
8029
+ addEventListener(type, handler, options = {}) {
8030
+ for (const listener of this.listeners(type)) if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
8031
+ let wrapper;
8032
+ if (type === "message") wrapper = function onMessage(data, isBinary) {
8033
+ const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
8034
+ event[kTarget] = this;
8035
+ callListener(handler, this, event);
8036
+ };
8037
+ else if (type === "close") wrapper = function onClose(code, message) {
8038
+ const event = new CloseEvent("close", {
8039
+ code,
8040
+ reason: message.toString(),
8041
+ wasClean: this._closeFrameReceived && this._closeFrameSent
8042
+ });
8043
+ event[kTarget] = this;
8044
+ callListener(handler, this, event);
8045
+ };
8046
+ else if (type === "error") wrapper = function onError(error) {
8047
+ const event = new ErrorEvent("error", {
8048
+ error,
8049
+ message: error.message
8050
+ });
8051
+ event[kTarget] = this;
8052
+ callListener(handler, this, event);
8053
+ };
8054
+ else if (type === "open") wrapper = function onOpen() {
8055
+ const event = new Event("open");
8056
+ event[kTarget] = this;
8057
+ callListener(handler, this, event);
8058
+ };
8059
+ else return;
8060
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
8061
+ wrapper[kListener] = handler;
8062
+ if (options.once) this.once(type, wrapper);
8063
+ else this.on(type, wrapper);
8064
+ },
8065
+ removeEventListener(type, handler) {
8066
+ for (const listener of this.listeners(type)) if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
8067
+ this.removeListener(type, listener);
8068
+ break;
8069
+ }
8070
+ }
8071
+ };
8072
+ module.exports = {
8073
+ CloseEvent,
8074
+ ErrorEvent,
8075
+ Event,
8076
+ EventTarget,
8077
+ MessageEvent
8078
+ };
8079
+ /**
8080
+ * Call an event listener
8081
+ *
8082
+ * @param {(Function|Object)} listener The listener to call
8083
+ * @param {*} thisArg The value to use as `this`` when calling the listener
8084
+ * @param {Event} event The event to pass to the listener
8085
+ * @private
8086
+ */
8087
+ function callListener(listener, thisArg, event) {
8088
+ if (typeof listener === "object" && listener.handleEvent) listener.handleEvent.call(listener, event);
8089
+ else listener.call(thisArg, event);
8090
+ }
8091
+ }));
8092
+
8093
+ //#endregion
8094
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/extension.js
8095
+ var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8096
+ const { tokenChars } = require_validation();
8097
+ /**
8098
+ * Adds an offer to the map of extension offers or a parameter to the map of
8099
+ * parameters.
8100
+ *
8101
+ * @param {Object} dest The map of extension offers or parameters
8102
+ * @param {String} name The extension or parameter name
8103
+ * @param {(Object|Boolean|String)} elem The extension parameters or the
8104
+ * parameter value
8105
+ * @private
8106
+ */
8107
+ function push(dest, name, elem) {
8108
+ if (dest[name] === void 0) dest[name] = [elem];
8109
+ else dest[name].push(elem);
8110
+ }
8111
+ /**
8112
+ * Parses the `Sec-WebSocket-Extensions` header into an object.
8113
+ *
8114
+ * @param {String} header The field value of the header
8115
+ * @return {Object} The parsed object
8116
+ * @public
8117
+ */
8118
+ function parse(header) {
8119
+ const offers = Object.create(null);
8120
+ let params = Object.create(null);
8121
+ let mustUnescape = false;
8122
+ let isEscaping = false;
8123
+ let inQuotes = false;
8124
+ let extensionName;
8125
+ let paramName;
8126
+ let start = -1;
8127
+ let code = -1;
8128
+ let end = -1;
8129
+ let i = 0;
8130
+ for (; i < header.length; i++) {
8131
+ code = header.charCodeAt(i);
8132
+ if (extensionName === void 0) if (end === -1 && tokenChars[code] === 1) {
8133
+ if (start === -1) start = i;
8134
+ } else if (i !== 0 && (code === 32 || code === 9)) {
8135
+ if (end === -1 && start !== -1) end = i;
8136
+ } else if (code === 59 || code === 44) {
8137
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
8138
+ if (end === -1) end = i;
8139
+ const name = header.slice(start, end);
8140
+ if (code === 44) {
8141
+ push(offers, name, params);
8142
+ params = Object.create(null);
8143
+ } else extensionName = name;
8144
+ start = end = -1;
8145
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
8146
+ else if (paramName === void 0) if (end === -1 && tokenChars[code] === 1) {
8147
+ if (start === -1) start = i;
8148
+ } else if (code === 32 || code === 9) {
8149
+ if (end === -1 && start !== -1) end = i;
8150
+ } else if (code === 59 || code === 44) {
8151
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
8152
+ if (end === -1) end = i;
8153
+ push(params, header.slice(start, end), true);
8154
+ if (code === 44) {
8155
+ push(offers, extensionName, params);
8156
+ params = Object.create(null);
8157
+ extensionName = void 0;
8158
+ }
8159
+ start = end = -1;
8160
+ } else if (code === 61 && start !== -1 && end === -1) {
8161
+ paramName = header.slice(start, i);
8162
+ start = end = -1;
8163
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
8164
+ else if (isEscaping) {
8165
+ if (tokenChars[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i}`);
8166
+ if (start === -1) start = i;
8167
+ else if (!mustUnescape) mustUnescape = true;
8168
+ isEscaping = false;
8169
+ } else if (inQuotes) if (tokenChars[code] === 1) {
8170
+ if (start === -1) start = i;
8171
+ } else if (code === 34 && start !== -1) {
8172
+ inQuotes = false;
8173
+ end = i;
8174
+ } else if (code === 92) isEscaping = true;
8175
+ else throw new SyntaxError(`Unexpected character at index ${i}`);
8176
+ else if (code === 34 && header.charCodeAt(i - 1) === 61) inQuotes = true;
8177
+ else if (end === -1 && tokenChars[code] === 1) {
8178
+ if (start === -1) start = i;
8179
+ } else if (start !== -1 && (code === 32 || code === 9)) {
8180
+ if (end === -1) end = i;
8181
+ } else if (code === 59 || code === 44) {
8182
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
8183
+ if (end === -1) end = i;
8184
+ let value = header.slice(start, end);
8185
+ if (mustUnescape) {
8186
+ value = value.replace(/\\/g, "");
8187
+ mustUnescape = false;
8188
+ }
8189
+ push(params, paramName, value);
8190
+ if (code === 44) {
8191
+ push(offers, extensionName, params);
8192
+ params = Object.create(null);
8193
+ extensionName = void 0;
8194
+ }
8195
+ paramName = void 0;
8196
+ start = end = -1;
8197
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
8198
+ }
8199
+ if (start === -1 || inQuotes || code === 32 || code === 9) throw new SyntaxError("Unexpected end of input");
8200
+ if (end === -1) end = i;
8201
+ const token = header.slice(start, end);
8202
+ if (extensionName === void 0) push(offers, token, params);
8203
+ else {
8204
+ if (paramName === void 0) push(params, token, true);
8205
+ else if (mustUnescape) push(params, paramName, token.replace(/\\/g, ""));
8206
+ else push(params, paramName, token);
8207
+ push(offers, extensionName, params);
8208
+ }
8209
+ return offers;
8210
+ }
8211
+ /**
8212
+ * Builds the `Sec-WebSocket-Extensions` header field value.
8213
+ *
8214
+ * @param {Object} extensions The map of extensions and parameters to format
8215
+ * @return {String} A string representing the given object
8216
+ * @public
8217
+ */
8218
+ function format(extensions) {
8219
+ return Object.keys(extensions).map((extension) => {
8220
+ let configurations = extensions[extension];
8221
+ if (!Array.isArray(configurations)) configurations = [configurations];
8222
+ return configurations.map((params) => {
8223
+ return [extension].concat(Object.keys(params).map((k) => {
8224
+ let values = params[k];
8225
+ if (!Array.isArray(values)) values = [values];
8226
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
8227
+ })).join("; ");
8228
+ }).join(", ");
8229
+ }).join(", ");
8230
+ }
8231
+ module.exports = {
8232
+ format,
8233
+ parse
8234
+ };
8235
+ }));
8236
+
8237
+ //#endregion
8238
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket.js
8239
+ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8240
+ const EventEmitter$2 = __require("events");
8241
+ const https = __require("https");
8242
+ const http$1 = __require("http");
8243
+ const net = __require("net");
8244
+ const tls = __require("tls");
8245
+ const { randomBytes, createHash: createHash$1 } = __require("crypto");
8246
+ const { Duplex: Duplex$2, Readable } = __require("stream");
8247
+ const { URL } = __require("url");
8248
+ const PerMessageDeflate = require_permessage_deflate();
8249
+ const Receiver = require_receiver();
8250
+ const Sender = require_sender();
8251
+ const { isBlob } = require_validation();
8252
+ const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants();
8253
+ const { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
8254
+ const { format, parse } = require_extension();
8255
+ const { toBuffer } = require_buffer_util();
8256
+ const kAborted = Symbol("kAborted");
8257
+ const protocolVersions = [8, 13];
8258
+ const readyStates = [
8259
+ "CONNECTING",
8260
+ "OPEN",
8261
+ "CLOSING",
8262
+ "CLOSED"
8263
+ ];
8264
+ const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
8265
+ /**
8266
+ * Class representing a WebSocket.
8267
+ *
8268
+ * @extends EventEmitter
8269
+ */
8270
+ var WebSocket = class WebSocket extends EventEmitter$2 {
8271
+ /**
8272
+ * Create a new `WebSocket`.
8273
+ *
8274
+ * @param {(String|URL)} address The URL to which to connect
8275
+ * @param {(String|String[])} [protocols] The subprotocols
8276
+ * @param {Object} [options] Connection options
8277
+ */
8278
+ constructor(address, protocols, options) {
8279
+ super();
8280
+ this._binaryType = BINARY_TYPES[0];
8281
+ this._closeCode = 1006;
8282
+ this._closeFrameReceived = false;
8283
+ this._closeFrameSent = false;
8284
+ this._closeMessage = EMPTY_BUFFER;
8285
+ this._closeTimer = null;
8286
+ this._errorEmitted = false;
8287
+ this._extensions = {};
8288
+ this._paused = false;
8289
+ this._protocol = "";
8290
+ this._readyState = WebSocket.CONNECTING;
8291
+ this._receiver = null;
8292
+ this._sender = null;
8293
+ this._socket = null;
8294
+ if (address !== null) {
8295
+ this._bufferedAmount = 0;
8296
+ this._isServer = false;
8297
+ this._redirects = 0;
8298
+ if (protocols === void 0) protocols = [];
8299
+ else if (!Array.isArray(protocols)) if (typeof protocols === "object" && protocols !== null) {
8300
+ options = protocols;
8301
+ protocols = [];
8302
+ } else protocols = [protocols];
8303
+ initAsClient(this, address, protocols, options);
8304
+ } else {
8305
+ this._autoPong = options.autoPong;
8306
+ this._closeTimeout = options.closeTimeout;
8307
+ this._isServer = true;
8308
+ }
8309
+ }
8310
+ /**
8311
+ * For historical reasons, the custom "nodebuffer" type is used by the default
8312
+ * instead of "blob".
8313
+ *
8314
+ * @type {String}
8315
+ */
8316
+ get binaryType() {
8317
+ return this._binaryType;
8318
+ }
8319
+ set binaryType(type) {
8320
+ if (!BINARY_TYPES.includes(type)) return;
8321
+ this._binaryType = type;
8322
+ if (this._receiver) this._receiver._binaryType = type;
8323
+ }
8324
+ /**
8325
+ * @type {Number}
8326
+ */
8327
+ get bufferedAmount() {
8328
+ if (!this._socket) return this._bufferedAmount;
8329
+ return this._socket._writableState.length + this._sender._bufferedBytes;
8330
+ }
8331
+ /**
8332
+ * @type {String}
8333
+ */
8334
+ get extensions() {
8335
+ return Object.keys(this._extensions).join();
8336
+ }
8337
+ /**
8338
+ * @type {Boolean}
8339
+ */
8340
+ get isPaused() {
8341
+ return this._paused;
8342
+ }
8343
+ /**
8344
+ * @type {Function}
8345
+ */
8346
+ /* istanbul ignore next */
8347
+ get onclose() {
8348
+ return null;
8349
+ }
8350
+ /**
8351
+ * @type {Function}
8352
+ */
8353
+ /* istanbul ignore next */
8354
+ get onerror() {
8355
+ return null;
8356
+ }
8357
+ /**
8358
+ * @type {Function}
8359
+ */
8360
+ /* istanbul ignore next */
8361
+ get onopen() {
8362
+ return null;
8363
+ }
8364
+ /**
8365
+ * @type {Function}
8366
+ */
8367
+ /* istanbul ignore next */
8368
+ get onmessage() {
8369
+ return null;
8370
+ }
8371
+ /**
8372
+ * @type {String}
8373
+ */
8374
+ get protocol() {
8375
+ return this._protocol;
8376
+ }
8377
+ /**
8378
+ * @type {Number}
8379
+ */
8380
+ get readyState() {
8381
+ return this._readyState;
8382
+ }
8383
+ /**
8384
+ * @type {String}
8385
+ */
8386
+ get url() {
8387
+ return this._url;
8388
+ }
8389
+ /**
8390
+ * Set up the socket and the internal resources.
8391
+ *
8392
+ * @param {Duplex} socket The network socket between the server and client
8393
+ * @param {Buffer} head The first packet of the upgraded stream
8394
+ * @param {Object} options Options object
8395
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
8396
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
8397
+ * multiple times in the same tick
8398
+ * @param {Function} [options.generateMask] The function used to generate the
8399
+ * masking key
8400
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
8401
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
8402
+ * not to skip UTF-8 validation for text and close messages
8403
+ * @private
8404
+ */
8405
+ setSocket(socket, head, options) {
8406
+ const receiver = new Receiver({
8407
+ allowSynchronousEvents: options.allowSynchronousEvents,
8408
+ binaryType: this.binaryType,
8409
+ extensions: this._extensions,
8410
+ isServer: this._isServer,
8411
+ maxPayload: options.maxPayload,
8412
+ skipUTF8Validation: options.skipUTF8Validation
8413
+ });
8414
+ const sender = new Sender(socket, this._extensions, options.generateMask);
8415
+ this._receiver = receiver;
8416
+ this._sender = sender;
8417
+ this._socket = socket;
8418
+ receiver[kWebSocket] = this;
8419
+ sender[kWebSocket] = this;
8420
+ socket[kWebSocket] = this;
8421
+ receiver.on("conclude", receiverOnConclude);
8422
+ receiver.on("drain", receiverOnDrain);
8423
+ receiver.on("error", receiverOnError);
8424
+ receiver.on("message", receiverOnMessage);
8425
+ receiver.on("ping", receiverOnPing);
8426
+ receiver.on("pong", receiverOnPong);
8427
+ sender.onerror = senderOnError;
8428
+ if (socket.setTimeout) socket.setTimeout(0);
8429
+ if (socket.setNoDelay) socket.setNoDelay();
8430
+ if (head.length > 0) socket.unshift(head);
8431
+ socket.on("close", socketOnClose);
8432
+ socket.on("data", socketOnData);
8433
+ socket.on("end", socketOnEnd);
8434
+ socket.on("error", socketOnError);
8435
+ this._readyState = WebSocket.OPEN;
8436
+ this.emit("open");
8437
+ }
8438
+ /**
8439
+ * Emit the `'close'` event.
8440
+ *
8441
+ * @private
8442
+ */
8443
+ emitClose() {
8444
+ if (!this._socket) {
8445
+ this._readyState = WebSocket.CLOSED;
8446
+ this.emit("close", this._closeCode, this._closeMessage);
8447
+ return;
8448
+ }
8449
+ if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
8450
+ this._receiver.removeAllListeners();
8451
+ this._readyState = WebSocket.CLOSED;
8452
+ this.emit("close", this._closeCode, this._closeMessage);
8453
+ }
8454
+ /**
8455
+ * Start a closing handshake.
8456
+ *
8457
+ * +----------+ +-----------+ +----------+
8458
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
8459
+ * | +----------+ +-----------+ +----------+ |
8460
+ * +----------+ +-----------+ |
8461
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
8462
+ * +----------+ +-----------+ |
8463
+ * | | | +---+ |
8464
+ * +------------------------+-->|fin| - - - -
8465
+ * | +---+ | +---+
8466
+ * - - - - -|fin|<---------------------+
8467
+ * +---+
8468
+ *
8469
+ * @param {Number} [code] Status code explaining why the connection is closing
8470
+ * @param {(String|Buffer)} [data] The reason why the connection is
8471
+ * closing
8472
+ * @public
8473
+ */
8474
+ close(code, data) {
8475
+ if (this.readyState === WebSocket.CLOSED) return;
8476
+ if (this.readyState === WebSocket.CONNECTING) {
8477
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
8478
+ return;
8479
+ }
8480
+ if (this.readyState === WebSocket.CLOSING) {
8481
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
8482
+ return;
8483
+ }
8484
+ this._readyState = WebSocket.CLOSING;
8485
+ this._sender.close(code, data, !this._isServer, (err) => {
8486
+ if (err) return;
8487
+ this._closeFrameSent = true;
8488
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
8489
+ });
8490
+ setCloseTimer(this);
8491
+ }
8492
+ /**
8493
+ * Pause the socket.
8494
+ *
8495
+ * @public
8496
+ */
8497
+ pause() {
8498
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
8499
+ this._paused = true;
8500
+ this._socket.pause();
8501
+ }
8502
+ /**
8503
+ * Send a ping.
8504
+ *
8505
+ * @param {*} [data] The data to send
8506
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
8507
+ * @param {Function} [cb] Callback which is executed when the ping is sent
8508
+ * @public
8509
+ */
8510
+ ping(data, mask, cb) {
8511
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
8512
+ if (typeof data === "function") {
8513
+ cb = data;
8514
+ data = mask = void 0;
8515
+ } else if (typeof mask === "function") {
8516
+ cb = mask;
8517
+ mask = void 0;
8518
+ }
8519
+ if (typeof data === "number") data = data.toString();
8520
+ if (this.readyState !== WebSocket.OPEN) {
8521
+ sendAfterClose(this, data, cb);
8522
+ return;
8523
+ }
8524
+ if (mask === void 0) mask = !this._isServer;
8525
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
8526
+ }
8527
+ /**
8528
+ * Send a pong.
8529
+ *
8530
+ * @param {*} [data] The data to send
8531
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
8532
+ * @param {Function} [cb] Callback which is executed when the pong is sent
8533
+ * @public
8534
+ */
8535
+ pong(data, mask, cb) {
8536
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
8537
+ if (typeof data === "function") {
8538
+ cb = data;
8539
+ data = mask = void 0;
8540
+ } else if (typeof mask === "function") {
8541
+ cb = mask;
8542
+ mask = void 0;
8543
+ }
8544
+ if (typeof data === "number") data = data.toString();
8545
+ if (this.readyState !== WebSocket.OPEN) {
8546
+ sendAfterClose(this, data, cb);
8547
+ return;
8548
+ }
8549
+ if (mask === void 0) mask = !this._isServer;
8550
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
8551
+ }
8552
+ /**
8553
+ * Resume the socket.
8554
+ *
8555
+ * @public
8556
+ */
8557
+ resume() {
8558
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
8559
+ this._paused = false;
8560
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
8561
+ }
8562
+ /**
8563
+ * Send a data message.
8564
+ *
8565
+ * @param {*} data The message to send
8566
+ * @param {Object} [options] Options object
8567
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
8568
+ * text
8569
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
8570
+ * `data`
8571
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
8572
+ * last one
8573
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
8574
+ * @param {Function} [cb] Callback which is executed when data is written out
8575
+ * @public
8576
+ */
8577
+ send(data, options, cb) {
8578
+ if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
8579
+ if (typeof options === "function") {
8580
+ cb = options;
8581
+ options = {};
8582
+ }
8583
+ if (typeof data === "number") data = data.toString();
8584
+ if (this.readyState !== WebSocket.OPEN) {
8585
+ sendAfterClose(this, data, cb);
8586
+ return;
8587
+ }
8588
+ const opts = {
8589
+ binary: typeof data !== "string",
8590
+ mask: !this._isServer,
8591
+ compress: true,
8592
+ fin: true,
8593
+ ...options
8594
+ };
8595
+ if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
8596
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
8597
+ }
8598
+ /**
8599
+ * Forcibly close the connection.
8600
+ *
8601
+ * @public
8602
+ */
8603
+ terminate() {
8604
+ if (this.readyState === WebSocket.CLOSED) return;
8605
+ if (this.readyState === WebSocket.CONNECTING) {
8606
+ abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
8607
+ return;
8608
+ }
8609
+ if (this._socket) {
8610
+ this._readyState = WebSocket.CLOSING;
8611
+ this._socket.destroy();
8612
+ }
8613
+ }
8614
+ };
8615
+ /**
8616
+ * @constant {Number} CONNECTING
8617
+ * @memberof WebSocket
8618
+ */
8619
+ Object.defineProperty(WebSocket, "CONNECTING", {
8620
+ enumerable: true,
8621
+ value: readyStates.indexOf("CONNECTING")
8622
+ });
8623
+ /**
8624
+ * @constant {Number} CONNECTING
8625
+ * @memberof WebSocket.prototype
8626
+ */
8627
+ Object.defineProperty(WebSocket.prototype, "CONNECTING", {
8628
+ enumerable: true,
8629
+ value: readyStates.indexOf("CONNECTING")
8630
+ });
8631
+ /**
8632
+ * @constant {Number} OPEN
8633
+ * @memberof WebSocket
8634
+ */
8635
+ Object.defineProperty(WebSocket, "OPEN", {
8636
+ enumerable: true,
8637
+ value: readyStates.indexOf("OPEN")
8638
+ });
8639
+ /**
8640
+ * @constant {Number} OPEN
8641
+ * @memberof WebSocket.prototype
8642
+ */
8643
+ Object.defineProperty(WebSocket.prototype, "OPEN", {
8644
+ enumerable: true,
8645
+ value: readyStates.indexOf("OPEN")
8646
+ });
8647
+ /**
8648
+ * @constant {Number} CLOSING
8649
+ * @memberof WebSocket
8650
+ */
8651
+ Object.defineProperty(WebSocket, "CLOSING", {
8652
+ enumerable: true,
8653
+ value: readyStates.indexOf("CLOSING")
8654
+ });
8655
+ /**
8656
+ * @constant {Number} CLOSING
8657
+ * @memberof WebSocket.prototype
8658
+ */
8659
+ Object.defineProperty(WebSocket.prototype, "CLOSING", {
8660
+ enumerable: true,
8661
+ value: readyStates.indexOf("CLOSING")
8662
+ });
8663
+ /**
8664
+ * @constant {Number} CLOSED
8665
+ * @memberof WebSocket
8666
+ */
8667
+ Object.defineProperty(WebSocket, "CLOSED", {
8668
+ enumerable: true,
8669
+ value: readyStates.indexOf("CLOSED")
8670
+ });
8671
+ /**
8672
+ * @constant {Number} CLOSED
8673
+ * @memberof WebSocket.prototype
8674
+ */
8675
+ Object.defineProperty(WebSocket.prototype, "CLOSED", {
8676
+ enumerable: true,
8677
+ value: readyStates.indexOf("CLOSED")
8678
+ });
8679
+ [
8680
+ "binaryType",
8681
+ "bufferedAmount",
8682
+ "extensions",
8683
+ "isPaused",
8684
+ "protocol",
8685
+ "readyState",
8686
+ "url"
8687
+ ].forEach((property) => {
8688
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
8689
+ });
8690
+ [
8691
+ "open",
8692
+ "error",
8693
+ "close",
8694
+ "message"
8695
+ ].forEach((method) => {
8696
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
8697
+ enumerable: true,
8698
+ get() {
8699
+ for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) return listener[kListener];
8700
+ return null;
8701
+ },
8702
+ set(handler) {
8703
+ for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) {
8704
+ this.removeListener(method, listener);
8705
+ break;
8706
+ }
8707
+ if (typeof handler !== "function") return;
8708
+ this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
8709
+ }
8710
+ });
8711
+ });
8712
+ WebSocket.prototype.addEventListener = addEventListener;
8713
+ WebSocket.prototype.removeEventListener = removeEventListener;
8714
+ module.exports = WebSocket;
8715
+ /**
8716
+ * Initialize a WebSocket client.
8717
+ *
8718
+ * @param {WebSocket} websocket The client to initialize
8719
+ * @param {(String|URL)} address The URL to which to connect
8720
+ * @param {Array} protocols The subprotocols
8721
+ * @param {Object} [options] Connection options
8722
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
8723
+ * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
8724
+ * times in the same tick
8725
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
8726
+ * automatically send a pong in response to a ping
8727
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
8728
+ * for the closing handshake to finish after `websocket.close()` is called
8729
+ * @param {Function} [options.finishRequest] A function which can be used to
8730
+ * customize the headers of each http request before it is sent
8731
+ * @param {Boolean} [options.followRedirects=false] Whether or not to follow
8732
+ * redirects
8733
+ * @param {Function} [options.generateMask] The function used to generate the
8734
+ * masking key
8735
+ * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
8736
+ * handshake request
8737
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
8738
+ * size
8739
+ * @param {Number} [options.maxRedirects=10] The maximum number of redirects
8740
+ * allowed
8741
+ * @param {String} [options.origin] Value of the `Origin` or
8742
+ * `Sec-WebSocket-Origin` header
8743
+ * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
8744
+ * permessage-deflate
8745
+ * @param {Number} [options.protocolVersion=13] Value of the
8746
+ * `Sec-WebSocket-Version` header
8747
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
8748
+ * not to skip UTF-8 validation for text and close messages
8749
+ * @private
8750
+ */
8751
+ function initAsClient(websocket, address, protocols, options) {
8752
+ const opts = {
8753
+ allowSynchronousEvents: true,
8754
+ autoPong: true,
8755
+ closeTimeout: CLOSE_TIMEOUT,
8756
+ protocolVersion: protocolVersions[1],
8757
+ maxPayload: 100 * 1024 * 1024,
8758
+ skipUTF8Validation: false,
8759
+ perMessageDeflate: true,
8760
+ followRedirects: false,
8761
+ maxRedirects: 10,
8762
+ ...options,
8763
+ socketPath: void 0,
8764
+ hostname: void 0,
8765
+ protocol: void 0,
8766
+ timeout: void 0,
8767
+ method: "GET",
8768
+ host: void 0,
8769
+ path: void 0,
8770
+ port: void 0
8771
+ };
8772
+ websocket._autoPong = opts.autoPong;
8773
+ websocket._closeTimeout = opts.closeTimeout;
8774
+ if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
8775
+ let parsedUrl;
8776
+ if (address instanceof URL) parsedUrl = address;
8777
+ else try {
8778
+ parsedUrl = new URL(address);
8779
+ } catch (e) {
8780
+ throw new SyntaxError(`Invalid URL: ${address}`);
8781
+ }
8782
+ if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
8783
+ else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
8784
+ websocket._url = parsedUrl.href;
8785
+ const isSecure = parsedUrl.protocol === "wss:";
8786
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
8787
+ let invalidUrlMessage;
8788
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
8789
+ else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
8790
+ else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
8791
+ if (invalidUrlMessage) {
8792
+ const err = new SyntaxError(invalidUrlMessage);
8793
+ if (websocket._redirects === 0) throw err;
8794
+ else {
8795
+ emitErrorAndClose(websocket, err);
8796
+ return;
8797
+ }
8798
+ }
8799
+ const defaultPort = isSecure ? 443 : 80;
8800
+ const key = randomBytes(16).toString("base64");
8801
+ const request = isSecure ? https.request : http$1.request;
8802
+ const protocolSet = /* @__PURE__ */ new Set();
8803
+ let perMessageDeflate;
8804
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
8805
+ opts.defaultPort = opts.defaultPort || defaultPort;
8806
+ opts.port = parsedUrl.port || defaultPort;
8807
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
8808
+ opts.headers = {
8809
+ ...opts.headers,
8810
+ "Sec-WebSocket-Version": opts.protocolVersion,
8811
+ "Sec-WebSocket-Key": key,
8812
+ Connection: "Upgrade",
8813
+ Upgrade: "websocket"
8814
+ };
8815
+ opts.path = parsedUrl.pathname + parsedUrl.search;
8816
+ opts.timeout = opts.handshakeTimeout;
8817
+ if (opts.perMessageDeflate) {
8818
+ perMessageDeflate = new PerMessageDeflate(opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload);
8819
+ opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() });
8820
+ }
8821
+ if (protocols.length) {
8822
+ for (const protocol of protocols) {
8823
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
8824
+ protocolSet.add(protocol);
8825
+ }
8826
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
8827
+ }
8828
+ if (opts.origin) if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
8829
+ else opts.headers.Origin = opts.origin;
8830
+ if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
8831
+ if (isIpcUrl) {
8832
+ const parts = opts.path.split(":");
8833
+ opts.socketPath = parts[0];
8834
+ opts.path = parts[1];
8835
+ }
8836
+ let req;
8837
+ if (opts.followRedirects) {
8838
+ if (websocket._redirects === 0) {
8839
+ websocket._originalIpc = isIpcUrl;
8840
+ websocket._originalSecure = isSecure;
8841
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
8842
+ const headers = options && options.headers;
8843
+ options = {
8844
+ ...options,
8845
+ headers: {}
8846
+ };
8847
+ if (headers) for (const [key, value] of Object.entries(headers)) options.headers[key.toLowerCase()] = value;
8848
+ } else if (websocket.listenerCount("redirect") === 0) {
8849
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
8850
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
8851
+ delete opts.headers.authorization;
8852
+ delete opts.headers.cookie;
8853
+ if (!isSameHost) delete opts.headers.host;
8854
+ opts.auth = void 0;
8855
+ }
8856
+ }
8857
+ if (opts.auth && !options.headers.authorization) options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
8858
+ req = websocket._req = request(opts);
8859
+ if (websocket._redirects) websocket.emit("redirect", websocket.url, req);
8860
+ } else req = websocket._req = request(opts);
8861
+ if (opts.timeout) req.on("timeout", () => {
8862
+ abortHandshake(websocket, req, "Opening handshake has timed out");
8863
+ });
8864
+ req.on("error", (err) => {
8865
+ if (req === null || req[kAborted]) return;
8866
+ req = websocket._req = null;
8867
+ emitErrorAndClose(websocket, err);
8868
+ });
8869
+ req.on("response", (res) => {
8870
+ const location = res.headers.location;
8871
+ const statusCode = res.statusCode;
8872
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
8873
+ if (++websocket._redirects > opts.maxRedirects) {
8874
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
8875
+ return;
8876
+ }
8877
+ req.abort();
8878
+ let addr;
8879
+ try {
8880
+ addr = new URL(location, address);
8881
+ } catch (e) {
8882
+ emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
8883
+ return;
8884
+ }
8885
+ initAsClient(websocket, addr, protocols, options);
8886
+ } else if (!websocket.emit("unexpected-response", req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
8887
+ });
8888
+ req.on("upgrade", (res, socket, head) => {
8889
+ websocket.emit("upgrade", res);
8890
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
8891
+ req = websocket._req = null;
8892
+ const upgrade = res.headers.upgrade;
8893
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
8894
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
8895
+ return;
8896
+ }
8897
+ const digest = createHash$1("sha1").update(key + GUID).digest("base64");
8898
+ if (res.headers["sec-websocket-accept"] !== digest) {
8899
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
8900
+ return;
8901
+ }
8902
+ const serverProt = res.headers["sec-websocket-protocol"];
8903
+ let protError;
8904
+ if (serverProt !== void 0) {
8905
+ if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
8906
+ else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
8907
+ } else if (protocolSet.size) protError = "Server sent no subprotocol";
8908
+ if (protError) {
8909
+ abortHandshake(websocket, socket, protError);
8910
+ return;
8911
+ }
8912
+ if (serverProt) websocket._protocol = serverProt;
8913
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
8914
+ if (secWebSocketExtensions !== void 0) {
8915
+ if (!perMessageDeflate) {
8916
+ abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
8917
+ return;
8918
+ }
8919
+ let extensions;
8920
+ try {
8921
+ extensions = parse(secWebSocketExtensions);
8922
+ } catch (err) {
8923
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
8924
+ return;
8925
+ }
8926
+ const extensionNames = Object.keys(extensions);
8927
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
8928
+ abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
8929
+ return;
8930
+ }
8931
+ try {
8932
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
8933
+ } catch (err) {
8934
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
8935
+ return;
8936
+ }
8937
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
8938
+ }
8939
+ websocket.setSocket(socket, head, {
8940
+ allowSynchronousEvents: opts.allowSynchronousEvents,
8941
+ generateMask: opts.generateMask,
8942
+ maxPayload: opts.maxPayload,
8943
+ skipUTF8Validation: opts.skipUTF8Validation
8944
+ });
8945
+ });
8946
+ if (opts.finishRequest) opts.finishRequest(req, websocket);
8947
+ else req.end();
8948
+ }
8949
+ /**
8950
+ * Emit the `'error'` and `'close'` events.
8951
+ *
8952
+ * @param {WebSocket} websocket The WebSocket instance
8953
+ * @param {Error} The error to emit
8954
+ * @private
8955
+ */
8956
+ function emitErrorAndClose(websocket, err) {
8957
+ websocket._readyState = WebSocket.CLOSING;
8958
+ websocket._errorEmitted = true;
8959
+ websocket.emit("error", err);
8960
+ websocket.emitClose();
8961
+ }
8962
+ /**
8963
+ * Create a `net.Socket` and initiate a connection.
8964
+ *
8965
+ * @param {Object} options Connection options
8966
+ * @return {net.Socket} The newly created socket used to start the connection
8967
+ * @private
8968
+ */
8969
+ function netConnect(options) {
8970
+ options.path = options.socketPath;
8971
+ return net.connect(options);
8972
+ }
8973
+ /**
8974
+ * Create a `tls.TLSSocket` and initiate a connection.
8975
+ *
8976
+ * @param {Object} options Connection options
8977
+ * @return {tls.TLSSocket} The newly created socket used to start the connection
8978
+ * @private
8979
+ */
8980
+ function tlsConnect(options) {
8981
+ options.path = void 0;
8982
+ if (!options.servername && options.servername !== "") options.servername = net.isIP(options.host) ? "" : options.host;
8983
+ return tls.connect(options);
8984
+ }
8985
+ /**
8986
+ * Abort the handshake and emit an error.
8987
+ *
8988
+ * @param {WebSocket} websocket The WebSocket instance
8989
+ * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
8990
+ * abort or the socket to destroy
8991
+ * @param {String} message The error message
8992
+ * @private
8993
+ */
8994
+ function abortHandshake(websocket, stream, message) {
8995
+ websocket._readyState = WebSocket.CLOSING;
8996
+ const err = new Error(message);
8997
+ Error.captureStackTrace(err, abortHandshake);
8998
+ if (stream.setHeader) {
8999
+ stream[kAborted] = true;
9000
+ stream.abort();
9001
+ if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
9002
+ process.nextTick(emitErrorAndClose, websocket, err);
9003
+ } else {
9004
+ stream.destroy(err);
9005
+ stream.once("error", websocket.emit.bind(websocket, "error"));
9006
+ stream.once("close", websocket.emitClose.bind(websocket));
9007
+ }
9008
+ }
9009
+ /**
9010
+ * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
9011
+ * when the `readyState` attribute is `CLOSING` or `CLOSED`.
9012
+ *
9013
+ * @param {WebSocket} websocket The WebSocket instance
9014
+ * @param {*} [data] The data to send
9015
+ * @param {Function} [cb] Callback
9016
+ * @private
9017
+ */
9018
+ function sendAfterClose(websocket, data, cb) {
9019
+ if (data) {
9020
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
9021
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
9022
+ else websocket._bufferedAmount += length;
9023
+ }
9024
+ if (cb) {
9025
+ const err = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
9026
+ process.nextTick(cb, err);
9027
+ }
9028
+ }
9029
+ /**
9030
+ * The listener of the `Receiver` `'conclude'` event.
9031
+ *
9032
+ * @param {Number} code The status code
9033
+ * @param {Buffer} reason The reason for closing
9034
+ * @private
9035
+ */
9036
+ function receiverOnConclude(code, reason) {
9037
+ const websocket = this[kWebSocket];
9038
+ websocket._closeFrameReceived = true;
9039
+ websocket._closeMessage = reason;
9040
+ websocket._closeCode = code;
9041
+ if (websocket._socket[kWebSocket] === void 0) return;
9042
+ websocket._socket.removeListener("data", socketOnData);
9043
+ process.nextTick(resume, websocket._socket);
9044
+ if (code === 1005) websocket.close();
9045
+ else websocket.close(code, reason);
9046
+ }
9047
+ /**
9048
+ * The listener of the `Receiver` `'drain'` event.
9049
+ *
9050
+ * @private
9051
+ */
9052
+ function receiverOnDrain() {
9053
+ const websocket = this[kWebSocket];
9054
+ if (!websocket.isPaused) websocket._socket.resume();
9055
+ }
9056
+ /**
9057
+ * The listener of the `Receiver` `'error'` event.
9058
+ *
9059
+ * @param {(RangeError|Error)} err The emitted error
9060
+ * @private
9061
+ */
9062
+ function receiverOnError(err) {
9063
+ const websocket = this[kWebSocket];
9064
+ if (websocket._socket[kWebSocket] !== void 0) {
9065
+ websocket._socket.removeListener("data", socketOnData);
9066
+ process.nextTick(resume, websocket._socket);
9067
+ websocket.close(err[kStatusCode]);
9068
+ }
9069
+ if (!websocket._errorEmitted) {
9070
+ websocket._errorEmitted = true;
9071
+ websocket.emit("error", err);
9072
+ }
9073
+ }
9074
+ /**
9075
+ * The listener of the `Receiver` `'finish'` event.
9076
+ *
9077
+ * @private
9078
+ */
9079
+ function receiverOnFinish() {
9080
+ this[kWebSocket].emitClose();
9081
+ }
9082
+ /**
9083
+ * The listener of the `Receiver` `'message'` event.
9084
+ *
9085
+ * @param {Buffer|ArrayBuffer|Buffer[])} data The message
9086
+ * @param {Boolean} isBinary Specifies whether the message is binary or not
9087
+ * @private
9088
+ */
9089
+ function receiverOnMessage(data, isBinary) {
9090
+ this[kWebSocket].emit("message", data, isBinary);
9091
+ }
9092
+ /**
9093
+ * The listener of the `Receiver` `'ping'` event.
9094
+ *
9095
+ * @param {Buffer} data The data included in the ping frame
9096
+ * @private
9097
+ */
9098
+ function receiverOnPing(data) {
9099
+ const websocket = this[kWebSocket];
9100
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
9101
+ websocket.emit("ping", data);
9102
+ }
9103
+ /**
9104
+ * The listener of the `Receiver` `'pong'` event.
9105
+ *
9106
+ * @param {Buffer} data The data included in the pong frame
9107
+ * @private
9108
+ */
9109
+ function receiverOnPong(data) {
9110
+ this[kWebSocket].emit("pong", data);
9111
+ }
9112
+ /**
9113
+ * Resume a readable stream
9114
+ *
9115
+ * @param {Readable} stream The readable stream
9116
+ * @private
9117
+ */
9118
+ function resume(stream) {
9119
+ stream.resume();
9120
+ }
9121
+ /**
9122
+ * The `Sender` error event handler.
9123
+ *
9124
+ * @param {Error} The error
9125
+ * @private
9126
+ */
9127
+ function senderOnError(err) {
9128
+ const websocket = this[kWebSocket];
9129
+ if (websocket.readyState === WebSocket.CLOSED) return;
9130
+ if (websocket.readyState === WebSocket.OPEN) {
9131
+ websocket._readyState = WebSocket.CLOSING;
9132
+ setCloseTimer(websocket);
9133
+ }
9134
+ this._socket.end();
9135
+ if (!websocket._errorEmitted) {
9136
+ websocket._errorEmitted = true;
9137
+ websocket.emit("error", err);
9138
+ }
9139
+ }
9140
+ /**
9141
+ * Set a timer to destroy the underlying raw socket of a WebSocket.
9142
+ *
9143
+ * @param {WebSocket} websocket The WebSocket instance
9144
+ * @private
9145
+ */
9146
+ function setCloseTimer(websocket) {
9147
+ websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
9148
+ }
9149
+ /**
9150
+ * The listener of the socket `'close'` event.
9151
+ *
9152
+ * @private
9153
+ */
9154
+ function socketOnClose() {
9155
+ const websocket = this[kWebSocket];
9156
+ this.removeListener("close", socketOnClose);
9157
+ this.removeListener("data", socketOnData);
9158
+ this.removeListener("end", socketOnEnd);
9159
+ websocket._readyState = WebSocket.CLOSING;
9160
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
9161
+ const chunk = this.read(this._readableState.length);
9162
+ websocket._receiver.write(chunk);
9163
+ }
9164
+ websocket._receiver.end();
9165
+ this[kWebSocket] = void 0;
9166
+ clearTimeout(websocket._closeTimer);
9167
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
9168
+ else {
9169
+ websocket._receiver.on("error", receiverOnFinish);
9170
+ websocket._receiver.on("finish", receiverOnFinish);
9171
+ }
9172
+ }
9173
+ /**
9174
+ * The listener of the socket `'data'` event.
9175
+ *
9176
+ * @param {Buffer} chunk A chunk of data
9177
+ * @private
9178
+ */
9179
+ function socketOnData(chunk) {
9180
+ if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
9181
+ }
9182
+ /**
9183
+ * The listener of the socket `'end'` event.
9184
+ *
9185
+ * @private
9186
+ */
9187
+ function socketOnEnd() {
9188
+ const websocket = this[kWebSocket];
9189
+ websocket._readyState = WebSocket.CLOSING;
9190
+ websocket._receiver.end();
9191
+ this.end();
9192
+ }
9193
+ /**
9194
+ * The listener of the socket `'error'` event.
9195
+ *
9196
+ * @private
9197
+ */
9198
+ function socketOnError() {
9199
+ const websocket = this[kWebSocket];
9200
+ this.removeListener("error", socketOnError);
9201
+ this.on("error", NOOP);
9202
+ if (websocket) {
9203
+ websocket._readyState = WebSocket.CLOSING;
9204
+ this.destroy();
9205
+ }
9206
+ }
9207
+ }));
9208
+
9209
+ //#endregion
9210
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/stream.js
9211
+ var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
9212
+ require_websocket();
9213
+ const { Duplex: Duplex$1 } = __require("stream");
9214
+ /**
9215
+ * Emits the `'close'` event on a stream.
9216
+ *
9217
+ * @param {Duplex} stream The stream.
9218
+ * @private
9219
+ */
9220
+ function emitClose(stream) {
9221
+ stream.emit("close");
9222
+ }
9223
+ /**
9224
+ * The listener of the `'end'` event.
9225
+ *
9226
+ * @private
9227
+ */
9228
+ function duplexOnEnd() {
9229
+ if (!this.destroyed && this._writableState.finished) this.destroy();
9230
+ }
9231
+ /**
9232
+ * The listener of the `'error'` event.
9233
+ *
9234
+ * @param {Error} err The error
9235
+ * @private
9236
+ */
9237
+ function duplexOnError(err) {
9238
+ this.removeListener("error", duplexOnError);
9239
+ this.destroy();
9240
+ if (this.listenerCount("error") === 0) this.emit("error", err);
9241
+ }
9242
+ /**
9243
+ * Wraps a `WebSocket` in a duplex stream.
9244
+ *
9245
+ * @param {WebSocket} ws The `WebSocket` to wrap
9246
+ * @param {Object} [options] The options for the `Duplex` constructor
9247
+ * @return {Duplex} The duplex stream
9248
+ * @public
9249
+ */
9250
+ function createWebSocketStream(ws, options) {
9251
+ let terminateOnDestroy = true;
9252
+ const duplex = new Duplex$1({
9253
+ ...options,
9254
+ autoDestroy: false,
9255
+ emitClose: false,
9256
+ objectMode: false,
9257
+ writableObjectMode: false
9258
+ });
9259
+ ws.on("message", function message(msg, isBinary) {
9260
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
9261
+ if (!duplex.push(data)) ws.pause();
9262
+ });
9263
+ ws.once("error", function error(err) {
9264
+ if (duplex.destroyed) return;
9265
+ terminateOnDestroy = false;
9266
+ duplex.destroy(err);
9267
+ });
9268
+ ws.once("close", function close() {
9269
+ if (duplex.destroyed) return;
9270
+ duplex.push(null);
9271
+ });
9272
+ duplex._destroy = function(err, callback) {
9273
+ if (ws.readyState === ws.CLOSED) {
9274
+ callback(err);
9275
+ process.nextTick(emitClose, duplex);
9276
+ return;
9277
+ }
9278
+ let called = false;
9279
+ ws.once("error", function error(err) {
9280
+ called = true;
9281
+ callback(err);
9282
+ });
9283
+ ws.once("close", function close() {
9284
+ if (!called) callback(err);
9285
+ process.nextTick(emitClose, duplex);
9286
+ });
9287
+ if (terminateOnDestroy) ws.terminate();
9288
+ };
9289
+ duplex._final = function(callback) {
9290
+ if (ws.readyState === ws.CONNECTING) {
9291
+ ws.once("open", function open() {
9292
+ duplex._final(callback);
9293
+ });
9294
+ return;
9295
+ }
9296
+ if (ws._socket === null) return;
9297
+ if (ws._socket._writableState.finished) {
9298
+ callback();
9299
+ if (duplex._readableState.endEmitted) duplex.destroy();
9300
+ } else {
9301
+ ws._socket.once("finish", function finish() {
9302
+ callback();
9303
+ });
9304
+ ws.close();
9305
+ }
9306
+ };
9307
+ duplex._read = function() {
9308
+ if (ws.isPaused) ws.resume();
9309
+ };
9310
+ duplex._write = function(chunk, encoding, callback) {
9311
+ if (ws.readyState === ws.CONNECTING) {
9312
+ ws.once("open", function open() {
9313
+ duplex._write(chunk, encoding, callback);
9314
+ });
9315
+ return;
9316
+ }
9317
+ ws.send(chunk, callback);
9318
+ };
9319
+ duplex.on("end", duplexOnEnd);
9320
+ duplex.on("error", duplexOnError);
9321
+ return duplex;
9322
+ }
9323
+ module.exports = createWebSocketStream;
9324
+ }));
9325
+
9326
+ //#endregion
9327
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/subprotocol.js
9328
+ var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
9329
+ const { tokenChars } = require_validation();
9330
+ /**
9331
+ * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
9332
+ *
9333
+ * @param {String} header The field value of the header
9334
+ * @return {Set} The subprotocol names
9335
+ * @public
9336
+ */
9337
+ function parse(header) {
9338
+ const protocols = /* @__PURE__ */ new Set();
9339
+ let start = -1;
9340
+ let end = -1;
9341
+ let i = 0;
9342
+ for (; i < header.length; i++) {
9343
+ const code = header.charCodeAt(i);
9344
+ if (end === -1 && tokenChars[code] === 1) {
9345
+ if (start === -1) start = i;
9346
+ } else if (i !== 0 && (code === 32 || code === 9)) {
9347
+ if (end === -1 && start !== -1) end = i;
9348
+ } else if (code === 44) {
9349
+ if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
9350
+ if (end === -1) end = i;
9351
+ const protocol = header.slice(start, end);
9352
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
9353
+ protocols.add(protocol);
9354
+ start = end = -1;
9355
+ } else throw new SyntaxError(`Unexpected character at index ${i}`);
9356
+ }
9357
+ if (start === -1 || end !== -1) throw new SyntaxError("Unexpected end of input");
9358
+ const protocol = header.slice(start, i);
9359
+ if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
9360
+ protocols.add(protocol);
9361
+ return protocols;
9362
+ }
9363
+ module.exports = { parse };
9364
+ }));
9365
+
9366
+ //#endregion
9367
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/lib/websocket-server.js
9368
+ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
9369
+ const EventEmitter$1 = __require("events");
9370
+ const http = __require("http");
9371
+ const { Duplex } = __require("stream");
9372
+ const { createHash } = __require("crypto");
9373
+ const extension = require_extension();
9374
+ const PerMessageDeflate = require_permessage_deflate();
9375
+ const subprotocol = require_subprotocol();
9376
+ const WebSocket = require_websocket();
9377
+ const { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
9378
+ const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
9379
+ const RUNNING = 0;
9380
+ const CLOSING = 1;
9381
+ const CLOSED = 2;
9382
+ /**
9383
+ * Class representing a WebSocket server.
9384
+ *
9385
+ * @extends EventEmitter
9386
+ */
9387
+ var WebSocketServer = class extends EventEmitter$1 {
9388
+ /**
9389
+ * Create a `WebSocketServer` instance.
9390
+ *
9391
+ * @param {Object} options Configuration options
9392
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
9393
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
9394
+ * multiple times in the same tick
9395
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
9396
+ * automatically send a pong in response to a ping
9397
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
9398
+ * pending connections
9399
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
9400
+ * track clients
9401
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
9402
+ * wait for the closing handshake to finish after `websocket.close()` is
9403
+ * called
9404
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
9405
+ * @param {String} [options.host] The hostname where to bind the server
9406
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
9407
+ * size
9408
+ * @param {Boolean} [options.noServer=false] Enable no server mode
9409
+ * @param {String} [options.path] Accept only connections matching this path
9410
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
9411
+ * permessage-deflate
9412
+ * @param {Number} [options.port] The port where to bind the server
9413
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
9414
+ * server to use
9415
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
9416
+ * not to skip UTF-8 validation for text and close messages
9417
+ * @param {Function} [options.verifyClient] A hook to reject connections
9418
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
9419
+ * class to use. It must be the `WebSocket` class or class that extends it
9420
+ * @param {Function} [callback] A listener for the `listening` event
9421
+ */
9422
+ constructor(options, callback) {
9423
+ super();
9424
+ options = {
9425
+ allowSynchronousEvents: true,
9426
+ autoPong: true,
9427
+ maxPayload: 100 * 1024 * 1024,
9428
+ skipUTF8Validation: false,
9429
+ perMessageDeflate: false,
9430
+ handleProtocols: null,
9431
+ clientTracking: true,
9432
+ closeTimeout: CLOSE_TIMEOUT,
9433
+ verifyClient: null,
9434
+ noServer: false,
9435
+ backlog: null,
9436
+ server: null,
9437
+ host: null,
9438
+ path: null,
9439
+ port: null,
9440
+ WebSocket,
9441
+ ...options
9442
+ };
9443
+ 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");
9444
+ if (options.port != null) {
9445
+ this._server = http.createServer((req, res) => {
9446
+ const body = http.STATUS_CODES[426];
9447
+ res.writeHead(426, {
9448
+ "Content-Length": body.length,
9449
+ "Content-Type": "text/plain"
9450
+ });
9451
+ res.end(body);
9452
+ });
9453
+ this._server.listen(options.port, options.host, options.backlog, callback);
9454
+ } else if (options.server) this._server = options.server;
9455
+ if (this._server) {
9456
+ const emitConnection = this.emit.bind(this, "connection");
9457
+ this._removeListeners = addListeners(this._server, {
9458
+ listening: this.emit.bind(this, "listening"),
9459
+ error: this.emit.bind(this, "error"),
9460
+ upgrade: (req, socket, head) => {
9461
+ this.handleUpgrade(req, socket, head, emitConnection);
9462
+ }
9463
+ });
9464
+ }
9465
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
9466
+ if (options.clientTracking) {
9467
+ this.clients = /* @__PURE__ */ new Set();
9468
+ this._shouldEmitClose = false;
9469
+ }
9470
+ this.options = options;
9471
+ this._state = RUNNING;
9472
+ }
9473
+ /**
9474
+ * Returns the bound address, the address family name, and port of the server
9475
+ * as reported by the operating system if listening on an IP socket.
9476
+ * If the server is listening on a pipe or UNIX domain socket, the name is
9477
+ * returned as a string.
9478
+ *
9479
+ * @return {(Object|String|null)} The address of the server
9480
+ * @public
9481
+ */
9482
+ address() {
9483
+ if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
9484
+ if (!this._server) return null;
9485
+ return this._server.address();
9486
+ }
9487
+ /**
9488
+ * Stop the server from accepting new connections and emit the `'close'` event
9489
+ * when all existing connections are closed.
9490
+ *
9491
+ * @param {Function} [cb] A one-time listener for the `'close'` event
9492
+ * @public
9493
+ */
9494
+ close(cb) {
9495
+ if (this._state === CLOSED) {
9496
+ if (cb) this.once("close", () => {
9497
+ cb(/* @__PURE__ */ new Error("The server is not running"));
9498
+ });
9499
+ process.nextTick(emitClose, this);
9500
+ return;
9501
+ }
9502
+ if (cb) this.once("close", cb);
9503
+ if (this._state === CLOSING) return;
9504
+ this._state = CLOSING;
9505
+ if (this.options.noServer || this.options.server) {
9506
+ if (this._server) {
9507
+ this._removeListeners();
9508
+ this._removeListeners = this._server = null;
9509
+ }
9510
+ if (this.clients) if (!this.clients.size) process.nextTick(emitClose, this);
9511
+ else this._shouldEmitClose = true;
9512
+ else process.nextTick(emitClose, this);
9513
+ } else {
9514
+ const server = this._server;
9515
+ this._removeListeners();
9516
+ this._removeListeners = this._server = null;
9517
+ server.close(() => {
9518
+ emitClose(this);
9519
+ });
9520
+ }
9521
+ }
9522
+ /**
9523
+ * See if a given request should be handled by this server instance.
9524
+ *
9525
+ * @param {http.IncomingMessage} req Request object to inspect
9526
+ * @return {Boolean} `true` if the request is valid, else `false`
9527
+ * @public
9528
+ */
9529
+ shouldHandle(req) {
9530
+ if (this.options.path) {
9531
+ const index = req.url.indexOf("?");
9532
+ if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return false;
9533
+ }
9534
+ return true;
9535
+ }
9536
+ /**
9537
+ * Handle a HTTP Upgrade request.
9538
+ *
9539
+ * @param {http.IncomingMessage} req The request object
9540
+ * @param {Duplex} socket The network socket between the server and client
9541
+ * @param {Buffer} head The first packet of the upgraded stream
9542
+ * @param {Function} cb Callback
9543
+ * @public
9544
+ */
9545
+ handleUpgrade(req, socket, head, cb) {
9546
+ socket.on("error", socketOnError);
9547
+ const key = req.headers["sec-websocket-key"];
9548
+ const upgrade = req.headers.upgrade;
9549
+ const version = +req.headers["sec-websocket-version"];
9550
+ if (req.method !== "GET") {
9551
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
9552
+ return;
9553
+ }
9554
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
9555
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
9556
+ return;
9557
+ }
9558
+ if (key === void 0 || !keyRegex.test(key)) {
9559
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
9560
+ return;
9561
+ }
9562
+ if (version !== 13 && version !== 8) {
9563
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
9564
+ return;
9565
+ }
9566
+ if (!this.shouldHandle(req)) {
9567
+ abortHandshake(socket, 400);
9568
+ return;
9569
+ }
9570
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
9571
+ let protocols = /* @__PURE__ */ new Set();
9572
+ if (secWebSocketProtocol !== void 0) try {
9573
+ protocols = subprotocol.parse(secWebSocketProtocol);
9574
+ } catch (err) {
9575
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
9576
+ return;
9577
+ }
9578
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
9579
+ const extensions = {};
9580
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
9581
+ const perMessageDeflate = new PerMessageDeflate(this.options.perMessageDeflate, true, this.options.maxPayload);
9582
+ try {
9583
+ const offers = extension.parse(secWebSocketExtensions);
9584
+ if (offers[PerMessageDeflate.extensionName]) {
9585
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
9586
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
9587
+ }
9588
+ } catch (err) {
9589
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
9590
+ return;
9591
+ }
9592
+ }
9593
+ if (this.options.verifyClient) {
9594
+ const info = {
9595
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
9596
+ secure: !!(req.socket.authorized || req.socket.encrypted),
9597
+ req
9598
+ };
9599
+ if (this.options.verifyClient.length === 2) {
9600
+ this.options.verifyClient(info, (verified, code, message, headers) => {
9601
+ if (!verified) return abortHandshake(socket, code || 401, message, headers);
9602
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
9603
+ });
9604
+ return;
9605
+ }
9606
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
9607
+ }
9608
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
9609
+ }
9610
+ /**
9611
+ * Upgrade the connection to WebSocket.
9612
+ *
9613
+ * @param {Object} extensions The accepted extensions
9614
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
9615
+ * @param {Set} protocols The subprotocols
9616
+ * @param {http.IncomingMessage} req The request object
9617
+ * @param {Duplex} socket The network socket between the server and client
9618
+ * @param {Buffer} head The first packet of the upgraded stream
9619
+ * @param {Function} cb Callback
9620
+ * @throws {Error} If called more than once with the same socket
9621
+ * @private
9622
+ */
9623
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
9624
+ if (!socket.readable || !socket.writable) return socket.destroy();
9625
+ if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
9626
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
9627
+ const headers = [
9628
+ "HTTP/1.1 101 Switching Protocols",
9629
+ "Upgrade: websocket",
9630
+ "Connection: Upgrade",
9631
+ `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
9632
+ ];
9633
+ const ws = new this.options.WebSocket(null, void 0, this.options);
9634
+ if (protocols.size) {
9635
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
9636
+ if (protocol) {
9637
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
9638
+ ws._protocol = protocol;
9639
+ }
9640
+ }
9641
+ if (extensions[PerMessageDeflate.extensionName]) {
9642
+ const params = extensions[PerMessageDeflate.extensionName].params;
9643
+ const value = extension.format({ [PerMessageDeflate.extensionName]: [params] });
9644
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
9645
+ ws._extensions = extensions;
9646
+ }
9647
+ this.emit("headers", headers, req);
9648
+ socket.write(headers.concat("\r\n").join("\r\n"));
9649
+ socket.removeListener("error", socketOnError);
9650
+ ws.setSocket(socket, head, {
9651
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
9652
+ maxPayload: this.options.maxPayload,
9653
+ skipUTF8Validation: this.options.skipUTF8Validation
9654
+ });
9655
+ if (this.clients) {
9656
+ this.clients.add(ws);
9657
+ ws.on("close", () => {
9658
+ this.clients.delete(ws);
9659
+ if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
9660
+ });
9661
+ }
9662
+ cb(ws, req);
9663
+ }
9664
+ };
9665
+ module.exports = WebSocketServer;
9666
+ /**
9667
+ * Add event listeners on an `EventEmitter` using a map of <event, listener>
9668
+ * pairs.
9669
+ *
9670
+ * @param {EventEmitter} server The event emitter
9671
+ * @param {Object.<String, Function>} map The listeners to add
9672
+ * @return {Function} A function that will remove the added listeners when
9673
+ * called
9674
+ * @private
9675
+ */
9676
+ function addListeners(server, map) {
9677
+ for (const event of Object.keys(map)) server.on(event, map[event]);
9678
+ return function removeListeners() {
9679
+ for (const event of Object.keys(map)) server.removeListener(event, map[event]);
9680
+ };
9681
+ }
9682
+ /**
9683
+ * Emit a `'close'` event on an `EventEmitter`.
9684
+ *
9685
+ * @param {EventEmitter} server The event emitter
9686
+ * @private
9687
+ */
9688
+ function emitClose(server) {
9689
+ server._state = CLOSED;
9690
+ server.emit("close");
9691
+ }
9692
+ /**
9693
+ * Handle socket errors.
9694
+ *
9695
+ * @private
9696
+ */
9697
+ function socketOnError() {
9698
+ this.destroy();
9699
+ }
9700
+ /**
9701
+ * Close the connection when preconditions are not fulfilled.
9702
+ *
9703
+ * @param {Duplex} socket The socket of the upgrade request
9704
+ * @param {Number} code The HTTP response status code
9705
+ * @param {String} [message] The HTTP response body
9706
+ * @param {Object} [headers] Additional HTTP response headers
9707
+ * @private
9708
+ */
9709
+ function abortHandshake(socket, code, message, headers) {
9710
+ message = message || http.STATUS_CODES[code];
9711
+ headers = {
9712
+ Connection: "close",
9713
+ "Content-Type": "text/html",
9714
+ "Content-Length": Buffer.byteLength(message),
9715
+ ...headers
9716
+ };
9717
+ socket.once("finish", socket.destroy);
9718
+ 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);
9719
+ }
9720
+ /**
9721
+ * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
9722
+ * one listener for it, otherwise call `abortHandshake()`.
9723
+ *
9724
+ * @param {WebSocketServer} server The WebSocket server
9725
+ * @param {http.IncomingMessage} req The request object
9726
+ * @param {Duplex} socket The socket of the upgrade request
9727
+ * @param {Number} code The HTTP response status code
9728
+ * @param {String} message The HTTP response body
9729
+ * @param {Object} [headers] The HTTP response headers
9730
+ * @private
9731
+ */
9732
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
9733
+ if (server.listenerCount("wsClientError")) {
9734
+ const err = new Error(message);
9735
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
9736
+ server.emit("wsClientError", err, socket, req);
9737
+ } else abortHandshake(socket, code, message, headers);
9738
+ }
9739
+ }));
9740
+
9741
+ //#endregion
9742
+ //#region node_modules/.pnpm/ws@8.19.0/node_modules/ws/wrapper.mjs
9743
+ var import_stream = /* @__PURE__ */ __toESM(require_stream(), 1);
9744
+ var import_receiver = /* @__PURE__ */ __toESM(require_receiver(), 1);
9745
+ var import_sender = /* @__PURE__ */ __toESM(require_sender(), 1);
9746
+ var import_websocket = /* @__PURE__ */ __toESM(require_websocket(), 1);
9747
+ var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
9748
+
9749
+ //#endregion
9750
+ //#region src/proxy/websocket-proxy.ts
9751
+ /**
9752
+ * WebSocket-to-TCP Proxy for Cap'n Proto
9753
+ *
9754
+ * Allows browsers to connect to native Cap'n Proto services (C++, etc.)
9755
+ * via WebSocket. Handles the protocol bridging between WebSocket (browser)
9756
+ * and raw TCP (Cap'n Proto services).
9757
+ */
9758
+ var ProxyConnection = class extends EventEmitter {
9759
+ ws;
9760
+ tcpSocket = null;
9761
+ stats;
9762
+ options;
9763
+ closed = false;
9764
+ constructor(ws, options) {
9765
+ super();
9766
+ this.ws = ws;
9767
+ this.options = options;
9768
+ this.stats = {
9769
+ wsMessagesIn: 0,
9770
+ wsMessagesOut: 0,
9771
+ tcpBytesIn: 0,
9772
+ tcpBytesOut: 0,
9773
+ connectedAt: /* @__PURE__ */ new Date()
9774
+ };
9775
+ this.setupWebSocket();
9776
+ }
9777
+ setupWebSocket() {
9778
+ this.ws.on("message", (data) => {
9779
+ this.handleWebSocketMessage(data);
9780
+ });
9781
+ this.ws.on("close", () => {
9782
+ this.log("WebSocket closed");
9783
+ this.close();
9784
+ });
9785
+ this.ws.on("error", (err) => {
9786
+ this.log("WebSocket error:", err);
9787
+ this.emit("error", err);
9788
+ this.close();
9789
+ });
9790
+ this.connectToTarget();
9791
+ }
9792
+ connectToTarget() {
9793
+ const timeout = this.options.connectionTimeout ?? 3e4;
9794
+ this.tcpSocket = createConnection({
9795
+ host: this.options.targetHost,
9796
+ port: this.options.targetPort,
9797
+ timeout
9798
+ });
9799
+ this.tcpSocket.on("connect", () => {
9800
+ this.log("Connected to target TCP service");
9801
+ this.emit("connected");
9802
+ });
9803
+ this.tcpSocket.on("data", (data) => {
9804
+ this.handleTcpData(data);
9805
+ });
9806
+ this.tcpSocket.on("close", () => {
9807
+ this.log("TCP connection closed");
9808
+ this.close();
9809
+ });
9810
+ this.tcpSocket.on("error", (err) => {
9811
+ this.log("TCP error:", err);
9812
+ this.emit("error", err);
9813
+ this.close();
9814
+ });
9815
+ this.tcpSocket.on("timeout", () => {
9816
+ this.log("TCP connection timeout");
9817
+ this.close();
9818
+ });
9819
+ }
9820
+ handleWebSocketMessage(data) {
9821
+ if (this.closed) return;
9822
+ const buffer = Buffer.isBuffer(data) ? data : Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
9823
+ const maxSize = this.options.maxMessageSize ?? 16 * 1024 * 1024;
9824
+ if (buffer.length > maxSize) {
9825
+ this.log(`Message too large: ${buffer.length} bytes`);
9826
+ this.close();
9827
+ return;
9828
+ }
9829
+ this.stats.wsMessagesIn++;
9830
+ this.stats.tcpBytesOut += buffer.length;
9831
+ if (this.tcpSocket?.writable) {
9832
+ this.tcpSocket.write(buffer);
9833
+ this.log(`Forwarded ${buffer.length} bytes to TCP`);
9834
+ }
9835
+ }
9836
+ handleTcpData(data) {
9837
+ if (this.closed) return;
9838
+ this.stats.tcpBytesIn += data.length;
9839
+ this.stats.wsMessagesOut++;
9840
+ if (this.ws.readyState === import_websocket.default.OPEN) {
9841
+ this.ws.send(data);
9842
+ this.log(`Forwarded ${data.length} bytes to WebSocket`);
9843
+ }
9844
+ }
9845
+ log(...args) {
9846
+ if (this.options.debug) console.log("[ProxyConnection]", ...args);
9847
+ }
9848
+ getStats() {
9849
+ return { ...this.stats };
9850
+ }
9851
+ close() {
9852
+ if (this.closed) return;
9853
+ this.closed = true;
9854
+ this.ws.close();
9855
+ this.tcpSocket?.destroy();
9856
+ this.emit("closed");
9857
+ }
9858
+ };
9859
+ var CapnpWebSocketProxy = class extends EventEmitter {
9860
+ wss;
9861
+ connections = /* @__PURE__ */ new Map();
9862
+ options;
9863
+ constructor(options) {
9864
+ super();
9865
+ this.options = options;
9866
+ this.wss = new import_websocket_server.default({ port: options.wsPort });
9867
+ this.setupServer();
9868
+ }
9869
+ setupServer() {
9870
+ this.wss.on("connection", (ws, req) => {
9871
+ const clientIp = req.socket.remoteAddress;
9872
+ this.log(`New WebSocket connection from ${clientIp}`);
9873
+ const connection = new ProxyConnection(ws, this.options);
9874
+ this.connections.set(ws, connection);
9875
+ connection.on("connected", () => {
9876
+ this.emit("connection", connection);
9877
+ });
9878
+ connection.on("error", (err) => {
9879
+ this.emit("error", err, connection);
9880
+ });
9881
+ connection.on("closed", () => {
9882
+ this.connections.delete(ws);
9883
+ this.emit("disconnection", connection);
9884
+ });
9885
+ });
9886
+ this.wss.on("error", (err) => {
9887
+ this.emit("error", err);
9888
+ });
9889
+ }
9890
+ log(...args) {
9891
+ if (this.options.debug) console.log("[CapnpWebSocketProxy]", ...args);
9892
+ }
9893
+ getConnectionCount() {
9894
+ return this.connections.size;
9895
+ }
9896
+ getAllStats() {
9897
+ return Array.from(this.connections.values()).map((c) => c.getStats());
9898
+ }
9899
+ close() {
9900
+ return new Promise((resolve) => {
9901
+ for (const connection of this.connections.values()) connection.close();
9902
+ this.connections.clear();
9903
+ this.wss.close(() => {
9904
+ this.emit("closed");
9905
+ resolve();
9906
+ });
9907
+ });
9908
+ }
9909
+ };
9910
+ if (import.meta.url === `file://${process.argv[1]}`) {
9911
+ const args = process.argv.slice(2);
9912
+ let wsPort = 8080;
9913
+ let targetHost = "localhost";
9914
+ let targetPort = 8081;
9915
+ let debug = false;
9916
+ for (let i = 0; i < args.length; i++) switch (args[i]) {
9917
+ case "--ws-port":
9918
+ case "-p":
9919
+ wsPort = Number.parseInt(args[++i], 10);
9920
+ break;
9921
+ case "--target":
9922
+ case "-t": {
9923
+ const [host, port] = args[++i].split(":");
9924
+ targetHost = host;
9925
+ targetPort = Number.parseInt(port, 10);
9926
+ break;
9927
+ }
9928
+ case "--debug":
9929
+ case "-d":
9930
+ debug = true;
9931
+ break;
9932
+ case "--help":
9933
+ case "-h":
9934
+ console.log(`
9935
+ Cap'n Proto WebSocket-to-TCP Proxy
9936
+
9937
+ Usage: npx @naeemo/capnp proxy [options]
9938
+
9939
+ Options:
9940
+ -p, --ws-port <port> WebSocket server port (default: 8080)
9941
+ -t, --target <host:port> Target TCP service (default: localhost:8081)
9942
+ -d, --debug Enable debug logging
9943
+ -h, --help Show this help
9944
+
9945
+ Example:
9946
+ npx @naeemo/capnp proxy -p 9000 -t 192.168.1.100:7000
9947
+ `);
9948
+ process.exit(0);
9949
+ }
9950
+ const proxy = new CapnpWebSocketProxy({
9951
+ wsPort,
9952
+ targetHost,
9953
+ targetPort,
9954
+ debug
9955
+ });
9956
+ console.log("WebSocket-to-TCP Proxy started");
9957
+ console.log(` WebSocket: ws://localhost:${wsPort}`);
9958
+ console.log(` Target: ${targetHost}:${targetPort}`);
9959
+ proxy.on("connection", () => {
9960
+ console.log(`Active connections: ${proxy.getConnectionCount()}`);
9961
+ });
9962
+ proxy.on("disconnection", () => {
9963
+ console.log(`Active connections: ${proxy.getConnectionCount()}`);
9964
+ });
9965
+ process.on("SIGINT", async () => {
9966
+ console.log("\nShutting down...");
9967
+ await proxy.close();
9968
+ process.exit(0);
9969
+ });
9970
+ }
9971
+
9972
+ //#endregion
9973
+ export { AnswerTable, BaseCapabilityClient, BulkTransfer, BulkTransferManager, CapnpWebSocketProxy, ConnectionManager, DEFAULT_BULK_CONFIG, DEFAULT_ESCROW_CONFIG, DEFAULT_FLOW_CONTROL, DEFAULT_JOIN_OPTIONS, DEFAULT_JOIN_SECURITY_POLICY, DEFAULT_REALTIME_CONFIG, DEFAULT_STREAMING_CAPABILITIES, DropPolicy, ElementSize, ExportTable, EzRpcTransport, ImportTable, Level3Handlers, Level4Handlers, ListBuilder, ListReader, MemoryPool, MessageBuilder, MessageReader, MultiSegmentMessageBuilder, OptimizedRpcMessageBuilder, PIPELINE_CLIENT_SYMBOL, PipelineOpTracker, PipelineResolutionTracker, PointerTag, QuestionTable, QueuedCallManager, RealtimeStream, RealtimeStreamManager, RestoreHandler, RpcConnection, SCHEMA_MESSAGE_TYPES, SchemaCapabilityClient, SchemaCapabilityServer, SchemaFormat, Segment, Stream, StreamManager, StreamPriority, StreamType, StreamingRpcConnection, StructBuilder, StructReader, SturdyRefManager, TcpTransport, UnionBuilder, UnionReader, WORD_SIZE, WebSocketTransport, configureGlobalMemoryPool, createBulkTransferManager, createDynamicReader, createDynamicReaderByTypeId, createDynamicReaderFromStruct, createDynamicWriter, createDynamicWriterByTypeId, createNestedDynamicWriter, createPipelineClient, createProvisionId, createRealtimeStreamManager, createRecipientId, createSchemaRegistry, createStream, createStreamManager, createStreamingConnection, createSturdyRef, createThirdPartyCapId, createUnionBuilder, createUnionReader, createZeroCopyView, decodePointer, deserializeRpcMessage, deserializeSchemaRequest, deserializeSchemaResponse, deserializeSturdyRef, dumpDynamicReader, encodeListPointer, encodeStructPointer, fastCopy, generateProvisionId, generateVatId, getGlobalMemoryPool, isPipelineClient, isSameBuffer, isStream, isSturdyRefValid, parseSchemaNodes, serializeDynamic, serializeDynamicByTypeId, serializeGetSchemaParams, serializeGetSchemaResults, serializeListSchemasResults, serializeRpcMessage, serializeSchemaRequest, serializeSchemaResponse, serializeSturdyRef, supportsStreaming };
6196
9974
  //# sourceMappingURL=index.js.map