@docyrus/docyrus 0.0.53 → 0.0.55

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/server-loader.js CHANGED
@@ -5024,12 +5024,12 @@ function combineExtensions(extensions) {
5024
5024
  }
5025
5025
  return all2;
5026
5026
  }
5027
- function syntaxExtension(all2, extension2) {
5027
+ function syntaxExtension(all2, extension3) {
5028
5028
  let hook;
5029
- for (hook in extension2) {
5029
+ for (hook in extension3) {
5030
5030
  const maybe = hasOwnProperty.call(all2, hook) ? all2[hook] : void 0;
5031
5031
  const left = maybe || (all2[hook] = {});
5032
- const right = extension2[hook];
5032
+ const right = extension3[hook];
5033
5033
  let code;
5034
5034
  if (right) {
5035
5035
  for (code in right) {
@@ -10057,20 +10057,20 @@ function configure(combined, extensions) {
10057
10057
  }
10058
10058
  }
10059
10059
  }
10060
- function extension(combined, extension2) {
10060
+ function extension(combined, extension3) {
10061
10061
  let key;
10062
- for (key in extension2) {
10063
- if (own3.call(extension2, key)) {
10062
+ for (key in extension3) {
10063
+ if (own3.call(extension3, key)) {
10064
10064
  switch (key) {
10065
10065
  case "canContainEols": {
10066
- const right = extension2[key];
10066
+ const right = extension3[key];
10067
10067
  if (right) {
10068
10068
  combined[key].push(...right);
10069
10069
  }
10070
10070
  break;
10071
10071
  }
10072
10072
  case "transforms": {
10073
- const right = extension2[key];
10073
+ const right = extension3[key];
10074
10074
  if (right) {
10075
10075
  combined[key].push(...right);
10076
10076
  }
@@ -10078,7 +10078,7 @@ function extension(combined, extension2) {
10078
10078
  }
10079
10079
  case "enter":
10080
10080
  case "exit": {
10081
- const right = extension2[key];
10081
+ const right = extension3[key];
10082
10082
  if (right) {
10083
10083
  Object.assign(combined[key], right);
10084
10084
  }
@@ -12032,8 +12032,8 @@ async function listKnowledgeFiles(knowledgeDir) {
12032
12032
  function countByExt(paths) {
12033
12033
  const stats = {};
12034
12034
  for (const pathValue of paths) {
12035
- const extension2 = (0, import_node_path7.extname)(pathValue) || "(no ext)";
12036
- stats[extension2] = (stats[extension2] || 0) + 1;
12035
+ const extension3 = (0, import_node_path7.extname)(pathValue) || "(no ext)";
12036
+ stats[extension3] = (stats[extension3] || 0) + 1;
12037
12037
  }
12038
12038
  return stats;
12039
12039
  }
@@ -14368,6 +14368,3622 @@ var init_graph2 = __esm({
14368
14368
  }
14369
14369
  });
14370
14370
 
14371
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js
14372
+ var require_constants = __commonJS({
14373
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js"(exports2, module2) {
14374
+ "use strict";
14375
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
14376
+ var hasBlob = typeof Blob !== "undefined";
14377
+ if (hasBlob) BINARY_TYPES.push("blob");
14378
+ module2.exports = {
14379
+ BINARY_TYPES,
14380
+ CLOSE_TIMEOUT: 3e4,
14381
+ EMPTY_BUFFER: Buffer.alloc(0),
14382
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
14383
+ hasBlob,
14384
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
14385
+ kListener: /* @__PURE__ */ Symbol("kListener"),
14386
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
14387
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
14388
+ NOOP: () => {
14389
+ }
14390
+ };
14391
+ }
14392
+ });
14393
+
14394
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js
14395
+ var require_buffer_util = __commonJS({
14396
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js"(exports2, module2) {
14397
+ "use strict";
14398
+ var { EMPTY_BUFFER } = require_constants();
14399
+ var FastBuffer = Buffer[Symbol.species];
14400
+ function concat(list2, totalLength) {
14401
+ if (list2.length === 0) return EMPTY_BUFFER;
14402
+ if (list2.length === 1) return list2[0];
14403
+ const target = Buffer.allocUnsafe(totalLength);
14404
+ let offset = 0;
14405
+ for (let i2 = 0; i2 < list2.length; i2++) {
14406
+ const buf = list2[i2];
14407
+ target.set(buf, offset);
14408
+ offset += buf.length;
14409
+ }
14410
+ if (offset < totalLength) {
14411
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
14412
+ }
14413
+ return target;
14414
+ }
14415
+ function _mask(source, mask, output, offset, length) {
14416
+ for (let i2 = 0; i2 < length; i2++) {
14417
+ output[offset + i2] = source[i2] ^ mask[i2 & 3];
14418
+ }
14419
+ }
14420
+ function _unmask(buffer, mask) {
14421
+ for (let i2 = 0; i2 < buffer.length; i2++) {
14422
+ buffer[i2] ^= mask[i2 & 3];
14423
+ }
14424
+ }
14425
+ function toArrayBuffer(buf) {
14426
+ if (buf.length === buf.buffer.byteLength) {
14427
+ return buf.buffer;
14428
+ }
14429
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
14430
+ }
14431
+ function toBuffer(data) {
14432
+ toBuffer.readOnly = true;
14433
+ if (Buffer.isBuffer(data)) return data;
14434
+ let buf;
14435
+ if (data instanceof ArrayBuffer) {
14436
+ buf = new FastBuffer(data);
14437
+ } else if (ArrayBuffer.isView(data)) {
14438
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
14439
+ } else {
14440
+ buf = Buffer.from(data);
14441
+ toBuffer.readOnly = false;
14442
+ }
14443
+ return buf;
14444
+ }
14445
+ module2.exports = {
14446
+ concat,
14447
+ mask: _mask,
14448
+ toArrayBuffer,
14449
+ toBuffer,
14450
+ unmask: _unmask
14451
+ };
14452
+ if (!process.env.WS_NO_BUFFER_UTIL) {
14453
+ try {
14454
+ const bufferUtil = require("bufferutil");
14455
+ module2.exports.mask = function(source, mask, output, offset, length) {
14456
+ if (length < 48) _mask(source, mask, output, offset, length);
14457
+ else bufferUtil.mask(source, mask, output, offset, length);
14458
+ };
14459
+ module2.exports.unmask = function(buffer, mask) {
14460
+ if (buffer.length < 32) _unmask(buffer, mask);
14461
+ else bufferUtil.unmask(buffer, mask);
14462
+ };
14463
+ } catch (e) {
14464
+ }
14465
+ }
14466
+ }
14467
+ });
14468
+
14469
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js
14470
+ var require_limiter = __commonJS({
14471
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js"(exports2, module2) {
14472
+ "use strict";
14473
+ var kDone = /* @__PURE__ */ Symbol("kDone");
14474
+ var kRun = /* @__PURE__ */ Symbol("kRun");
14475
+ var Limiter = class {
14476
+ /**
14477
+ * Creates a new `Limiter`.
14478
+ *
14479
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
14480
+ * to run concurrently
14481
+ */
14482
+ constructor(concurrency) {
14483
+ this[kDone] = () => {
14484
+ this.pending--;
14485
+ this[kRun]();
14486
+ };
14487
+ this.concurrency = concurrency || Infinity;
14488
+ this.jobs = [];
14489
+ this.pending = 0;
14490
+ }
14491
+ /**
14492
+ * Adds a job to the queue.
14493
+ *
14494
+ * @param {Function} job The job to run
14495
+ * @public
14496
+ */
14497
+ add(job) {
14498
+ this.jobs.push(job);
14499
+ this[kRun]();
14500
+ }
14501
+ /**
14502
+ * Removes a job from the queue and runs it if possible.
14503
+ *
14504
+ * @private
14505
+ */
14506
+ [kRun]() {
14507
+ if (this.pending === this.concurrency) return;
14508
+ if (this.jobs.length) {
14509
+ const job = this.jobs.shift();
14510
+ this.pending++;
14511
+ job(this[kDone]);
14512
+ }
14513
+ }
14514
+ };
14515
+ module2.exports = Limiter;
14516
+ }
14517
+ });
14518
+
14519
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js
14520
+ var require_permessage_deflate = __commonJS({
14521
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
14522
+ "use strict";
14523
+ var zlib = require("zlib");
14524
+ var bufferUtil = require_buffer_util();
14525
+ var Limiter = require_limiter();
14526
+ var { kStatusCode } = require_constants();
14527
+ var FastBuffer = Buffer[Symbol.species];
14528
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
14529
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
14530
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
14531
+ var kCallback = /* @__PURE__ */ Symbol("callback");
14532
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
14533
+ var kError = /* @__PURE__ */ Symbol("error");
14534
+ var zlibLimiter;
14535
+ var PerMessageDeflate2 = class {
14536
+ /**
14537
+ * Creates a PerMessageDeflate instance.
14538
+ *
14539
+ * @param {Object} [options] Configuration options
14540
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
14541
+ * for, or request, a custom client window size
14542
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
14543
+ * acknowledge disabling of client context takeover
14544
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
14545
+ * calls to zlib
14546
+ * @param {Boolean} [options.isServer=false] Create the instance in either
14547
+ * server or client mode
14548
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
14549
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
14550
+ * use of a custom server window size
14551
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
14552
+ * disabling of server context takeover
14553
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
14554
+ * messages should not be compressed if context takeover is disabled
14555
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
14556
+ * deflate
14557
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
14558
+ * inflate
14559
+ */
14560
+ constructor(options) {
14561
+ this._options = options || {};
14562
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
14563
+ this._maxPayload = this._options.maxPayload | 0;
14564
+ this._isServer = !!this._options.isServer;
14565
+ this._deflate = null;
14566
+ this._inflate = null;
14567
+ this.params = null;
14568
+ if (!zlibLimiter) {
14569
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
14570
+ zlibLimiter = new Limiter(concurrency);
14571
+ }
14572
+ }
14573
+ /**
14574
+ * @type {String}
14575
+ */
14576
+ static get extensionName() {
14577
+ return "permessage-deflate";
14578
+ }
14579
+ /**
14580
+ * Create an extension negotiation offer.
14581
+ *
14582
+ * @return {Object} Extension parameters
14583
+ * @public
14584
+ */
14585
+ offer() {
14586
+ const params = {};
14587
+ if (this._options.serverNoContextTakeover) {
14588
+ params.server_no_context_takeover = true;
14589
+ }
14590
+ if (this._options.clientNoContextTakeover) {
14591
+ params.client_no_context_takeover = true;
14592
+ }
14593
+ if (this._options.serverMaxWindowBits) {
14594
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
14595
+ }
14596
+ if (this._options.clientMaxWindowBits) {
14597
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
14598
+ } else if (this._options.clientMaxWindowBits == null) {
14599
+ params.client_max_window_bits = true;
14600
+ }
14601
+ return params;
14602
+ }
14603
+ /**
14604
+ * Accept an extension negotiation offer/response.
14605
+ *
14606
+ * @param {Array} configurations The extension negotiation offers/reponse
14607
+ * @return {Object} Accepted configuration
14608
+ * @public
14609
+ */
14610
+ accept(configurations) {
14611
+ configurations = this.normalizeParams(configurations);
14612
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
14613
+ return this.params;
14614
+ }
14615
+ /**
14616
+ * Releases all resources used by the extension.
14617
+ *
14618
+ * @public
14619
+ */
14620
+ cleanup() {
14621
+ if (this._inflate) {
14622
+ this._inflate.close();
14623
+ this._inflate = null;
14624
+ }
14625
+ if (this._deflate) {
14626
+ const callback = this._deflate[kCallback];
14627
+ this._deflate.close();
14628
+ this._deflate = null;
14629
+ if (callback) {
14630
+ callback(
14631
+ new Error(
14632
+ "The deflate stream was closed while data was being processed"
14633
+ )
14634
+ );
14635
+ }
14636
+ }
14637
+ }
14638
+ /**
14639
+ * Accept an extension negotiation offer.
14640
+ *
14641
+ * @param {Array} offers The extension negotiation offers
14642
+ * @return {Object} Accepted configuration
14643
+ * @private
14644
+ */
14645
+ acceptAsServer(offers) {
14646
+ const opts = this._options;
14647
+ const accepted = offers.find((params) => {
14648
+ 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) {
14649
+ return false;
14650
+ }
14651
+ return true;
14652
+ });
14653
+ if (!accepted) {
14654
+ throw new Error("None of the extension offers can be accepted");
14655
+ }
14656
+ if (opts.serverNoContextTakeover) {
14657
+ accepted.server_no_context_takeover = true;
14658
+ }
14659
+ if (opts.clientNoContextTakeover) {
14660
+ accepted.client_no_context_takeover = true;
14661
+ }
14662
+ if (typeof opts.serverMaxWindowBits === "number") {
14663
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
14664
+ }
14665
+ if (typeof opts.clientMaxWindowBits === "number") {
14666
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
14667
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
14668
+ delete accepted.client_max_window_bits;
14669
+ }
14670
+ return accepted;
14671
+ }
14672
+ /**
14673
+ * Accept the extension negotiation response.
14674
+ *
14675
+ * @param {Array} response The extension negotiation response
14676
+ * @return {Object} Accepted configuration
14677
+ * @private
14678
+ */
14679
+ acceptAsClient(response) {
14680
+ const params = response[0];
14681
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
14682
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
14683
+ }
14684
+ if (!params.client_max_window_bits) {
14685
+ if (typeof this._options.clientMaxWindowBits === "number") {
14686
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
14687
+ }
14688
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
14689
+ throw new Error(
14690
+ 'Unexpected or invalid parameter "client_max_window_bits"'
14691
+ );
14692
+ }
14693
+ return params;
14694
+ }
14695
+ /**
14696
+ * Normalize parameters.
14697
+ *
14698
+ * @param {Array} configurations The extension negotiation offers/reponse
14699
+ * @return {Array} The offers/response with normalized parameters
14700
+ * @private
14701
+ */
14702
+ normalizeParams(configurations) {
14703
+ configurations.forEach((params) => {
14704
+ Object.keys(params).forEach((key) => {
14705
+ let value2 = params[key];
14706
+ if (value2.length > 1) {
14707
+ throw new Error(`Parameter "${key}" must have only a single value`);
14708
+ }
14709
+ value2 = value2[0];
14710
+ if (key === "client_max_window_bits") {
14711
+ if (value2 !== true) {
14712
+ const num = +value2;
14713
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
14714
+ throw new TypeError(
14715
+ `Invalid value for parameter "${key}": ${value2}`
14716
+ );
14717
+ }
14718
+ value2 = num;
14719
+ } else if (!this._isServer) {
14720
+ throw new TypeError(
14721
+ `Invalid value for parameter "${key}": ${value2}`
14722
+ );
14723
+ }
14724
+ } else if (key === "server_max_window_bits") {
14725
+ const num = +value2;
14726
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
14727
+ throw new TypeError(
14728
+ `Invalid value for parameter "${key}": ${value2}`
14729
+ );
14730
+ }
14731
+ value2 = num;
14732
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
14733
+ if (value2 !== true) {
14734
+ throw new TypeError(
14735
+ `Invalid value for parameter "${key}": ${value2}`
14736
+ );
14737
+ }
14738
+ } else {
14739
+ throw new Error(`Unknown parameter "${key}"`);
14740
+ }
14741
+ params[key] = value2;
14742
+ });
14743
+ });
14744
+ return configurations;
14745
+ }
14746
+ /**
14747
+ * Decompress data. Concurrency limited.
14748
+ *
14749
+ * @param {Buffer} data Compressed data
14750
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
14751
+ * @param {Function} callback Callback
14752
+ * @public
14753
+ */
14754
+ decompress(data, fin, callback) {
14755
+ zlibLimiter.add((done) => {
14756
+ this._decompress(data, fin, (err2, result) => {
14757
+ done();
14758
+ callback(err2, result);
14759
+ });
14760
+ });
14761
+ }
14762
+ /**
14763
+ * Compress data. Concurrency limited.
14764
+ *
14765
+ * @param {(Buffer|String)} data Data to compress
14766
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
14767
+ * @param {Function} callback Callback
14768
+ * @public
14769
+ */
14770
+ compress(data, fin, callback) {
14771
+ zlibLimiter.add((done) => {
14772
+ this._compress(data, fin, (err2, result) => {
14773
+ done();
14774
+ callback(err2, result);
14775
+ });
14776
+ });
14777
+ }
14778
+ /**
14779
+ * Decompress data.
14780
+ *
14781
+ * @param {Buffer} data Compressed data
14782
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
14783
+ * @param {Function} callback Callback
14784
+ * @private
14785
+ */
14786
+ _decompress(data, fin, callback) {
14787
+ const endpoint = this._isServer ? "client" : "server";
14788
+ if (!this._inflate) {
14789
+ const key = `${endpoint}_max_window_bits`;
14790
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
14791
+ this._inflate = zlib.createInflateRaw({
14792
+ ...this._options.zlibInflateOptions,
14793
+ windowBits
14794
+ });
14795
+ this._inflate[kPerMessageDeflate] = this;
14796
+ this._inflate[kTotalLength] = 0;
14797
+ this._inflate[kBuffers] = [];
14798
+ this._inflate.on("error", inflateOnError);
14799
+ this._inflate.on("data", inflateOnData);
14800
+ }
14801
+ this._inflate[kCallback] = callback;
14802
+ this._inflate.write(data);
14803
+ if (fin) this._inflate.write(TRAILER);
14804
+ this._inflate.flush(() => {
14805
+ const err2 = this._inflate[kError];
14806
+ if (err2) {
14807
+ this._inflate.close();
14808
+ this._inflate = null;
14809
+ callback(err2);
14810
+ return;
14811
+ }
14812
+ const data2 = bufferUtil.concat(
14813
+ this._inflate[kBuffers],
14814
+ this._inflate[kTotalLength]
14815
+ );
14816
+ if (this._inflate._readableState.endEmitted) {
14817
+ this._inflate.close();
14818
+ this._inflate = null;
14819
+ } else {
14820
+ this._inflate[kTotalLength] = 0;
14821
+ this._inflate[kBuffers] = [];
14822
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
14823
+ this._inflate.reset();
14824
+ }
14825
+ }
14826
+ callback(null, data2);
14827
+ });
14828
+ }
14829
+ /**
14830
+ * Compress data.
14831
+ *
14832
+ * @param {(Buffer|String)} data Data to compress
14833
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
14834
+ * @param {Function} callback Callback
14835
+ * @private
14836
+ */
14837
+ _compress(data, fin, callback) {
14838
+ const endpoint = this._isServer ? "server" : "client";
14839
+ if (!this._deflate) {
14840
+ const key = `${endpoint}_max_window_bits`;
14841
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
14842
+ this._deflate = zlib.createDeflateRaw({
14843
+ ...this._options.zlibDeflateOptions,
14844
+ windowBits
14845
+ });
14846
+ this._deflate[kTotalLength] = 0;
14847
+ this._deflate[kBuffers] = [];
14848
+ this._deflate.on("data", deflateOnData);
14849
+ }
14850
+ this._deflate[kCallback] = callback;
14851
+ this._deflate.write(data);
14852
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
14853
+ if (!this._deflate) {
14854
+ return;
14855
+ }
14856
+ let data2 = bufferUtil.concat(
14857
+ this._deflate[kBuffers],
14858
+ this._deflate[kTotalLength]
14859
+ );
14860
+ if (fin) {
14861
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
14862
+ }
14863
+ this._deflate[kCallback] = null;
14864
+ this._deflate[kTotalLength] = 0;
14865
+ this._deflate[kBuffers] = [];
14866
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
14867
+ this._deflate.reset();
14868
+ }
14869
+ callback(null, data2);
14870
+ });
14871
+ }
14872
+ };
14873
+ module2.exports = PerMessageDeflate2;
14874
+ function deflateOnData(chunk) {
14875
+ this[kBuffers].push(chunk);
14876
+ this[kTotalLength] += chunk.length;
14877
+ }
14878
+ function inflateOnData(chunk) {
14879
+ this[kTotalLength] += chunk.length;
14880
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
14881
+ this[kBuffers].push(chunk);
14882
+ return;
14883
+ }
14884
+ this[kError] = new RangeError("Max payload size exceeded");
14885
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
14886
+ this[kError][kStatusCode] = 1009;
14887
+ this.removeListener("data", inflateOnData);
14888
+ this.reset();
14889
+ }
14890
+ function inflateOnError(err2) {
14891
+ this[kPerMessageDeflate]._inflate = null;
14892
+ if (this[kError]) {
14893
+ this[kCallback](this[kError]);
14894
+ return;
14895
+ }
14896
+ err2[kStatusCode] = 1007;
14897
+ this[kCallback](err2);
14898
+ }
14899
+ }
14900
+ });
14901
+
14902
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js
14903
+ var require_validation = __commonJS({
14904
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js"(exports2, module2) {
14905
+ "use strict";
14906
+ var { isUtf8 } = require("buffer");
14907
+ var { hasBlob } = require_constants();
14908
+ var tokenChars = [
14909
+ 0,
14910
+ 0,
14911
+ 0,
14912
+ 0,
14913
+ 0,
14914
+ 0,
14915
+ 0,
14916
+ 0,
14917
+ 0,
14918
+ 0,
14919
+ 0,
14920
+ 0,
14921
+ 0,
14922
+ 0,
14923
+ 0,
14924
+ 0,
14925
+ // 0 - 15
14926
+ 0,
14927
+ 0,
14928
+ 0,
14929
+ 0,
14930
+ 0,
14931
+ 0,
14932
+ 0,
14933
+ 0,
14934
+ 0,
14935
+ 0,
14936
+ 0,
14937
+ 0,
14938
+ 0,
14939
+ 0,
14940
+ 0,
14941
+ 0,
14942
+ // 16 - 31
14943
+ 0,
14944
+ 1,
14945
+ 0,
14946
+ 1,
14947
+ 1,
14948
+ 1,
14949
+ 1,
14950
+ 1,
14951
+ 0,
14952
+ 0,
14953
+ 1,
14954
+ 1,
14955
+ 0,
14956
+ 1,
14957
+ 1,
14958
+ 0,
14959
+ // 32 - 47
14960
+ 1,
14961
+ 1,
14962
+ 1,
14963
+ 1,
14964
+ 1,
14965
+ 1,
14966
+ 1,
14967
+ 1,
14968
+ 1,
14969
+ 1,
14970
+ 0,
14971
+ 0,
14972
+ 0,
14973
+ 0,
14974
+ 0,
14975
+ 0,
14976
+ // 48 - 63
14977
+ 0,
14978
+ 1,
14979
+ 1,
14980
+ 1,
14981
+ 1,
14982
+ 1,
14983
+ 1,
14984
+ 1,
14985
+ 1,
14986
+ 1,
14987
+ 1,
14988
+ 1,
14989
+ 1,
14990
+ 1,
14991
+ 1,
14992
+ 1,
14993
+ // 64 - 79
14994
+ 1,
14995
+ 1,
14996
+ 1,
14997
+ 1,
14998
+ 1,
14999
+ 1,
15000
+ 1,
15001
+ 1,
15002
+ 1,
15003
+ 1,
15004
+ 1,
15005
+ 0,
15006
+ 0,
15007
+ 0,
15008
+ 1,
15009
+ 1,
15010
+ // 80 - 95
15011
+ 1,
15012
+ 1,
15013
+ 1,
15014
+ 1,
15015
+ 1,
15016
+ 1,
15017
+ 1,
15018
+ 1,
15019
+ 1,
15020
+ 1,
15021
+ 1,
15022
+ 1,
15023
+ 1,
15024
+ 1,
15025
+ 1,
15026
+ 1,
15027
+ // 96 - 111
15028
+ 1,
15029
+ 1,
15030
+ 1,
15031
+ 1,
15032
+ 1,
15033
+ 1,
15034
+ 1,
15035
+ 1,
15036
+ 1,
15037
+ 1,
15038
+ 1,
15039
+ 0,
15040
+ 1,
15041
+ 0,
15042
+ 1,
15043
+ 0
15044
+ // 112 - 127
15045
+ ];
15046
+ function isValidStatusCode(code) {
15047
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
15048
+ }
15049
+ function _isValidUTF8(buf) {
15050
+ const len = buf.length;
15051
+ let i2 = 0;
15052
+ while (i2 < len) {
15053
+ if ((buf[i2] & 128) === 0) {
15054
+ i2++;
15055
+ } else if ((buf[i2] & 224) === 192) {
15056
+ if (i2 + 1 === len || (buf[i2 + 1] & 192) !== 128 || (buf[i2] & 254) === 192) {
15057
+ return false;
15058
+ }
15059
+ i2 += 2;
15060
+ } else if ((buf[i2] & 240) === 224) {
15061
+ if (i2 + 2 >= len || (buf[i2 + 1] & 192) !== 128 || (buf[i2 + 2] & 192) !== 128 || buf[i2] === 224 && (buf[i2 + 1] & 224) === 128 || // Overlong
15062
+ buf[i2] === 237 && (buf[i2 + 1] & 224) === 160) {
15063
+ return false;
15064
+ }
15065
+ i2 += 3;
15066
+ } else if ((buf[i2] & 248) === 240) {
15067
+ if (i2 + 3 >= len || (buf[i2 + 1] & 192) !== 128 || (buf[i2 + 2] & 192) !== 128 || (buf[i2 + 3] & 192) !== 128 || buf[i2] === 240 && (buf[i2 + 1] & 240) === 128 || // Overlong
15068
+ buf[i2] === 244 && buf[i2 + 1] > 143 || buf[i2] > 244) {
15069
+ return false;
15070
+ }
15071
+ i2 += 4;
15072
+ } else {
15073
+ return false;
15074
+ }
15075
+ }
15076
+ return true;
15077
+ }
15078
+ function isBlob(value2) {
15079
+ return hasBlob && typeof value2 === "object" && typeof value2.arrayBuffer === "function" && typeof value2.type === "string" && typeof value2.stream === "function" && (value2[Symbol.toStringTag] === "Blob" || value2[Symbol.toStringTag] === "File");
15080
+ }
15081
+ module2.exports = {
15082
+ isBlob,
15083
+ isValidStatusCode,
15084
+ isValidUTF8: _isValidUTF8,
15085
+ tokenChars
15086
+ };
15087
+ if (isUtf8) {
15088
+ module2.exports.isValidUTF8 = function(buf) {
15089
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
15090
+ };
15091
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
15092
+ try {
15093
+ const isValidUTF8 = require("utf-8-validate");
15094
+ module2.exports.isValidUTF8 = function(buf) {
15095
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
15096
+ };
15097
+ } catch (e) {
15098
+ }
15099
+ }
15100
+ }
15101
+ });
15102
+
15103
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js
15104
+ var require_receiver = __commonJS({
15105
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js"(exports2, module2) {
15106
+ "use strict";
15107
+ var { Writable } = require("stream");
15108
+ var PerMessageDeflate2 = require_permessage_deflate();
15109
+ var {
15110
+ BINARY_TYPES,
15111
+ EMPTY_BUFFER,
15112
+ kStatusCode,
15113
+ kWebSocket
15114
+ } = require_constants();
15115
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
15116
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
15117
+ var FastBuffer = Buffer[Symbol.species];
15118
+ var GET_INFO = 0;
15119
+ var GET_PAYLOAD_LENGTH_16 = 1;
15120
+ var GET_PAYLOAD_LENGTH_64 = 2;
15121
+ var GET_MASK = 3;
15122
+ var GET_DATA = 4;
15123
+ var INFLATING = 5;
15124
+ var DEFER_EVENT = 6;
15125
+ var Receiver2 = class extends Writable {
15126
+ /**
15127
+ * Creates a Receiver instance.
15128
+ *
15129
+ * @param {Object} [options] Options object
15130
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
15131
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
15132
+ * multiple times in the same tick
15133
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
15134
+ * @param {Object} [options.extensions] An object containing the negotiated
15135
+ * extensions
15136
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
15137
+ * client or server mode
15138
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
15139
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
15140
+ * not to skip UTF-8 validation for text and close messages
15141
+ */
15142
+ constructor(options = {}) {
15143
+ super();
15144
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
15145
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
15146
+ this._extensions = options.extensions || {};
15147
+ this._isServer = !!options.isServer;
15148
+ this._maxPayload = options.maxPayload | 0;
15149
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
15150
+ this[kWebSocket] = void 0;
15151
+ this._bufferedBytes = 0;
15152
+ this._buffers = [];
15153
+ this._compressed = false;
15154
+ this._payloadLength = 0;
15155
+ this._mask = void 0;
15156
+ this._fragmented = 0;
15157
+ this._masked = false;
15158
+ this._fin = false;
15159
+ this._opcode = 0;
15160
+ this._totalPayloadLength = 0;
15161
+ this._messageLength = 0;
15162
+ this._fragments = [];
15163
+ this._errored = false;
15164
+ this._loop = false;
15165
+ this._state = GET_INFO;
15166
+ }
15167
+ /**
15168
+ * Implements `Writable.prototype._write()`.
15169
+ *
15170
+ * @param {Buffer} chunk The chunk of data to write
15171
+ * @param {String} encoding The character encoding of `chunk`
15172
+ * @param {Function} cb Callback
15173
+ * @private
15174
+ */
15175
+ _write(chunk, encoding, cb) {
15176
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
15177
+ this._bufferedBytes += chunk.length;
15178
+ this._buffers.push(chunk);
15179
+ this.startLoop(cb);
15180
+ }
15181
+ /**
15182
+ * Consumes `n` bytes from the buffered data.
15183
+ *
15184
+ * @param {Number} n The number of bytes to consume
15185
+ * @return {Buffer} The consumed bytes
15186
+ * @private
15187
+ */
15188
+ consume(n) {
15189
+ this._bufferedBytes -= n;
15190
+ if (n === this._buffers[0].length) return this._buffers.shift();
15191
+ if (n < this._buffers[0].length) {
15192
+ const buf = this._buffers[0];
15193
+ this._buffers[0] = new FastBuffer(
15194
+ buf.buffer,
15195
+ buf.byteOffset + n,
15196
+ buf.length - n
15197
+ );
15198
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
15199
+ }
15200
+ const dst = Buffer.allocUnsafe(n);
15201
+ do {
15202
+ const buf = this._buffers[0];
15203
+ const offset = dst.length - n;
15204
+ if (n >= buf.length) {
15205
+ dst.set(this._buffers.shift(), offset);
15206
+ } else {
15207
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
15208
+ this._buffers[0] = new FastBuffer(
15209
+ buf.buffer,
15210
+ buf.byteOffset + n,
15211
+ buf.length - n
15212
+ );
15213
+ }
15214
+ n -= buf.length;
15215
+ } while (n > 0);
15216
+ return dst;
15217
+ }
15218
+ /**
15219
+ * Starts the parsing loop.
15220
+ *
15221
+ * @param {Function} cb Callback
15222
+ * @private
15223
+ */
15224
+ startLoop(cb) {
15225
+ this._loop = true;
15226
+ do {
15227
+ switch (this._state) {
15228
+ case GET_INFO:
15229
+ this.getInfo(cb);
15230
+ break;
15231
+ case GET_PAYLOAD_LENGTH_16:
15232
+ this.getPayloadLength16(cb);
15233
+ break;
15234
+ case GET_PAYLOAD_LENGTH_64:
15235
+ this.getPayloadLength64(cb);
15236
+ break;
15237
+ case GET_MASK:
15238
+ this.getMask();
15239
+ break;
15240
+ case GET_DATA:
15241
+ this.getData(cb);
15242
+ break;
15243
+ case INFLATING:
15244
+ case DEFER_EVENT:
15245
+ this._loop = false;
15246
+ return;
15247
+ }
15248
+ } while (this._loop);
15249
+ if (!this._errored) cb();
15250
+ }
15251
+ /**
15252
+ * Reads the first two bytes of a frame.
15253
+ *
15254
+ * @param {Function} cb Callback
15255
+ * @private
15256
+ */
15257
+ getInfo(cb) {
15258
+ if (this._bufferedBytes < 2) {
15259
+ this._loop = false;
15260
+ return;
15261
+ }
15262
+ const buf = this.consume(2);
15263
+ if ((buf[0] & 48) !== 0) {
15264
+ const error48 = this.createError(
15265
+ RangeError,
15266
+ "RSV2 and RSV3 must be clear",
15267
+ true,
15268
+ 1002,
15269
+ "WS_ERR_UNEXPECTED_RSV_2_3"
15270
+ );
15271
+ cb(error48);
15272
+ return;
15273
+ }
15274
+ const compressed = (buf[0] & 64) === 64;
15275
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
15276
+ const error48 = this.createError(
15277
+ RangeError,
15278
+ "RSV1 must be clear",
15279
+ true,
15280
+ 1002,
15281
+ "WS_ERR_UNEXPECTED_RSV_1"
15282
+ );
15283
+ cb(error48);
15284
+ return;
15285
+ }
15286
+ this._fin = (buf[0] & 128) === 128;
15287
+ this._opcode = buf[0] & 15;
15288
+ this._payloadLength = buf[1] & 127;
15289
+ if (this._opcode === 0) {
15290
+ if (compressed) {
15291
+ const error48 = this.createError(
15292
+ RangeError,
15293
+ "RSV1 must be clear",
15294
+ true,
15295
+ 1002,
15296
+ "WS_ERR_UNEXPECTED_RSV_1"
15297
+ );
15298
+ cb(error48);
15299
+ return;
15300
+ }
15301
+ if (!this._fragmented) {
15302
+ const error48 = this.createError(
15303
+ RangeError,
15304
+ "invalid opcode 0",
15305
+ true,
15306
+ 1002,
15307
+ "WS_ERR_INVALID_OPCODE"
15308
+ );
15309
+ cb(error48);
15310
+ return;
15311
+ }
15312
+ this._opcode = this._fragmented;
15313
+ } else if (this._opcode === 1 || this._opcode === 2) {
15314
+ if (this._fragmented) {
15315
+ const error48 = this.createError(
15316
+ RangeError,
15317
+ `invalid opcode ${this._opcode}`,
15318
+ true,
15319
+ 1002,
15320
+ "WS_ERR_INVALID_OPCODE"
15321
+ );
15322
+ cb(error48);
15323
+ return;
15324
+ }
15325
+ this._compressed = compressed;
15326
+ } else if (this._opcode > 7 && this._opcode < 11) {
15327
+ if (!this._fin) {
15328
+ const error48 = this.createError(
15329
+ RangeError,
15330
+ "FIN must be set",
15331
+ true,
15332
+ 1002,
15333
+ "WS_ERR_EXPECTED_FIN"
15334
+ );
15335
+ cb(error48);
15336
+ return;
15337
+ }
15338
+ if (compressed) {
15339
+ const error48 = this.createError(
15340
+ RangeError,
15341
+ "RSV1 must be clear",
15342
+ true,
15343
+ 1002,
15344
+ "WS_ERR_UNEXPECTED_RSV_1"
15345
+ );
15346
+ cb(error48);
15347
+ return;
15348
+ }
15349
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
15350
+ const error48 = this.createError(
15351
+ RangeError,
15352
+ `invalid payload length ${this._payloadLength}`,
15353
+ true,
15354
+ 1002,
15355
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
15356
+ );
15357
+ cb(error48);
15358
+ return;
15359
+ }
15360
+ } else {
15361
+ const error48 = this.createError(
15362
+ RangeError,
15363
+ `invalid opcode ${this._opcode}`,
15364
+ true,
15365
+ 1002,
15366
+ "WS_ERR_INVALID_OPCODE"
15367
+ );
15368
+ cb(error48);
15369
+ return;
15370
+ }
15371
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
15372
+ this._masked = (buf[1] & 128) === 128;
15373
+ if (this._isServer) {
15374
+ if (!this._masked) {
15375
+ const error48 = this.createError(
15376
+ RangeError,
15377
+ "MASK must be set",
15378
+ true,
15379
+ 1002,
15380
+ "WS_ERR_EXPECTED_MASK"
15381
+ );
15382
+ cb(error48);
15383
+ return;
15384
+ }
15385
+ } else if (this._masked) {
15386
+ const error48 = this.createError(
15387
+ RangeError,
15388
+ "MASK must be clear",
15389
+ true,
15390
+ 1002,
15391
+ "WS_ERR_UNEXPECTED_MASK"
15392
+ );
15393
+ cb(error48);
15394
+ return;
15395
+ }
15396
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
15397
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
15398
+ else this.haveLength(cb);
15399
+ }
15400
+ /**
15401
+ * Gets extended payload length (7+16).
15402
+ *
15403
+ * @param {Function} cb Callback
15404
+ * @private
15405
+ */
15406
+ getPayloadLength16(cb) {
15407
+ if (this._bufferedBytes < 2) {
15408
+ this._loop = false;
15409
+ return;
15410
+ }
15411
+ this._payloadLength = this.consume(2).readUInt16BE(0);
15412
+ this.haveLength(cb);
15413
+ }
15414
+ /**
15415
+ * Gets extended payload length (7+64).
15416
+ *
15417
+ * @param {Function} cb Callback
15418
+ * @private
15419
+ */
15420
+ getPayloadLength64(cb) {
15421
+ if (this._bufferedBytes < 8) {
15422
+ this._loop = false;
15423
+ return;
15424
+ }
15425
+ const buf = this.consume(8);
15426
+ const num = buf.readUInt32BE(0);
15427
+ if (num > Math.pow(2, 53 - 32) - 1) {
15428
+ const error48 = this.createError(
15429
+ RangeError,
15430
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
15431
+ false,
15432
+ 1009,
15433
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
15434
+ );
15435
+ cb(error48);
15436
+ return;
15437
+ }
15438
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
15439
+ this.haveLength(cb);
15440
+ }
15441
+ /**
15442
+ * Payload length has been read.
15443
+ *
15444
+ * @param {Function} cb Callback
15445
+ * @private
15446
+ */
15447
+ haveLength(cb) {
15448
+ if (this._payloadLength && this._opcode < 8) {
15449
+ this._totalPayloadLength += this._payloadLength;
15450
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
15451
+ const error48 = this.createError(
15452
+ RangeError,
15453
+ "Max payload size exceeded",
15454
+ false,
15455
+ 1009,
15456
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
15457
+ );
15458
+ cb(error48);
15459
+ return;
15460
+ }
15461
+ }
15462
+ if (this._masked) this._state = GET_MASK;
15463
+ else this._state = GET_DATA;
15464
+ }
15465
+ /**
15466
+ * Reads mask bytes.
15467
+ *
15468
+ * @private
15469
+ */
15470
+ getMask() {
15471
+ if (this._bufferedBytes < 4) {
15472
+ this._loop = false;
15473
+ return;
15474
+ }
15475
+ this._mask = this.consume(4);
15476
+ this._state = GET_DATA;
15477
+ }
15478
+ /**
15479
+ * Reads data bytes.
15480
+ *
15481
+ * @param {Function} cb Callback
15482
+ * @private
15483
+ */
15484
+ getData(cb) {
15485
+ let data = EMPTY_BUFFER;
15486
+ if (this._payloadLength) {
15487
+ if (this._bufferedBytes < this._payloadLength) {
15488
+ this._loop = false;
15489
+ return;
15490
+ }
15491
+ data = this.consume(this._payloadLength);
15492
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
15493
+ unmask(data, this._mask);
15494
+ }
15495
+ }
15496
+ if (this._opcode > 7) {
15497
+ this.controlMessage(data, cb);
15498
+ return;
15499
+ }
15500
+ if (this._compressed) {
15501
+ this._state = INFLATING;
15502
+ this.decompress(data, cb);
15503
+ return;
15504
+ }
15505
+ if (data.length) {
15506
+ this._messageLength = this._totalPayloadLength;
15507
+ this._fragments.push(data);
15508
+ }
15509
+ this.dataMessage(cb);
15510
+ }
15511
+ /**
15512
+ * Decompresses data.
15513
+ *
15514
+ * @param {Buffer} data Compressed data
15515
+ * @param {Function} cb Callback
15516
+ * @private
15517
+ */
15518
+ decompress(data, cb) {
15519
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
15520
+ perMessageDeflate.decompress(data, this._fin, (err2, buf) => {
15521
+ if (err2) return cb(err2);
15522
+ if (buf.length) {
15523
+ this._messageLength += buf.length;
15524
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
15525
+ const error48 = this.createError(
15526
+ RangeError,
15527
+ "Max payload size exceeded",
15528
+ false,
15529
+ 1009,
15530
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
15531
+ );
15532
+ cb(error48);
15533
+ return;
15534
+ }
15535
+ this._fragments.push(buf);
15536
+ }
15537
+ this.dataMessage(cb);
15538
+ if (this._state === GET_INFO) this.startLoop(cb);
15539
+ });
15540
+ }
15541
+ /**
15542
+ * Handles a data message.
15543
+ *
15544
+ * @param {Function} cb Callback
15545
+ * @private
15546
+ */
15547
+ dataMessage(cb) {
15548
+ if (!this._fin) {
15549
+ this._state = GET_INFO;
15550
+ return;
15551
+ }
15552
+ const messageLength = this._messageLength;
15553
+ const fragments = this._fragments;
15554
+ this._totalPayloadLength = 0;
15555
+ this._messageLength = 0;
15556
+ this._fragmented = 0;
15557
+ this._fragments = [];
15558
+ if (this._opcode === 2) {
15559
+ let data;
15560
+ if (this._binaryType === "nodebuffer") {
15561
+ data = concat(fragments, messageLength);
15562
+ } else if (this._binaryType === "arraybuffer") {
15563
+ data = toArrayBuffer(concat(fragments, messageLength));
15564
+ } else if (this._binaryType === "blob") {
15565
+ data = new Blob(fragments);
15566
+ } else {
15567
+ data = fragments;
15568
+ }
15569
+ if (this._allowSynchronousEvents) {
15570
+ this.emit("message", data, true);
15571
+ this._state = GET_INFO;
15572
+ } else {
15573
+ this._state = DEFER_EVENT;
15574
+ setImmediate(() => {
15575
+ this.emit("message", data, true);
15576
+ this._state = GET_INFO;
15577
+ this.startLoop(cb);
15578
+ });
15579
+ }
15580
+ } else {
15581
+ const buf = concat(fragments, messageLength);
15582
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
15583
+ const error48 = this.createError(
15584
+ Error,
15585
+ "invalid UTF-8 sequence",
15586
+ true,
15587
+ 1007,
15588
+ "WS_ERR_INVALID_UTF8"
15589
+ );
15590
+ cb(error48);
15591
+ return;
15592
+ }
15593
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
15594
+ this.emit("message", buf, false);
15595
+ this._state = GET_INFO;
15596
+ } else {
15597
+ this._state = DEFER_EVENT;
15598
+ setImmediate(() => {
15599
+ this.emit("message", buf, false);
15600
+ this._state = GET_INFO;
15601
+ this.startLoop(cb);
15602
+ });
15603
+ }
15604
+ }
15605
+ }
15606
+ /**
15607
+ * Handles a control message.
15608
+ *
15609
+ * @param {Buffer} data Data to handle
15610
+ * @return {(Error|RangeError|undefined)} A possible error
15611
+ * @private
15612
+ */
15613
+ controlMessage(data, cb) {
15614
+ if (this._opcode === 8) {
15615
+ if (data.length === 0) {
15616
+ this._loop = false;
15617
+ this.emit("conclude", 1005, EMPTY_BUFFER);
15618
+ this.end();
15619
+ } else {
15620
+ const code = data.readUInt16BE(0);
15621
+ if (!isValidStatusCode(code)) {
15622
+ const error48 = this.createError(
15623
+ RangeError,
15624
+ `invalid status code ${code}`,
15625
+ true,
15626
+ 1002,
15627
+ "WS_ERR_INVALID_CLOSE_CODE"
15628
+ );
15629
+ cb(error48);
15630
+ return;
15631
+ }
15632
+ const buf = new FastBuffer(
15633
+ data.buffer,
15634
+ data.byteOffset + 2,
15635
+ data.length - 2
15636
+ );
15637
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
15638
+ const error48 = this.createError(
15639
+ Error,
15640
+ "invalid UTF-8 sequence",
15641
+ true,
15642
+ 1007,
15643
+ "WS_ERR_INVALID_UTF8"
15644
+ );
15645
+ cb(error48);
15646
+ return;
15647
+ }
15648
+ this._loop = false;
15649
+ this.emit("conclude", code, buf);
15650
+ this.end();
15651
+ }
15652
+ this._state = GET_INFO;
15653
+ return;
15654
+ }
15655
+ if (this._allowSynchronousEvents) {
15656
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
15657
+ this._state = GET_INFO;
15658
+ } else {
15659
+ this._state = DEFER_EVENT;
15660
+ setImmediate(() => {
15661
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
15662
+ this._state = GET_INFO;
15663
+ this.startLoop(cb);
15664
+ });
15665
+ }
15666
+ }
15667
+ /**
15668
+ * Builds an error object.
15669
+ *
15670
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
15671
+ * @param {String} message The error message
15672
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
15673
+ * `message`
15674
+ * @param {Number} statusCode The status code
15675
+ * @param {String} errorCode The exposed error code
15676
+ * @return {(Error|RangeError)} The error
15677
+ * @private
15678
+ */
15679
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
15680
+ this._loop = false;
15681
+ this._errored = true;
15682
+ const err2 = new ErrorCtor(
15683
+ prefix ? `Invalid WebSocket frame: ${message}` : message
15684
+ );
15685
+ Error.captureStackTrace(err2, this.createError);
15686
+ err2.code = errorCode;
15687
+ err2[kStatusCode] = statusCode;
15688
+ return err2;
15689
+ }
15690
+ };
15691
+ module2.exports = Receiver2;
15692
+ }
15693
+ });
15694
+
15695
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js
15696
+ var require_sender = __commonJS({
15697
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js"(exports2, module2) {
15698
+ "use strict";
15699
+ var { Duplex } = require("stream");
15700
+ var { randomFillSync } = require("crypto");
15701
+ var PerMessageDeflate2 = require_permessage_deflate();
15702
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
15703
+ var { isBlob, isValidStatusCode } = require_validation();
15704
+ var { mask: applyMask, toBuffer } = require_buffer_util();
15705
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
15706
+ var maskBuffer = Buffer.alloc(4);
15707
+ var RANDOM_POOL_SIZE = 8 * 1024;
15708
+ var randomPool;
15709
+ var randomPoolPointer = RANDOM_POOL_SIZE;
15710
+ var DEFAULT = 0;
15711
+ var DEFLATING = 1;
15712
+ var GET_BLOB_DATA = 2;
15713
+ var Sender2 = class _Sender {
15714
+ /**
15715
+ * Creates a Sender instance.
15716
+ *
15717
+ * @param {Duplex} socket The connection socket
15718
+ * @param {Object} [extensions] An object containing the negotiated extensions
15719
+ * @param {Function} [generateMask] The function used to generate the masking
15720
+ * key
15721
+ */
15722
+ constructor(socket, extensions, generateMask) {
15723
+ this._extensions = extensions || {};
15724
+ if (generateMask) {
15725
+ this._generateMask = generateMask;
15726
+ this._maskBuffer = Buffer.alloc(4);
15727
+ }
15728
+ this._socket = socket;
15729
+ this._firstFragment = true;
15730
+ this._compress = false;
15731
+ this._bufferedBytes = 0;
15732
+ this._queue = [];
15733
+ this._state = DEFAULT;
15734
+ this.onerror = NOOP;
15735
+ this[kWebSocket] = void 0;
15736
+ }
15737
+ /**
15738
+ * Frames a piece of data according to the HyBi WebSocket protocol.
15739
+ *
15740
+ * @param {(Buffer|String)} data The data to frame
15741
+ * @param {Object} options Options object
15742
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
15743
+ * FIN bit
15744
+ * @param {Function} [options.generateMask] The function used to generate the
15745
+ * masking key
15746
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
15747
+ * `data`
15748
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
15749
+ * key
15750
+ * @param {Number} options.opcode The opcode
15751
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
15752
+ * modified
15753
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
15754
+ * RSV1 bit
15755
+ * @return {(Buffer|String)[]} The framed data
15756
+ * @public
15757
+ */
15758
+ static frame(data, options) {
15759
+ let mask;
15760
+ let merge2 = false;
15761
+ let offset = 2;
15762
+ let skipMasking = false;
15763
+ if (options.mask) {
15764
+ mask = options.maskBuffer || maskBuffer;
15765
+ if (options.generateMask) {
15766
+ options.generateMask(mask);
15767
+ } else {
15768
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
15769
+ if (randomPool === void 0) {
15770
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
15771
+ }
15772
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
15773
+ randomPoolPointer = 0;
15774
+ }
15775
+ mask[0] = randomPool[randomPoolPointer++];
15776
+ mask[1] = randomPool[randomPoolPointer++];
15777
+ mask[2] = randomPool[randomPoolPointer++];
15778
+ mask[3] = randomPool[randomPoolPointer++];
15779
+ }
15780
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
15781
+ offset = 6;
15782
+ }
15783
+ let dataLength;
15784
+ if (typeof data === "string") {
15785
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
15786
+ dataLength = options[kByteLength];
15787
+ } else {
15788
+ data = Buffer.from(data);
15789
+ dataLength = data.length;
15790
+ }
15791
+ } else {
15792
+ dataLength = data.length;
15793
+ merge2 = options.mask && options.readOnly && !skipMasking;
15794
+ }
15795
+ let payloadLength = dataLength;
15796
+ if (dataLength >= 65536) {
15797
+ offset += 8;
15798
+ payloadLength = 127;
15799
+ } else if (dataLength > 125) {
15800
+ offset += 2;
15801
+ payloadLength = 126;
15802
+ }
15803
+ const target = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset);
15804
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
15805
+ if (options.rsv1) target[0] |= 64;
15806
+ target[1] = payloadLength;
15807
+ if (payloadLength === 126) {
15808
+ target.writeUInt16BE(dataLength, 2);
15809
+ } else if (payloadLength === 127) {
15810
+ target[2] = target[3] = 0;
15811
+ target.writeUIntBE(dataLength, 4, 6);
15812
+ }
15813
+ if (!options.mask) return [target, data];
15814
+ target[1] |= 128;
15815
+ target[offset - 4] = mask[0];
15816
+ target[offset - 3] = mask[1];
15817
+ target[offset - 2] = mask[2];
15818
+ target[offset - 1] = mask[3];
15819
+ if (skipMasking) return [target, data];
15820
+ if (merge2) {
15821
+ applyMask(data, mask, target, offset, dataLength);
15822
+ return [target];
15823
+ }
15824
+ applyMask(data, mask, data, 0, dataLength);
15825
+ return [target, data];
15826
+ }
15827
+ /**
15828
+ * Sends a close message to the other peer.
15829
+ *
15830
+ * @param {Number} [code] The status code component of the body
15831
+ * @param {(String|Buffer)} [data] The message component of the body
15832
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
15833
+ * @param {Function} [cb] Callback
15834
+ * @public
15835
+ */
15836
+ close(code, data, mask, cb) {
15837
+ let buf;
15838
+ if (code === void 0) {
15839
+ buf = EMPTY_BUFFER;
15840
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
15841
+ throw new TypeError("First argument must be a valid error code number");
15842
+ } else if (data === void 0 || !data.length) {
15843
+ buf = Buffer.allocUnsafe(2);
15844
+ buf.writeUInt16BE(code, 0);
15845
+ } else {
15846
+ const length = Buffer.byteLength(data);
15847
+ if (length > 123) {
15848
+ throw new RangeError("The message must not be greater than 123 bytes");
15849
+ }
15850
+ buf = Buffer.allocUnsafe(2 + length);
15851
+ buf.writeUInt16BE(code, 0);
15852
+ if (typeof data === "string") {
15853
+ buf.write(data, 2);
15854
+ } else {
15855
+ buf.set(data, 2);
15856
+ }
15857
+ }
15858
+ const options = {
15859
+ [kByteLength]: buf.length,
15860
+ fin: true,
15861
+ generateMask: this._generateMask,
15862
+ mask,
15863
+ maskBuffer: this._maskBuffer,
15864
+ opcode: 8,
15865
+ readOnly: false,
15866
+ rsv1: false
15867
+ };
15868
+ if (this._state !== DEFAULT) {
15869
+ this.enqueue([this.dispatch, buf, false, options, cb]);
15870
+ } else {
15871
+ this.sendFrame(_Sender.frame(buf, options), cb);
15872
+ }
15873
+ }
15874
+ /**
15875
+ * Sends a ping message to the other peer.
15876
+ *
15877
+ * @param {*} data The message to send
15878
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
15879
+ * @param {Function} [cb] Callback
15880
+ * @public
15881
+ */
15882
+ ping(data, mask, cb) {
15883
+ let byteLength;
15884
+ let readOnly;
15885
+ if (typeof data === "string") {
15886
+ byteLength = Buffer.byteLength(data);
15887
+ readOnly = false;
15888
+ } else if (isBlob(data)) {
15889
+ byteLength = data.size;
15890
+ readOnly = false;
15891
+ } else {
15892
+ data = toBuffer(data);
15893
+ byteLength = data.length;
15894
+ readOnly = toBuffer.readOnly;
15895
+ }
15896
+ if (byteLength > 125) {
15897
+ throw new RangeError("The data size must not be greater than 125 bytes");
15898
+ }
15899
+ const options = {
15900
+ [kByteLength]: byteLength,
15901
+ fin: true,
15902
+ generateMask: this._generateMask,
15903
+ mask,
15904
+ maskBuffer: this._maskBuffer,
15905
+ opcode: 9,
15906
+ readOnly,
15907
+ rsv1: false
15908
+ };
15909
+ if (isBlob(data)) {
15910
+ if (this._state !== DEFAULT) {
15911
+ this.enqueue([this.getBlobData, data, false, options, cb]);
15912
+ } else {
15913
+ this.getBlobData(data, false, options, cb);
15914
+ }
15915
+ } else if (this._state !== DEFAULT) {
15916
+ this.enqueue([this.dispatch, data, false, options, cb]);
15917
+ } else {
15918
+ this.sendFrame(_Sender.frame(data, options), cb);
15919
+ }
15920
+ }
15921
+ /**
15922
+ * Sends a pong message to the other peer.
15923
+ *
15924
+ * @param {*} data The message to send
15925
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
15926
+ * @param {Function} [cb] Callback
15927
+ * @public
15928
+ */
15929
+ pong(data, mask, cb) {
15930
+ let byteLength;
15931
+ let readOnly;
15932
+ if (typeof data === "string") {
15933
+ byteLength = Buffer.byteLength(data);
15934
+ readOnly = false;
15935
+ } else if (isBlob(data)) {
15936
+ byteLength = data.size;
15937
+ readOnly = false;
15938
+ } else {
15939
+ data = toBuffer(data);
15940
+ byteLength = data.length;
15941
+ readOnly = toBuffer.readOnly;
15942
+ }
15943
+ if (byteLength > 125) {
15944
+ throw new RangeError("The data size must not be greater than 125 bytes");
15945
+ }
15946
+ const options = {
15947
+ [kByteLength]: byteLength,
15948
+ fin: true,
15949
+ generateMask: this._generateMask,
15950
+ mask,
15951
+ maskBuffer: this._maskBuffer,
15952
+ opcode: 10,
15953
+ readOnly,
15954
+ rsv1: false
15955
+ };
15956
+ if (isBlob(data)) {
15957
+ if (this._state !== DEFAULT) {
15958
+ this.enqueue([this.getBlobData, data, false, options, cb]);
15959
+ } else {
15960
+ this.getBlobData(data, false, options, cb);
15961
+ }
15962
+ } else if (this._state !== DEFAULT) {
15963
+ this.enqueue([this.dispatch, data, false, options, cb]);
15964
+ } else {
15965
+ this.sendFrame(_Sender.frame(data, options), cb);
15966
+ }
15967
+ }
15968
+ /**
15969
+ * Sends a data message to the other peer.
15970
+ *
15971
+ * @param {*} data The message to send
15972
+ * @param {Object} options Options object
15973
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
15974
+ * or text
15975
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
15976
+ * compress `data`
15977
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
15978
+ * last one
15979
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
15980
+ * `data`
15981
+ * @param {Function} [cb] Callback
15982
+ * @public
15983
+ */
15984
+ send(data, options, cb) {
15985
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
15986
+ let opcode = options.binary ? 2 : 1;
15987
+ let rsv1 = options.compress;
15988
+ let byteLength;
15989
+ let readOnly;
15990
+ if (typeof data === "string") {
15991
+ byteLength = Buffer.byteLength(data);
15992
+ readOnly = false;
15993
+ } else if (isBlob(data)) {
15994
+ byteLength = data.size;
15995
+ readOnly = false;
15996
+ } else {
15997
+ data = toBuffer(data);
15998
+ byteLength = data.length;
15999
+ readOnly = toBuffer.readOnly;
16000
+ }
16001
+ if (this._firstFragment) {
16002
+ this._firstFragment = false;
16003
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
16004
+ rsv1 = byteLength >= perMessageDeflate._threshold;
16005
+ }
16006
+ this._compress = rsv1;
16007
+ } else {
16008
+ rsv1 = false;
16009
+ opcode = 0;
16010
+ }
16011
+ if (options.fin) this._firstFragment = true;
16012
+ const opts = {
16013
+ [kByteLength]: byteLength,
16014
+ fin: options.fin,
16015
+ generateMask: this._generateMask,
16016
+ mask: options.mask,
16017
+ maskBuffer: this._maskBuffer,
16018
+ opcode,
16019
+ readOnly,
16020
+ rsv1
16021
+ };
16022
+ if (isBlob(data)) {
16023
+ if (this._state !== DEFAULT) {
16024
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
16025
+ } else {
16026
+ this.getBlobData(data, this._compress, opts, cb);
16027
+ }
16028
+ } else if (this._state !== DEFAULT) {
16029
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
16030
+ } else {
16031
+ this.dispatch(data, this._compress, opts, cb);
16032
+ }
16033
+ }
16034
+ /**
16035
+ * Gets the contents of a blob as binary data.
16036
+ *
16037
+ * @param {Blob} blob The blob
16038
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
16039
+ * the data
16040
+ * @param {Object} options Options object
16041
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
16042
+ * FIN bit
16043
+ * @param {Function} [options.generateMask] The function used to generate the
16044
+ * masking key
16045
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
16046
+ * `data`
16047
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
16048
+ * key
16049
+ * @param {Number} options.opcode The opcode
16050
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
16051
+ * modified
16052
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
16053
+ * RSV1 bit
16054
+ * @param {Function} [cb] Callback
16055
+ * @private
16056
+ */
16057
+ getBlobData(blob, compress, options, cb) {
16058
+ this._bufferedBytes += options[kByteLength];
16059
+ this._state = GET_BLOB_DATA;
16060
+ blob.arrayBuffer().then((arrayBuffer) => {
16061
+ if (this._socket.destroyed) {
16062
+ const err2 = new Error(
16063
+ "The socket was closed while the blob was being read"
16064
+ );
16065
+ process.nextTick(callCallbacks, this, err2, cb);
16066
+ return;
16067
+ }
16068
+ this._bufferedBytes -= options[kByteLength];
16069
+ const data = toBuffer(arrayBuffer);
16070
+ if (!compress) {
16071
+ this._state = DEFAULT;
16072
+ this.sendFrame(_Sender.frame(data, options), cb);
16073
+ this.dequeue();
16074
+ } else {
16075
+ this.dispatch(data, compress, options, cb);
16076
+ }
16077
+ }).catch((err2) => {
16078
+ process.nextTick(onError, this, err2, cb);
16079
+ });
16080
+ }
16081
+ /**
16082
+ * Dispatches a message.
16083
+ *
16084
+ * @param {(Buffer|String)} data The message to send
16085
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
16086
+ * `data`
16087
+ * @param {Object} options Options object
16088
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
16089
+ * FIN bit
16090
+ * @param {Function} [options.generateMask] The function used to generate the
16091
+ * masking key
16092
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
16093
+ * `data`
16094
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
16095
+ * key
16096
+ * @param {Number} options.opcode The opcode
16097
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
16098
+ * modified
16099
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
16100
+ * RSV1 bit
16101
+ * @param {Function} [cb] Callback
16102
+ * @private
16103
+ */
16104
+ dispatch(data, compress, options, cb) {
16105
+ if (!compress) {
16106
+ this.sendFrame(_Sender.frame(data, options), cb);
16107
+ return;
16108
+ }
16109
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
16110
+ this._bufferedBytes += options[kByteLength];
16111
+ this._state = DEFLATING;
16112
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
16113
+ if (this._socket.destroyed) {
16114
+ const err2 = new Error(
16115
+ "The socket was closed while data was being compressed"
16116
+ );
16117
+ callCallbacks(this, err2, cb);
16118
+ return;
16119
+ }
16120
+ this._bufferedBytes -= options[kByteLength];
16121
+ this._state = DEFAULT;
16122
+ options.readOnly = false;
16123
+ this.sendFrame(_Sender.frame(buf, options), cb);
16124
+ this.dequeue();
16125
+ });
16126
+ }
16127
+ /**
16128
+ * Executes queued send operations.
16129
+ *
16130
+ * @private
16131
+ */
16132
+ dequeue() {
16133
+ while (this._state === DEFAULT && this._queue.length) {
16134
+ const params = this._queue.shift();
16135
+ this._bufferedBytes -= params[3][kByteLength];
16136
+ Reflect.apply(params[0], this, params.slice(1));
16137
+ }
16138
+ }
16139
+ /**
16140
+ * Enqueues a send operation.
16141
+ *
16142
+ * @param {Array} params Send operation parameters.
16143
+ * @private
16144
+ */
16145
+ enqueue(params) {
16146
+ this._bufferedBytes += params[3][kByteLength];
16147
+ this._queue.push(params);
16148
+ }
16149
+ /**
16150
+ * Sends a frame.
16151
+ *
16152
+ * @param {(Buffer | String)[]} list The frame to send
16153
+ * @param {Function} [cb] Callback
16154
+ * @private
16155
+ */
16156
+ sendFrame(list2, cb) {
16157
+ if (list2.length === 2) {
16158
+ this._socket.cork();
16159
+ this._socket.write(list2[0]);
16160
+ this._socket.write(list2[1], cb);
16161
+ this._socket.uncork();
16162
+ } else {
16163
+ this._socket.write(list2[0], cb);
16164
+ }
16165
+ }
16166
+ };
16167
+ module2.exports = Sender2;
16168
+ function callCallbacks(sender, err2, cb) {
16169
+ if (typeof cb === "function") cb(err2);
16170
+ for (let i2 = 0; i2 < sender._queue.length; i2++) {
16171
+ const params = sender._queue[i2];
16172
+ const callback = params[params.length - 1];
16173
+ if (typeof callback === "function") callback(err2);
16174
+ }
16175
+ }
16176
+ function onError(sender, err2, cb) {
16177
+ callCallbacks(sender, err2, cb);
16178
+ sender.onerror(err2);
16179
+ }
16180
+ }
16181
+ });
16182
+
16183
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js
16184
+ var require_event_target = __commonJS({
16185
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js"(exports2, module2) {
16186
+ "use strict";
16187
+ var { kForOnEventAttribute, kListener } = require_constants();
16188
+ var kCode = /* @__PURE__ */ Symbol("kCode");
16189
+ var kData = /* @__PURE__ */ Symbol("kData");
16190
+ var kError = /* @__PURE__ */ Symbol("kError");
16191
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
16192
+ var kReason = /* @__PURE__ */ Symbol("kReason");
16193
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
16194
+ var kType = /* @__PURE__ */ Symbol("kType");
16195
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
16196
+ var Event = class {
16197
+ /**
16198
+ * Create a new `Event`.
16199
+ *
16200
+ * @param {String} type The name of the event
16201
+ * @throws {TypeError} If the `type` argument is not specified
16202
+ */
16203
+ constructor(type) {
16204
+ this[kTarget] = null;
16205
+ this[kType] = type;
16206
+ }
16207
+ /**
16208
+ * @type {*}
16209
+ */
16210
+ get target() {
16211
+ return this[kTarget];
16212
+ }
16213
+ /**
16214
+ * @type {String}
16215
+ */
16216
+ get type() {
16217
+ return this[kType];
16218
+ }
16219
+ };
16220
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
16221
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
16222
+ var CloseEvent = class extends Event {
16223
+ /**
16224
+ * Create a new `CloseEvent`.
16225
+ *
16226
+ * @param {String} type The name of the event
16227
+ * @param {Object} [options] A dictionary object that allows for setting
16228
+ * attributes via object members of the same name
16229
+ * @param {Number} [options.code=0] The status code explaining why the
16230
+ * connection was closed
16231
+ * @param {String} [options.reason=''] A human-readable string explaining why
16232
+ * the connection was closed
16233
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
16234
+ * connection was cleanly closed
16235
+ */
16236
+ constructor(type, options = {}) {
16237
+ super(type);
16238
+ this[kCode] = options.code === void 0 ? 0 : options.code;
16239
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
16240
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
16241
+ }
16242
+ /**
16243
+ * @type {Number}
16244
+ */
16245
+ get code() {
16246
+ return this[kCode];
16247
+ }
16248
+ /**
16249
+ * @type {String}
16250
+ */
16251
+ get reason() {
16252
+ return this[kReason];
16253
+ }
16254
+ /**
16255
+ * @type {Boolean}
16256
+ */
16257
+ get wasClean() {
16258
+ return this[kWasClean];
16259
+ }
16260
+ };
16261
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
16262
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
16263
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
16264
+ var ErrorEvent = class extends Event {
16265
+ /**
16266
+ * Create a new `ErrorEvent`.
16267
+ *
16268
+ * @param {String} type The name of the event
16269
+ * @param {Object} [options] A dictionary object that allows for setting
16270
+ * attributes via object members of the same name
16271
+ * @param {*} [options.error=null] The error that generated this event
16272
+ * @param {String} [options.message=''] The error message
16273
+ */
16274
+ constructor(type, options = {}) {
16275
+ super(type);
16276
+ this[kError] = options.error === void 0 ? null : options.error;
16277
+ this[kMessage] = options.message === void 0 ? "" : options.message;
16278
+ }
16279
+ /**
16280
+ * @type {*}
16281
+ */
16282
+ get error() {
16283
+ return this[kError];
16284
+ }
16285
+ /**
16286
+ * @type {String}
16287
+ */
16288
+ get message() {
16289
+ return this[kMessage];
16290
+ }
16291
+ };
16292
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
16293
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
16294
+ var MessageEvent = class extends Event {
16295
+ /**
16296
+ * Create a new `MessageEvent`.
16297
+ *
16298
+ * @param {String} type The name of the event
16299
+ * @param {Object} [options] A dictionary object that allows for setting
16300
+ * attributes via object members of the same name
16301
+ * @param {*} [options.data=null] The message content
16302
+ */
16303
+ constructor(type, options = {}) {
16304
+ super(type);
16305
+ this[kData] = options.data === void 0 ? null : options.data;
16306
+ }
16307
+ /**
16308
+ * @type {*}
16309
+ */
16310
+ get data() {
16311
+ return this[kData];
16312
+ }
16313
+ };
16314
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
16315
+ var EventTarget = {
16316
+ /**
16317
+ * Register an event listener.
16318
+ *
16319
+ * @param {String} type A string representing the event type to listen for
16320
+ * @param {(Function|Object)} handler The listener to add
16321
+ * @param {Object} [options] An options object specifies characteristics about
16322
+ * the event listener
16323
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
16324
+ * listener should be invoked at most once after being added. If `true`,
16325
+ * the listener would be automatically removed when invoked.
16326
+ * @public
16327
+ */
16328
+ addEventListener(type, handler2, options = {}) {
16329
+ for (const listener of this.listeners(type)) {
16330
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler2 && !listener[kForOnEventAttribute]) {
16331
+ return;
16332
+ }
16333
+ }
16334
+ let wrapper;
16335
+ if (type === "message") {
16336
+ wrapper = function onMessage(data, isBinary) {
16337
+ const event = new MessageEvent("message", {
16338
+ data: isBinary ? data : data.toString()
16339
+ });
16340
+ event[kTarget] = this;
16341
+ callListener(handler2, this, event);
16342
+ };
16343
+ } else if (type === "close") {
16344
+ wrapper = function onClose(code, message) {
16345
+ const event = new CloseEvent("close", {
16346
+ code,
16347
+ reason: message.toString(),
16348
+ wasClean: this._closeFrameReceived && this._closeFrameSent
16349
+ });
16350
+ event[kTarget] = this;
16351
+ callListener(handler2, this, event);
16352
+ };
16353
+ } else if (type === "error") {
16354
+ wrapper = function onError(error48) {
16355
+ const event = new ErrorEvent("error", {
16356
+ error: error48,
16357
+ message: error48.message
16358
+ });
16359
+ event[kTarget] = this;
16360
+ callListener(handler2, this, event);
16361
+ };
16362
+ } else if (type === "open") {
16363
+ wrapper = function onOpen() {
16364
+ const event = new Event("open");
16365
+ event[kTarget] = this;
16366
+ callListener(handler2, this, event);
16367
+ };
16368
+ } else {
16369
+ return;
16370
+ }
16371
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
16372
+ wrapper[kListener] = handler2;
16373
+ if (options.once) {
16374
+ this.once(type, wrapper);
16375
+ } else {
16376
+ this.on(type, wrapper);
16377
+ }
16378
+ },
16379
+ /**
16380
+ * Remove an event listener.
16381
+ *
16382
+ * @param {String} type A string representing the event type to remove
16383
+ * @param {(Function|Object)} handler The listener to remove
16384
+ * @public
16385
+ */
16386
+ removeEventListener(type, handler2) {
16387
+ for (const listener of this.listeners(type)) {
16388
+ if (listener[kListener] === handler2 && !listener[kForOnEventAttribute]) {
16389
+ this.removeListener(type, listener);
16390
+ break;
16391
+ }
16392
+ }
16393
+ }
16394
+ };
16395
+ module2.exports = {
16396
+ CloseEvent,
16397
+ ErrorEvent,
16398
+ Event,
16399
+ EventTarget,
16400
+ MessageEvent
16401
+ };
16402
+ function callListener(listener, thisArg, event) {
16403
+ if (typeof listener === "object" && listener.handleEvent) {
16404
+ listener.handleEvent.call(listener, event);
16405
+ } else {
16406
+ listener.call(thisArg, event);
16407
+ }
16408
+ }
16409
+ }
16410
+ });
16411
+
16412
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js
16413
+ var require_extension = __commonJS({
16414
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js"(exports2, module2) {
16415
+ "use strict";
16416
+ var { tokenChars } = require_validation();
16417
+ function push2(dest, name2, elem) {
16418
+ if (dest[name2] === void 0) dest[name2] = [elem];
16419
+ else dest[name2].push(elem);
16420
+ }
16421
+ function parse4(header) {
16422
+ const offers = /* @__PURE__ */ Object.create(null);
16423
+ let params = /* @__PURE__ */ Object.create(null);
16424
+ let mustUnescape = false;
16425
+ let isEscaping = false;
16426
+ let inQuotes = false;
16427
+ let extensionName;
16428
+ let paramName;
16429
+ let start2 = -1;
16430
+ let code = -1;
16431
+ let end = -1;
16432
+ let i2 = 0;
16433
+ for (; i2 < header.length; i2++) {
16434
+ code = header.charCodeAt(i2);
16435
+ if (extensionName === void 0) {
16436
+ if (end === -1 && tokenChars[code] === 1) {
16437
+ if (start2 === -1) start2 = i2;
16438
+ } else if (i2 !== 0 && (code === 32 || code === 9)) {
16439
+ if (end === -1 && start2 !== -1) end = i2;
16440
+ } else if (code === 59 || code === 44) {
16441
+ if (start2 === -1) {
16442
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
16443
+ }
16444
+ if (end === -1) end = i2;
16445
+ const name2 = header.slice(start2, end);
16446
+ if (code === 44) {
16447
+ push2(offers, name2, params);
16448
+ params = /* @__PURE__ */ Object.create(null);
16449
+ } else {
16450
+ extensionName = name2;
16451
+ }
16452
+ start2 = end = -1;
16453
+ } else {
16454
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
16455
+ }
16456
+ } else if (paramName === void 0) {
16457
+ if (end === -1 && tokenChars[code] === 1) {
16458
+ if (start2 === -1) start2 = i2;
16459
+ } else if (code === 32 || code === 9) {
16460
+ if (end === -1 && start2 !== -1) end = i2;
16461
+ } else if (code === 59 || code === 44) {
16462
+ if (start2 === -1) {
16463
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
16464
+ }
16465
+ if (end === -1) end = i2;
16466
+ push2(params, header.slice(start2, end), true);
16467
+ if (code === 44) {
16468
+ push2(offers, extensionName, params);
16469
+ params = /* @__PURE__ */ Object.create(null);
16470
+ extensionName = void 0;
16471
+ }
16472
+ start2 = end = -1;
16473
+ } else if (code === 61 && start2 !== -1 && end === -1) {
16474
+ paramName = header.slice(start2, i2);
16475
+ start2 = end = -1;
16476
+ } else {
16477
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
16478
+ }
16479
+ } else {
16480
+ if (isEscaping) {
16481
+ if (tokenChars[code] !== 1) {
16482
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
16483
+ }
16484
+ if (start2 === -1) start2 = i2;
16485
+ else if (!mustUnescape) mustUnescape = true;
16486
+ isEscaping = false;
16487
+ } else if (inQuotes) {
16488
+ if (tokenChars[code] === 1) {
16489
+ if (start2 === -1) start2 = i2;
16490
+ } else if (code === 34 && start2 !== -1) {
16491
+ inQuotes = false;
16492
+ end = i2;
16493
+ } else if (code === 92) {
16494
+ isEscaping = true;
16495
+ } else {
16496
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
16497
+ }
16498
+ } else if (code === 34 && header.charCodeAt(i2 - 1) === 61) {
16499
+ inQuotes = true;
16500
+ } else if (end === -1 && tokenChars[code] === 1) {
16501
+ if (start2 === -1) start2 = i2;
16502
+ } else if (start2 !== -1 && (code === 32 || code === 9)) {
16503
+ if (end === -1) end = i2;
16504
+ } else if (code === 59 || code === 44) {
16505
+ if (start2 === -1) {
16506
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
16507
+ }
16508
+ if (end === -1) end = i2;
16509
+ let value2 = header.slice(start2, end);
16510
+ if (mustUnescape) {
16511
+ value2 = value2.replace(/\\/g, "");
16512
+ mustUnescape = false;
16513
+ }
16514
+ push2(params, paramName, value2);
16515
+ if (code === 44) {
16516
+ push2(offers, extensionName, params);
16517
+ params = /* @__PURE__ */ Object.create(null);
16518
+ extensionName = void 0;
16519
+ }
16520
+ paramName = void 0;
16521
+ start2 = end = -1;
16522
+ } else {
16523
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
16524
+ }
16525
+ }
16526
+ }
16527
+ if (start2 === -1 || inQuotes || code === 32 || code === 9) {
16528
+ throw new SyntaxError("Unexpected end of input");
16529
+ }
16530
+ if (end === -1) end = i2;
16531
+ const token = header.slice(start2, end);
16532
+ if (extensionName === void 0) {
16533
+ push2(offers, token, params);
16534
+ } else {
16535
+ if (paramName === void 0) {
16536
+ push2(params, token, true);
16537
+ } else if (mustUnescape) {
16538
+ push2(params, paramName, token.replace(/\\/g, ""));
16539
+ } else {
16540
+ push2(params, paramName, token);
16541
+ }
16542
+ push2(offers, extensionName, params);
16543
+ }
16544
+ return offers;
16545
+ }
16546
+ function format(extensions) {
16547
+ return Object.keys(extensions).map((extension3) => {
16548
+ let configurations = extensions[extension3];
16549
+ if (!Array.isArray(configurations)) configurations = [configurations];
16550
+ return configurations.map((params) => {
16551
+ return [extension3].concat(
16552
+ Object.keys(params).map((k) => {
16553
+ let values = params[k];
16554
+ if (!Array.isArray(values)) values = [values];
16555
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
16556
+ })
16557
+ ).join("; ");
16558
+ }).join(", ");
16559
+ }).join(", ");
16560
+ }
16561
+ module2.exports = { format, parse: parse4 };
16562
+ }
16563
+ });
16564
+
16565
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js
16566
+ var require_websocket = __commonJS({
16567
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js"(exports2, module2) {
16568
+ "use strict";
16569
+ var EventEmitter = require("events");
16570
+ var https = require("https");
16571
+ var http = require("http");
16572
+ var net = require("net");
16573
+ var tls = require("tls");
16574
+ var { randomBytes, createHash: createHash5 } = require("crypto");
16575
+ var { Duplex, Readable: Readable2 } = require("stream");
16576
+ var { URL: URL2 } = require("url");
16577
+ var PerMessageDeflate2 = require_permessage_deflate();
16578
+ var Receiver2 = require_receiver();
16579
+ var Sender2 = require_sender();
16580
+ var { isBlob } = require_validation();
16581
+ var {
16582
+ BINARY_TYPES,
16583
+ CLOSE_TIMEOUT,
16584
+ EMPTY_BUFFER,
16585
+ GUID,
16586
+ kForOnEventAttribute,
16587
+ kListener,
16588
+ kStatusCode,
16589
+ kWebSocket,
16590
+ NOOP
16591
+ } = require_constants();
16592
+ var {
16593
+ EventTarget: { addEventListener: addEventListener2, removeEventListener }
16594
+ } = require_event_target();
16595
+ var { format, parse: parse4 } = require_extension();
16596
+ var { toBuffer } = require_buffer_util();
16597
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
16598
+ var protocolVersions = [8, 13];
16599
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
16600
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
16601
+ var WebSocket2 = class _WebSocket extends EventEmitter {
16602
+ /**
16603
+ * Create a new `WebSocket`.
16604
+ *
16605
+ * @param {(String|URL)} address The URL to which to connect
16606
+ * @param {(String|String[])} [protocols] The subprotocols
16607
+ * @param {Object} [options] Connection options
16608
+ */
16609
+ constructor(address, protocols, options) {
16610
+ super();
16611
+ this._binaryType = BINARY_TYPES[0];
16612
+ this._closeCode = 1006;
16613
+ this._closeFrameReceived = false;
16614
+ this._closeFrameSent = false;
16615
+ this._closeMessage = EMPTY_BUFFER;
16616
+ this._closeTimer = null;
16617
+ this._errorEmitted = false;
16618
+ this._extensions = {};
16619
+ this._paused = false;
16620
+ this._protocol = "";
16621
+ this._readyState = _WebSocket.CONNECTING;
16622
+ this._receiver = null;
16623
+ this._sender = null;
16624
+ this._socket = null;
16625
+ if (address !== null) {
16626
+ this._bufferedAmount = 0;
16627
+ this._isServer = false;
16628
+ this._redirects = 0;
16629
+ if (protocols === void 0) {
16630
+ protocols = [];
16631
+ } else if (!Array.isArray(protocols)) {
16632
+ if (typeof protocols === "object" && protocols !== null) {
16633
+ options = protocols;
16634
+ protocols = [];
16635
+ } else {
16636
+ protocols = [protocols];
16637
+ }
16638
+ }
16639
+ initAsClient(this, address, protocols, options);
16640
+ } else {
16641
+ this._autoPong = options.autoPong;
16642
+ this._closeTimeout = options.closeTimeout;
16643
+ this._isServer = true;
16644
+ }
16645
+ }
16646
+ /**
16647
+ * For historical reasons, the custom "nodebuffer" type is used by the default
16648
+ * instead of "blob".
16649
+ *
16650
+ * @type {String}
16651
+ */
16652
+ get binaryType() {
16653
+ return this._binaryType;
16654
+ }
16655
+ set binaryType(type) {
16656
+ if (!BINARY_TYPES.includes(type)) return;
16657
+ this._binaryType = type;
16658
+ if (this._receiver) this._receiver._binaryType = type;
16659
+ }
16660
+ /**
16661
+ * @type {Number}
16662
+ */
16663
+ get bufferedAmount() {
16664
+ if (!this._socket) return this._bufferedAmount;
16665
+ return this._socket._writableState.length + this._sender._bufferedBytes;
16666
+ }
16667
+ /**
16668
+ * @type {String}
16669
+ */
16670
+ get extensions() {
16671
+ return Object.keys(this._extensions).join();
16672
+ }
16673
+ /**
16674
+ * @type {Boolean}
16675
+ */
16676
+ get isPaused() {
16677
+ return this._paused;
16678
+ }
16679
+ /**
16680
+ * @type {Function}
16681
+ */
16682
+ /* istanbul ignore next */
16683
+ get onclose() {
16684
+ return null;
16685
+ }
16686
+ /**
16687
+ * @type {Function}
16688
+ */
16689
+ /* istanbul ignore next */
16690
+ get onerror() {
16691
+ return null;
16692
+ }
16693
+ /**
16694
+ * @type {Function}
16695
+ */
16696
+ /* istanbul ignore next */
16697
+ get onopen() {
16698
+ return null;
16699
+ }
16700
+ /**
16701
+ * @type {Function}
16702
+ */
16703
+ /* istanbul ignore next */
16704
+ get onmessage() {
16705
+ return null;
16706
+ }
16707
+ /**
16708
+ * @type {String}
16709
+ */
16710
+ get protocol() {
16711
+ return this._protocol;
16712
+ }
16713
+ /**
16714
+ * @type {Number}
16715
+ */
16716
+ get readyState() {
16717
+ return this._readyState;
16718
+ }
16719
+ /**
16720
+ * @type {String}
16721
+ */
16722
+ get url() {
16723
+ return this._url;
16724
+ }
16725
+ /**
16726
+ * Set up the socket and the internal resources.
16727
+ *
16728
+ * @param {Duplex} socket The network socket between the server and client
16729
+ * @param {Buffer} head The first packet of the upgraded stream
16730
+ * @param {Object} options Options object
16731
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
16732
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
16733
+ * multiple times in the same tick
16734
+ * @param {Function} [options.generateMask] The function used to generate the
16735
+ * masking key
16736
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
16737
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
16738
+ * not to skip UTF-8 validation for text and close messages
16739
+ * @private
16740
+ */
16741
+ setSocket(socket, head, options) {
16742
+ const receiver = new Receiver2({
16743
+ allowSynchronousEvents: options.allowSynchronousEvents,
16744
+ binaryType: this.binaryType,
16745
+ extensions: this._extensions,
16746
+ isServer: this._isServer,
16747
+ maxPayload: options.maxPayload,
16748
+ skipUTF8Validation: options.skipUTF8Validation
16749
+ });
16750
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
16751
+ this._receiver = receiver;
16752
+ this._sender = sender;
16753
+ this._socket = socket;
16754
+ receiver[kWebSocket] = this;
16755
+ sender[kWebSocket] = this;
16756
+ socket[kWebSocket] = this;
16757
+ receiver.on("conclude", receiverOnConclude);
16758
+ receiver.on("drain", receiverOnDrain);
16759
+ receiver.on("error", receiverOnError);
16760
+ receiver.on("message", receiverOnMessage);
16761
+ receiver.on("ping", receiverOnPing);
16762
+ receiver.on("pong", receiverOnPong);
16763
+ sender.onerror = senderOnError;
16764
+ if (socket.setTimeout) socket.setTimeout(0);
16765
+ if (socket.setNoDelay) socket.setNoDelay();
16766
+ if (head.length > 0) socket.unshift(head);
16767
+ socket.on("close", socketOnClose);
16768
+ socket.on("data", socketOnData);
16769
+ socket.on("end", socketOnEnd);
16770
+ socket.on("error", socketOnError);
16771
+ this._readyState = _WebSocket.OPEN;
16772
+ this.emit("open");
16773
+ }
16774
+ /**
16775
+ * Emit the `'close'` event.
16776
+ *
16777
+ * @private
16778
+ */
16779
+ emitClose() {
16780
+ if (!this._socket) {
16781
+ this._readyState = _WebSocket.CLOSED;
16782
+ this.emit("close", this._closeCode, this._closeMessage);
16783
+ return;
16784
+ }
16785
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
16786
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
16787
+ }
16788
+ this._receiver.removeAllListeners();
16789
+ this._readyState = _WebSocket.CLOSED;
16790
+ this.emit("close", this._closeCode, this._closeMessage);
16791
+ }
16792
+ /**
16793
+ * Start a closing handshake.
16794
+ *
16795
+ * +----------+ +-----------+ +----------+
16796
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
16797
+ * | +----------+ +-----------+ +----------+ |
16798
+ * +----------+ +-----------+ |
16799
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
16800
+ * +----------+ +-----------+ |
16801
+ * | | | +---+ |
16802
+ * +------------------------+-->|fin| - - - -
16803
+ * | +---+ | +---+
16804
+ * - - - - -|fin|<---------------------+
16805
+ * +---+
16806
+ *
16807
+ * @param {Number} [code] Status code explaining why the connection is closing
16808
+ * @param {(String|Buffer)} [data] The reason why the connection is
16809
+ * closing
16810
+ * @public
16811
+ */
16812
+ close(code, data) {
16813
+ if (this.readyState === _WebSocket.CLOSED) return;
16814
+ if (this.readyState === _WebSocket.CONNECTING) {
16815
+ const msg = "WebSocket was closed before the connection was established";
16816
+ abortHandshake(this, this._req, msg);
16817
+ return;
16818
+ }
16819
+ if (this.readyState === _WebSocket.CLOSING) {
16820
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
16821
+ this._socket.end();
16822
+ }
16823
+ return;
16824
+ }
16825
+ this._readyState = _WebSocket.CLOSING;
16826
+ this._sender.close(code, data, !this._isServer, (err2) => {
16827
+ if (err2) return;
16828
+ this._closeFrameSent = true;
16829
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
16830
+ this._socket.end();
16831
+ }
16832
+ });
16833
+ setCloseTimer(this);
16834
+ }
16835
+ /**
16836
+ * Pause the socket.
16837
+ *
16838
+ * @public
16839
+ */
16840
+ pause() {
16841
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
16842
+ return;
16843
+ }
16844
+ this._paused = true;
16845
+ this._socket.pause();
16846
+ }
16847
+ /**
16848
+ * Send a ping.
16849
+ *
16850
+ * @param {*} [data] The data to send
16851
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
16852
+ * @param {Function} [cb] Callback which is executed when the ping is sent
16853
+ * @public
16854
+ */
16855
+ ping(data, mask, cb) {
16856
+ if (this.readyState === _WebSocket.CONNECTING) {
16857
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
16858
+ }
16859
+ if (typeof data === "function") {
16860
+ cb = data;
16861
+ data = mask = void 0;
16862
+ } else if (typeof mask === "function") {
16863
+ cb = mask;
16864
+ mask = void 0;
16865
+ }
16866
+ if (typeof data === "number") data = data.toString();
16867
+ if (this.readyState !== _WebSocket.OPEN) {
16868
+ sendAfterClose(this, data, cb);
16869
+ return;
16870
+ }
16871
+ if (mask === void 0) mask = !this._isServer;
16872
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
16873
+ }
16874
+ /**
16875
+ * Send a pong.
16876
+ *
16877
+ * @param {*} [data] The data to send
16878
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
16879
+ * @param {Function} [cb] Callback which is executed when the pong is sent
16880
+ * @public
16881
+ */
16882
+ pong(data, mask, cb) {
16883
+ if (this.readyState === _WebSocket.CONNECTING) {
16884
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
16885
+ }
16886
+ if (typeof data === "function") {
16887
+ cb = data;
16888
+ data = mask = void 0;
16889
+ } else if (typeof mask === "function") {
16890
+ cb = mask;
16891
+ mask = void 0;
16892
+ }
16893
+ if (typeof data === "number") data = data.toString();
16894
+ if (this.readyState !== _WebSocket.OPEN) {
16895
+ sendAfterClose(this, data, cb);
16896
+ return;
16897
+ }
16898
+ if (mask === void 0) mask = !this._isServer;
16899
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
16900
+ }
16901
+ /**
16902
+ * Resume the socket.
16903
+ *
16904
+ * @public
16905
+ */
16906
+ resume() {
16907
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
16908
+ return;
16909
+ }
16910
+ this._paused = false;
16911
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
16912
+ }
16913
+ /**
16914
+ * Send a data message.
16915
+ *
16916
+ * @param {*} data The message to send
16917
+ * @param {Object} [options] Options object
16918
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
16919
+ * text
16920
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
16921
+ * `data`
16922
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
16923
+ * last one
16924
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
16925
+ * @param {Function} [cb] Callback which is executed when data is written out
16926
+ * @public
16927
+ */
16928
+ send(data, options, cb) {
16929
+ if (this.readyState === _WebSocket.CONNECTING) {
16930
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
16931
+ }
16932
+ if (typeof options === "function") {
16933
+ cb = options;
16934
+ options = {};
16935
+ }
16936
+ if (typeof data === "number") data = data.toString();
16937
+ if (this.readyState !== _WebSocket.OPEN) {
16938
+ sendAfterClose(this, data, cb);
16939
+ return;
16940
+ }
16941
+ const opts = {
16942
+ binary: typeof data !== "string",
16943
+ mask: !this._isServer,
16944
+ compress: true,
16945
+ fin: true,
16946
+ ...options
16947
+ };
16948
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
16949
+ opts.compress = false;
16950
+ }
16951
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
16952
+ }
16953
+ /**
16954
+ * Forcibly close the connection.
16955
+ *
16956
+ * @public
16957
+ */
16958
+ terminate() {
16959
+ if (this.readyState === _WebSocket.CLOSED) return;
16960
+ if (this.readyState === _WebSocket.CONNECTING) {
16961
+ const msg = "WebSocket was closed before the connection was established";
16962
+ abortHandshake(this, this._req, msg);
16963
+ return;
16964
+ }
16965
+ if (this._socket) {
16966
+ this._readyState = _WebSocket.CLOSING;
16967
+ this._socket.destroy();
16968
+ }
16969
+ }
16970
+ };
16971
+ Object.defineProperty(WebSocket2, "CONNECTING", {
16972
+ enumerable: true,
16973
+ value: readyStates.indexOf("CONNECTING")
16974
+ });
16975
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
16976
+ enumerable: true,
16977
+ value: readyStates.indexOf("CONNECTING")
16978
+ });
16979
+ Object.defineProperty(WebSocket2, "OPEN", {
16980
+ enumerable: true,
16981
+ value: readyStates.indexOf("OPEN")
16982
+ });
16983
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
16984
+ enumerable: true,
16985
+ value: readyStates.indexOf("OPEN")
16986
+ });
16987
+ Object.defineProperty(WebSocket2, "CLOSING", {
16988
+ enumerable: true,
16989
+ value: readyStates.indexOf("CLOSING")
16990
+ });
16991
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
16992
+ enumerable: true,
16993
+ value: readyStates.indexOf("CLOSING")
16994
+ });
16995
+ Object.defineProperty(WebSocket2, "CLOSED", {
16996
+ enumerable: true,
16997
+ value: readyStates.indexOf("CLOSED")
16998
+ });
16999
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
17000
+ enumerable: true,
17001
+ value: readyStates.indexOf("CLOSED")
17002
+ });
17003
+ [
17004
+ "binaryType",
17005
+ "bufferedAmount",
17006
+ "extensions",
17007
+ "isPaused",
17008
+ "protocol",
17009
+ "readyState",
17010
+ "url"
17011
+ ].forEach((property) => {
17012
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
17013
+ });
17014
+ ["open", "error", "close", "message"].forEach((method) => {
17015
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
17016
+ enumerable: true,
17017
+ get() {
17018
+ for (const listener of this.listeners(method)) {
17019
+ if (listener[kForOnEventAttribute]) return listener[kListener];
17020
+ }
17021
+ return null;
17022
+ },
17023
+ set(handler2) {
17024
+ for (const listener of this.listeners(method)) {
17025
+ if (listener[kForOnEventAttribute]) {
17026
+ this.removeListener(method, listener);
17027
+ break;
17028
+ }
17029
+ }
17030
+ if (typeof handler2 !== "function") return;
17031
+ this.addEventListener(method, handler2, {
17032
+ [kForOnEventAttribute]: true
17033
+ });
17034
+ }
17035
+ });
17036
+ });
17037
+ WebSocket2.prototype.addEventListener = addEventListener2;
17038
+ WebSocket2.prototype.removeEventListener = removeEventListener;
17039
+ module2.exports = WebSocket2;
17040
+ function initAsClient(websocket, address, protocols, options) {
17041
+ const opts = {
17042
+ allowSynchronousEvents: true,
17043
+ autoPong: true,
17044
+ closeTimeout: CLOSE_TIMEOUT,
17045
+ protocolVersion: protocolVersions[1],
17046
+ maxPayload: 100 * 1024 * 1024,
17047
+ skipUTF8Validation: false,
17048
+ perMessageDeflate: true,
17049
+ followRedirects: false,
17050
+ maxRedirects: 10,
17051
+ ...options,
17052
+ socketPath: void 0,
17053
+ hostname: void 0,
17054
+ protocol: void 0,
17055
+ timeout: void 0,
17056
+ method: "GET",
17057
+ host: void 0,
17058
+ path: void 0,
17059
+ port: void 0
17060
+ };
17061
+ websocket._autoPong = opts.autoPong;
17062
+ websocket._closeTimeout = opts.closeTimeout;
17063
+ if (!protocolVersions.includes(opts.protocolVersion)) {
17064
+ throw new RangeError(
17065
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
17066
+ );
17067
+ }
17068
+ let parsedUrl;
17069
+ if (address instanceof URL2) {
17070
+ parsedUrl = address;
17071
+ } else {
17072
+ try {
17073
+ parsedUrl = new URL2(address);
17074
+ } catch {
17075
+ throw new SyntaxError(`Invalid URL: ${address}`);
17076
+ }
17077
+ }
17078
+ if (parsedUrl.protocol === "http:") {
17079
+ parsedUrl.protocol = "ws:";
17080
+ } else if (parsedUrl.protocol === "https:") {
17081
+ parsedUrl.protocol = "wss:";
17082
+ }
17083
+ websocket._url = parsedUrl.href;
17084
+ const isSecure = parsedUrl.protocol === "wss:";
17085
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
17086
+ let invalidUrlMessage;
17087
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
17088
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
17089
+ } else if (isIpcUrl && !parsedUrl.pathname) {
17090
+ invalidUrlMessage = "The URL's pathname is empty";
17091
+ } else if (parsedUrl.hash) {
17092
+ invalidUrlMessage = "The URL contains a fragment identifier";
17093
+ }
17094
+ if (invalidUrlMessage) {
17095
+ const err2 = new SyntaxError(invalidUrlMessage);
17096
+ if (websocket._redirects === 0) {
17097
+ throw err2;
17098
+ } else {
17099
+ emitErrorAndClose(websocket, err2);
17100
+ return;
17101
+ }
17102
+ }
17103
+ const defaultPort = isSecure ? 443 : 80;
17104
+ const key = randomBytes(16).toString("base64");
17105
+ const request = isSecure ? https.request : http.request;
17106
+ const protocolSet = /* @__PURE__ */ new Set();
17107
+ let perMessageDeflate;
17108
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
17109
+ opts.defaultPort = opts.defaultPort || defaultPort;
17110
+ opts.port = parsedUrl.port || defaultPort;
17111
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
17112
+ opts.headers = {
17113
+ ...opts.headers,
17114
+ "Sec-WebSocket-Version": opts.protocolVersion,
17115
+ "Sec-WebSocket-Key": key,
17116
+ Connection: "Upgrade",
17117
+ Upgrade: "websocket"
17118
+ };
17119
+ opts.path = parsedUrl.pathname + parsedUrl.search;
17120
+ opts.timeout = opts.handshakeTimeout;
17121
+ if (opts.perMessageDeflate) {
17122
+ perMessageDeflate = new PerMessageDeflate2({
17123
+ ...opts.perMessageDeflate,
17124
+ isServer: false,
17125
+ maxPayload: opts.maxPayload
17126
+ });
17127
+ opts.headers["Sec-WebSocket-Extensions"] = format({
17128
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
17129
+ });
17130
+ }
17131
+ if (protocols.length) {
17132
+ for (const protocol of protocols) {
17133
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
17134
+ throw new SyntaxError(
17135
+ "An invalid or duplicated subprotocol was specified"
17136
+ );
17137
+ }
17138
+ protocolSet.add(protocol);
17139
+ }
17140
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
17141
+ }
17142
+ if (opts.origin) {
17143
+ if (opts.protocolVersion < 13) {
17144
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
17145
+ } else {
17146
+ opts.headers.Origin = opts.origin;
17147
+ }
17148
+ }
17149
+ if (parsedUrl.username || parsedUrl.password) {
17150
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
17151
+ }
17152
+ if (isIpcUrl) {
17153
+ const parts2 = opts.path.split(":");
17154
+ opts.socketPath = parts2[0];
17155
+ opts.path = parts2[1];
17156
+ }
17157
+ let req;
17158
+ if (opts.followRedirects) {
17159
+ if (websocket._redirects === 0) {
17160
+ websocket._originalIpc = isIpcUrl;
17161
+ websocket._originalSecure = isSecure;
17162
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
17163
+ const headers = options && options.headers;
17164
+ options = { ...options, headers: {} };
17165
+ if (headers) {
17166
+ for (const [key2, value2] of Object.entries(headers)) {
17167
+ options.headers[key2.toLowerCase()] = value2;
17168
+ }
17169
+ }
17170
+ } else if (websocket.listenerCount("redirect") === 0) {
17171
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
17172
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
17173
+ delete opts.headers.authorization;
17174
+ delete opts.headers.cookie;
17175
+ if (!isSameHost) delete opts.headers.host;
17176
+ opts.auth = void 0;
17177
+ }
17178
+ }
17179
+ if (opts.auth && !options.headers.authorization) {
17180
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
17181
+ }
17182
+ req = websocket._req = request(opts);
17183
+ if (websocket._redirects) {
17184
+ websocket.emit("redirect", websocket.url, req);
17185
+ }
17186
+ } else {
17187
+ req = websocket._req = request(opts);
17188
+ }
17189
+ if (opts.timeout) {
17190
+ req.on("timeout", () => {
17191
+ abortHandshake(websocket, req, "Opening handshake has timed out");
17192
+ });
17193
+ }
17194
+ req.on("error", (err2) => {
17195
+ if (req === null || req[kAborted]) return;
17196
+ req = websocket._req = null;
17197
+ emitErrorAndClose(websocket, err2);
17198
+ });
17199
+ req.on("response", (res) => {
17200
+ const location = res.headers.location;
17201
+ const statusCode = res.statusCode;
17202
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
17203
+ if (++websocket._redirects > opts.maxRedirects) {
17204
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
17205
+ return;
17206
+ }
17207
+ req.abort();
17208
+ let addr2;
17209
+ try {
17210
+ addr2 = new URL2(location, address);
17211
+ } catch (e) {
17212
+ const err2 = new SyntaxError(`Invalid URL: ${location}`);
17213
+ emitErrorAndClose(websocket, err2);
17214
+ return;
17215
+ }
17216
+ initAsClient(websocket, addr2, protocols, options);
17217
+ } else if (!websocket.emit("unexpected-response", req, res)) {
17218
+ abortHandshake(
17219
+ websocket,
17220
+ req,
17221
+ `Unexpected server response: ${res.statusCode}`
17222
+ );
17223
+ }
17224
+ });
17225
+ req.on("upgrade", (res, socket, head) => {
17226
+ websocket.emit("upgrade", res);
17227
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
17228
+ req = websocket._req = null;
17229
+ const upgrade = res.headers.upgrade;
17230
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
17231
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
17232
+ return;
17233
+ }
17234
+ const digest = createHash5("sha1").update(key + GUID).digest("base64");
17235
+ if (res.headers["sec-websocket-accept"] !== digest) {
17236
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
17237
+ return;
17238
+ }
17239
+ const serverProt = res.headers["sec-websocket-protocol"];
17240
+ let protError;
17241
+ if (serverProt !== void 0) {
17242
+ if (!protocolSet.size) {
17243
+ protError = "Server sent a subprotocol but none was requested";
17244
+ } else if (!protocolSet.has(serverProt)) {
17245
+ protError = "Server sent an invalid subprotocol";
17246
+ }
17247
+ } else if (protocolSet.size) {
17248
+ protError = "Server sent no subprotocol";
17249
+ }
17250
+ if (protError) {
17251
+ abortHandshake(websocket, socket, protError);
17252
+ return;
17253
+ }
17254
+ if (serverProt) websocket._protocol = serverProt;
17255
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
17256
+ if (secWebSocketExtensions !== void 0) {
17257
+ if (!perMessageDeflate) {
17258
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
17259
+ abortHandshake(websocket, socket, message);
17260
+ return;
17261
+ }
17262
+ let extensions;
17263
+ try {
17264
+ extensions = parse4(secWebSocketExtensions);
17265
+ } catch (err2) {
17266
+ const message = "Invalid Sec-WebSocket-Extensions header";
17267
+ abortHandshake(websocket, socket, message);
17268
+ return;
17269
+ }
17270
+ const extensionNames = Object.keys(extensions);
17271
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
17272
+ const message = "Server indicated an extension that was not requested";
17273
+ abortHandshake(websocket, socket, message);
17274
+ return;
17275
+ }
17276
+ try {
17277
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
17278
+ } catch (err2) {
17279
+ const message = "Invalid Sec-WebSocket-Extensions header";
17280
+ abortHandshake(websocket, socket, message);
17281
+ return;
17282
+ }
17283
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
17284
+ }
17285
+ websocket.setSocket(socket, head, {
17286
+ allowSynchronousEvents: opts.allowSynchronousEvents,
17287
+ generateMask: opts.generateMask,
17288
+ maxPayload: opts.maxPayload,
17289
+ skipUTF8Validation: opts.skipUTF8Validation
17290
+ });
17291
+ });
17292
+ if (opts.finishRequest) {
17293
+ opts.finishRequest(req, websocket);
17294
+ } else {
17295
+ req.end();
17296
+ }
17297
+ }
17298
+ function emitErrorAndClose(websocket, err2) {
17299
+ websocket._readyState = WebSocket2.CLOSING;
17300
+ websocket._errorEmitted = true;
17301
+ websocket.emit("error", err2);
17302
+ websocket.emitClose();
17303
+ }
17304
+ function netConnect(options) {
17305
+ options.path = options.socketPath;
17306
+ return net.connect(options);
17307
+ }
17308
+ function tlsConnect(options) {
17309
+ options.path = void 0;
17310
+ if (!options.servername && options.servername !== "") {
17311
+ options.servername = net.isIP(options.host) ? "" : options.host;
17312
+ }
17313
+ return tls.connect(options);
17314
+ }
17315
+ function abortHandshake(websocket, stream, message) {
17316
+ websocket._readyState = WebSocket2.CLOSING;
17317
+ const err2 = new Error(message);
17318
+ Error.captureStackTrace(err2, abortHandshake);
17319
+ if (stream.setHeader) {
17320
+ stream[kAborted] = true;
17321
+ stream.abort();
17322
+ if (stream.socket && !stream.socket.destroyed) {
17323
+ stream.socket.destroy();
17324
+ }
17325
+ process.nextTick(emitErrorAndClose, websocket, err2);
17326
+ } else {
17327
+ stream.destroy(err2);
17328
+ stream.once("error", websocket.emit.bind(websocket, "error"));
17329
+ stream.once("close", websocket.emitClose.bind(websocket));
17330
+ }
17331
+ }
17332
+ function sendAfterClose(websocket, data, cb) {
17333
+ if (data) {
17334
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
17335
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
17336
+ else websocket._bufferedAmount += length;
17337
+ }
17338
+ if (cb) {
17339
+ const err2 = new Error(
17340
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
17341
+ );
17342
+ process.nextTick(cb, err2);
17343
+ }
17344
+ }
17345
+ function receiverOnConclude(code, reason) {
17346
+ const websocket = this[kWebSocket];
17347
+ websocket._closeFrameReceived = true;
17348
+ websocket._closeMessage = reason;
17349
+ websocket._closeCode = code;
17350
+ if (websocket._socket[kWebSocket] === void 0) return;
17351
+ websocket._socket.removeListener("data", socketOnData);
17352
+ process.nextTick(resume, websocket._socket);
17353
+ if (code === 1005) websocket.close();
17354
+ else websocket.close(code, reason);
17355
+ }
17356
+ function receiverOnDrain() {
17357
+ const websocket = this[kWebSocket];
17358
+ if (!websocket.isPaused) websocket._socket.resume();
17359
+ }
17360
+ function receiverOnError(err2) {
17361
+ const websocket = this[kWebSocket];
17362
+ if (websocket._socket[kWebSocket] !== void 0) {
17363
+ websocket._socket.removeListener("data", socketOnData);
17364
+ process.nextTick(resume, websocket._socket);
17365
+ websocket.close(err2[kStatusCode]);
17366
+ }
17367
+ if (!websocket._errorEmitted) {
17368
+ websocket._errorEmitted = true;
17369
+ websocket.emit("error", err2);
17370
+ }
17371
+ }
17372
+ function receiverOnFinish() {
17373
+ this[kWebSocket].emitClose();
17374
+ }
17375
+ function receiverOnMessage(data, isBinary) {
17376
+ this[kWebSocket].emit("message", data, isBinary);
17377
+ }
17378
+ function receiverOnPing(data) {
17379
+ const websocket = this[kWebSocket];
17380
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
17381
+ websocket.emit("ping", data);
17382
+ }
17383
+ function receiverOnPong(data) {
17384
+ this[kWebSocket].emit("pong", data);
17385
+ }
17386
+ function resume(stream) {
17387
+ stream.resume();
17388
+ }
17389
+ function senderOnError(err2) {
17390
+ const websocket = this[kWebSocket];
17391
+ if (websocket.readyState === WebSocket2.CLOSED) return;
17392
+ if (websocket.readyState === WebSocket2.OPEN) {
17393
+ websocket._readyState = WebSocket2.CLOSING;
17394
+ setCloseTimer(websocket);
17395
+ }
17396
+ this._socket.end();
17397
+ if (!websocket._errorEmitted) {
17398
+ websocket._errorEmitted = true;
17399
+ websocket.emit("error", err2);
17400
+ }
17401
+ }
17402
+ function setCloseTimer(websocket) {
17403
+ websocket._closeTimer = setTimeout(
17404
+ websocket._socket.destroy.bind(websocket._socket),
17405
+ websocket._closeTimeout
17406
+ );
17407
+ }
17408
+ function socketOnClose() {
17409
+ const websocket = this[kWebSocket];
17410
+ this.removeListener("close", socketOnClose);
17411
+ this.removeListener("data", socketOnData);
17412
+ this.removeListener("end", socketOnEnd);
17413
+ websocket._readyState = WebSocket2.CLOSING;
17414
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
17415
+ const chunk = this.read(this._readableState.length);
17416
+ websocket._receiver.write(chunk);
17417
+ }
17418
+ websocket._receiver.end();
17419
+ this[kWebSocket] = void 0;
17420
+ clearTimeout(websocket._closeTimer);
17421
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
17422
+ websocket.emitClose();
17423
+ } else {
17424
+ websocket._receiver.on("error", receiverOnFinish);
17425
+ websocket._receiver.on("finish", receiverOnFinish);
17426
+ }
17427
+ }
17428
+ function socketOnData(chunk) {
17429
+ if (!this[kWebSocket]._receiver.write(chunk)) {
17430
+ this.pause();
17431
+ }
17432
+ }
17433
+ function socketOnEnd() {
17434
+ const websocket = this[kWebSocket];
17435
+ websocket._readyState = WebSocket2.CLOSING;
17436
+ websocket._receiver.end();
17437
+ this.end();
17438
+ }
17439
+ function socketOnError() {
17440
+ const websocket = this[kWebSocket];
17441
+ this.removeListener("error", socketOnError);
17442
+ this.on("error", NOOP);
17443
+ if (websocket) {
17444
+ websocket._readyState = WebSocket2.CLOSING;
17445
+ this.destroy();
17446
+ }
17447
+ }
17448
+ }
17449
+ });
17450
+
17451
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js
17452
+ var require_stream = __commonJS({
17453
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js"(exports2, module2) {
17454
+ "use strict";
17455
+ var WebSocket2 = require_websocket();
17456
+ var { Duplex } = require("stream");
17457
+ function emitClose(stream) {
17458
+ stream.emit("close");
17459
+ }
17460
+ function duplexOnEnd() {
17461
+ if (!this.destroyed && this._writableState.finished) {
17462
+ this.destroy();
17463
+ }
17464
+ }
17465
+ function duplexOnError(err2) {
17466
+ this.removeListener("error", duplexOnError);
17467
+ this.destroy();
17468
+ if (this.listenerCount("error") === 0) {
17469
+ this.emit("error", err2);
17470
+ }
17471
+ }
17472
+ function createWebSocketStream2(ws, options) {
17473
+ let terminateOnDestroy = true;
17474
+ const duplex = new Duplex({
17475
+ ...options,
17476
+ autoDestroy: false,
17477
+ emitClose: false,
17478
+ objectMode: false,
17479
+ writableObjectMode: false
17480
+ });
17481
+ ws.on("message", function message(msg, isBinary) {
17482
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
17483
+ if (!duplex.push(data)) ws.pause();
17484
+ });
17485
+ ws.once("error", function error48(err2) {
17486
+ if (duplex.destroyed) return;
17487
+ terminateOnDestroy = false;
17488
+ duplex.destroy(err2);
17489
+ });
17490
+ ws.once("close", function close2() {
17491
+ if (duplex.destroyed) return;
17492
+ duplex.push(null);
17493
+ });
17494
+ duplex._destroy = function(err2, callback) {
17495
+ if (ws.readyState === ws.CLOSED) {
17496
+ callback(err2);
17497
+ process.nextTick(emitClose, duplex);
17498
+ return;
17499
+ }
17500
+ let called = false;
17501
+ ws.once("error", function error48(err3) {
17502
+ called = true;
17503
+ callback(err3);
17504
+ });
17505
+ ws.once("close", function close2() {
17506
+ if (!called) callback(err2);
17507
+ process.nextTick(emitClose, duplex);
17508
+ });
17509
+ if (terminateOnDestroy) ws.terminate();
17510
+ };
17511
+ duplex._final = function(callback) {
17512
+ if (ws.readyState === ws.CONNECTING) {
17513
+ ws.once("open", function open() {
17514
+ duplex._final(callback);
17515
+ });
17516
+ return;
17517
+ }
17518
+ if (ws._socket === null) return;
17519
+ if (ws._socket._writableState.finished) {
17520
+ callback();
17521
+ if (duplex._readableState.endEmitted) duplex.destroy();
17522
+ } else {
17523
+ ws._socket.once("finish", function finish() {
17524
+ callback();
17525
+ });
17526
+ ws.close();
17527
+ }
17528
+ };
17529
+ duplex._read = function() {
17530
+ if (ws.isPaused) ws.resume();
17531
+ };
17532
+ duplex._write = function(chunk, encoding, callback) {
17533
+ if (ws.readyState === ws.CONNECTING) {
17534
+ ws.once("open", function open() {
17535
+ duplex._write(chunk, encoding, callback);
17536
+ });
17537
+ return;
17538
+ }
17539
+ ws.send(chunk, callback);
17540
+ };
17541
+ duplex.on("end", duplexOnEnd);
17542
+ duplex.on("error", duplexOnError);
17543
+ return duplex;
17544
+ }
17545
+ module2.exports = createWebSocketStream2;
17546
+ }
17547
+ });
17548
+
17549
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js
17550
+ var require_subprotocol = __commonJS({
17551
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js"(exports2, module2) {
17552
+ "use strict";
17553
+ var { tokenChars } = require_validation();
17554
+ function parse4(header) {
17555
+ const protocols = /* @__PURE__ */ new Set();
17556
+ let start2 = -1;
17557
+ let end = -1;
17558
+ let i2 = 0;
17559
+ for (i2; i2 < header.length; i2++) {
17560
+ const code = header.charCodeAt(i2);
17561
+ if (end === -1 && tokenChars[code] === 1) {
17562
+ if (start2 === -1) start2 = i2;
17563
+ } else if (i2 !== 0 && (code === 32 || code === 9)) {
17564
+ if (end === -1 && start2 !== -1) end = i2;
17565
+ } else if (code === 44) {
17566
+ if (start2 === -1) {
17567
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
17568
+ }
17569
+ if (end === -1) end = i2;
17570
+ const protocol2 = header.slice(start2, end);
17571
+ if (protocols.has(protocol2)) {
17572
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
17573
+ }
17574
+ protocols.add(protocol2);
17575
+ start2 = end = -1;
17576
+ } else {
17577
+ throw new SyntaxError(`Unexpected character at index ${i2}`);
17578
+ }
17579
+ }
17580
+ if (start2 === -1 || end !== -1) {
17581
+ throw new SyntaxError("Unexpected end of input");
17582
+ }
17583
+ const protocol = header.slice(start2, i2);
17584
+ if (protocols.has(protocol)) {
17585
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
17586
+ }
17587
+ protocols.add(protocol);
17588
+ return protocols;
17589
+ }
17590
+ module2.exports = { parse: parse4 };
17591
+ }
17592
+ });
17593
+
17594
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js
17595
+ var require_websocket_server = __commonJS({
17596
+ "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js"(exports2, module2) {
17597
+ "use strict";
17598
+ var EventEmitter = require("events");
17599
+ var http = require("http");
17600
+ var { Duplex } = require("stream");
17601
+ var { createHash: createHash5 } = require("crypto");
17602
+ var extension3 = require_extension();
17603
+ var PerMessageDeflate2 = require_permessage_deflate();
17604
+ var subprotocol2 = require_subprotocol();
17605
+ var WebSocket2 = require_websocket();
17606
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
17607
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
17608
+ var RUNNING = 0;
17609
+ var CLOSING = 1;
17610
+ var CLOSED = 2;
17611
+ var WebSocketServer2 = class extends EventEmitter {
17612
+ /**
17613
+ * Create a `WebSocketServer` instance.
17614
+ *
17615
+ * @param {Object} options Configuration options
17616
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
17617
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
17618
+ * multiple times in the same tick
17619
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
17620
+ * automatically send a pong in response to a ping
17621
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
17622
+ * pending connections
17623
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
17624
+ * track clients
17625
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
17626
+ * wait for the closing handshake to finish after `websocket.close()` is
17627
+ * called
17628
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
17629
+ * @param {String} [options.host] The hostname where to bind the server
17630
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
17631
+ * size
17632
+ * @param {Boolean} [options.noServer=false] Enable no server mode
17633
+ * @param {String} [options.path] Accept only connections matching this path
17634
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
17635
+ * permessage-deflate
17636
+ * @param {Number} [options.port] The port where to bind the server
17637
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
17638
+ * server to use
17639
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
17640
+ * not to skip UTF-8 validation for text and close messages
17641
+ * @param {Function} [options.verifyClient] A hook to reject connections
17642
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
17643
+ * class to use. It must be the `WebSocket` class or class that extends it
17644
+ * @param {Function} [callback] A listener for the `listening` event
17645
+ */
17646
+ constructor(options, callback) {
17647
+ super();
17648
+ options = {
17649
+ allowSynchronousEvents: true,
17650
+ autoPong: true,
17651
+ maxPayload: 100 * 1024 * 1024,
17652
+ skipUTF8Validation: false,
17653
+ perMessageDeflate: false,
17654
+ handleProtocols: null,
17655
+ clientTracking: true,
17656
+ closeTimeout: CLOSE_TIMEOUT,
17657
+ verifyClient: null,
17658
+ noServer: false,
17659
+ backlog: null,
17660
+ // use default (511 as implemented in net.js)
17661
+ server: null,
17662
+ host: null,
17663
+ path: null,
17664
+ port: null,
17665
+ WebSocket: WebSocket2,
17666
+ ...options
17667
+ };
17668
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
17669
+ throw new TypeError(
17670
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
17671
+ );
17672
+ }
17673
+ if (options.port != null) {
17674
+ this._server = http.createServer((req, res) => {
17675
+ const body2 = http.STATUS_CODES[426];
17676
+ res.writeHead(426, {
17677
+ "Content-Length": body2.length,
17678
+ "Content-Type": "text/plain"
17679
+ });
17680
+ res.end(body2);
17681
+ });
17682
+ this._server.listen(
17683
+ options.port,
17684
+ options.host,
17685
+ options.backlog,
17686
+ callback
17687
+ );
17688
+ } else if (options.server) {
17689
+ this._server = options.server;
17690
+ }
17691
+ if (this._server) {
17692
+ const emitConnection = this.emit.bind(this, "connection");
17693
+ this._removeListeners = addListeners(this._server, {
17694
+ listening: this.emit.bind(this, "listening"),
17695
+ error: this.emit.bind(this, "error"),
17696
+ upgrade: (req, socket, head) => {
17697
+ this.handleUpgrade(req, socket, head, emitConnection);
17698
+ }
17699
+ });
17700
+ }
17701
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
17702
+ if (options.clientTracking) {
17703
+ this.clients = /* @__PURE__ */ new Set();
17704
+ this._shouldEmitClose = false;
17705
+ }
17706
+ this.options = options;
17707
+ this._state = RUNNING;
17708
+ }
17709
+ /**
17710
+ * Returns the bound address, the address family name, and port of the server
17711
+ * as reported by the operating system if listening on an IP socket.
17712
+ * If the server is listening on a pipe or UNIX domain socket, the name is
17713
+ * returned as a string.
17714
+ *
17715
+ * @return {(Object|String|null)} The address of the server
17716
+ * @public
17717
+ */
17718
+ address() {
17719
+ if (this.options.noServer) {
17720
+ throw new Error('The server is operating in "noServer" mode');
17721
+ }
17722
+ if (!this._server) return null;
17723
+ return this._server.address();
17724
+ }
17725
+ /**
17726
+ * Stop the server from accepting new connections and emit the `'close'` event
17727
+ * when all existing connections are closed.
17728
+ *
17729
+ * @param {Function} [cb] A one-time listener for the `'close'` event
17730
+ * @public
17731
+ */
17732
+ close(cb) {
17733
+ if (this._state === CLOSED) {
17734
+ if (cb) {
17735
+ this.once("close", () => {
17736
+ cb(new Error("The server is not running"));
17737
+ });
17738
+ }
17739
+ process.nextTick(emitClose, this);
17740
+ return;
17741
+ }
17742
+ if (cb) this.once("close", cb);
17743
+ if (this._state === CLOSING) return;
17744
+ this._state = CLOSING;
17745
+ if (this.options.noServer || this.options.server) {
17746
+ if (this._server) {
17747
+ this._removeListeners();
17748
+ this._removeListeners = this._server = null;
17749
+ }
17750
+ if (this.clients) {
17751
+ if (!this.clients.size) {
17752
+ process.nextTick(emitClose, this);
17753
+ } else {
17754
+ this._shouldEmitClose = true;
17755
+ }
17756
+ } else {
17757
+ process.nextTick(emitClose, this);
17758
+ }
17759
+ } else {
17760
+ const server = this._server;
17761
+ this._removeListeners();
17762
+ this._removeListeners = this._server = null;
17763
+ server.close(() => {
17764
+ emitClose(this);
17765
+ });
17766
+ }
17767
+ }
17768
+ /**
17769
+ * See if a given request should be handled by this server instance.
17770
+ *
17771
+ * @param {http.IncomingMessage} req Request object to inspect
17772
+ * @return {Boolean} `true` if the request is valid, else `false`
17773
+ * @public
17774
+ */
17775
+ shouldHandle(req) {
17776
+ if (this.options.path) {
17777
+ const index2 = req.url.indexOf("?");
17778
+ const pathname = index2 !== -1 ? req.url.slice(0, index2) : req.url;
17779
+ if (pathname !== this.options.path) return false;
17780
+ }
17781
+ return true;
17782
+ }
17783
+ /**
17784
+ * Handle a HTTP Upgrade request.
17785
+ *
17786
+ * @param {http.IncomingMessage} req The request object
17787
+ * @param {Duplex} socket The network socket between the server and client
17788
+ * @param {Buffer} head The first packet of the upgraded stream
17789
+ * @param {Function} cb Callback
17790
+ * @public
17791
+ */
17792
+ handleUpgrade(req, socket, head, cb) {
17793
+ socket.on("error", socketOnError);
17794
+ const key = req.headers["sec-websocket-key"];
17795
+ const upgrade = req.headers.upgrade;
17796
+ const version2 = +req.headers["sec-websocket-version"];
17797
+ if (req.method !== "GET") {
17798
+ const message = "Invalid HTTP method";
17799
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
17800
+ return;
17801
+ }
17802
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
17803
+ const message = "Invalid Upgrade header";
17804
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
17805
+ return;
17806
+ }
17807
+ if (key === void 0 || !keyRegex.test(key)) {
17808
+ const message = "Missing or invalid Sec-WebSocket-Key header";
17809
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
17810
+ return;
17811
+ }
17812
+ if (version2 !== 13 && version2 !== 8) {
17813
+ const message = "Missing or invalid Sec-WebSocket-Version header";
17814
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
17815
+ "Sec-WebSocket-Version": "13, 8"
17816
+ });
17817
+ return;
17818
+ }
17819
+ if (!this.shouldHandle(req)) {
17820
+ abortHandshake(socket, 400);
17821
+ return;
17822
+ }
17823
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
17824
+ let protocols = /* @__PURE__ */ new Set();
17825
+ if (secWebSocketProtocol !== void 0) {
17826
+ try {
17827
+ protocols = subprotocol2.parse(secWebSocketProtocol);
17828
+ } catch (err2) {
17829
+ const message = "Invalid Sec-WebSocket-Protocol header";
17830
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
17831
+ return;
17832
+ }
17833
+ }
17834
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
17835
+ const extensions = {};
17836
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
17837
+ const perMessageDeflate = new PerMessageDeflate2({
17838
+ ...this.options.perMessageDeflate,
17839
+ isServer: true,
17840
+ maxPayload: this.options.maxPayload
17841
+ });
17842
+ try {
17843
+ const offers = extension3.parse(secWebSocketExtensions);
17844
+ if (offers[PerMessageDeflate2.extensionName]) {
17845
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
17846
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
17847
+ }
17848
+ } catch (err2) {
17849
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
17850
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
17851
+ return;
17852
+ }
17853
+ }
17854
+ if (this.options.verifyClient) {
17855
+ const info2 = {
17856
+ origin: req.headers[`${version2 === 8 ? "sec-websocket-origin" : "origin"}`],
17857
+ secure: !!(req.socket.authorized || req.socket.encrypted),
17858
+ req
17859
+ };
17860
+ if (this.options.verifyClient.length === 2) {
17861
+ this.options.verifyClient(info2, (verified, code, message, headers) => {
17862
+ if (!verified) {
17863
+ return abortHandshake(socket, code || 401, message, headers);
17864
+ }
17865
+ this.completeUpgrade(
17866
+ extensions,
17867
+ key,
17868
+ protocols,
17869
+ req,
17870
+ socket,
17871
+ head,
17872
+ cb
17873
+ );
17874
+ });
17875
+ return;
17876
+ }
17877
+ if (!this.options.verifyClient(info2)) return abortHandshake(socket, 401);
17878
+ }
17879
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
17880
+ }
17881
+ /**
17882
+ * Upgrade the connection to WebSocket.
17883
+ *
17884
+ * @param {Object} extensions The accepted extensions
17885
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
17886
+ * @param {Set} protocols The subprotocols
17887
+ * @param {http.IncomingMessage} req The request object
17888
+ * @param {Duplex} socket The network socket between the server and client
17889
+ * @param {Buffer} head The first packet of the upgraded stream
17890
+ * @param {Function} cb Callback
17891
+ * @throws {Error} If called more than once with the same socket
17892
+ * @private
17893
+ */
17894
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
17895
+ if (!socket.readable || !socket.writable) return socket.destroy();
17896
+ if (socket[kWebSocket]) {
17897
+ throw new Error(
17898
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
17899
+ );
17900
+ }
17901
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
17902
+ const digest = createHash5("sha1").update(key + GUID).digest("base64");
17903
+ const headers = [
17904
+ "HTTP/1.1 101 Switching Protocols",
17905
+ "Upgrade: websocket",
17906
+ "Connection: Upgrade",
17907
+ `Sec-WebSocket-Accept: ${digest}`
17908
+ ];
17909
+ const ws = new this.options.WebSocket(null, void 0, this.options);
17910
+ if (protocols.size) {
17911
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
17912
+ if (protocol) {
17913
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
17914
+ ws._protocol = protocol;
17915
+ }
17916
+ }
17917
+ if (extensions[PerMessageDeflate2.extensionName]) {
17918
+ const params = extensions[PerMessageDeflate2.extensionName].params;
17919
+ const value2 = extension3.format({
17920
+ [PerMessageDeflate2.extensionName]: [params]
17921
+ });
17922
+ headers.push(`Sec-WebSocket-Extensions: ${value2}`);
17923
+ ws._extensions = extensions;
17924
+ }
17925
+ this.emit("headers", headers, req);
17926
+ socket.write(headers.concat("\r\n").join("\r\n"));
17927
+ socket.removeListener("error", socketOnError);
17928
+ ws.setSocket(socket, head, {
17929
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
17930
+ maxPayload: this.options.maxPayload,
17931
+ skipUTF8Validation: this.options.skipUTF8Validation
17932
+ });
17933
+ if (this.clients) {
17934
+ this.clients.add(ws);
17935
+ ws.on("close", () => {
17936
+ this.clients.delete(ws);
17937
+ if (this._shouldEmitClose && !this.clients.size) {
17938
+ process.nextTick(emitClose, this);
17939
+ }
17940
+ });
17941
+ }
17942
+ cb(ws, req);
17943
+ }
17944
+ };
17945
+ module2.exports = WebSocketServer2;
17946
+ function addListeners(server, map2) {
17947
+ for (const event of Object.keys(map2)) server.on(event, map2[event]);
17948
+ return function removeListeners() {
17949
+ for (const event of Object.keys(map2)) {
17950
+ server.removeListener(event, map2[event]);
17951
+ }
17952
+ };
17953
+ }
17954
+ function emitClose(server) {
17955
+ server._state = CLOSED;
17956
+ server.emit("close");
17957
+ }
17958
+ function socketOnError() {
17959
+ this.destroy();
17960
+ }
17961
+ function abortHandshake(socket, code, message, headers) {
17962
+ message = message || http.STATUS_CODES[code];
17963
+ headers = {
17964
+ Connection: "close",
17965
+ "Content-Type": "text/html",
17966
+ "Content-Length": Buffer.byteLength(message),
17967
+ ...headers
17968
+ };
17969
+ socket.once("finish", socket.destroy);
17970
+ socket.end(
17971
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
17972
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
17973
+ );
17974
+ }
17975
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
17976
+ if (server.listenerCount("wsClientError")) {
17977
+ const err2 = new Error(message);
17978
+ Error.captureStackTrace(err2, abortHandshakeOrEmitwsClientError);
17979
+ server.emit("wsClientError", err2, socket, req);
17980
+ } else {
17981
+ abortHandshake(socket, code, message, headers);
17982
+ }
17983
+ }
17984
+ }
17985
+ });
17986
+
14371
17987
  // ../../node_modules/.pnpm/@hono+node-server@1.19.13_hono@4.12.12/node_modules/@hono/node-server/dist/index.mjs
14372
17988
  var dist_exports = {};
14373
17989
  __export(dist_exports, {
@@ -14421,14 +18037,14 @@ function writeFromReadableStream(stream, writable) {
14421
18037
  }
14422
18038
  return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
14423
18039
  }
14424
- var import_http, import_http2, import_http22, import_stream, import_crypto, RequestError, toRequestError, GlobalRequest, Request2, newHeadersFromIncoming, wrapBodyStream, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, headersKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, outgoingEnded, incomingDraining, DRAIN_TIMEOUT_MS, MAX_DRAIN_BYTES, drainIncoming, handleRequestError, handleFetchError, handleResponseError, flushHeaders, responseViaCache, isPromise, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
18040
+ var import_http, import_http2, import_http22, import_stream2, import_crypto, RequestError, toRequestError, GlobalRequest, Request2, newHeadersFromIncoming, wrapBodyStream, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, headersKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, outgoingEnded, incomingDraining, DRAIN_TIMEOUT_MS, MAX_DRAIN_BYTES, drainIncoming, handleRequestError, handleFetchError, handleResponseError, flushHeaders, responseViaCache, isPromise, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
14425
18041
  var init_dist = __esm({
14426
18042
  "../../node_modules/.pnpm/@hono+node-server@1.19.13_hono@4.12.12/node_modules/@hono/node-server/dist/index.mjs"() {
14427
18043
  "use strict";
14428
18044
  import_http = require("http");
14429
18045
  import_http2 = require("http2");
14430
18046
  import_http22 = require("http2");
14431
- import_stream = require("stream");
18047
+ import_stream2 = require("stream");
14432
18048
  import_crypto = __toESM(require("crypto"), 1);
14433
18049
  RequestError = class extends Error {
14434
18050
  constructor(message, options) {
@@ -14497,7 +18113,7 @@ var init_dist = __esm({
14497
18113
  init2.body = new ReadableStream({
14498
18114
  async pull(controller) {
14499
18115
  try {
14500
- reader ||= import_stream.Readable.toWeb(incoming).getReader();
18116
+ reader ||= import_stream2.Readable.toWeb(incoming).getReader();
14501
18117
  const { done, value: value2 } = await reader.read();
14502
18118
  if (done) {
14503
18119
  controller.close();
@@ -14510,7 +18126,7 @@ var init_dist = __esm({
14510
18126
  }
14511
18127
  });
14512
18128
  } else {
14513
- init2.body = import_stream.Readable.toWeb(incoming);
18129
+ init2.body = import_stream2.Readable.toWeb(incoming);
14514
18130
  }
14515
18131
  }
14516
18132
  return new Request2(url2, init2);
@@ -15002,7 +18618,7 @@ var init_dist = __esm({
15002
18618
 
15003
18619
  // src/server/server-loader.ts
15004
18620
  var import_node_fs13 = require("node:fs");
15005
- var import_node_url2 = require("node:url");
18621
+ var import_node_url3 = require("node:url");
15006
18622
  var import_node_path23 = require("node:path");
15007
18623
  var import_picocolors2 = __toESM(require_picocolors());
15008
18624
 
@@ -34440,8 +38056,8 @@ var Module2 = (() => {
34440
38056
  var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string" && process.type != "renderer";
34441
38057
  var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
34442
38058
  if (ENVIRONMENT_IS_NODE) {
34443
- const { createRequire: createRequire2 } = await import("module");
34444
- var require = createRequire2(import_meta.url);
38059
+ const { createRequire: createRequire3 } = await import("module");
38060
+ var require = createRequire3(import_meta.url);
34445
38061
  }
34446
38062
  Module.currentQueryProgressCallback = null;
34447
38063
  Module.currentProgressCallback = null;
@@ -36344,8 +39960,8 @@ var grammarMap = {
36344
39960
  };
36345
39961
  var SOURCE_EXTENSIONS = new Set(Object.keys(grammarMap));
36346
39962
  function wasmDir() {
36347
- const require2 = (0, import_node_module.createRequire)(__filename);
36348
- const packageJsonPath = require2.resolve("@repomix/tree-sitter-wasms/package.json");
39963
+ const require3 = (0, import_node_module.createRequire)(__filename);
39964
+ const packageJsonPath = require3.resolve("@repomix/tree-sitter-wasms/package.json");
36349
39965
  return (0, import_node_path9.join)((0, import_node_path9.dirname)(packageJsonPath), "out");
36350
39966
  }
36351
39967
  async function ensureParser() {
@@ -36358,8 +39974,8 @@ async function ensureParser() {
36358
39974
  }
36359
39975
  return parserInstance;
36360
39976
  }
36361
- async function getLanguage(extension2) {
36362
- const wasmFile = grammarMap[extension2];
39977
+ async function getLanguage(extension3) {
39978
+ const wasmFile = grammarMap[extension3];
36363
39979
  if (!wasmFile) {
36364
39980
  return null;
36365
39981
  }
@@ -36991,8 +40607,8 @@ function extractCSymbols(tree) {
36991
40607
  return symbols;
36992
40608
  }
36993
40609
  async function parseSourceSymbols(filePath, content3) {
36994
- const extension2 = filePath.match(/\.[^.]+$/u)?.[0] || "";
36995
- const language = await getLanguage(extension2);
40610
+ const extension3 = filePath.match(/\.[^.]+$/u)?.[0] || "";
40611
+ const language = await getLanguage(extension3);
36996
40612
  if (!language) {
36997
40613
  return [];
36998
40614
  }
@@ -37003,16 +40619,16 @@ async function parseSourceSymbols(filePath, content3) {
37003
40619
  return [];
37004
40620
  }
37005
40621
  try {
37006
- if (extension2 === ".py") {
40622
+ if (extension3 === ".py") {
37007
40623
  return extractPySymbols(tree);
37008
40624
  }
37009
- if (extension2 === ".rs") {
40625
+ if (extension3 === ".rs") {
37010
40626
  return extractRustSymbols(tree);
37011
40627
  }
37012
- if (extension2 === ".go") {
40628
+ if (extension3 === ".go") {
37013
40629
  return extractGoSymbols(tree);
37014
40630
  }
37015
- if (extension2 === ".c" || extension2 === ".h") {
40631
+ if (extension3 === ".c" || extension3 === ".h") {
37016
40632
  return extractCSymbols(tree);
37017
40633
  }
37018
40634
  return extractTsSymbols(tree);
@@ -37106,8 +40722,8 @@ async function getKnowledgeSection(context, query) {
37106
40722
  }
37107
40723
  const hashIndex = ref.target.indexOf("#");
37108
40724
  const filePart = hashIndex === -1 ? ref.target : ref.target.slice(0, hashIndex);
37109
- const extension2 = (0, import_node_path10.extname)(filePart);
37110
- if (SOURCE_EXTENSIONS.has(extension2)) {
40725
+ const extension3 = (0, import_node_path10.extname)(filePart);
40726
+ if (SOURCE_EXTENSIONS.has(extension3)) {
37111
40727
  const key = ref.target.toLowerCase();
37112
40728
  if (seen.has(key)) {
37113
40729
  continue;
@@ -37835,10 +41451,10 @@ async function tryResolveSourceRef(target, projectRoot) {
37835
41451
  const hashIndex = target.indexOf("#");
37836
41452
  const filePart = hashIndex === -1 ? target : target.slice(0, hashIndex);
37837
41453
  const symbolPart = hashIndex === -1 ? "" : target.slice(hashIndex + 1);
37838
- const extension2 = (0, import_node_path13.extname)(filePart);
37839
- if (!SOURCE_EXTENSIONS.has(extension2)) {
37840
- if (extension2 && hashIndex !== -1) {
37841
- return `broken link [[${target}]] - unsupported file extension "${extension2}"`;
41454
+ const extension3 = (0, import_node_path13.extname)(filePart);
41455
+ if (!SOURCE_EXTENSIONS.has(extension3)) {
41456
+ if (extension3 && hashIndex !== -1) {
41457
+ return `broken link [[${target}]] - unsupported file extension "${extension3}"`;
37842
41458
  }
37843
41459
  return `broken link [[${target}]] - no matching section found`;
37844
41460
  }
@@ -38718,12 +42334,12 @@ var import_node_child_process2 = require("node:child_process");
38718
42334
  var import_node_fs11 = require("node:fs");
38719
42335
  var import_promises15 = __toESM(require("node:fs/promises"));
38720
42336
  var import_node_path19 = __toESM(require("node:path"));
38721
- function git(args2, cwd) {
38722
- return (0, import_node_child_process2.execFileSync)("git", args2, { cwd, encoding: "utf8", timeout: 15e3 }).trim();
42337
+ function git(args2, cwd, timeout = 15e3) {
42338
+ return (0, import_node_child_process2.execFileSync)("git", args2, { cwd, encoding: "utf8", timeout, stdio: ["pipe", "pipe", "pipe"] }).trim();
38723
42339
  }
38724
- function gitSafe(args2, cwd) {
42340
+ function gitSafe(args2, cwd, timeout) {
38725
42341
  try {
38726
- return git(args2, cwd);
42342
+ return git(args2, cwd, timeout);
38727
42343
  } catch {
38728
42344
  return null;
38729
42345
  }
@@ -38862,7 +42478,13 @@ function formatEntry(commit) {
38862
42478
  return `${breaking}${scope}${commit.subject}`;
38863
42479
  }
38864
42480
  function detectDocyrusBackendChanges(root, sinceTag) {
38865
- const range = sinceTag ? `${sinceTag}..HEAD` : "HEAD~50..HEAD";
42481
+ let range;
42482
+ if (sinceTag) {
42483
+ range = `${sinceTag}..HEAD`;
42484
+ } else {
42485
+ const rootCommit = gitSafe(["rev-list", "--max-parents=0", "HEAD"], root);
42486
+ range = rootCommit ? `${rootCommit}..HEAD` : "HEAD";
42487
+ }
38866
42488
  const entries = [];
38867
42489
  const diffFiles = gitSafe(["diff", "--name-only", range], root);
38868
42490
  if (!diffFiles) {
@@ -39016,7 +42638,7 @@ async function executeRelease(params) {
39016
42638
  `, "utf8");
39017
42639
  }
39018
42640
  git(["add", "-A"], root);
39019
- git(["commit", "-m", `chore(release): v${nextVersion}`], root);
42641
+ git(["commit", "-m", `chore(release): v${nextVersion}`], root, 12e4);
39020
42642
  if (!params.skipTag) {
39021
42643
  git(["tag", `v${nextVersion}`], root);
39022
42644
  }
@@ -39688,6 +43310,125 @@ function serializeModels(params) {
39688
43310
  }));
39689
43311
  }
39690
43312
 
43313
+ // src/server/ptyBridge.ts
43314
+ var import_node_module2 = require("node:module");
43315
+ var import_node_url2 = require("node:url");
43316
+
43317
+ // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/wrapper.mjs
43318
+ var import_stream = __toESM(require_stream(), 1);
43319
+ var import_extension = __toESM(require_extension(), 1);
43320
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
43321
+ var import_receiver = __toESM(require_receiver(), 1);
43322
+ var import_sender = __toESM(require_sender(), 1);
43323
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
43324
+ var import_websocket = __toESM(require_websocket(), 1);
43325
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
43326
+
43327
+ // src/server/ptyBridge.ts
43328
+ var import_meta2 = {};
43329
+ var require2 = (0, import_node_module2.createRequire)(import_meta2.url);
43330
+ var pty = require2("node-pty");
43331
+ var TERMINAL_PATH = "/api/terminal";
43332
+ var DEFAULT_COLS = 80;
43333
+ var DEFAULT_ROWS = 24;
43334
+ function getDefaultShell() {
43335
+ if (process.platform === "win32") {
43336
+ return process.env.COMSPEC || "cmd.exe";
43337
+ }
43338
+ return process.env.SHELL || "/bin/sh";
43339
+ }
43340
+ function tryParseResizeMessage(data) {
43341
+ const text3 = typeof data === "string" ? data : data.toString("utf-8");
43342
+ if (text3.length === 0 || text3[0] !== "{") {
43343
+ return null;
43344
+ }
43345
+ try {
43346
+ const parsed = JSON.parse(text3);
43347
+ if (parsed && typeof parsed === "object" && parsed.type === "resize" && typeof parsed.cols === "number" && typeof parsed.rows === "number" && parsed.cols > 0 && parsed.rows > 0) {
43348
+ return parsed;
43349
+ }
43350
+ } catch {
43351
+ }
43352
+ return null;
43353
+ }
43354
+ function killPtyProcess(ptyProcess, signal = "SIGTERM") {
43355
+ if (process.platform !== "win32" && ptyProcess.pid) {
43356
+ try {
43357
+ process.kill(-ptyProcess.pid, signal);
43358
+ return;
43359
+ } catch {
43360
+ }
43361
+ }
43362
+ try {
43363
+ ptyProcess.kill(signal);
43364
+ } catch {
43365
+ }
43366
+ }
43367
+ function attachPtyBridge(server, authToken) {
43368
+ const wss = new import_websocket_server.default({ noServer: true });
43369
+ server.on("upgrade", (request, socket, head) => {
43370
+ const parsedUrl = (0, import_node_url2.parse)(request.url || "", true);
43371
+ if (parsedUrl.pathname !== TERMINAL_PATH) {
43372
+ return;
43373
+ }
43374
+ if (authToken) {
43375
+ const token = extractBearerToken(request.headers.authorization || null) || (typeof parsedUrl.query.token === "string" ? parsedUrl.query.token : null);
43376
+ if (!isBearerTokenAuthorized(token, authToken)) {
43377
+ socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
43378
+ socket.destroy();
43379
+ return;
43380
+ }
43381
+ }
43382
+ wss.handleUpgrade(request, socket, head, (ws) => {
43383
+ wss.emit("connection", ws, request);
43384
+ });
43385
+ });
43386
+ wss.on("connection", (ws) => {
43387
+ const shell = getDefaultShell();
43388
+ const ptyProcess = pty.spawn(shell, [], {
43389
+ name: "xterm-256color",
43390
+ cols: DEFAULT_COLS,
43391
+ rows: DEFAULT_ROWS,
43392
+ cwd: process.cwd(),
43393
+ env: {
43394
+ ...process.env,
43395
+ TERM: "xterm-256color",
43396
+ COLORTERM: "truecolor"
43397
+ }
43398
+ });
43399
+ const onData = ptyProcess.onData((data) => {
43400
+ if (ws.readyState === import_websocket.default.OPEN) {
43401
+ ws.send(data);
43402
+ }
43403
+ });
43404
+ const onExit = ptyProcess.onExit(({ exitCode }) => {
43405
+ if (ws.readyState === import_websocket.default.OPEN) {
43406
+ ws.send(JSON.stringify({ type: "exit", code: exitCode }));
43407
+ ws.close();
43408
+ }
43409
+ });
43410
+ ws.on("message", (rawData) => {
43411
+ const resize = tryParseResizeMessage(rawData);
43412
+ if (resize) {
43413
+ ptyProcess.resize(resize.cols, resize.rows);
43414
+ return;
43415
+ }
43416
+ const text3 = typeof rawData === "string" ? rawData : rawData.toString("utf-8");
43417
+ ptyProcess.write(text3);
43418
+ });
43419
+ ws.on("close", () => {
43420
+ onData.dispose();
43421
+ onExit.dispose();
43422
+ killPtyProcess(ptyProcess);
43423
+ });
43424
+ ws.on("error", () => {
43425
+ onData.dispose();
43426
+ onExit.dispose();
43427
+ killPtyProcess(ptyProcess);
43428
+ });
43429
+ });
43430
+ }
43431
+
39691
43432
  // src/server/oauthFlowManager.ts
39692
43433
  var import_node_crypto4 = require("node:crypto");
39693
43434
  function normalizeError(error48) {
@@ -42728,6 +46469,8 @@ async function createAgentServer(params) {
42728
46469
  process.stderr.write(` GET /api/tools \u2014 list all tools
42729
46470
  `);
42730
46471
  process.stderr.write(` * /api/cli/** \u2014 proxy any docyrus CLI command
46472
+ `);
46473
+ process.stderr.write(` WS /api/terminal \u2014 PTY terminal (WebSocket)
42731
46474
 
42732
46475
  `);
42733
46476
  }
@@ -42739,6 +46482,7 @@ async function createAgentServer(params) {
42739
46482
  printBanner(candidatePort);
42740
46483
  resolveStart();
42741
46484
  });
46485
+ attachPtyBridge(server, authToken);
42742
46486
  server.on("error", (err2) => {
42743
46487
  if (err2.code === "EADDRINUSE") {
42744
46488
  process.stderr.write(` Port ${candidatePort} in use, trying ${candidatePort + 1}...
@@ -42957,7 +46701,7 @@ function readLoaderRequest() {
42957
46701
  }
42958
46702
  async function loadPiExports() {
42959
46703
  const piPackageDir = readRequiredEnv("PI_PACKAGE_DIR");
42960
- const moduleUrl = (0, import_node_url2.pathToFileURL)((0, import_node_path23.join)(piPackageDir, "dist", "index.js")).href;
46704
+ const moduleUrl = (0, import_node_url3.pathToFileURL)((0, import_node_path23.join)(piPackageDir, "dist", "index.js")).href;
42961
46705
  return await import(moduleUrl);
42962
46706
  }
42963
46707
  function resolvePackagedPiResourceRoot() {