openclaw-overlay-plugin 0.8.16 → 0.8.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,41 +1,12 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined") return require.apply(this, arguments);
11
- throw Error('Dynamic require of "' + x + '" is not supported');
12
- });
13
3
  var __esm = (fn, res) => function __init() {
14
4
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
5
  };
16
- var __commonJS = (cb, mod) => function __require2() {
17
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
- };
19
6
  var __export = (target, all) => {
20
7
  for (var name in all)
21
8
  __defProp(target, name, { get: all[name], enumerable: true });
22
9
  };
23
- var __copyProps = (to, from, except, desc) => {
24
- if (from && typeof from === "object" || typeof from === "function") {
25
- for (let key of __getOwnPropNames(from))
26
- if (!__hasOwnProp.call(to, key) && key !== except)
27
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
28
- }
29
- return to;
30
- };
31
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32
- // If the importer is in node compatibility mode or this is not an ESM
33
- // file that has been converted to a CommonJS file using a Babel-
34
- // compatible transform (i.e. "__esModule" has not been set), then set
35
- // "default" to the CommonJS "module.exports" for node compatibility.
36
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37
- mod
38
- ));
39
10
 
40
11
  // src/scripts/config.ts
41
12
  var config_exports = {};
@@ -452,3899 +423,255 @@ var init_wallet = __esm({
452
423
  return acceptPayment(this._setup, params);
453
424
  }
454
425
  // ---------------------------------------------------------------------------
455
- // Access to underlying toolbox objects (for advanced use)
456
- // ---------------------------------------------------------------------------
457
- /** Get the underlying wallet-toolbox SetupWallet for advanced operations. */
458
- getSetup() {
459
- return this._setup;
460
- }
461
- // ---------------------------------------------------------------------------
462
- // Private helpers
463
- // ---------------------------------------------------------------------------
464
- /**
465
- * Internal: manually construct a BRC-100 wallet backed by SQLite.
466
- *
467
- * We build this by hand instead of using Setup.createWalletSQLite because
468
- * the toolbox has a bug where its internal randomBytesHex is a stub.
469
- * We use the same components but wire them up correctly.
470
- */
471
- static async buildSetup(config, rootKeyHex) {
472
- const chain = toChain(config.network);
473
- log("Building setup for chain: %s (network: %s)", chain, config.network);
474
- const taalApiKey = config.taalApiKey ?? DEFAULT_TAAL_API_KEYS[chain];
475
- const rootKey = PrivateKey.fromHex(rootKeyHex);
476
- const identityKey = rootKey.toPublicKey().toString();
477
- const keyDeriver = new CachedKeyDeriver2(rootKey);
478
- const storage = new WalletStorageManager(identityKey);
479
- const serviceOptions = Services.createDefaultOptions(chain);
480
- const chaintracksUrl = process["env"].BSV_CHAINTRACKS_URL || "https://chaintracks-us-1.bsvb.tech";
481
- const arcUrl = process["env"].BSV_ARC_URL;
482
- const isTestMode = config.enableMonitor === false;
483
- if (!isTestMode) {
484
- serviceOptions.chaintracks = new ChaintracksServiceClient(chain, chaintracksUrl);
485
- if (arcUrl) {
486
- serviceOptions.arcUrl = arcUrl;
487
- }
488
- }
489
- serviceOptions.taalApiKey = taalApiKey;
490
- const services = new Services(serviceOptions);
491
- const monopts = Monitor.createDefaultWalletMonitorOptions(chain, storage, services);
492
- const monitor = new Monitor(monopts);
493
- if (!isTestMode) {
494
- monitor.addDefaultTasks();
495
- } else {
496
- monitor.tasks = [];
497
- }
498
- const wallet = isTestMode ? void 0 : new Wallet({ chain, keyDeriver, storage, services, monitor });
499
- const filePath = path3.join(config.storageDir, `${DEFAULT_DB_NAME}.sqlite`);
500
- const knex = knexLib({
501
- client: "sqlite3",
502
- connection: { filename: filePath },
503
- useNullAsDefault: true
504
- });
505
- const feeModelValue = config.feeModel ?? (process["env"].BSV_FEE_MODEL ? parseInt(process["env"].BSV_FEE_MODEL, 10) : 100);
506
- const activeStorage = new StorageKnex({
507
- chain,
508
- knex,
509
- commissionSatoshis: 0,
510
- commissionPubKeyHex: void 0,
511
- feeModel: { model: "sat/kb", value: feeModelValue }
512
- });
513
- await activeStorage.migrate(DEFAULT_DB_NAME, randomBytesHex(33));
514
- await activeStorage.makeAvailable();
515
- await storage.addWalletStorageProvider(activeStorage);
516
- await activeStorage.findOrInsertUser(identityKey);
517
- return {
518
- rootKey,
519
- identityKey,
520
- keyDeriver,
521
- chain,
522
- network: config.network,
523
- storage,
524
- services: isTestMode ? void 0 : services,
525
- monitor: isTestMode ? void 0 : monitor,
526
- wallet
527
- };
528
- }
529
- };
530
- }
531
- });
532
-
533
- // ../plugin-core/dist/index.js
534
- var init_dist = __esm({
535
- "../plugin-core/dist/index.js"() {
536
- "use strict";
537
- init_wallet();
538
- init_config2();
539
- init_payment();
540
- init_verify();
541
- }
542
- });
543
-
544
- // src/scripts/utils/storage.ts
545
- import fs7 from "node:fs";
546
- function ensureStateDir() {
547
- fs7.mkdirSync(OVERLAY_STATE_DIR, { recursive: true });
548
- }
549
- function loadRegistration() {
550
- try {
551
- if (fs7.existsSync(PATHS.registration)) {
552
- return JSON.parse(fs7.readFileSync(PATHS.registration, "utf-8"));
553
- }
554
- } catch {
555
- }
556
- return null;
557
- }
558
- function saveRegistration(data) {
559
- ensureStateDir();
560
- fs7.writeFileSync(PATHS.registration, JSON.stringify(data, null, 2), "utf-8");
561
- }
562
- function deleteRegistration() {
563
- try {
564
- fs7.unlinkSync(PATHS.registration);
565
- } catch {
566
- }
567
- }
568
- function loadServices() {
569
- try {
570
- if (fs7.existsSync(PATHS.services)) {
571
- return JSON.parse(fs7.readFileSync(PATHS.services, "utf-8"));
572
- }
573
- } catch {
574
- }
575
- return [];
576
- }
577
- function saveServices(services) {
578
- ensureStateDir();
579
- fs7.writeFileSync(PATHS.services, JSON.stringify(services, null, 2), "utf-8");
580
- }
581
- function appendToJsonl(filePath, entry) {
582
- ensureStateDir();
583
- fs7.appendFileSync(filePath, JSON.stringify(entry) + "\n");
584
- }
585
- function readJsonl(filePath) {
586
- if (!fs7.existsSync(filePath)) return [];
587
- const lines = fs7.readFileSync(filePath, "utf-8").trim().split("\n").filter(Boolean);
588
- return lines.map((line) => {
589
- try {
590
- return JSON.parse(line);
591
- } catch {
592
- return null;
593
- }
594
- }).filter(Boolean);
595
- }
596
- function updateServiceQueueStatus(requestId, newStatus, additionalFields = {}) {
597
- if (!fs7.existsSync(PATHS.serviceQueue)) return false;
598
- const lines = fs7.readFileSync(PATHS.serviceQueue, "utf-8").trim().split("\n").filter(Boolean);
599
- let updated = false;
600
- const updatedLines = lines.map((line) => {
601
- try {
602
- const entry = JSON.parse(line);
603
- if (entry.requestId === requestId) {
604
- updated = true;
605
- return JSON.stringify({
606
- ...entry,
607
- status: newStatus,
608
- ...additionalFields,
609
- updatedAt: Date.now()
610
- });
611
- }
612
- return line;
613
- } catch {
614
- return line;
615
- }
616
- });
617
- if (updated) {
618
- fs7.writeFileSync(PATHS.serviceQueue, updatedLines.join("\n") + "\n");
619
- }
620
- return updated;
621
- }
622
- var init_storage = __esm({
623
- "src/scripts/utils/storage.ts"() {
624
- "use strict";
625
- init_config();
626
- }
627
- });
628
-
629
- // src/scripts/overlay/transaction.ts
630
- import { Utils as Utils4, PushDrop, Transaction } from "@bsv/sdk";
631
- async function buildPushDropScript(wallet, payload) {
632
- const jsonBytes = Utils4.toArray(JSON.stringify(payload), "utf8");
633
- const fields = [jsonBytes];
634
- const token = new PushDrop(wallet._setup.wallet);
635
- const script = await token.lock(fields, [0, PROTOCOL_ID], "1", "self", true, true);
636
- return script.toHex();
637
- }
638
- async function buildRealOverlayTransaction(payload, topic) {
639
- const wallet = await BSVAgentWallet.load({ network: NETWORK, storageDir: WALLET_DIR });
640
- const lockingScript = await buildPushDropScript(wallet, payload);
641
- const response = await wallet._setup.wallet.createAction({
642
- description: "topic manager submission",
643
- outputs: [
644
- {
645
- lockingScript,
646
- satoshis: 1,
647
- outputDescription: "overlay",
648
- basket: topic
649
- // basket is the topic manager
650
- }
651
- ],
652
- options: {
653
- acceptDelayedBroadcast: false
654
- }
655
- });
656
- const submitResp = await fetch(`${OVERLAY_URL}/submit`, {
657
- method: "POST",
658
- headers: {
659
- "Content-Type": "application/octet-stream",
660
- "X-Topics": JSON.stringify([topic])
661
- },
662
- body: new Uint8Array(response.tx)
663
- });
664
- if (!submitResp.ok) {
665
- const errText = await submitResp.text();
666
- throw new Error(`Overlay submission failed: ${submitResp.status} \u2014 ${errText}`);
667
- }
668
- const wocNet = NETWORK === "mainnet" ? "" : "test.";
669
- return {
670
- txid: response.txid,
671
- funded: "stored-beef",
672
- explorer: `https://${wocNet}whatsonchain.com/tx/${response.txid}`
673
- };
674
- }
675
- async function lookupOverlay(service, query) {
676
- const resp = await fetch(`${OVERLAY_URL}/lookup`, {
677
- method: "POST",
678
- headers: { "Content-Type": "application/json" },
679
- body: JSON.stringify({ service, query })
680
- });
681
- if (!resp.ok) {
682
- const errText = await resp.text();
683
- throw new Error(`Lookup failed: ${resp.status} \u2014 ${errText}`);
684
- }
685
- return resp.json();
686
- }
687
- async function parseOverlayOutput(beefData, outputIndex) {
688
- try {
689
- const tx = Transaction.fromBEEF(beefData);
690
- const txid = tx.id("hex");
691
- const output = tx.outputs[outputIndex];
692
- if (!output) return { data: null, txid: null };
693
- const { fields } = PushDrop.decode(output.lockingScript);
694
- return { data: JSON.parse(Utils4.toUTF8(fields[0])), txid };
695
- } catch {
696
- return { data: null, txid: null };
697
- }
698
- }
699
- var init_transaction = __esm({
700
- "src/scripts/overlay/transaction.ts"() {
701
- "use strict";
702
- init_config();
703
- init_dist();
704
- }
705
- });
706
-
707
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js
708
- var require_constants = __commonJS({
709
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js"(exports, module) {
710
- "use strict";
711
- var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
712
- var hasBlob = typeof Blob !== "undefined";
713
- if (hasBlob) BINARY_TYPES.push("blob");
714
- module.exports = {
715
- BINARY_TYPES,
716
- CLOSE_TIMEOUT: 3e4,
717
- EMPTY_BUFFER: Buffer.alloc(0),
718
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
719
- hasBlob,
720
- kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
721
- kListener: /* @__PURE__ */ Symbol("kListener"),
722
- kStatusCode: /* @__PURE__ */ Symbol("status-code"),
723
- kWebSocket: /* @__PURE__ */ Symbol("websocket"),
724
- NOOP: () => {
725
- }
726
- };
727
- }
728
- });
729
-
730
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js
731
- var require_buffer_util = __commonJS({
732
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js"(exports, module) {
733
- "use strict";
734
- var { EMPTY_BUFFER } = require_constants();
735
- var FastBuffer = Buffer[Symbol.species];
736
- function concat(list, totalLength) {
737
- if (list.length === 0) return EMPTY_BUFFER;
738
- if (list.length === 1) return list[0];
739
- const target = Buffer.allocUnsafe(totalLength);
740
- let offset = 0;
741
- for (let i = 0; i < list.length; i++) {
742
- const buf = list[i];
743
- target.set(buf, offset);
744
- offset += buf.length;
745
- }
746
- if (offset < totalLength) {
747
- return new FastBuffer(target.buffer, target.byteOffset, offset);
748
- }
749
- return target;
750
- }
751
- function _mask(source, mask, output, offset, length) {
752
- for (let i = 0; i < length; i++) {
753
- output[offset + i] = source[i] ^ mask[i & 3];
754
- }
755
- }
756
- function _unmask(buffer, mask) {
757
- for (let i = 0; i < buffer.length; i++) {
758
- buffer[i] ^= mask[i & 3];
759
- }
760
- }
761
- function toArrayBuffer(buf) {
762
- if (buf.length === buf.buffer.byteLength) {
763
- return buf.buffer;
764
- }
765
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
766
- }
767
- function toBuffer(data) {
768
- toBuffer.readOnly = true;
769
- if (Buffer.isBuffer(data)) return data;
770
- let buf;
771
- if (data instanceof ArrayBuffer) {
772
- buf = new FastBuffer(data);
773
- } else if (ArrayBuffer.isView(data)) {
774
- buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
775
- } else {
776
- buf = Buffer.from(data);
777
- toBuffer.readOnly = false;
778
- }
779
- return buf;
780
- }
781
- module.exports = {
782
- concat,
783
- mask: _mask,
784
- toArrayBuffer,
785
- toBuffer,
786
- unmask: _unmask
787
- };
788
- if (!process.env.WS_NO_BUFFER_UTIL) {
789
- try {
790
- const bufferUtil = __require("bufferutil");
791
- module.exports.mask = function(source, mask, output, offset, length) {
792
- if (length < 48) _mask(source, mask, output, offset, length);
793
- else bufferUtil.mask(source, mask, output, offset, length);
794
- };
795
- module.exports.unmask = function(buffer, mask) {
796
- if (buffer.length < 32) _unmask(buffer, mask);
797
- else bufferUtil.unmask(buffer, mask);
798
- };
799
- } catch (e) {
800
- }
801
- }
802
- }
803
- });
804
-
805
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js
806
- var require_limiter = __commonJS({
807
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js"(exports, module) {
808
- "use strict";
809
- var kDone = /* @__PURE__ */ Symbol("kDone");
810
- var kRun = /* @__PURE__ */ Symbol("kRun");
811
- var Limiter = class {
812
- /**
813
- * Creates a new `Limiter`.
814
- *
815
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
816
- * to run concurrently
817
- */
818
- constructor(concurrency) {
819
- this[kDone] = () => {
820
- this.pending--;
821
- this[kRun]();
822
- };
823
- this.concurrency = concurrency || Infinity;
824
- this.jobs = [];
825
- this.pending = 0;
826
- }
827
- /**
828
- * Adds a job to the queue.
829
- *
830
- * @param {Function} job The job to run
831
- * @public
832
- */
833
- add(job) {
834
- this.jobs.push(job);
835
- this[kRun]();
836
- }
837
- /**
838
- * Removes a job from the queue and runs it if possible.
839
- *
840
- * @private
841
- */
842
- [kRun]() {
843
- if (this.pending === this.concurrency) return;
844
- if (this.jobs.length) {
845
- const job = this.jobs.shift();
846
- this.pending++;
847
- job(this[kDone]);
848
- }
849
- }
850
- };
851
- module.exports = Limiter;
852
- }
853
- });
854
-
855
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js
856
- var require_permessage_deflate = __commonJS({
857
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
858
- "use strict";
859
- var zlib = __require("zlib");
860
- var bufferUtil = require_buffer_util();
861
- var Limiter = require_limiter();
862
- var { kStatusCode } = require_constants();
863
- var FastBuffer = Buffer[Symbol.species];
864
- var TRAILER = Buffer.from([0, 0, 255, 255]);
865
- var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
866
- var kTotalLength = /* @__PURE__ */ Symbol("total-length");
867
- var kCallback = /* @__PURE__ */ Symbol("callback");
868
- var kBuffers = /* @__PURE__ */ Symbol("buffers");
869
- var kError = /* @__PURE__ */ Symbol("error");
870
- var zlibLimiter;
871
- var PerMessageDeflate2 = class {
872
- /**
873
- * Creates a PerMessageDeflate instance.
874
- *
875
- * @param {Object} [options] Configuration options
876
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
877
- * for, or request, a custom client window size
878
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
879
- * acknowledge disabling of client context takeover
880
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
881
- * calls to zlib
882
- * @param {Boolean} [options.isServer=false] Create the instance in either
883
- * server or client mode
884
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
885
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
886
- * use of a custom server window size
887
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
888
- * disabling of server context takeover
889
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
890
- * messages should not be compressed if context takeover is disabled
891
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
892
- * deflate
893
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
894
- * inflate
895
- */
896
- constructor(options) {
897
- this._options = options || {};
898
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
899
- this._maxPayload = this._options.maxPayload | 0;
900
- this._isServer = !!this._options.isServer;
901
- this._deflate = null;
902
- this._inflate = null;
903
- this.params = null;
904
- if (!zlibLimiter) {
905
- const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
906
- zlibLimiter = new Limiter(concurrency);
907
- }
908
- }
909
- /**
910
- * @type {String}
911
- */
912
- static get extensionName() {
913
- return "permessage-deflate";
914
- }
915
- /**
916
- * Create an extension negotiation offer.
917
- *
918
- * @return {Object} Extension parameters
919
- * @public
920
- */
921
- offer() {
922
- const params = {};
923
- if (this._options.serverNoContextTakeover) {
924
- params.server_no_context_takeover = true;
925
- }
926
- if (this._options.clientNoContextTakeover) {
927
- params.client_no_context_takeover = true;
928
- }
929
- if (this._options.serverMaxWindowBits) {
930
- params.server_max_window_bits = this._options.serverMaxWindowBits;
931
- }
932
- if (this._options.clientMaxWindowBits) {
933
- params.client_max_window_bits = this._options.clientMaxWindowBits;
934
- } else if (this._options.clientMaxWindowBits == null) {
935
- params.client_max_window_bits = true;
936
- }
937
- return params;
938
- }
939
- /**
940
- * Accept an extension negotiation offer/response.
941
- *
942
- * @param {Array} configurations The extension negotiation offers/reponse
943
- * @return {Object} Accepted configuration
944
- * @public
945
- */
946
- accept(configurations) {
947
- configurations = this.normalizeParams(configurations);
948
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
949
- return this.params;
950
- }
951
- /**
952
- * Releases all resources used by the extension.
953
- *
954
- * @public
955
- */
956
- cleanup() {
957
- if (this._inflate) {
958
- this._inflate.close();
959
- this._inflate = null;
960
- }
961
- if (this._deflate) {
962
- const callback = this._deflate[kCallback];
963
- this._deflate.close();
964
- this._deflate = null;
965
- if (callback) {
966
- callback(
967
- new Error(
968
- "The deflate stream was closed while data was being processed"
969
- )
970
- );
971
- }
972
- }
973
- }
974
- /**
975
- * Accept an extension negotiation offer.
976
- *
977
- * @param {Array} offers The extension negotiation offers
978
- * @return {Object} Accepted configuration
979
- * @private
980
- */
981
- acceptAsServer(offers) {
982
- const opts = this._options;
983
- const accepted = offers.find((params) => {
984
- 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) {
985
- return false;
986
- }
987
- return true;
988
- });
989
- if (!accepted) {
990
- throw new Error("None of the extension offers can be accepted");
991
- }
992
- if (opts.serverNoContextTakeover) {
993
- accepted.server_no_context_takeover = true;
994
- }
995
- if (opts.clientNoContextTakeover) {
996
- accepted.client_no_context_takeover = true;
997
- }
998
- if (typeof opts.serverMaxWindowBits === "number") {
999
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
1000
- }
1001
- if (typeof opts.clientMaxWindowBits === "number") {
1002
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
1003
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
1004
- delete accepted.client_max_window_bits;
1005
- }
1006
- return accepted;
1007
- }
1008
- /**
1009
- * Accept the extension negotiation response.
1010
- *
1011
- * @param {Array} response The extension negotiation response
1012
- * @return {Object} Accepted configuration
1013
- * @private
1014
- */
1015
- acceptAsClient(response) {
1016
- const params = response[0];
1017
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
1018
- throw new Error('Unexpected parameter "client_no_context_takeover"');
1019
- }
1020
- if (!params.client_max_window_bits) {
1021
- if (typeof this._options.clientMaxWindowBits === "number") {
1022
- params.client_max_window_bits = this._options.clientMaxWindowBits;
1023
- }
1024
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
1025
- throw new Error(
1026
- 'Unexpected or invalid parameter "client_max_window_bits"'
1027
- );
1028
- }
1029
- return params;
1030
- }
1031
- /**
1032
- * Normalize parameters.
1033
- *
1034
- * @param {Array} configurations The extension negotiation offers/reponse
1035
- * @return {Array} The offers/response with normalized parameters
1036
- * @private
1037
- */
1038
- normalizeParams(configurations) {
1039
- configurations.forEach((params) => {
1040
- Object.keys(params).forEach((key) => {
1041
- let value = params[key];
1042
- if (value.length > 1) {
1043
- throw new Error(`Parameter "${key}" must have only a single value`);
1044
- }
1045
- value = value[0];
1046
- if (key === "client_max_window_bits") {
1047
- if (value !== true) {
1048
- const num = +value;
1049
- if (!Number.isInteger(num) || num < 8 || num > 15) {
1050
- throw new TypeError(
1051
- `Invalid value for parameter "${key}": ${value}`
1052
- );
1053
- }
1054
- value = num;
1055
- } else if (!this._isServer) {
1056
- throw new TypeError(
1057
- `Invalid value for parameter "${key}": ${value}`
1058
- );
1059
- }
1060
- } else if (key === "server_max_window_bits") {
1061
- const num = +value;
1062
- if (!Number.isInteger(num) || num < 8 || num > 15) {
1063
- throw new TypeError(
1064
- `Invalid value for parameter "${key}": ${value}`
1065
- );
1066
- }
1067
- value = num;
1068
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
1069
- if (value !== true) {
1070
- throw new TypeError(
1071
- `Invalid value for parameter "${key}": ${value}`
1072
- );
1073
- }
1074
- } else {
1075
- throw new Error(`Unknown parameter "${key}"`);
1076
- }
1077
- params[key] = value;
1078
- });
1079
- });
1080
- return configurations;
1081
- }
1082
- /**
1083
- * Decompress data. Concurrency limited.
1084
- *
1085
- * @param {Buffer} data Compressed data
1086
- * @param {Boolean} fin Specifies whether or not this is the last fragment
1087
- * @param {Function} callback Callback
1088
- * @public
1089
- */
1090
- decompress(data, fin, callback) {
1091
- zlibLimiter.add((done) => {
1092
- this._decompress(data, fin, (err, result) => {
1093
- done();
1094
- callback(err, result);
1095
- });
1096
- });
1097
- }
1098
- /**
1099
- * Compress data. Concurrency limited.
1100
- *
1101
- * @param {(Buffer|String)} data Data to compress
1102
- * @param {Boolean} fin Specifies whether or not this is the last fragment
1103
- * @param {Function} callback Callback
1104
- * @public
1105
- */
1106
- compress(data, fin, callback) {
1107
- zlibLimiter.add((done) => {
1108
- this._compress(data, fin, (err, result) => {
1109
- done();
1110
- callback(err, result);
1111
- });
1112
- });
1113
- }
1114
- /**
1115
- * Decompress data.
1116
- *
1117
- * @param {Buffer} data Compressed data
1118
- * @param {Boolean} fin Specifies whether or not this is the last fragment
1119
- * @param {Function} callback Callback
1120
- * @private
1121
- */
1122
- _decompress(data, fin, callback) {
1123
- const endpoint = this._isServer ? "client" : "server";
1124
- if (!this._inflate) {
1125
- const key = `${endpoint}_max_window_bits`;
1126
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
1127
- this._inflate = zlib.createInflateRaw({
1128
- ...this._options.zlibInflateOptions,
1129
- windowBits
1130
- });
1131
- this._inflate[kPerMessageDeflate] = this;
1132
- this._inflate[kTotalLength] = 0;
1133
- this._inflate[kBuffers] = [];
1134
- this._inflate.on("error", inflateOnError);
1135
- this._inflate.on("data", inflateOnData);
1136
- }
1137
- this._inflate[kCallback] = callback;
1138
- this._inflate.write(data);
1139
- if (fin) this._inflate.write(TRAILER);
1140
- this._inflate.flush(() => {
1141
- const err = this._inflate[kError];
1142
- if (err) {
1143
- this._inflate.close();
1144
- this._inflate = null;
1145
- callback(err);
1146
- return;
1147
- }
1148
- const data2 = bufferUtil.concat(
1149
- this._inflate[kBuffers],
1150
- this._inflate[kTotalLength]
1151
- );
1152
- if (this._inflate._readableState.endEmitted) {
1153
- this._inflate.close();
1154
- this._inflate = null;
1155
- } else {
1156
- this._inflate[kTotalLength] = 0;
1157
- this._inflate[kBuffers] = [];
1158
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
1159
- this._inflate.reset();
1160
- }
1161
- }
1162
- callback(null, data2);
1163
- });
1164
- }
1165
- /**
1166
- * Compress data.
1167
- *
1168
- * @param {(Buffer|String)} data Data to compress
1169
- * @param {Boolean} fin Specifies whether or not this is the last fragment
1170
- * @param {Function} callback Callback
1171
- * @private
1172
- */
1173
- _compress(data, fin, callback) {
1174
- const endpoint = this._isServer ? "server" : "client";
1175
- if (!this._deflate) {
1176
- const key = `${endpoint}_max_window_bits`;
1177
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
1178
- this._deflate = zlib.createDeflateRaw({
1179
- ...this._options.zlibDeflateOptions,
1180
- windowBits
1181
- });
1182
- this._deflate[kTotalLength] = 0;
1183
- this._deflate[kBuffers] = [];
1184
- this._deflate.on("data", deflateOnData);
1185
- }
1186
- this._deflate[kCallback] = callback;
1187
- this._deflate.write(data);
1188
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
1189
- if (!this._deflate) {
1190
- return;
1191
- }
1192
- let data2 = bufferUtil.concat(
1193
- this._deflate[kBuffers],
1194
- this._deflate[kTotalLength]
1195
- );
1196
- if (fin) {
1197
- data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
1198
- }
1199
- this._deflate[kCallback] = null;
1200
- this._deflate[kTotalLength] = 0;
1201
- this._deflate[kBuffers] = [];
1202
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
1203
- this._deflate.reset();
1204
- }
1205
- callback(null, data2);
1206
- });
1207
- }
1208
- };
1209
- module.exports = PerMessageDeflate2;
1210
- function deflateOnData(chunk) {
1211
- this[kBuffers].push(chunk);
1212
- this[kTotalLength] += chunk.length;
1213
- }
1214
- function inflateOnData(chunk) {
1215
- this[kTotalLength] += chunk.length;
1216
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
1217
- this[kBuffers].push(chunk);
1218
- return;
1219
- }
1220
- this[kError] = new RangeError("Max payload size exceeded");
1221
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
1222
- this[kError][kStatusCode] = 1009;
1223
- this.removeListener("data", inflateOnData);
1224
- this.reset();
1225
- }
1226
- function inflateOnError(err) {
1227
- this[kPerMessageDeflate]._inflate = null;
1228
- if (this[kError]) {
1229
- this[kCallback](this[kError]);
1230
- return;
1231
- }
1232
- err[kStatusCode] = 1007;
1233
- this[kCallback](err);
1234
- }
1235
- }
1236
- });
1237
-
1238
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js
1239
- var require_validation = __commonJS({
1240
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js"(exports, module) {
1241
- "use strict";
1242
- var { isUtf8 } = __require("buffer");
1243
- var { hasBlob } = require_constants();
1244
- var tokenChars = [
1245
- 0,
1246
- 0,
1247
- 0,
1248
- 0,
1249
- 0,
1250
- 0,
1251
- 0,
1252
- 0,
1253
- 0,
1254
- 0,
1255
- 0,
1256
- 0,
1257
- 0,
1258
- 0,
1259
- 0,
1260
- 0,
1261
- // 0 - 15
1262
- 0,
1263
- 0,
1264
- 0,
1265
- 0,
1266
- 0,
1267
- 0,
1268
- 0,
1269
- 0,
1270
- 0,
1271
- 0,
1272
- 0,
1273
- 0,
1274
- 0,
1275
- 0,
1276
- 0,
1277
- 0,
1278
- // 16 - 31
1279
- 0,
1280
- 1,
1281
- 0,
1282
- 1,
1283
- 1,
1284
- 1,
1285
- 1,
1286
- 1,
1287
- 0,
1288
- 0,
1289
- 1,
1290
- 1,
1291
- 0,
1292
- 1,
1293
- 1,
1294
- 0,
1295
- // 32 - 47
1296
- 1,
1297
- 1,
1298
- 1,
1299
- 1,
1300
- 1,
1301
- 1,
1302
- 1,
1303
- 1,
1304
- 1,
1305
- 1,
1306
- 0,
1307
- 0,
1308
- 0,
1309
- 0,
1310
- 0,
1311
- 0,
1312
- // 48 - 63
1313
- 0,
1314
- 1,
1315
- 1,
1316
- 1,
1317
- 1,
1318
- 1,
1319
- 1,
1320
- 1,
1321
- 1,
1322
- 1,
1323
- 1,
1324
- 1,
1325
- 1,
1326
- 1,
1327
- 1,
1328
- 1,
1329
- // 64 - 79
1330
- 1,
1331
- 1,
1332
- 1,
1333
- 1,
1334
- 1,
1335
- 1,
1336
- 1,
1337
- 1,
1338
- 1,
1339
- 1,
1340
- 1,
1341
- 0,
1342
- 0,
1343
- 0,
1344
- 1,
1345
- 1,
1346
- // 80 - 95
1347
- 1,
1348
- 1,
1349
- 1,
1350
- 1,
1351
- 1,
1352
- 1,
1353
- 1,
1354
- 1,
1355
- 1,
1356
- 1,
1357
- 1,
1358
- 1,
1359
- 1,
1360
- 1,
1361
- 1,
1362
- 1,
1363
- // 96 - 111
1364
- 1,
1365
- 1,
1366
- 1,
1367
- 1,
1368
- 1,
1369
- 1,
1370
- 1,
1371
- 1,
1372
- 1,
1373
- 1,
1374
- 1,
1375
- 0,
1376
- 1,
1377
- 0,
1378
- 1,
1379
- 0
1380
- // 112 - 127
1381
- ];
1382
- function isValidStatusCode(code) {
1383
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
1384
- }
1385
- function _isValidUTF8(buf) {
1386
- const len = buf.length;
1387
- let i = 0;
1388
- while (i < len) {
1389
- if ((buf[i] & 128) === 0) {
1390
- i++;
1391
- } else if ((buf[i] & 224) === 192) {
1392
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
1393
- return false;
1394
- }
1395
- i += 2;
1396
- } else if ((buf[i] & 240) === 224) {
1397
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
1398
- buf[i] === 237 && (buf[i + 1] & 224) === 160) {
1399
- return false;
1400
- }
1401
- i += 3;
1402
- } else if ((buf[i] & 248) === 240) {
1403
- if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
1404
- buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
1405
- return false;
1406
- }
1407
- i += 4;
1408
- } else {
1409
- return false;
1410
- }
1411
- }
1412
- return true;
1413
- }
1414
- function isBlob(value) {
1415
- return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
1416
- }
1417
- module.exports = {
1418
- isBlob,
1419
- isValidStatusCode,
1420
- isValidUTF8: _isValidUTF8,
1421
- tokenChars
1422
- };
1423
- if (isUtf8) {
1424
- module.exports.isValidUTF8 = function(buf) {
1425
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
1426
- };
1427
- } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
1428
- try {
1429
- const isValidUTF8 = __require("utf-8-validate");
1430
- module.exports.isValidUTF8 = function(buf) {
1431
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
1432
- };
1433
- } catch (e) {
1434
- }
1435
- }
1436
- }
1437
- });
1438
-
1439
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js
1440
- var require_receiver = __commonJS({
1441
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js"(exports, module) {
1442
- "use strict";
1443
- var { Writable } = __require("stream");
1444
- var PerMessageDeflate2 = require_permessage_deflate();
1445
- var {
1446
- BINARY_TYPES,
1447
- EMPTY_BUFFER,
1448
- kStatusCode,
1449
- kWebSocket
1450
- } = require_constants();
1451
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
1452
- var { isValidStatusCode, isValidUTF8 } = require_validation();
1453
- var FastBuffer = Buffer[Symbol.species];
1454
- var GET_INFO = 0;
1455
- var GET_PAYLOAD_LENGTH_16 = 1;
1456
- var GET_PAYLOAD_LENGTH_64 = 2;
1457
- var GET_MASK = 3;
1458
- var GET_DATA = 4;
1459
- var INFLATING = 5;
1460
- var DEFER_EVENT = 6;
1461
- var Receiver2 = class extends Writable {
1462
- /**
1463
- * Creates a Receiver instance.
1464
- *
1465
- * @param {Object} [options] Options object
1466
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
1467
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
1468
- * multiple times in the same tick
1469
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
1470
- * @param {Object} [options.extensions] An object containing the negotiated
1471
- * extensions
1472
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
1473
- * client or server mode
1474
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
1475
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
1476
- * not to skip UTF-8 validation for text and close messages
1477
- */
1478
- constructor(options = {}) {
1479
- super();
1480
- this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
1481
- this._binaryType = options.binaryType || BINARY_TYPES[0];
1482
- this._extensions = options.extensions || {};
1483
- this._isServer = !!options.isServer;
1484
- this._maxPayload = options.maxPayload | 0;
1485
- this._skipUTF8Validation = !!options.skipUTF8Validation;
1486
- this[kWebSocket] = void 0;
1487
- this._bufferedBytes = 0;
1488
- this._buffers = [];
1489
- this._compressed = false;
1490
- this._payloadLength = 0;
1491
- this._mask = void 0;
1492
- this._fragmented = 0;
1493
- this._masked = false;
1494
- this._fin = false;
1495
- this._opcode = 0;
1496
- this._totalPayloadLength = 0;
1497
- this._messageLength = 0;
1498
- this._fragments = [];
1499
- this._errored = false;
1500
- this._loop = false;
1501
- this._state = GET_INFO;
1502
- }
1503
- /**
1504
- * Implements `Writable.prototype._write()`.
1505
- *
1506
- * @param {Buffer} chunk The chunk of data to write
1507
- * @param {String} encoding The character encoding of `chunk`
1508
- * @param {Function} cb Callback
1509
- * @private
1510
- */
1511
- _write(chunk, encoding, cb) {
1512
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
1513
- this._bufferedBytes += chunk.length;
1514
- this._buffers.push(chunk);
1515
- this.startLoop(cb);
1516
- }
1517
- /**
1518
- * Consumes `n` bytes from the buffered data.
1519
- *
1520
- * @param {Number} n The number of bytes to consume
1521
- * @return {Buffer} The consumed bytes
1522
- * @private
1523
- */
1524
- consume(n) {
1525
- this._bufferedBytes -= n;
1526
- if (n === this._buffers[0].length) return this._buffers.shift();
1527
- if (n < this._buffers[0].length) {
1528
- const buf = this._buffers[0];
1529
- this._buffers[0] = new FastBuffer(
1530
- buf.buffer,
1531
- buf.byteOffset + n,
1532
- buf.length - n
1533
- );
1534
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
1535
- }
1536
- const dst = Buffer.allocUnsafe(n);
1537
- do {
1538
- const buf = this._buffers[0];
1539
- const offset = dst.length - n;
1540
- if (n >= buf.length) {
1541
- dst.set(this._buffers.shift(), offset);
1542
- } else {
1543
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
1544
- this._buffers[0] = new FastBuffer(
1545
- buf.buffer,
1546
- buf.byteOffset + n,
1547
- buf.length - n
1548
- );
1549
- }
1550
- n -= buf.length;
1551
- } while (n > 0);
1552
- return dst;
1553
- }
1554
- /**
1555
- * Starts the parsing loop.
1556
- *
1557
- * @param {Function} cb Callback
1558
- * @private
1559
- */
1560
- startLoop(cb) {
1561
- this._loop = true;
1562
- do {
1563
- switch (this._state) {
1564
- case GET_INFO:
1565
- this.getInfo(cb);
1566
- break;
1567
- case GET_PAYLOAD_LENGTH_16:
1568
- this.getPayloadLength16(cb);
1569
- break;
1570
- case GET_PAYLOAD_LENGTH_64:
1571
- this.getPayloadLength64(cb);
1572
- break;
1573
- case GET_MASK:
1574
- this.getMask();
1575
- break;
1576
- case GET_DATA:
1577
- this.getData(cb);
1578
- break;
1579
- case INFLATING:
1580
- case DEFER_EVENT:
1581
- this._loop = false;
1582
- return;
1583
- }
1584
- } while (this._loop);
1585
- if (!this._errored) cb();
1586
- }
1587
- /**
1588
- * Reads the first two bytes of a frame.
1589
- *
1590
- * @param {Function} cb Callback
1591
- * @private
1592
- */
1593
- getInfo(cb) {
1594
- if (this._bufferedBytes < 2) {
1595
- this._loop = false;
1596
- return;
1597
- }
1598
- const buf = this.consume(2);
1599
- if ((buf[0] & 48) !== 0) {
1600
- const error = this.createError(
1601
- RangeError,
1602
- "RSV2 and RSV3 must be clear",
1603
- true,
1604
- 1002,
1605
- "WS_ERR_UNEXPECTED_RSV_2_3"
1606
- );
1607
- cb(error);
1608
- return;
1609
- }
1610
- const compressed = (buf[0] & 64) === 64;
1611
- if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
1612
- const error = this.createError(
1613
- RangeError,
1614
- "RSV1 must be clear",
1615
- true,
1616
- 1002,
1617
- "WS_ERR_UNEXPECTED_RSV_1"
1618
- );
1619
- cb(error);
1620
- return;
1621
- }
1622
- this._fin = (buf[0] & 128) === 128;
1623
- this._opcode = buf[0] & 15;
1624
- this._payloadLength = buf[1] & 127;
1625
- if (this._opcode === 0) {
1626
- if (compressed) {
1627
- const error = this.createError(
1628
- RangeError,
1629
- "RSV1 must be clear",
1630
- true,
1631
- 1002,
1632
- "WS_ERR_UNEXPECTED_RSV_1"
1633
- );
1634
- cb(error);
1635
- return;
1636
- }
1637
- if (!this._fragmented) {
1638
- const error = this.createError(
1639
- RangeError,
1640
- "invalid opcode 0",
1641
- true,
1642
- 1002,
1643
- "WS_ERR_INVALID_OPCODE"
1644
- );
1645
- cb(error);
1646
- return;
1647
- }
1648
- this._opcode = this._fragmented;
1649
- } else if (this._opcode === 1 || this._opcode === 2) {
1650
- if (this._fragmented) {
1651
- const error = this.createError(
1652
- RangeError,
1653
- `invalid opcode ${this._opcode}`,
1654
- true,
1655
- 1002,
1656
- "WS_ERR_INVALID_OPCODE"
1657
- );
1658
- cb(error);
1659
- return;
1660
- }
1661
- this._compressed = compressed;
1662
- } else if (this._opcode > 7 && this._opcode < 11) {
1663
- if (!this._fin) {
1664
- const error = this.createError(
1665
- RangeError,
1666
- "FIN must be set",
1667
- true,
1668
- 1002,
1669
- "WS_ERR_EXPECTED_FIN"
1670
- );
1671
- cb(error);
1672
- return;
1673
- }
1674
- if (compressed) {
1675
- const error = this.createError(
1676
- RangeError,
1677
- "RSV1 must be clear",
1678
- true,
1679
- 1002,
1680
- "WS_ERR_UNEXPECTED_RSV_1"
1681
- );
1682
- cb(error);
1683
- return;
1684
- }
1685
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1686
- const error = this.createError(
1687
- RangeError,
1688
- `invalid payload length ${this._payloadLength}`,
1689
- true,
1690
- 1002,
1691
- "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1692
- );
1693
- cb(error);
1694
- return;
1695
- }
1696
- } else {
1697
- const error = this.createError(
1698
- RangeError,
1699
- `invalid opcode ${this._opcode}`,
1700
- true,
1701
- 1002,
1702
- "WS_ERR_INVALID_OPCODE"
1703
- );
1704
- cb(error);
1705
- return;
1706
- }
1707
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1708
- this._masked = (buf[1] & 128) === 128;
1709
- if (this._isServer) {
1710
- if (!this._masked) {
1711
- const error = this.createError(
1712
- RangeError,
1713
- "MASK must be set",
1714
- true,
1715
- 1002,
1716
- "WS_ERR_EXPECTED_MASK"
1717
- );
1718
- cb(error);
1719
- return;
1720
- }
1721
- } else if (this._masked) {
1722
- const error = this.createError(
1723
- RangeError,
1724
- "MASK must be clear",
1725
- true,
1726
- 1002,
1727
- "WS_ERR_UNEXPECTED_MASK"
1728
- );
1729
- cb(error);
1730
- return;
1731
- }
1732
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1733
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1734
- else this.haveLength(cb);
1735
- }
1736
- /**
1737
- * Gets extended payload length (7+16).
1738
- *
1739
- * @param {Function} cb Callback
1740
- * @private
1741
- */
1742
- getPayloadLength16(cb) {
1743
- if (this._bufferedBytes < 2) {
1744
- this._loop = false;
1745
- return;
1746
- }
1747
- this._payloadLength = this.consume(2).readUInt16BE(0);
1748
- this.haveLength(cb);
1749
- }
1750
- /**
1751
- * Gets extended payload length (7+64).
1752
- *
1753
- * @param {Function} cb Callback
1754
- * @private
1755
- */
1756
- getPayloadLength64(cb) {
1757
- if (this._bufferedBytes < 8) {
1758
- this._loop = false;
1759
- return;
1760
- }
1761
- const buf = this.consume(8);
1762
- const num = buf.readUInt32BE(0);
1763
- if (num > Math.pow(2, 53 - 32) - 1) {
1764
- const error = this.createError(
1765
- RangeError,
1766
- "Unsupported WebSocket frame: payload length > 2^53 - 1",
1767
- false,
1768
- 1009,
1769
- "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1770
- );
1771
- cb(error);
1772
- return;
1773
- }
1774
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1775
- this.haveLength(cb);
1776
- }
1777
- /**
1778
- * Payload length has been read.
1779
- *
1780
- * @param {Function} cb Callback
1781
- * @private
1782
- */
1783
- haveLength(cb) {
1784
- if (this._payloadLength && this._opcode < 8) {
1785
- this._totalPayloadLength += this._payloadLength;
1786
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1787
- const error = this.createError(
1788
- RangeError,
1789
- "Max payload size exceeded",
1790
- false,
1791
- 1009,
1792
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1793
- );
1794
- cb(error);
1795
- return;
1796
- }
1797
- }
1798
- if (this._masked) this._state = GET_MASK;
1799
- else this._state = GET_DATA;
1800
- }
1801
- /**
1802
- * Reads mask bytes.
1803
- *
1804
- * @private
1805
- */
1806
- getMask() {
1807
- if (this._bufferedBytes < 4) {
1808
- this._loop = false;
1809
- return;
1810
- }
1811
- this._mask = this.consume(4);
1812
- this._state = GET_DATA;
1813
- }
1814
- /**
1815
- * Reads data bytes.
1816
- *
1817
- * @param {Function} cb Callback
1818
- * @private
1819
- */
1820
- getData(cb) {
1821
- let data = EMPTY_BUFFER;
1822
- if (this._payloadLength) {
1823
- if (this._bufferedBytes < this._payloadLength) {
1824
- this._loop = false;
1825
- return;
1826
- }
1827
- data = this.consume(this._payloadLength);
1828
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1829
- unmask(data, this._mask);
1830
- }
1831
- }
1832
- if (this._opcode > 7) {
1833
- this.controlMessage(data, cb);
1834
- return;
1835
- }
1836
- if (this._compressed) {
1837
- this._state = INFLATING;
1838
- this.decompress(data, cb);
1839
- return;
1840
- }
1841
- if (data.length) {
1842
- this._messageLength = this._totalPayloadLength;
1843
- this._fragments.push(data);
1844
- }
1845
- this.dataMessage(cb);
1846
- }
1847
- /**
1848
- * Decompresses data.
1849
- *
1850
- * @param {Buffer} data Compressed data
1851
- * @param {Function} cb Callback
1852
- * @private
1853
- */
1854
- decompress(data, cb) {
1855
- const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1856
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1857
- if (err) return cb(err);
1858
- if (buf.length) {
1859
- this._messageLength += buf.length;
1860
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1861
- const error = this.createError(
1862
- RangeError,
1863
- "Max payload size exceeded",
1864
- false,
1865
- 1009,
1866
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1867
- );
1868
- cb(error);
1869
- return;
1870
- }
1871
- this._fragments.push(buf);
1872
- }
1873
- this.dataMessage(cb);
1874
- if (this._state === GET_INFO) this.startLoop(cb);
1875
- });
1876
- }
1877
- /**
1878
- * Handles a data message.
1879
- *
1880
- * @param {Function} cb Callback
1881
- * @private
1882
- */
1883
- dataMessage(cb) {
1884
- if (!this._fin) {
1885
- this._state = GET_INFO;
1886
- return;
1887
- }
1888
- const messageLength = this._messageLength;
1889
- const fragments = this._fragments;
1890
- this._totalPayloadLength = 0;
1891
- this._messageLength = 0;
1892
- this._fragmented = 0;
1893
- this._fragments = [];
1894
- if (this._opcode === 2) {
1895
- let data;
1896
- if (this._binaryType === "nodebuffer") {
1897
- data = concat(fragments, messageLength);
1898
- } else if (this._binaryType === "arraybuffer") {
1899
- data = toArrayBuffer(concat(fragments, messageLength));
1900
- } else if (this._binaryType === "blob") {
1901
- data = new Blob(fragments);
1902
- } else {
1903
- data = fragments;
1904
- }
1905
- if (this._allowSynchronousEvents) {
1906
- this.emit("message", data, true);
1907
- this._state = GET_INFO;
1908
- } else {
1909
- this._state = DEFER_EVENT;
1910
- setImmediate(() => {
1911
- this.emit("message", data, true);
1912
- this._state = GET_INFO;
1913
- this.startLoop(cb);
1914
- });
1915
- }
1916
- } else {
1917
- const buf = concat(fragments, messageLength);
1918
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1919
- const error = this.createError(
1920
- Error,
1921
- "invalid UTF-8 sequence",
1922
- true,
1923
- 1007,
1924
- "WS_ERR_INVALID_UTF8"
1925
- );
1926
- cb(error);
1927
- return;
1928
- }
1929
- if (this._state === INFLATING || this._allowSynchronousEvents) {
1930
- this.emit("message", buf, false);
1931
- this._state = GET_INFO;
1932
- } else {
1933
- this._state = DEFER_EVENT;
1934
- setImmediate(() => {
1935
- this.emit("message", buf, false);
1936
- this._state = GET_INFO;
1937
- this.startLoop(cb);
1938
- });
1939
- }
1940
- }
1941
- }
1942
- /**
1943
- * Handles a control message.
1944
- *
1945
- * @param {Buffer} data Data to handle
1946
- * @return {(Error|RangeError|undefined)} A possible error
1947
- * @private
1948
- */
1949
- controlMessage(data, cb) {
1950
- if (this._opcode === 8) {
1951
- if (data.length === 0) {
1952
- this._loop = false;
1953
- this.emit("conclude", 1005, EMPTY_BUFFER);
1954
- this.end();
1955
- } else {
1956
- const code = data.readUInt16BE(0);
1957
- if (!isValidStatusCode(code)) {
1958
- const error = this.createError(
1959
- RangeError,
1960
- `invalid status code ${code}`,
1961
- true,
1962
- 1002,
1963
- "WS_ERR_INVALID_CLOSE_CODE"
1964
- );
1965
- cb(error);
1966
- return;
1967
- }
1968
- const buf = new FastBuffer(
1969
- data.buffer,
1970
- data.byteOffset + 2,
1971
- data.length - 2
1972
- );
1973
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1974
- const error = this.createError(
1975
- Error,
1976
- "invalid UTF-8 sequence",
1977
- true,
1978
- 1007,
1979
- "WS_ERR_INVALID_UTF8"
1980
- );
1981
- cb(error);
1982
- return;
1983
- }
1984
- this._loop = false;
1985
- this.emit("conclude", code, buf);
1986
- this.end();
1987
- }
1988
- this._state = GET_INFO;
1989
- return;
1990
- }
1991
- if (this._allowSynchronousEvents) {
1992
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1993
- this._state = GET_INFO;
1994
- } else {
1995
- this._state = DEFER_EVENT;
1996
- setImmediate(() => {
1997
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1998
- this._state = GET_INFO;
1999
- this.startLoop(cb);
2000
- });
2001
- }
2002
- }
2003
- /**
2004
- * Builds an error object.
2005
- *
2006
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
2007
- * @param {String} message The error message
2008
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
2009
- * `message`
2010
- * @param {Number} statusCode The status code
2011
- * @param {String} errorCode The exposed error code
2012
- * @return {(Error|RangeError)} The error
2013
- * @private
2014
- */
2015
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
2016
- this._loop = false;
2017
- this._errored = true;
2018
- const err = new ErrorCtor(
2019
- prefix ? `Invalid WebSocket frame: ${message}` : message
2020
- );
2021
- Error.captureStackTrace(err, this.createError);
2022
- err.code = errorCode;
2023
- err[kStatusCode] = statusCode;
2024
- return err;
2025
- }
2026
- };
2027
- module.exports = Receiver2;
2028
- }
2029
- });
2030
-
2031
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js
2032
- var require_sender = __commonJS({
2033
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js"(exports, module) {
2034
- "use strict";
2035
- var { Duplex } = __require("stream");
2036
- var { randomFillSync } = __require("crypto");
2037
- var PerMessageDeflate2 = require_permessage_deflate();
2038
- var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
2039
- var { isBlob, isValidStatusCode } = require_validation();
2040
- var { mask: applyMask, toBuffer } = require_buffer_util();
2041
- var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
2042
- var maskBuffer = Buffer.alloc(4);
2043
- var RANDOM_POOL_SIZE = 8 * 1024;
2044
- var randomPool;
2045
- var randomPoolPointer = RANDOM_POOL_SIZE;
2046
- var DEFAULT = 0;
2047
- var DEFLATING = 1;
2048
- var GET_BLOB_DATA = 2;
2049
- var Sender2 = class _Sender {
2050
- /**
2051
- * Creates a Sender instance.
2052
- *
2053
- * @param {Duplex} socket The connection socket
2054
- * @param {Object} [extensions] An object containing the negotiated extensions
2055
- * @param {Function} [generateMask] The function used to generate the masking
2056
- * key
2057
- */
2058
- constructor(socket, extensions, generateMask) {
2059
- this._extensions = extensions || {};
2060
- if (generateMask) {
2061
- this._generateMask = generateMask;
2062
- this._maskBuffer = Buffer.alloc(4);
2063
- }
2064
- this._socket = socket;
2065
- this._firstFragment = true;
2066
- this._compress = false;
2067
- this._bufferedBytes = 0;
2068
- this._queue = [];
2069
- this._state = DEFAULT;
2070
- this.onerror = NOOP;
2071
- this[kWebSocket] = void 0;
2072
- }
2073
- /**
2074
- * Frames a piece of data according to the HyBi WebSocket protocol.
2075
- *
2076
- * @param {(Buffer|String)} data The data to frame
2077
- * @param {Object} options Options object
2078
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
2079
- * FIN bit
2080
- * @param {Function} [options.generateMask] The function used to generate the
2081
- * masking key
2082
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
2083
- * `data`
2084
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
2085
- * key
2086
- * @param {Number} options.opcode The opcode
2087
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
2088
- * modified
2089
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
2090
- * RSV1 bit
2091
- * @return {(Buffer|String)[]} The framed data
2092
- * @public
2093
- */
2094
- static frame(data, options) {
2095
- let mask;
2096
- let merge = false;
2097
- let offset = 2;
2098
- let skipMasking = false;
2099
- if (options.mask) {
2100
- mask = options.maskBuffer || maskBuffer;
2101
- if (options.generateMask) {
2102
- options.generateMask(mask);
2103
- } else {
2104
- if (randomPoolPointer === RANDOM_POOL_SIZE) {
2105
- if (randomPool === void 0) {
2106
- randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
2107
- }
2108
- randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
2109
- randomPoolPointer = 0;
2110
- }
2111
- mask[0] = randomPool[randomPoolPointer++];
2112
- mask[1] = randomPool[randomPoolPointer++];
2113
- mask[2] = randomPool[randomPoolPointer++];
2114
- mask[3] = randomPool[randomPoolPointer++];
2115
- }
2116
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
2117
- offset = 6;
2118
- }
2119
- let dataLength;
2120
- if (typeof data === "string") {
2121
- if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
2122
- dataLength = options[kByteLength];
2123
- } else {
2124
- data = Buffer.from(data);
2125
- dataLength = data.length;
2126
- }
2127
- } else {
2128
- dataLength = data.length;
2129
- merge = options.mask && options.readOnly && !skipMasking;
2130
- }
2131
- let payloadLength = dataLength;
2132
- if (dataLength >= 65536) {
2133
- offset += 8;
2134
- payloadLength = 127;
2135
- } else if (dataLength > 125) {
2136
- offset += 2;
2137
- payloadLength = 126;
2138
- }
2139
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
2140
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
2141
- if (options.rsv1) target[0] |= 64;
2142
- target[1] = payloadLength;
2143
- if (payloadLength === 126) {
2144
- target.writeUInt16BE(dataLength, 2);
2145
- } else if (payloadLength === 127) {
2146
- target[2] = target[3] = 0;
2147
- target.writeUIntBE(dataLength, 4, 6);
2148
- }
2149
- if (!options.mask) return [target, data];
2150
- target[1] |= 128;
2151
- target[offset - 4] = mask[0];
2152
- target[offset - 3] = mask[1];
2153
- target[offset - 2] = mask[2];
2154
- target[offset - 1] = mask[3];
2155
- if (skipMasking) return [target, data];
2156
- if (merge) {
2157
- applyMask(data, mask, target, offset, dataLength);
2158
- return [target];
2159
- }
2160
- applyMask(data, mask, data, 0, dataLength);
2161
- return [target, data];
2162
- }
2163
- /**
2164
- * Sends a close message to the other peer.
2165
- *
2166
- * @param {Number} [code] The status code component of the body
2167
- * @param {(String|Buffer)} [data] The message component of the body
2168
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
2169
- * @param {Function} [cb] Callback
2170
- * @public
2171
- */
2172
- close(code, data, mask, cb) {
2173
- let buf;
2174
- if (code === void 0) {
2175
- buf = EMPTY_BUFFER;
2176
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
2177
- throw new TypeError("First argument must be a valid error code number");
2178
- } else if (data === void 0 || !data.length) {
2179
- buf = Buffer.allocUnsafe(2);
2180
- buf.writeUInt16BE(code, 0);
2181
- } else {
2182
- const length = Buffer.byteLength(data);
2183
- if (length > 123) {
2184
- throw new RangeError("The message must not be greater than 123 bytes");
2185
- }
2186
- buf = Buffer.allocUnsafe(2 + length);
2187
- buf.writeUInt16BE(code, 0);
2188
- if (typeof data === "string") {
2189
- buf.write(data, 2);
2190
- } else {
2191
- buf.set(data, 2);
2192
- }
2193
- }
2194
- const options = {
2195
- [kByteLength]: buf.length,
2196
- fin: true,
2197
- generateMask: this._generateMask,
2198
- mask,
2199
- maskBuffer: this._maskBuffer,
2200
- opcode: 8,
2201
- readOnly: false,
2202
- rsv1: false
2203
- };
2204
- if (this._state !== DEFAULT) {
2205
- this.enqueue([this.dispatch, buf, false, options, cb]);
2206
- } else {
2207
- this.sendFrame(_Sender.frame(buf, options), cb);
2208
- }
2209
- }
2210
- /**
2211
- * Sends a ping message to the other peer.
2212
- *
2213
- * @param {*} data The message to send
2214
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
2215
- * @param {Function} [cb] Callback
2216
- * @public
2217
- */
2218
- ping(data, mask, cb) {
2219
- let byteLength;
2220
- let readOnly;
2221
- if (typeof data === "string") {
2222
- byteLength = Buffer.byteLength(data);
2223
- readOnly = false;
2224
- } else if (isBlob(data)) {
2225
- byteLength = data.size;
2226
- readOnly = false;
2227
- } else {
2228
- data = toBuffer(data);
2229
- byteLength = data.length;
2230
- readOnly = toBuffer.readOnly;
2231
- }
2232
- if (byteLength > 125) {
2233
- throw new RangeError("The data size must not be greater than 125 bytes");
2234
- }
2235
- const options = {
2236
- [kByteLength]: byteLength,
2237
- fin: true,
2238
- generateMask: this._generateMask,
2239
- mask,
2240
- maskBuffer: this._maskBuffer,
2241
- opcode: 9,
2242
- readOnly,
2243
- rsv1: false
2244
- };
2245
- if (isBlob(data)) {
2246
- if (this._state !== DEFAULT) {
2247
- this.enqueue([this.getBlobData, data, false, options, cb]);
2248
- } else {
2249
- this.getBlobData(data, false, options, cb);
2250
- }
2251
- } else if (this._state !== DEFAULT) {
2252
- this.enqueue([this.dispatch, data, false, options, cb]);
2253
- } else {
2254
- this.sendFrame(_Sender.frame(data, options), cb);
2255
- }
2256
- }
2257
- /**
2258
- * Sends a pong message to the other peer.
2259
- *
2260
- * @param {*} data The message to send
2261
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
2262
- * @param {Function} [cb] Callback
2263
- * @public
2264
- */
2265
- pong(data, mask, cb) {
2266
- let byteLength;
2267
- let readOnly;
2268
- if (typeof data === "string") {
2269
- byteLength = Buffer.byteLength(data);
2270
- readOnly = false;
2271
- } else if (isBlob(data)) {
2272
- byteLength = data.size;
2273
- readOnly = false;
2274
- } else {
2275
- data = toBuffer(data);
2276
- byteLength = data.length;
2277
- readOnly = toBuffer.readOnly;
2278
- }
2279
- if (byteLength > 125) {
2280
- throw new RangeError("The data size must not be greater than 125 bytes");
2281
- }
2282
- const options = {
2283
- [kByteLength]: byteLength,
2284
- fin: true,
2285
- generateMask: this._generateMask,
2286
- mask,
2287
- maskBuffer: this._maskBuffer,
2288
- opcode: 10,
2289
- readOnly,
2290
- rsv1: false
2291
- };
2292
- if (isBlob(data)) {
2293
- if (this._state !== DEFAULT) {
2294
- this.enqueue([this.getBlobData, data, false, options, cb]);
2295
- } else {
2296
- this.getBlobData(data, false, options, cb);
2297
- }
2298
- } else if (this._state !== DEFAULT) {
2299
- this.enqueue([this.dispatch, data, false, options, cb]);
2300
- } else {
2301
- this.sendFrame(_Sender.frame(data, options), cb);
2302
- }
2303
- }
2304
- /**
2305
- * Sends a data message to the other peer.
2306
- *
2307
- * @param {*} data The message to send
2308
- * @param {Object} options Options object
2309
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
2310
- * or text
2311
- * @param {Boolean} [options.compress=false] Specifies whether or not to
2312
- * compress `data`
2313
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
2314
- * last one
2315
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
2316
- * `data`
2317
- * @param {Function} [cb] Callback
2318
- * @public
2319
- */
2320
- send(data, options, cb) {
2321
- const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
2322
- let opcode = options.binary ? 2 : 1;
2323
- let rsv1 = options.compress;
2324
- let byteLength;
2325
- let readOnly;
2326
- if (typeof data === "string") {
2327
- byteLength = Buffer.byteLength(data);
2328
- readOnly = false;
2329
- } else if (isBlob(data)) {
2330
- byteLength = data.size;
2331
- readOnly = false;
2332
- } else {
2333
- data = toBuffer(data);
2334
- byteLength = data.length;
2335
- readOnly = toBuffer.readOnly;
2336
- }
2337
- if (this._firstFragment) {
2338
- this._firstFragment = false;
2339
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
2340
- rsv1 = byteLength >= perMessageDeflate._threshold;
2341
- }
2342
- this._compress = rsv1;
2343
- } else {
2344
- rsv1 = false;
2345
- opcode = 0;
2346
- }
2347
- if (options.fin) this._firstFragment = true;
2348
- const opts = {
2349
- [kByteLength]: byteLength,
2350
- fin: options.fin,
2351
- generateMask: this._generateMask,
2352
- mask: options.mask,
2353
- maskBuffer: this._maskBuffer,
2354
- opcode,
2355
- readOnly,
2356
- rsv1
2357
- };
2358
- if (isBlob(data)) {
2359
- if (this._state !== DEFAULT) {
2360
- this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
2361
- } else {
2362
- this.getBlobData(data, this._compress, opts, cb);
2363
- }
2364
- } else if (this._state !== DEFAULT) {
2365
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
2366
- } else {
2367
- this.dispatch(data, this._compress, opts, cb);
2368
- }
2369
- }
2370
- /**
2371
- * Gets the contents of a blob as binary data.
2372
- *
2373
- * @param {Blob} blob The blob
2374
- * @param {Boolean} [compress=false] Specifies whether or not to compress
2375
- * the data
2376
- * @param {Object} options Options object
2377
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
2378
- * FIN bit
2379
- * @param {Function} [options.generateMask] The function used to generate the
2380
- * masking key
2381
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
2382
- * `data`
2383
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
2384
- * key
2385
- * @param {Number} options.opcode The opcode
2386
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
2387
- * modified
2388
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
2389
- * RSV1 bit
2390
- * @param {Function} [cb] Callback
2391
- * @private
2392
- */
2393
- getBlobData(blob, compress, options, cb) {
2394
- this._bufferedBytes += options[kByteLength];
2395
- this._state = GET_BLOB_DATA;
2396
- blob.arrayBuffer().then((arrayBuffer) => {
2397
- if (this._socket.destroyed) {
2398
- const err = new Error(
2399
- "The socket was closed while the blob was being read"
2400
- );
2401
- process.nextTick(callCallbacks, this, err, cb);
2402
- return;
2403
- }
2404
- this._bufferedBytes -= options[kByteLength];
2405
- const data = toBuffer(arrayBuffer);
2406
- if (!compress) {
2407
- this._state = DEFAULT;
2408
- this.sendFrame(_Sender.frame(data, options), cb);
2409
- this.dequeue();
2410
- } else {
2411
- this.dispatch(data, compress, options, cb);
2412
- }
2413
- }).catch((err) => {
2414
- process.nextTick(onError, this, err, cb);
2415
- });
2416
- }
2417
- /**
2418
- * Dispatches a message.
2419
- *
2420
- * @param {(Buffer|String)} data The message to send
2421
- * @param {Boolean} [compress=false] Specifies whether or not to compress
2422
- * `data`
2423
- * @param {Object} options Options object
2424
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
2425
- * FIN bit
2426
- * @param {Function} [options.generateMask] The function used to generate the
2427
- * masking key
2428
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
2429
- * `data`
2430
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
2431
- * key
2432
- * @param {Number} options.opcode The opcode
2433
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
2434
- * modified
2435
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
2436
- * RSV1 bit
2437
- * @param {Function} [cb] Callback
2438
- * @private
2439
- */
2440
- dispatch(data, compress, options, cb) {
2441
- if (!compress) {
2442
- this.sendFrame(_Sender.frame(data, options), cb);
2443
- return;
2444
- }
2445
- const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
2446
- this._bufferedBytes += options[kByteLength];
2447
- this._state = DEFLATING;
2448
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
2449
- if (this._socket.destroyed) {
2450
- const err = new Error(
2451
- "The socket was closed while data was being compressed"
2452
- );
2453
- callCallbacks(this, err, cb);
2454
- return;
2455
- }
2456
- this._bufferedBytes -= options[kByteLength];
2457
- this._state = DEFAULT;
2458
- options.readOnly = false;
2459
- this.sendFrame(_Sender.frame(buf, options), cb);
2460
- this.dequeue();
2461
- });
2462
- }
2463
- /**
2464
- * Executes queued send operations.
2465
- *
2466
- * @private
2467
- */
2468
- dequeue() {
2469
- while (this._state === DEFAULT && this._queue.length) {
2470
- const params = this._queue.shift();
2471
- this._bufferedBytes -= params[3][kByteLength];
2472
- Reflect.apply(params[0], this, params.slice(1));
2473
- }
2474
- }
2475
- /**
2476
- * Enqueues a send operation.
2477
- *
2478
- * @param {Array} params Send operation parameters.
2479
- * @private
2480
- */
2481
- enqueue(params) {
2482
- this._bufferedBytes += params[3][kByteLength];
2483
- this._queue.push(params);
2484
- }
2485
- /**
2486
- * Sends a frame.
2487
- *
2488
- * @param {(Buffer | String)[]} list The frame to send
2489
- * @param {Function} [cb] Callback
2490
- * @private
2491
- */
2492
- sendFrame(list, cb) {
2493
- if (list.length === 2) {
2494
- this._socket.cork();
2495
- this._socket.write(list[0]);
2496
- this._socket.write(list[1], cb);
2497
- this._socket.uncork();
2498
- } else {
2499
- this._socket.write(list[0], cb);
2500
- }
2501
- }
2502
- };
2503
- module.exports = Sender2;
2504
- function callCallbacks(sender, err, cb) {
2505
- if (typeof cb === "function") cb(err);
2506
- for (let i = 0; i < sender._queue.length; i++) {
2507
- const params = sender._queue[i];
2508
- const callback = params[params.length - 1];
2509
- if (typeof callback === "function") callback(err);
2510
- }
2511
- }
2512
- function onError(sender, err, cb) {
2513
- callCallbacks(sender, err, cb);
2514
- sender.onerror(err);
2515
- }
2516
- }
2517
- });
2518
-
2519
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js
2520
- var require_event_target = __commonJS({
2521
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js"(exports, module) {
2522
- "use strict";
2523
- var { kForOnEventAttribute, kListener } = require_constants();
2524
- var kCode = /* @__PURE__ */ Symbol("kCode");
2525
- var kData = /* @__PURE__ */ Symbol("kData");
2526
- var kError = /* @__PURE__ */ Symbol("kError");
2527
- var kMessage = /* @__PURE__ */ Symbol("kMessage");
2528
- var kReason = /* @__PURE__ */ Symbol("kReason");
2529
- var kTarget = /* @__PURE__ */ Symbol("kTarget");
2530
- var kType = /* @__PURE__ */ Symbol("kType");
2531
- var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
2532
- var Event = class {
2533
- /**
2534
- * Create a new `Event`.
2535
- *
2536
- * @param {String} type The name of the event
2537
- * @throws {TypeError} If the `type` argument is not specified
2538
- */
2539
- constructor(type) {
2540
- this[kTarget] = null;
2541
- this[kType] = type;
2542
- }
2543
- /**
2544
- * @type {*}
2545
- */
2546
- get target() {
2547
- return this[kTarget];
2548
- }
2549
- /**
2550
- * @type {String}
2551
- */
2552
- get type() {
2553
- return this[kType];
2554
- }
2555
- };
2556
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
2557
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
2558
- var CloseEvent = class extends Event {
2559
- /**
2560
- * Create a new `CloseEvent`.
2561
- *
2562
- * @param {String} type The name of the event
2563
- * @param {Object} [options] A dictionary object that allows for setting
2564
- * attributes via object members of the same name
2565
- * @param {Number} [options.code=0] The status code explaining why the
2566
- * connection was closed
2567
- * @param {String} [options.reason=''] A human-readable string explaining why
2568
- * the connection was closed
2569
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
2570
- * connection was cleanly closed
2571
- */
2572
- constructor(type, options = {}) {
2573
- super(type);
2574
- this[kCode] = options.code === void 0 ? 0 : options.code;
2575
- this[kReason] = options.reason === void 0 ? "" : options.reason;
2576
- this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
2577
- }
2578
- /**
2579
- * @type {Number}
2580
- */
2581
- get code() {
2582
- return this[kCode];
2583
- }
2584
- /**
2585
- * @type {String}
2586
- */
2587
- get reason() {
2588
- return this[kReason];
2589
- }
2590
- /**
2591
- * @type {Boolean}
2592
- */
2593
- get wasClean() {
2594
- return this[kWasClean];
2595
- }
2596
- };
2597
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
2598
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
2599
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
2600
- var ErrorEvent = class extends Event {
2601
- /**
2602
- * Create a new `ErrorEvent`.
2603
- *
2604
- * @param {String} type The name of the event
2605
- * @param {Object} [options] A dictionary object that allows for setting
2606
- * attributes via object members of the same name
2607
- * @param {*} [options.error=null] The error that generated this event
2608
- * @param {String} [options.message=''] The error message
2609
- */
2610
- constructor(type, options = {}) {
2611
- super(type);
2612
- this[kError] = options.error === void 0 ? null : options.error;
2613
- this[kMessage] = options.message === void 0 ? "" : options.message;
2614
- }
2615
- /**
2616
- * @type {*}
2617
- */
2618
- get error() {
2619
- return this[kError];
2620
- }
2621
- /**
2622
- * @type {String}
2623
- */
2624
- get message() {
2625
- return this[kMessage];
2626
- }
2627
- };
2628
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
2629
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
2630
- var MessageEvent = class extends Event {
2631
- /**
2632
- * Create a new `MessageEvent`.
2633
- *
2634
- * @param {String} type The name of the event
2635
- * @param {Object} [options] A dictionary object that allows for setting
2636
- * attributes via object members of the same name
2637
- * @param {*} [options.data=null] The message content
2638
- */
2639
- constructor(type, options = {}) {
2640
- super(type);
2641
- this[kData] = options.data === void 0 ? null : options.data;
2642
- }
2643
- /**
2644
- * @type {*}
2645
- */
2646
- get data() {
2647
- return this[kData];
2648
- }
2649
- };
2650
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2651
- var EventTarget = {
2652
- /**
2653
- * Register an event listener.
2654
- *
2655
- * @param {String} type A string representing the event type to listen for
2656
- * @param {(Function|Object)} handler The listener to add
2657
- * @param {Object} [options] An options object specifies characteristics about
2658
- * the event listener
2659
- * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2660
- * listener should be invoked at most once after being added. If `true`,
2661
- * the listener would be automatically removed when invoked.
2662
- * @public
2663
- */
2664
- addEventListener(type, handler, options = {}) {
2665
- for (const listener of this.listeners(type)) {
2666
- if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2667
- return;
2668
- }
2669
- }
2670
- let wrapper;
2671
- if (type === "message") {
2672
- wrapper = function onMessage(data, isBinary) {
2673
- const event = new MessageEvent("message", {
2674
- data: isBinary ? data : data.toString()
2675
- });
2676
- event[kTarget] = this;
2677
- callListener(handler, this, event);
2678
- };
2679
- } else if (type === "close") {
2680
- wrapper = function onClose(code, message) {
2681
- const event = new CloseEvent("close", {
2682
- code,
2683
- reason: message.toString(),
2684
- wasClean: this._closeFrameReceived && this._closeFrameSent
2685
- });
2686
- event[kTarget] = this;
2687
- callListener(handler, this, event);
2688
- };
2689
- } else if (type === "error") {
2690
- wrapper = function onError(error) {
2691
- const event = new ErrorEvent("error", {
2692
- error,
2693
- message: error.message
2694
- });
2695
- event[kTarget] = this;
2696
- callListener(handler, this, event);
2697
- };
2698
- } else if (type === "open") {
2699
- wrapper = function onOpen() {
2700
- const event = new Event("open");
2701
- event[kTarget] = this;
2702
- callListener(handler, this, event);
2703
- };
2704
- } else {
2705
- return;
2706
- }
2707
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2708
- wrapper[kListener] = handler;
2709
- if (options.once) {
2710
- this.once(type, wrapper);
2711
- } else {
2712
- this.on(type, wrapper);
2713
- }
2714
- },
2715
- /**
2716
- * Remove an event listener.
2717
- *
2718
- * @param {String} type A string representing the event type to remove
2719
- * @param {(Function|Object)} handler The listener to remove
2720
- * @public
2721
- */
2722
- removeEventListener(type, handler) {
2723
- for (const listener of this.listeners(type)) {
2724
- if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2725
- this.removeListener(type, listener);
2726
- break;
2727
- }
2728
- }
2729
- }
2730
- };
2731
- module.exports = {
2732
- CloseEvent,
2733
- ErrorEvent,
2734
- Event,
2735
- EventTarget,
2736
- MessageEvent
2737
- };
2738
- function callListener(listener, thisArg, event) {
2739
- if (typeof listener === "object" && listener.handleEvent) {
2740
- listener.handleEvent.call(listener, event);
2741
- } else {
2742
- listener.call(thisArg, event);
2743
- }
2744
- }
2745
- }
2746
- });
2747
-
2748
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js
2749
- var require_extension = __commonJS({
2750
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js"(exports, module) {
2751
- "use strict";
2752
- var { tokenChars } = require_validation();
2753
- function push(dest, name, elem) {
2754
- if (dest[name] === void 0) dest[name] = [elem];
2755
- else dest[name].push(elem);
2756
- }
2757
- function parse(header) {
2758
- const offers = /* @__PURE__ */ Object.create(null);
2759
- let params = /* @__PURE__ */ Object.create(null);
2760
- let mustUnescape = false;
2761
- let isEscaping = false;
2762
- let inQuotes = false;
2763
- let extensionName;
2764
- let paramName;
2765
- let start = -1;
2766
- let code = -1;
2767
- let end = -1;
2768
- let i = 0;
2769
- for (; i < header.length; i++) {
2770
- code = header.charCodeAt(i);
2771
- if (extensionName === void 0) {
2772
- if (end === -1 && tokenChars[code] === 1) {
2773
- if (start === -1) start = i;
2774
- } else if (i !== 0 && (code === 32 || code === 9)) {
2775
- if (end === -1 && start !== -1) end = i;
2776
- } else if (code === 59 || code === 44) {
2777
- if (start === -1) {
2778
- throw new SyntaxError(`Unexpected character at index ${i}`);
2779
- }
2780
- if (end === -1) end = i;
2781
- const name = header.slice(start, end);
2782
- if (code === 44) {
2783
- push(offers, name, params);
2784
- params = /* @__PURE__ */ Object.create(null);
2785
- } else {
2786
- extensionName = name;
2787
- }
2788
- start = end = -1;
2789
- } else {
2790
- throw new SyntaxError(`Unexpected character at index ${i}`);
2791
- }
2792
- } else if (paramName === void 0) {
2793
- if (end === -1 && tokenChars[code] === 1) {
2794
- if (start === -1) start = i;
2795
- } else if (code === 32 || code === 9) {
2796
- if (end === -1 && start !== -1) end = i;
2797
- } else if (code === 59 || code === 44) {
2798
- if (start === -1) {
2799
- throw new SyntaxError(`Unexpected character at index ${i}`);
2800
- }
2801
- if (end === -1) end = i;
2802
- push(params, header.slice(start, end), true);
2803
- if (code === 44) {
2804
- push(offers, extensionName, params);
2805
- params = /* @__PURE__ */ Object.create(null);
2806
- extensionName = void 0;
2807
- }
2808
- start = end = -1;
2809
- } else if (code === 61 && start !== -1 && end === -1) {
2810
- paramName = header.slice(start, i);
2811
- start = end = -1;
2812
- } else {
2813
- throw new SyntaxError(`Unexpected character at index ${i}`);
2814
- }
2815
- } else {
2816
- if (isEscaping) {
2817
- if (tokenChars[code] !== 1) {
2818
- throw new SyntaxError(`Unexpected character at index ${i}`);
2819
- }
2820
- if (start === -1) start = i;
2821
- else if (!mustUnescape) mustUnescape = true;
2822
- isEscaping = false;
2823
- } else if (inQuotes) {
2824
- if (tokenChars[code] === 1) {
2825
- if (start === -1) start = i;
2826
- } else if (code === 34 && start !== -1) {
2827
- inQuotes = false;
2828
- end = i;
2829
- } else if (code === 92) {
2830
- isEscaping = true;
2831
- } else {
2832
- throw new SyntaxError(`Unexpected character at index ${i}`);
2833
- }
2834
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2835
- inQuotes = true;
2836
- } else if (end === -1 && tokenChars[code] === 1) {
2837
- if (start === -1) start = i;
2838
- } else if (start !== -1 && (code === 32 || code === 9)) {
2839
- if (end === -1) end = i;
2840
- } else if (code === 59 || code === 44) {
2841
- if (start === -1) {
2842
- throw new SyntaxError(`Unexpected character at index ${i}`);
2843
- }
2844
- if (end === -1) end = i;
2845
- let value = header.slice(start, end);
2846
- if (mustUnescape) {
2847
- value = value.replace(/\\/g, "");
2848
- mustUnescape = false;
2849
- }
2850
- push(params, paramName, value);
2851
- if (code === 44) {
2852
- push(offers, extensionName, params);
2853
- params = /* @__PURE__ */ Object.create(null);
2854
- extensionName = void 0;
2855
- }
2856
- paramName = void 0;
2857
- start = end = -1;
2858
- } else {
2859
- throw new SyntaxError(`Unexpected character at index ${i}`);
2860
- }
2861
- }
2862
- }
2863
- if (start === -1 || inQuotes || code === 32 || code === 9) {
2864
- throw new SyntaxError("Unexpected end of input");
2865
- }
2866
- if (end === -1) end = i;
2867
- const token = header.slice(start, end);
2868
- if (extensionName === void 0) {
2869
- push(offers, token, params);
2870
- } else {
2871
- if (paramName === void 0) {
2872
- push(params, token, true);
2873
- } else if (mustUnescape) {
2874
- push(params, paramName, token.replace(/\\/g, ""));
2875
- } else {
2876
- push(params, paramName, token);
2877
- }
2878
- push(offers, extensionName, params);
2879
- }
2880
- return offers;
2881
- }
2882
- function format(extensions) {
2883
- return Object.keys(extensions).map((extension2) => {
2884
- let configurations = extensions[extension2];
2885
- if (!Array.isArray(configurations)) configurations = [configurations];
2886
- return configurations.map((params) => {
2887
- return [extension2].concat(
2888
- Object.keys(params).map((k) => {
2889
- let values = params[k];
2890
- if (!Array.isArray(values)) values = [values];
2891
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2892
- })
2893
- ).join("; ");
2894
- }).join(", ");
2895
- }).join(", ");
2896
- }
2897
- module.exports = { format, parse };
2898
- }
2899
- });
2900
-
2901
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js
2902
- var require_websocket = __commonJS({
2903
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js"(exports, module) {
2904
- "use strict";
2905
- var EventEmitter = __require("events");
2906
- var https = __require("https");
2907
- var http = __require("http");
2908
- var net = __require("net");
2909
- var tls = __require("tls");
2910
- var { randomBytes, createHash } = __require("crypto");
2911
- var { Duplex, Readable } = __require("stream");
2912
- var { URL } = __require("url");
2913
- var PerMessageDeflate2 = require_permessage_deflate();
2914
- var Receiver2 = require_receiver();
2915
- var Sender2 = require_sender();
2916
- var { isBlob } = require_validation();
2917
- var {
2918
- BINARY_TYPES,
2919
- CLOSE_TIMEOUT,
2920
- EMPTY_BUFFER,
2921
- GUID,
2922
- kForOnEventAttribute,
2923
- kListener,
2924
- kStatusCode,
2925
- kWebSocket,
2926
- NOOP
2927
- } = require_constants();
2928
- var {
2929
- EventTarget: { addEventListener, removeEventListener }
2930
- } = require_event_target();
2931
- var { format, parse } = require_extension();
2932
- var { toBuffer } = require_buffer_util();
2933
- var kAborted = /* @__PURE__ */ Symbol("kAborted");
2934
- var protocolVersions = [8, 13];
2935
- var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2936
- var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2937
- var WebSocket2 = class _WebSocket extends EventEmitter {
2938
- /**
2939
- * Create a new `WebSocket`.
2940
- *
2941
- * @param {(String|URL)} address The URL to which to connect
2942
- * @param {(String|String[])} [protocols] The subprotocols
2943
- * @param {Object} [options] Connection options
2944
- */
2945
- constructor(address, protocols, options) {
2946
- super();
2947
- this._binaryType = BINARY_TYPES[0];
2948
- this._closeCode = 1006;
2949
- this._closeFrameReceived = false;
2950
- this._closeFrameSent = false;
2951
- this._closeMessage = EMPTY_BUFFER;
2952
- this._closeTimer = null;
2953
- this._errorEmitted = false;
2954
- this._extensions = {};
2955
- this._paused = false;
2956
- this._protocol = "";
2957
- this._readyState = _WebSocket.CONNECTING;
2958
- this._receiver = null;
2959
- this._sender = null;
2960
- this._socket = null;
2961
- if (address !== null) {
2962
- this._bufferedAmount = 0;
2963
- this._isServer = false;
2964
- this._redirects = 0;
2965
- if (protocols === void 0) {
2966
- protocols = [];
2967
- } else if (!Array.isArray(protocols)) {
2968
- if (typeof protocols === "object" && protocols !== null) {
2969
- options = protocols;
2970
- protocols = [];
2971
- } else {
2972
- protocols = [protocols];
2973
- }
2974
- }
2975
- initAsClient(this, address, protocols, options);
2976
- } else {
2977
- this._autoPong = options.autoPong;
2978
- this._closeTimeout = options.closeTimeout;
2979
- this._isServer = true;
2980
- }
2981
- }
2982
- /**
2983
- * For historical reasons, the custom "nodebuffer" type is used by the default
2984
- * instead of "blob".
2985
- *
2986
- * @type {String}
2987
- */
2988
- get binaryType() {
2989
- return this._binaryType;
2990
- }
2991
- set binaryType(type) {
2992
- if (!BINARY_TYPES.includes(type)) return;
2993
- this._binaryType = type;
2994
- if (this._receiver) this._receiver._binaryType = type;
2995
- }
2996
- /**
2997
- * @type {Number}
2998
- */
2999
- get bufferedAmount() {
3000
- if (!this._socket) return this._bufferedAmount;
3001
- return this._socket._writableState.length + this._sender._bufferedBytes;
3002
- }
3003
- /**
3004
- * @type {String}
3005
- */
3006
- get extensions() {
3007
- return Object.keys(this._extensions).join();
3008
- }
3009
- /**
3010
- * @type {Boolean}
3011
- */
3012
- get isPaused() {
3013
- return this._paused;
3014
- }
3015
- /**
3016
- * @type {Function}
3017
- */
3018
- /* istanbul ignore next */
3019
- get onclose() {
3020
- return null;
3021
- }
3022
- /**
3023
- * @type {Function}
3024
- */
3025
- /* istanbul ignore next */
3026
- get onerror() {
3027
- return null;
3028
- }
3029
- /**
3030
- * @type {Function}
3031
- */
3032
- /* istanbul ignore next */
3033
- get onopen() {
3034
- return null;
3035
- }
3036
- /**
3037
- * @type {Function}
3038
- */
3039
- /* istanbul ignore next */
3040
- get onmessage() {
3041
- return null;
3042
- }
3043
- /**
3044
- * @type {String}
3045
- */
3046
- get protocol() {
3047
- return this._protocol;
3048
- }
3049
- /**
3050
- * @type {Number}
3051
- */
3052
- get readyState() {
3053
- return this._readyState;
3054
- }
3055
- /**
3056
- * @type {String}
3057
- */
3058
- get url() {
3059
- return this._url;
3060
- }
3061
- /**
3062
- * Set up the socket and the internal resources.
3063
- *
3064
- * @param {Duplex} socket The network socket between the server and client
3065
- * @param {Buffer} head The first packet of the upgraded stream
3066
- * @param {Object} options Options object
3067
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
3068
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3069
- * multiple times in the same tick
3070
- * @param {Function} [options.generateMask] The function used to generate the
3071
- * masking key
3072
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
3073
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3074
- * not to skip UTF-8 validation for text and close messages
3075
- * @private
3076
- */
3077
- setSocket(socket, head, options) {
3078
- const receiver = new Receiver2({
3079
- allowSynchronousEvents: options.allowSynchronousEvents,
3080
- binaryType: this.binaryType,
3081
- extensions: this._extensions,
3082
- isServer: this._isServer,
3083
- maxPayload: options.maxPayload,
3084
- skipUTF8Validation: options.skipUTF8Validation
3085
- });
3086
- const sender = new Sender2(socket, this._extensions, options.generateMask);
3087
- this._receiver = receiver;
3088
- this._sender = sender;
3089
- this._socket = socket;
3090
- receiver[kWebSocket] = this;
3091
- sender[kWebSocket] = this;
3092
- socket[kWebSocket] = this;
3093
- receiver.on("conclude", receiverOnConclude);
3094
- receiver.on("drain", receiverOnDrain);
3095
- receiver.on("error", receiverOnError);
3096
- receiver.on("message", receiverOnMessage);
3097
- receiver.on("ping", receiverOnPing);
3098
- receiver.on("pong", receiverOnPong);
3099
- sender.onerror = senderOnError;
3100
- if (socket.setTimeout) socket.setTimeout(0);
3101
- if (socket.setNoDelay) socket.setNoDelay();
3102
- if (head.length > 0) socket.unshift(head);
3103
- socket.on("close", socketOnClose);
3104
- socket.on("data", socketOnData);
3105
- socket.on("end", socketOnEnd);
3106
- socket.on("error", socketOnError);
3107
- this._readyState = _WebSocket.OPEN;
3108
- this.emit("open");
3109
- }
3110
- /**
3111
- * Emit the `'close'` event.
3112
- *
3113
- * @private
3114
- */
3115
- emitClose() {
3116
- if (!this._socket) {
3117
- this._readyState = _WebSocket.CLOSED;
3118
- this.emit("close", this._closeCode, this._closeMessage);
3119
- return;
3120
- }
3121
- if (this._extensions[PerMessageDeflate2.extensionName]) {
3122
- this._extensions[PerMessageDeflate2.extensionName].cleanup();
3123
- }
3124
- this._receiver.removeAllListeners();
3125
- this._readyState = _WebSocket.CLOSED;
3126
- this.emit("close", this._closeCode, this._closeMessage);
3127
- }
3128
- /**
3129
- * Start a closing handshake.
3130
- *
3131
- * +----------+ +-----------+ +----------+
3132
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
3133
- * | +----------+ +-----------+ +----------+ |
3134
- * +----------+ +-----------+ |
3135
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
3136
- * +----------+ +-----------+ |
3137
- * | | | +---+ |
3138
- * +------------------------+-->|fin| - - - -
3139
- * | +---+ | +---+
3140
- * - - - - -|fin|<---------------------+
3141
- * +---+
3142
- *
3143
- * @param {Number} [code] Status code explaining why the connection is closing
3144
- * @param {(String|Buffer)} [data] The reason why the connection is
3145
- * closing
3146
- * @public
3147
- */
3148
- close(code, data) {
3149
- if (this.readyState === _WebSocket.CLOSED) return;
3150
- if (this.readyState === _WebSocket.CONNECTING) {
3151
- const msg = "WebSocket was closed before the connection was established";
3152
- abortHandshake(this, this._req, msg);
3153
- return;
3154
- }
3155
- if (this.readyState === _WebSocket.CLOSING) {
3156
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
3157
- this._socket.end();
3158
- }
3159
- return;
3160
- }
3161
- this._readyState = _WebSocket.CLOSING;
3162
- this._sender.close(code, data, !this._isServer, (err) => {
3163
- if (err) return;
3164
- this._closeFrameSent = true;
3165
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
3166
- this._socket.end();
3167
- }
3168
- });
3169
- setCloseTimer(this);
3170
- }
3171
- /**
3172
- * Pause the socket.
3173
- *
3174
- * @public
3175
- */
3176
- pause() {
3177
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
3178
- return;
3179
- }
3180
- this._paused = true;
3181
- this._socket.pause();
3182
- }
3183
- /**
3184
- * Send a ping.
3185
- *
3186
- * @param {*} [data] The data to send
3187
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
3188
- * @param {Function} [cb] Callback which is executed when the ping is sent
3189
- * @public
3190
- */
3191
- ping(data, mask, cb) {
3192
- if (this.readyState === _WebSocket.CONNECTING) {
3193
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
3194
- }
3195
- if (typeof data === "function") {
3196
- cb = data;
3197
- data = mask = void 0;
3198
- } else if (typeof mask === "function") {
3199
- cb = mask;
3200
- mask = void 0;
3201
- }
3202
- if (typeof data === "number") data = data.toString();
3203
- if (this.readyState !== _WebSocket.OPEN) {
3204
- sendAfterClose(this, data, cb);
3205
- return;
3206
- }
3207
- if (mask === void 0) mask = !this._isServer;
3208
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
3209
- }
3210
- /**
3211
- * Send a pong.
3212
- *
3213
- * @param {*} [data] The data to send
3214
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
3215
- * @param {Function} [cb] Callback which is executed when the pong is sent
3216
- * @public
3217
- */
3218
- pong(data, mask, cb) {
3219
- if (this.readyState === _WebSocket.CONNECTING) {
3220
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
3221
- }
3222
- if (typeof data === "function") {
3223
- cb = data;
3224
- data = mask = void 0;
3225
- } else if (typeof mask === "function") {
3226
- cb = mask;
3227
- mask = void 0;
3228
- }
3229
- if (typeof data === "number") data = data.toString();
3230
- if (this.readyState !== _WebSocket.OPEN) {
3231
- sendAfterClose(this, data, cb);
3232
- return;
3233
- }
3234
- if (mask === void 0) mask = !this._isServer;
3235
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
3236
- }
3237
- /**
3238
- * Resume the socket.
3239
- *
3240
- * @public
3241
- */
3242
- resume() {
3243
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
3244
- return;
3245
- }
3246
- this._paused = false;
3247
- if (!this._receiver._writableState.needDrain) this._socket.resume();
3248
- }
3249
- /**
3250
- * Send a data message.
3251
- *
3252
- * @param {*} data The message to send
3253
- * @param {Object} [options] Options object
3254
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
3255
- * text
3256
- * @param {Boolean} [options.compress] Specifies whether or not to compress
3257
- * `data`
3258
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
3259
- * last one
3260
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
3261
- * @param {Function} [cb] Callback which is executed when data is written out
3262
- * @public
3263
- */
3264
- send(data, options, cb) {
3265
- if (this.readyState === _WebSocket.CONNECTING) {
3266
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
3267
- }
3268
- if (typeof options === "function") {
3269
- cb = options;
3270
- options = {};
3271
- }
3272
- if (typeof data === "number") data = data.toString();
3273
- if (this.readyState !== _WebSocket.OPEN) {
3274
- sendAfterClose(this, data, cb);
3275
- return;
3276
- }
3277
- const opts = {
3278
- binary: typeof data !== "string",
3279
- mask: !this._isServer,
3280
- compress: true,
3281
- fin: true,
3282
- ...options
3283
- };
3284
- if (!this._extensions[PerMessageDeflate2.extensionName]) {
3285
- opts.compress = false;
3286
- }
3287
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
3288
- }
3289
- /**
3290
- * Forcibly close the connection.
3291
- *
3292
- * @public
3293
- */
3294
- terminate() {
3295
- if (this.readyState === _WebSocket.CLOSED) return;
3296
- if (this.readyState === _WebSocket.CONNECTING) {
3297
- const msg = "WebSocket was closed before the connection was established";
3298
- abortHandshake(this, this._req, msg);
3299
- return;
3300
- }
3301
- if (this._socket) {
3302
- this._readyState = _WebSocket.CLOSING;
3303
- this._socket.destroy();
3304
- }
3305
- }
3306
- };
3307
- Object.defineProperty(WebSocket2, "CONNECTING", {
3308
- enumerable: true,
3309
- value: readyStates.indexOf("CONNECTING")
3310
- });
3311
- Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
3312
- enumerable: true,
3313
- value: readyStates.indexOf("CONNECTING")
3314
- });
3315
- Object.defineProperty(WebSocket2, "OPEN", {
3316
- enumerable: true,
3317
- value: readyStates.indexOf("OPEN")
3318
- });
3319
- Object.defineProperty(WebSocket2.prototype, "OPEN", {
3320
- enumerable: true,
3321
- value: readyStates.indexOf("OPEN")
3322
- });
3323
- Object.defineProperty(WebSocket2, "CLOSING", {
3324
- enumerable: true,
3325
- value: readyStates.indexOf("CLOSING")
3326
- });
3327
- Object.defineProperty(WebSocket2.prototype, "CLOSING", {
3328
- enumerable: true,
3329
- value: readyStates.indexOf("CLOSING")
3330
- });
3331
- Object.defineProperty(WebSocket2, "CLOSED", {
3332
- enumerable: true,
3333
- value: readyStates.indexOf("CLOSED")
3334
- });
3335
- Object.defineProperty(WebSocket2.prototype, "CLOSED", {
3336
- enumerable: true,
3337
- value: readyStates.indexOf("CLOSED")
3338
- });
3339
- [
3340
- "binaryType",
3341
- "bufferedAmount",
3342
- "extensions",
3343
- "isPaused",
3344
- "protocol",
3345
- "readyState",
3346
- "url"
3347
- ].forEach((property) => {
3348
- Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
3349
- });
3350
- ["open", "error", "close", "message"].forEach((method) => {
3351
- Object.defineProperty(WebSocket2.prototype, `on${method}`, {
3352
- enumerable: true,
3353
- get() {
3354
- for (const listener of this.listeners(method)) {
3355
- if (listener[kForOnEventAttribute]) return listener[kListener];
3356
- }
3357
- return null;
3358
- },
3359
- set(handler) {
3360
- for (const listener of this.listeners(method)) {
3361
- if (listener[kForOnEventAttribute]) {
3362
- this.removeListener(method, listener);
3363
- break;
3364
- }
3365
- }
3366
- if (typeof handler !== "function") return;
3367
- this.addEventListener(method, handler, {
3368
- [kForOnEventAttribute]: true
3369
- });
3370
- }
3371
- });
3372
- });
3373
- WebSocket2.prototype.addEventListener = addEventListener;
3374
- WebSocket2.prototype.removeEventListener = removeEventListener;
3375
- module.exports = WebSocket2;
3376
- function initAsClient(websocket, address, protocols, options) {
3377
- const opts = {
3378
- allowSynchronousEvents: true,
3379
- autoPong: true,
3380
- closeTimeout: CLOSE_TIMEOUT,
3381
- protocolVersion: protocolVersions[1],
3382
- maxPayload: 100 * 1024 * 1024,
3383
- skipUTF8Validation: false,
3384
- perMessageDeflate: true,
3385
- followRedirects: false,
3386
- maxRedirects: 10,
3387
- ...options,
3388
- socketPath: void 0,
3389
- hostname: void 0,
3390
- protocol: void 0,
3391
- timeout: void 0,
3392
- method: "GET",
3393
- host: void 0,
3394
- path: void 0,
3395
- port: void 0
3396
- };
3397
- websocket._autoPong = opts.autoPong;
3398
- websocket._closeTimeout = opts.closeTimeout;
3399
- if (!protocolVersions.includes(opts.protocolVersion)) {
3400
- throw new RangeError(
3401
- `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
3402
- );
3403
- }
3404
- let parsedUrl;
3405
- if (address instanceof URL) {
3406
- parsedUrl = address;
3407
- } else {
3408
- try {
3409
- parsedUrl = new URL(address);
3410
- } catch {
3411
- throw new SyntaxError(`Invalid URL: ${address}`);
3412
- }
3413
- }
3414
- if (parsedUrl.protocol === "http:") {
3415
- parsedUrl.protocol = "ws:";
3416
- } else if (parsedUrl.protocol === "https:") {
3417
- parsedUrl.protocol = "wss:";
3418
- }
3419
- websocket._url = parsedUrl.href;
3420
- const isSecure = parsedUrl.protocol === "wss:";
3421
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
3422
- let invalidUrlMessage;
3423
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
3424
- invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
3425
- } else if (isIpcUrl && !parsedUrl.pathname) {
3426
- invalidUrlMessage = "The URL's pathname is empty";
3427
- } else if (parsedUrl.hash) {
3428
- invalidUrlMessage = "The URL contains a fragment identifier";
3429
- }
3430
- if (invalidUrlMessage) {
3431
- const err = new SyntaxError(invalidUrlMessage);
3432
- if (websocket._redirects === 0) {
3433
- throw err;
3434
- } else {
3435
- emitErrorAndClose(websocket, err);
3436
- return;
3437
- }
3438
- }
3439
- const defaultPort = isSecure ? 443 : 80;
3440
- const key = randomBytes(16).toString("base64");
3441
- const request = isSecure ? https.request : http.request;
3442
- const protocolSet = /* @__PURE__ */ new Set();
3443
- let perMessageDeflate;
3444
- opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
3445
- opts.defaultPort = opts.defaultPort || defaultPort;
3446
- opts.port = parsedUrl.port || defaultPort;
3447
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
3448
- opts.headers = {
3449
- ...opts.headers,
3450
- "Sec-WebSocket-Version": opts.protocolVersion,
3451
- "Sec-WebSocket-Key": key,
3452
- Connection: "Upgrade",
3453
- Upgrade: "websocket"
3454
- };
3455
- opts.path = parsedUrl.pathname + parsedUrl.search;
3456
- opts.timeout = opts.handshakeTimeout;
3457
- if (opts.perMessageDeflate) {
3458
- perMessageDeflate = new PerMessageDeflate2({
3459
- ...opts.perMessageDeflate,
3460
- isServer: false,
3461
- maxPayload: opts.maxPayload
3462
- });
3463
- opts.headers["Sec-WebSocket-Extensions"] = format({
3464
- [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
3465
- });
3466
- }
3467
- if (protocols.length) {
3468
- for (const protocol of protocols) {
3469
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
3470
- throw new SyntaxError(
3471
- "An invalid or duplicated subprotocol was specified"
3472
- );
3473
- }
3474
- protocolSet.add(protocol);
3475
- }
3476
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
3477
- }
3478
- if (opts.origin) {
3479
- if (opts.protocolVersion < 13) {
3480
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
3481
- } else {
3482
- opts.headers.Origin = opts.origin;
3483
- }
3484
- }
3485
- if (parsedUrl.username || parsedUrl.password) {
3486
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
3487
- }
3488
- if (isIpcUrl) {
3489
- const parts = opts.path.split(":");
3490
- opts.socketPath = parts[0];
3491
- opts.path = parts[1];
3492
- }
3493
- let req;
3494
- if (opts.followRedirects) {
3495
- if (websocket._redirects === 0) {
3496
- websocket._originalIpc = isIpcUrl;
3497
- websocket._originalSecure = isSecure;
3498
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
3499
- const headers = options && options.headers;
3500
- options = { ...options, headers: {} };
3501
- if (headers) {
3502
- for (const [key2, value] of Object.entries(headers)) {
3503
- options.headers[key2.toLowerCase()] = value;
3504
- }
3505
- }
3506
- } else if (websocket.listenerCount("redirect") === 0) {
3507
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
3508
- if (!isSameHost || websocket._originalSecure && !isSecure) {
3509
- delete opts.headers.authorization;
3510
- delete opts.headers.cookie;
3511
- if (!isSameHost) delete opts.headers.host;
3512
- opts.auth = void 0;
3513
- }
3514
- }
3515
- if (opts.auth && !options.headers.authorization) {
3516
- options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
3517
- }
3518
- req = websocket._req = request(opts);
3519
- if (websocket._redirects) {
3520
- websocket.emit("redirect", websocket.url, req);
3521
- }
3522
- } else {
3523
- req = websocket._req = request(opts);
3524
- }
3525
- if (opts.timeout) {
3526
- req.on("timeout", () => {
3527
- abortHandshake(websocket, req, "Opening handshake has timed out");
3528
- });
3529
- }
3530
- req.on("error", (err) => {
3531
- if (req === null || req[kAborted]) return;
3532
- req = websocket._req = null;
3533
- emitErrorAndClose(websocket, err);
3534
- });
3535
- req.on("response", (res) => {
3536
- const location = res.headers.location;
3537
- const statusCode = res.statusCode;
3538
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
3539
- if (++websocket._redirects > opts.maxRedirects) {
3540
- abortHandshake(websocket, req, "Maximum redirects exceeded");
3541
- return;
3542
- }
3543
- req.abort();
3544
- let addr;
3545
- try {
3546
- addr = new URL(location, address);
3547
- } catch (e) {
3548
- const err = new SyntaxError(`Invalid URL: ${location}`);
3549
- emitErrorAndClose(websocket, err);
3550
- return;
3551
- }
3552
- initAsClient(websocket, addr, protocols, options);
3553
- } else if (!websocket.emit("unexpected-response", req, res)) {
3554
- abortHandshake(
3555
- websocket,
3556
- req,
3557
- `Unexpected server response: ${res.statusCode}`
3558
- );
3559
- }
3560
- });
3561
- req.on("upgrade", (res, socket, head) => {
3562
- websocket.emit("upgrade", res);
3563
- if (websocket.readyState !== WebSocket2.CONNECTING) return;
3564
- req = websocket._req = null;
3565
- const upgrade = res.headers.upgrade;
3566
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3567
- abortHandshake(websocket, socket, "Invalid Upgrade header");
3568
- return;
3569
- }
3570
- const digest = createHash("sha1").update(key + GUID).digest("base64");
3571
- if (res.headers["sec-websocket-accept"] !== digest) {
3572
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
3573
- return;
3574
- }
3575
- const serverProt = res.headers["sec-websocket-protocol"];
3576
- let protError;
3577
- if (serverProt !== void 0) {
3578
- if (!protocolSet.size) {
3579
- protError = "Server sent a subprotocol but none was requested";
3580
- } else if (!protocolSet.has(serverProt)) {
3581
- protError = "Server sent an invalid subprotocol";
3582
- }
3583
- } else if (protocolSet.size) {
3584
- protError = "Server sent no subprotocol";
3585
- }
3586
- if (protError) {
3587
- abortHandshake(websocket, socket, protError);
3588
- return;
3589
- }
3590
- if (serverProt) websocket._protocol = serverProt;
3591
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
3592
- if (secWebSocketExtensions !== void 0) {
3593
- if (!perMessageDeflate) {
3594
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
3595
- abortHandshake(websocket, socket, message);
3596
- return;
3597
- }
3598
- let extensions;
3599
- try {
3600
- extensions = parse(secWebSocketExtensions);
3601
- } catch (err) {
3602
- const message = "Invalid Sec-WebSocket-Extensions header";
3603
- abortHandshake(websocket, socket, message);
3604
- return;
3605
- }
3606
- const extensionNames = Object.keys(extensions);
3607
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
3608
- const message = "Server indicated an extension that was not requested";
3609
- abortHandshake(websocket, socket, message);
3610
- return;
3611
- }
3612
- try {
3613
- perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
3614
- } catch (err) {
3615
- const message = "Invalid Sec-WebSocket-Extensions header";
3616
- abortHandshake(websocket, socket, message);
3617
- return;
3618
- }
3619
- websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3620
- }
3621
- websocket.setSocket(socket, head, {
3622
- allowSynchronousEvents: opts.allowSynchronousEvents,
3623
- generateMask: opts.generateMask,
3624
- maxPayload: opts.maxPayload,
3625
- skipUTF8Validation: opts.skipUTF8Validation
3626
- });
3627
- });
3628
- if (opts.finishRequest) {
3629
- opts.finishRequest(req, websocket);
3630
- } else {
3631
- req.end();
3632
- }
3633
- }
3634
- function emitErrorAndClose(websocket, err) {
3635
- websocket._readyState = WebSocket2.CLOSING;
3636
- websocket._errorEmitted = true;
3637
- websocket.emit("error", err);
3638
- websocket.emitClose();
3639
- }
3640
- function netConnect(options) {
3641
- options.path = options.socketPath;
3642
- return net.connect(options);
3643
- }
3644
- function tlsConnect(options) {
3645
- options.path = void 0;
3646
- if (!options.servername && options.servername !== "") {
3647
- options.servername = net.isIP(options.host) ? "" : options.host;
3648
- }
3649
- return tls.connect(options);
3650
- }
3651
- function abortHandshake(websocket, stream, message) {
3652
- websocket._readyState = WebSocket2.CLOSING;
3653
- const err = new Error(message);
3654
- Error.captureStackTrace(err, abortHandshake);
3655
- if (stream.setHeader) {
3656
- stream[kAborted] = true;
3657
- stream.abort();
3658
- if (stream.socket && !stream.socket.destroyed) {
3659
- stream.socket.destroy();
3660
- }
3661
- process.nextTick(emitErrorAndClose, websocket, err);
3662
- } else {
3663
- stream.destroy(err);
3664
- stream.once("error", websocket.emit.bind(websocket, "error"));
3665
- stream.once("close", websocket.emitClose.bind(websocket));
3666
- }
3667
- }
3668
- function sendAfterClose(websocket, data, cb) {
3669
- if (data) {
3670
- const length = isBlob(data) ? data.size : toBuffer(data).length;
3671
- if (websocket._socket) websocket._sender._bufferedBytes += length;
3672
- else websocket._bufferedAmount += length;
3673
- }
3674
- if (cb) {
3675
- const err = new Error(
3676
- `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3677
- );
3678
- process.nextTick(cb, err);
3679
- }
3680
- }
3681
- function receiverOnConclude(code, reason) {
3682
- const websocket = this[kWebSocket];
3683
- websocket._closeFrameReceived = true;
3684
- websocket._closeMessage = reason;
3685
- websocket._closeCode = code;
3686
- if (websocket._socket[kWebSocket] === void 0) return;
3687
- websocket._socket.removeListener("data", socketOnData);
3688
- process.nextTick(resume, websocket._socket);
3689
- if (code === 1005) websocket.close();
3690
- else websocket.close(code, reason);
3691
- }
3692
- function receiverOnDrain() {
3693
- const websocket = this[kWebSocket];
3694
- if (!websocket.isPaused) websocket._socket.resume();
3695
- }
3696
- function receiverOnError(err) {
3697
- const websocket = this[kWebSocket];
3698
- if (websocket._socket[kWebSocket] !== void 0) {
3699
- websocket._socket.removeListener("data", socketOnData);
3700
- process.nextTick(resume, websocket._socket);
3701
- websocket.close(err[kStatusCode]);
3702
- }
3703
- if (!websocket._errorEmitted) {
3704
- websocket._errorEmitted = true;
3705
- websocket.emit("error", err);
3706
- }
3707
- }
3708
- function receiverOnFinish() {
3709
- this[kWebSocket].emitClose();
3710
- }
3711
- function receiverOnMessage(data, isBinary) {
3712
- this[kWebSocket].emit("message", data, isBinary);
3713
- }
3714
- function receiverOnPing(data) {
3715
- const websocket = this[kWebSocket];
3716
- if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3717
- websocket.emit("ping", data);
3718
- }
3719
- function receiverOnPong(data) {
3720
- this[kWebSocket].emit("pong", data);
3721
- }
3722
- function resume(stream) {
3723
- stream.resume();
3724
- }
3725
- function senderOnError(err) {
3726
- const websocket = this[kWebSocket];
3727
- if (websocket.readyState === WebSocket2.CLOSED) return;
3728
- if (websocket.readyState === WebSocket2.OPEN) {
3729
- websocket._readyState = WebSocket2.CLOSING;
3730
- setCloseTimer(websocket);
3731
- }
3732
- this._socket.end();
3733
- if (!websocket._errorEmitted) {
3734
- websocket._errorEmitted = true;
3735
- websocket.emit("error", err);
3736
- }
3737
- }
3738
- function setCloseTimer(websocket) {
3739
- websocket._closeTimer = setTimeout(
3740
- websocket._socket.destroy.bind(websocket._socket),
3741
- websocket._closeTimeout
3742
- );
3743
- }
3744
- function socketOnClose() {
3745
- const websocket = this[kWebSocket];
3746
- this.removeListener("close", socketOnClose);
3747
- this.removeListener("data", socketOnData);
3748
- this.removeListener("end", socketOnEnd);
3749
- websocket._readyState = WebSocket2.CLOSING;
3750
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3751
- const chunk = this.read(this._readableState.length);
3752
- websocket._receiver.write(chunk);
3753
- }
3754
- websocket._receiver.end();
3755
- this[kWebSocket] = void 0;
3756
- clearTimeout(websocket._closeTimer);
3757
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3758
- websocket.emitClose();
3759
- } else {
3760
- websocket._receiver.on("error", receiverOnFinish);
3761
- websocket._receiver.on("finish", receiverOnFinish);
3762
- }
3763
- }
3764
- function socketOnData(chunk) {
3765
- if (!this[kWebSocket]._receiver.write(chunk)) {
3766
- this.pause();
3767
- }
3768
- }
3769
- function socketOnEnd() {
3770
- const websocket = this[kWebSocket];
3771
- websocket._readyState = WebSocket2.CLOSING;
3772
- websocket._receiver.end();
3773
- this.end();
3774
- }
3775
- function socketOnError() {
3776
- const websocket = this[kWebSocket];
3777
- this.removeListener("error", socketOnError);
3778
- this.on("error", NOOP);
3779
- if (websocket) {
3780
- websocket._readyState = WebSocket2.CLOSING;
3781
- this.destroy();
3782
- }
3783
- }
3784
- }
3785
- });
3786
-
3787
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js
3788
- var require_stream = __commonJS({
3789
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js"(exports, module) {
3790
- "use strict";
3791
- var WebSocket2 = require_websocket();
3792
- var { Duplex } = __require("stream");
3793
- function emitClose(stream) {
3794
- stream.emit("close");
3795
- }
3796
- function duplexOnEnd() {
3797
- if (!this.destroyed && this._writableState.finished) {
3798
- this.destroy();
3799
- }
3800
- }
3801
- function duplexOnError(err) {
3802
- this.removeListener("error", duplexOnError);
3803
- this.destroy();
3804
- if (this.listenerCount("error") === 0) {
3805
- this.emit("error", err);
3806
- }
3807
- }
3808
- function createWebSocketStream2(ws, options) {
3809
- let terminateOnDestroy = true;
3810
- const duplex = new Duplex({
3811
- ...options,
3812
- autoDestroy: false,
3813
- emitClose: false,
3814
- objectMode: false,
3815
- writableObjectMode: false
3816
- });
3817
- ws.on("message", function message(msg, isBinary) {
3818
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3819
- if (!duplex.push(data)) ws.pause();
3820
- });
3821
- ws.once("error", function error(err) {
3822
- if (duplex.destroyed) return;
3823
- terminateOnDestroy = false;
3824
- duplex.destroy(err);
3825
- });
3826
- ws.once("close", function close() {
3827
- if (duplex.destroyed) return;
3828
- duplex.push(null);
3829
- });
3830
- duplex._destroy = function(err, callback) {
3831
- if (ws.readyState === ws.CLOSED) {
3832
- callback(err);
3833
- process.nextTick(emitClose, duplex);
3834
- return;
3835
- }
3836
- let called = false;
3837
- ws.once("error", function error(err2) {
3838
- called = true;
3839
- callback(err2);
3840
- });
3841
- ws.once("close", function close() {
3842
- if (!called) callback(err);
3843
- process.nextTick(emitClose, duplex);
3844
- });
3845
- if (terminateOnDestroy) ws.terminate();
3846
- };
3847
- duplex._final = function(callback) {
3848
- if (ws.readyState === ws.CONNECTING) {
3849
- ws.once("open", function open() {
3850
- duplex._final(callback);
3851
- });
3852
- return;
3853
- }
3854
- if (ws._socket === null) return;
3855
- if (ws._socket._writableState.finished) {
3856
- callback();
3857
- if (duplex._readableState.endEmitted) duplex.destroy();
3858
- } else {
3859
- ws._socket.once("finish", function finish() {
3860
- callback();
3861
- });
3862
- ws.close();
3863
- }
3864
- };
3865
- duplex._read = function() {
3866
- if (ws.isPaused) ws.resume();
3867
- };
3868
- duplex._write = function(chunk, encoding, callback) {
3869
- if (ws.readyState === ws.CONNECTING) {
3870
- ws.once("open", function open() {
3871
- duplex._write(chunk, encoding, callback);
3872
- });
3873
- return;
3874
- }
3875
- ws.send(chunk, callback);
3876
- };
3877
- duplex.on("end", duplexOnEnd);
3878
- duplex.on("error", duplexOnError);
3879
- return duplex;
3880
- }
3881
- module.exports = createWebSocketStream2;
3882
- }
3883
- });
3884
-
3885
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js
3886
- var require_subprotocol = __commonJS({
3887
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js"(exports, module) {
3888
- "use strict";
3889
- var { tokenChars } = require_validation();
3890
- function parse(header) {
3891
- const protocols = /* @__PURE__ */ new Set();
3892
- let start = -1;
3893
- let end = -1;
3894
- let i = 0;
3895
- for (i; i < header.length; i++) {
3896
- const code = header.charCodeAt(i);
3897
- if (end === -1 && tokenChars[code] === 1) {
3898
- if (start === -1) start = i;
3899
- } else if (i !== 0 && (code === 32 || code === 9)) {
3900
- if (end === -1 && start !== -1) end = i;
3901
- } else if (code === 44) {
3902
- if (start === -1) {
3903
- throw new SyntaxError(`Unexpected character at index ${i}`);
3904
- }
3905
- if (end === -1) end = i;
3906
- const protocol2 = header.slice(start, end);
3907
- if (protocols.has(protocol2)) {
3908
- throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3909
- }
3910
- protocols.add(protocol2);
3911
- start = end = -1;
3912
- } else {
3913
- throw new SyntaxError(`Unexpected character at index ${i}`);
3914
- }
3915
- }
3916
- if (start === -1 || end !== -1) {
3917
- throw new SyntaxError("Unexpected end of input");
3918
- }
3919
- const protocol = header.slice(start, i);
3920
- if (protocols.has(protocol)) {
3921
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3922
- }
3923
- protocols.add(protocol);
3924
- return protocols;
3925
- }
3926
- module.exports = { parse };
3927
- }
3928
- });
3929
-
3930
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js
3931
- var require_websocket_server = __commonJS({
3932
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js"(exports, module) {
3933
- "use strict";
3934
- var EventEmitter = __require("events");
3935
- var http = __require("http");
3936
- var { Duplex } = __require("stream");
3937
- var { createHash } = __require("crypto");
3938
- var extension2 = require_extension();
3939
- var PerMessageDeflate2 = require_permessage_deflate();
3940
- var subprotocol2 = require_subprotocol();
3941
- var WebSocket2 = require_websocket();
3942
- var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3943
- var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3944
- var RUNNING = 0;
3945
- var CLOSING = 1;
3946
- var CLOSED = 2;
3947
- var WebSocketServer2 = class extends EventEmitter {
3948
- /**
3949
- * Create a `WebSocketServer` instance.
3950
- *
3951
- * @param {Object} options Configuration options
3952
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3953
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3954
- * multiple times in the same tick
3955
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3956
- * automatically send a pong in response to a ping
3957
- * @param {Number} [options.backlog=511] The maximum length of the queue of
3958
- * pending connections
3959
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3960
- * track clients
3961
- * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3962
- * wait for the closing handshake to finish after `websocket.close()` is
3963
- * called
3964
- * @param {Function} [options.handleProtocols] A hook to handle protocols
3965
- * @param {String} [options.host] The hostname where to bind the server
3966
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3967
- * size
3968
- * @param {Boolean} [options.noServer=false] Enable no server mode
3969
- * @param {String} [options.path] Accept only connections matching this path
3970
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3971
- * permessage-deflate
3972
- * @param {Number} [options.port] The port where to bind the server
3973
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3974
- * server to use
3975
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3976
- * not to skip UTF-8 validation for text and close messages
3977
- * @param {Function} [options.verifyClient] A hook to reject connections
3978
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3979
- * class to use. It must be the `WebSocket` class or class that extends it
3980
- * @param {Function} [callback] A listener for the `listening` event
3981
- */
3982
- constructor(options, callback) {
3983
- super();
3984
- options = {
3985
- allowSynchronousEvents: true,
3986
- autoPong: true,
3987
- maxPayload: 100 * 1024 * 1024,
3988
- skipUTF8Validation: false,
3989
- perMessageDeflate: false,
3990
- handleProtocols: null,
3991
- clientTracking: true,
3992
- closeTimeout: CLOSE_TIMEOUT,
3993
- verifyClient: null,
3994
- noServer: false,
3995
- backlog: null,
3996
- // use default (511 as implemented in net.js)
3997
- server: null,
3998
- host: null,
3999
- path: null,
4000
- port: null,
4001
- WebSocket: WebSocket2,
4002
- ...options
4003
- };
4004
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
4005
- throw new TypeError(
4006
- 'One and only one of the "port", "server", or "noServer" options must be specified'
4007
- );
4008
- }
4009
- if (options.port != null) {
4010
- this._server = http.createServer((req, res) => {
4011
- const body = http.STATUS_CODES[426];
4012
- res.writeHead(426, {
4013
- "Content-Length": body.length,
4014
- "Content-Type": "text/plain"
4015
- });
4016
- res.end(body);
4017
- });
4018
- this._server.listen(
4019
- options.port,
4020
- options.host,
4021
- options.backlog,
4022
- callback
4023
- );
4024
- } else if (options.server) {
4025
- this._server = options.server;
4026
- }
4027
- if (this._server) {
4028
- const emitConnection = this.emit.bind(this, "connection");
4029
- this._removeListeners = addListeners(this._server, {
4030
- listening: this.emit.bind(this, "listening"),
4031
- error: this.emit.bind(this, "error"),
4032
- upgrade: (req, socket, head) => {
4033
- this.handleUpgrade(req, socket, head, emitConnection);
4034
- }
4035
- });
4036
- }
4037
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
4038
- if (options.clientTracking) {
4039
- this.clients = /* @__PURE__ */ new Set();
4040
- this._shouldEmitClose = false;
4041
- }
4042
- this.options = options;
4043
- this._state = RUNNING;
4044
- }
4045
- /**
4046
- * Returns the bound address, the address family name, and port of the server
4047
- * as reported by the operating system if listening on an IP socket.
4048
- * If the server is listening on a pipe or UNIX domain socket, the name is
4049
- * returned as a string.
4050
- *
4051
- * @return {(Object|String|null)} The address of the server
4052
- * @public
4053
- */
4054
- address() {
4055
- if (this.options.noServer) {
4056
- throw new Error('The server is operating in "noServer" mode');
4057
- }
4058
- if (!this._server) return null;
4059
- return this._server.address();
4060
- }
4061
- /**
4062
- * Stop the server from accepting new connections and emit the `'close'` event
4063
- * when all existing connections are closed.
4064
- *
4065
- * @param {Function} [cb] A one-time listener for the `'close'` event
4066
- * @public
4067
- */
4068
- close(cb) {
4069
- if (this._state === CLOSED) {
4070
- if (cb) {
4071
- this.once("close", () => {
4072
- cb(new Error("The server is not running"));
4073
- });
4074
- }
4075
- process.nextTick(emitClose, this);
4076
- return;
4077
- }
4078
- if (cb) this.once("close", cb);
4079
- if (this._state === CLOSING) return;
4080
- this._state = CLOSING;
4081
- if (this.options.noServer || this.options.server) {
4082
- if (this._server) {
4083
- this._removeListeners();
4084
- this._removeListeners = this._server = null;
4085
- }
4086
- if (this.clients) {
4087
- if (!this.clients.size) {
4088
- process.nextTick(emitClose, this);
4089
- } else {
4090
- this._shouldEmitClose = true;
4091
- }
4092
- } else {
4093
- process.nextTick(emitClose, this);
4094
- }
4095
- } else {
4096
- const server = this._server;
4097
- this._removeListeners();
4098
- this._removeListeners = this._server = null;
4099
- server.close(() => {
4100
- emitClose(this);
4101
- });
4102
- }
4103
- }
4104
- /**
4105
- * See if a given request should be handled by this server instance.
4106
- *
4107
- * @param {http.IncomingMessage} req Request object to inspect
4108
- * @return {Boolean} `true` if the request is valid, else `false`
4109
- * @public
4110
- */
4111
- shouldHandle(req) {
4112
- if (this.options.path) {
4113
- const index = req.url.indexOf("?");
4114
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
4115
- if (pathname !== this.options.path) return false;
4116
- }
4117
- return true;
4118
- }
4119
- /**
4120
- * Handle a HTTP Upgrade request.
4121
- *
4122
- * @param {http.IncomingMessage} req The request object
4123
- * @param {Duplex} socket The network socket between the server and client
4124
- * @param {Buffer} head The first packet of the upgraded stream
4125
- * @param {Function} cb Callback
4126
- * @public
4127
- */
4128
- handleUpgrade(req, socket, head, cb) {
4129
- socket.on("error", socketOnError);
4130
- const key = req.headers["sec-websocket-key"];
4131
- const upgrade = req.headers.upgrade;
4132
- const version = +req.headers["sec-websocket-version"];
4133
- if (req.method !== "GET") {
4134
- const message = "Invalid HTTP method";
4135
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
4136
- return;
4137
- }
4138
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
4139
- const message = "Invalid Upgrade header";
4140
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
4141
- return;
4142
- }
4143
- if (key === void 0 || !keyRegex.test(key)) {
4144
- const message = "Missing or invalid Sec-WebSocket-Key header";
4145
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
4146
- return;
4147
- }
4148
- if (version !== 13 && version !== 8) {
4149
- const message = "Missing or invalid Sec-WebSocket-Version header";
4150
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
4151
- "Sec-WebSocket-Version": "13, 8"
4152
- });
4153
- return;
4154
- }
4155
- if (!this.shouldHandle(req)) {
4156
- abortHandshake(socket, 400);
4157
- return;
4158
- }
4159
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
4160
- let protocols = /* @__PURE__ */ new Set();
4161
- if (secWebSocketProtocol !== void 0) {
4162
- try {
4163
- protocols = subprotocol2.parse(secWebSocketProtocol);
4164
- } catch (err) {
4165
- const message = "Invalid Sec-WebSocket-Protocol header";
4166
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
4167
- return;
4168
- }
4169
- }
4170
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
4171
- const extensions = {};
4172
- if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
4173
- const perMessageDeflate = new PerMessageDeflate2({
4174
- ...this.options.perMessageDeflate,
4175
- isServer: true,
4176
- maxPayload: this.options.maxPayload
4177
- });
4178
- try {
4179
- const offers = extension2.parse(secWebSocketExtensions);
4180
- if (offers[PerMessageDeflate2.extensionName]) {
4181
- perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
4182
- extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
4183
- }
4184
- } catch (err) {
4185
- const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
4186
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
4187
- return;
4188
- }
4189
- }
4190
- if (this.options.verifyClient) {
4191
- const info = {
4192
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
4193
- secure: !!(req.socket.authorized || req.socket.encrypted),
4194
- req
4195
- };
4196
- if (this.options.verifyClient.length === 2) {
4197
- this.options.verifyClient(info, (verified, code, message, headers) => {
4198
- if (!verified) {
4199
- return abortHandshake(socket, code || 401, message, headers);
4200
- }
4201
- this.completeUpgrade(
4202
- extensions,
4203
- key,
4204
- protocols,
4205
- req,
4206
- socket,
4207
- head,
4208
- cb
4209
- );
4210
- });
4211
- return;
4212
- }
4213
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
4214
- }
4215
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
426
+ // Access to underlying toolbox objects (for advanced use)
427
+ // ---------------------------------------------------------------------------
428
+ /** Get the underlying wallet-toolbox SetupWallet for advanced operations. */
429
+ getSetup() {
430
+ return this._setup;
4216
431
  }
432
+ // ---------------------------------------------------------------------------
433
+ // Private helpers
434
+ // ---------------------------------------------------------------------------
4217
435
  /**
4218
- * Upgrade the connection to WebSocket.
436
+ * Internal: manually construct a BRC-100 wallet backed by SQLite.
4219
437
  *
4220
- * @param {Object} extensions The accepted extensions
4221
- * @param {String} key The value of the `Sec-WebSocket-Key` header
4222
- * @param {Set} protocols The subprotocols
4223
- * @param {http.IncomingMessage} req The request object
4224
- * @param {Duplex} socket The network socket between the server and client
4225
- * @param {Buffer} head The first packet of the upgraded stream
4226
- * @param {Function} cb Callback
4227
- * @throws {Error} If called more than once with the same socket
4228
- * @private
438
+ * We build this by hand instead of using Setup.createWalletSQLite because
439
+ * the toolbox has a bug where its internal randomBytesHex is a stub.
440
+ * We use the same components but wire them up correctly.
4229
441
  */
4230
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
4231
- if (!socket.readable || !socket.writable) return socket.destroy();
4232
- if (socket[kWebSocket]) {
4233
- throw new Error(
4234
- "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
4235
- );
4236
- }
4237
- if (this._state > RUNNING) return abortHandshake(socket, 503);
4238
- const digest = createHash("sha1").update(key + GUID).digest("base64");
4239
- const headers = [
4240
- "HTTP/1.1 101 Switching Protocols",
4241
- "Upgrade: websocket",
4242
- "Connection: Upgrade",
4243
- `Sec-WebSocket-Accept: ${digest}`
4244
- ];
4245
- const ws = new this.options.WebSocket(null, void 0, this.options);
4246
- if (protocols.size) {
4247
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
4248
- if (protocol) {
4249
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
4250
- ws._protocol = protocol;
442
+ static async buildSetup(config, rootKeyHex) {
443
+ const chain = toChain(config.network);
444
+ log("Building setup for chain: %s (network: %s)", chain, config.network);
445
+ const taalApiKey = config.taalApiKey ?? DEFAULT_TAAL_API_KEYS[chain];
446
+ const rootKey = PrivateKey.fromHex(rootKeyHex);
447
+ const identityKey = rootKey.toPublicKey().toString();
448
+ const keyDeriver = new CachedKeyDeriver2(rootKey);
449
+ const storage = new WalletStorageManager(identityKey);
450
+ const serviceOptions = Services.createDefaultOptions(chain);
451
+ const chaintracksUrl = process["env"].BSV_CHAINTRACKS_URL || "https://chaintracks-us-1.bsvb.tech";
452
+ const arcUrl = process["env"].BSV_ARC_URL;
453
+ const isTestMode = config.enableMonitor === false;
454
+ if (!isTestMode) {
455
+ serviceOptions.chaintracks = new ChaintracksServiceClient(chain, chaintracksUrl);
456
+ if (arcUrl) {
457
+ serviceOptions.arcUrl = arcUrl;
4251
458
  }
4252
459
  }
4253
- if (extensions[PerMessageDeflate2.extensionName]) {
4254
- const params = extensions[PerMessageDeflate2.extensionName].params;
4255
- const value = extension2.format({
4256
- [PerMessageDeflate2.extensionName]: [params]
4257
- });
4258
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
4259
- ws._extensions = extensions;
460
+ serviceOptions.taalApiKey = taalApiKey;
461
+ const services = new Services(serviceOptions);
462
+ const monopts = Monitor.createDefaultWalletMonitorOptions(chain, storage, services);
463
+ const monitor = new Monitor(monopts);
464
+ if (!isTestMode) {
465
+ monitor.addDefaultTasks();
466
+ } else {
467
+ monitor.tasks = [];
4260
468
  }
4261
- this.emit("headers", headers, req);
4262
- socket.write(headers.concat("\r\n").join("\r\n"));
4263
- socket.removeListener("error", socketOnError);
4264
- ws.setSocket(socket, head, {
4265
- allowSynchronousEvents: this.options.allowSynchronousEvents,
4266
- maxPayload: this.options.maxPayload,
4267
- skipUTF8Validation: this.options.skipUTF8Validation
469
+ const wallet = isTestMode ? void 0 : new Wallet({ chain, keyDeriver, storage, services, monitor });
470
+ const filePath = path3.join(config.storageDir, `${DEFAULT_DB_NAME}.sqlite`);
471
+ const knex = knexLib({
472
+ client: "sqlite3",
473
+ connection: { filename: filePath },
474
+ useNullAsDefault: true
4268
475
  });
4269
- if (this.clients) {
4270
- this.clients.add(ws);
4271
- ws.on("close", () => {
4272
- this.clients.delete(ws);
4273
- if (this._shouldEmitClose && !this.clients.size) {
4274
- process.nextTick(emitClose, this);
4275
- }
4276
- });
4277
- }
4278
- cb(ws, req);
476
+ const feeModelValue = config.feeModel ?? (process["env"].BSV_FEE_MODEL ? parseInt(process["env"].BSV_FEE_MODEL, 10) : 100);
477
+ const activeStorage = new StorageKnex({
478
+ chain,
479
+ knex,
480
+ commissionSatoshis: 0,
481
+ commissionPubKeyHex: void 0,
482
+ feeModel: { model: "sat/kb", value: feeModelValue }
483
+ });
484
+ await activeStorage.migrate(DEFAULT_DB_NAME, randomBytesHex(33));
485
+ await activeStorage.makeAvailable();
486
+ await storage.addWalletStorageProvider(activeStorage);
487
+ await activeStorage.findOrInsertUser(identityKey);
488
+ return {
489
+ rootKey,
490
+ identityKey,
491
+ keyDeriver,
492
+ chain,
493
+ network: config.network,
494
+ storage,
495
+ services: isTestMode ? void 0 : services,
496
+ monitor: isTestMode ? void 0 : monitor,
497
+ wallet
498
+ };
4279
499
  }
4280
500
  };
4281
- module.exports = WebSocketServer2;
4282
- function addListeners(server, map) {
4283
- for (const event of Object.keys(map)) server.on(event, map[event]);
4284
- return function removeListeners() {
4285
- for (const event of Object.keys(map)) {
4286
- server.removeListener(event, map[event]);
4287
- }
4288
- };
4289
- }
4290
- function emitClose(server) {
4291
- server._state = CLOSED;
4292
- server.emit("close");
501
+ }
502
+ });
503
+
504
+ // ../plugin-core/dist/index.js
505
+ var init_dist = __esm({
506
+ "../plugin-core/dist/index.js"() {
507
+ "use strict";
508
+ init_wallet();
509
+ init_config2();
510
+ init_payment();
511
+ init_verify();
512
+ }
513
+ });
514
+
515
+ // src/scripts/utils/storage.ts
516
+ import fs7 from "node:fs";
517
+ function ensureStateDir() {
518
+ fs7.mkdirSync(OVERLAY_STATE_DIR, { recursive: true });
519
+ }
520
+ function loadRegistration() {
521
+ try {
522
+ if (fs7.existsSync(PATHS.registration)) {
523
+ return JSON.parse(fs7.readFileSync(PATHS.registration, "utf-8"));
4293
524
  }
4294
- function socketOnError() {
4295
- this.destroy();
525
+ } catch {
526
+ }
527
+ return null;
528
+ }
529
+ function saveRegistration(data) {
530
+ ensureStateDir();
531
+ fs7.writeFileSync(PATHS.registration, JSON.stringify(data, null, 2), "utf-8");
532
+ }
533
+ function deleteRegistration() {
534
+ try {
535
+ fs7.unlinkSync(PATHS.registration);
536
+ } catch {
537
+ }
538
+ }
539
+ function loadServices() {
540
+ try {
541
+ if (fs7.existsSync(PATHS.services)) {
542
+ return JSON.parse(fs7.readFileSync(PATHS.services, "utf-8"));
4296
543
  }
4297
- function abortHandshake(socket, code, message, headers) {
4298
- message = message || http.STATUS_CODES[code];
4299
- headers = {
4300
- Connection: "close",
4301
- "Content-Type": "text/html",
4302
- "Content-Length": Buffer.byteLength(message),
4303
- ...headers
4304
- };
4305
- socket.once("finish", socket.destroy);
4306
- socket.end(
4307
- `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
4308
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
4309
- );
544
+ } catch {
545
+ }
546
+ return [];
547
+ }
548
+ function saveServices(services) {
549
+ ensureStateDir();
550
+ fs7.writeFileSync(PATHS.services, JSON.stringify(services, null, 2), "utf-8");
551
+ }
552
+ function appendToJsonl(filePath, entry) {
553
+ ensureStateDir();
554
+ fs7.appendFileSync(filePath, JSON.stringify(entry) + "\n");
555
+ }
556
+ function readJsonl(filePath) {
557
+ if (!fs7.existsSync(filePath)) return [];
558
+ const lines = fs7.readFileSync(filePath, "utf-8").trim().split("\n").filter(Boolean);
559
+ return lines.map((line) => {
560
+ try {
561
+ return JSON.parse(line);
562
+ } catch {
563
+ return null;
4310
564
  }
4311
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
4312
- if (server.listenerCount("wsClientError")) {
4313
- const err = new Error(message);
4314
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
4315
- server.emit("wsClientError", err, socket, req);
4316
- } else {
4317
- abortHandshake(socket, code, message, headers);
565
+ }).filter(Boolean);
566
+ }
567
+ function updateServiceQueueStatus(requestId, newStatus, additionalFields = {}) {
568
+ if (!fs7.existsSync(PATHS.serviceQueue)) return false;
569
+ const lines = fs7.readFileSync(PATHS.serviceQueue, "utf-8").trim().split("\n").filter(Boolean);
570
+ let updated = false;
571
+ const updatedLines = lines.map((line) => {
572
+ try {
573
+ const entry = JSON.parse(line);
574
+ if (entry.requestId === requestId) {
575
+ updated = true;
576
+ return JSON.stringify({
577
+ ...entry,
578
+ status: newStatus,
579
+ ...additionalFields,
580
+ updatedAt: Date.now()
581
+ });
4318
582
  }
583
+ return line;
584
+ } catch {
585
+ return line;
4319
586
  }
587
+ });
588
+ if (updated) {
589
+ fs7.writeFileSync(PATHS.serviceQueue, updatedLines.join("\n") + "\n");
590
+ }
591
+ return updated;
592
+ }
593
+ var init_storage = __esm({
594
+ "src/scripts/utils/storage.ts"() {
595
+ "use strict";
596
+ init_config();
4320
597
  }
4321
598
  });
4322
599
 
4323
- // ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/wrapper.mjs
4324
- var wrapper_exports = {};
4325
- __export(wrapper_exports, {
4326
- PerMessageDeflate: () => import_permessage_deflate.default,
4327
- Receiver: () => import_receiver.default,
4328
- Sender: () => import_sender.default,
4329
- WebSocket: () => import_websocket.default,
4330
- WebSocketServer: () => import_websocket_server.default,
4331
- createWebSocketStream: () => import_stream.default,
4332
- default: () => wrapper_default,
4333
- extension: () => import_extension.default,
4334
- subprotocol: () => import_subprotocol.default
4335
- });
4336
- var import_stream, import_extension, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket, import_websocket_server, wrapper_default;
4337
- var init_wrapper = __esm({
4338
- "../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/wrapper.mjs"() {
4339
- import_stream = __toESM(require_stream(), 1);
4340
- import_extension = __toESM(require_extension(), 1);
4341
- import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
4342
- import_receiver = __toESM(require_receiver(), 1);
4343
- import_sender = __toESM(require_sender(), 1);
4344
- import_subprotocol = __toESM(require_subprotocol(), 1);
4345
- import_websocket = __toESM(require_websocket(), 1);
4346
- import_websocket_server = __toESM(require_websocket_server(), 1);
4347
- wrapper_default = import_websocket.default;
600
+ // src/scripts/overlay/transaction.ts
601
+ import { Utils as Utils4, PushDrop, Transaction } from "@bsv/sdk";
602
+ async function buildPushDropScript(wallet, payload) {
603
+ const jsonBytes = Utils4.toArray(JSON.stringify(payload), "utf8");
604
+ const fields = [jsonBytes];
605
+ const token = new PushDrop(wallet._setup.wallet);
606
+ const script = await token.lock(fields, [0, PROTOCOL_ID], "1", "self", true, true);
607
+ return script.toHex();
608
+ }
609
+ async function buildRealOverlayTransaction(payload, topic) {
610
+ const wallet = await BSVAgentWallet.load({ network: NETWORK, storageDir: WALLET_DIR });
611
+ const lockingScript = await buildPushDropScript(wallet, payload);
612
+ const response = await wallet._setup.wallet.createAction({
613
+ description: "topic manager submission",
614
+ outputs: [
615
+ {
616
+ lockingScript,
617
+ satoshis: 1,
618
+ outputDescription: "overlay",
619
+ basket: topic
620
+ // basket is the topic manager
621
+ }
622
+ ],
623
+ options: {
624
+ acceptDelayedBroadcast: false
625
+ }
626
+ });
627
+ const submitResp = await fetch(`${OVERLAY_URL}/submit`, {
628
+ method: "POST",
629
+ headers: {
630
+ "Content-Type": "application/octet-stream",
631
+ "X-Topics": JSON.stringify([topic])
632
+ },
633
+ body: new Uint8Array(response.tx)
634
+ });
635
+ if (!submitResp.ok) {
636
+ const errText = await submitResp.text();
637
+ throw new Error(`Overlay submission failed: ${submitResp.status} \u2014 ${errText}`);
638
+ }
639
+ const wocNet = NETWORK === "mainnet" ? "" : "test.";
640
+ return {
641
+ txid: response.txid,
642
+ funded: "stored-beef",
643
+ explorer: `https://${wocNet}whatsonchain.com/tx/${response.txid}`
644
+ };
645
+ }
646
+ async function lookupOverlay(service, query) {
647
+ const resp = await fetch(`${OVERLAY_URL}/lookup`, {
648
+ method: "POST",
649
+ headers: { "Content-Type": "application/json" },
650
+ body: JSON.stringify({ service, query })
651
+ });
652
+ if (!resp.ok) {
653
+ const errText = await resp.text();
654
+ throw new Error(`Lookup failed: ${resp.status} \u2014 ${errText}`);
655
+ }
656
+ return resp.json();
657
+ }
658
+ async function parseOverlayOutput(beefData, outputIndex) {
659
+ try {
660
+ const tx = Transaction.fromBEEF(beefData);
661
+ const txid = tx.id("hex");
662
+ const output = tx.outputs[outputIndex];
663
+ if (!output) return { data: null, txid: null };
664
+ const { fields } = PushDrop.decode(output.lockingScript);
665
+ return { data: JSON.parse(Utils4.toUTF8(fields[0])), txid };
666
+ } catch {
667
+ return { data: null, txid: null };
668
+ }
669
+ }
670
+ var init_transaction = __esm({
671
+ "src/scripts/overlay/transaction.ts"() {
672
+ "use strict";
673
+ init_config();
674
+ init_dist();
4348
675
  }
4349
676
  });
4350
677
 
@@ -6267,7 +2594,7 @@ var log2 = debug2("openclaw:plugin:overlay:connect");
6267
2594
  async function cmdConnect(onMessage, signal) {
6268
2595
  let WebSocketClient;
6269
2596
  try {
6270
- const ws = await Promise.resolve().then(() => (init_wrapper(), wrapper_exports));
2597
+ const ws = await import("ws");
6271
2598
  WebSocketClient = ws.default || ws.WebSocket || ws;
6272
2599
  } catch {
6273
2600
  return fail("WebSocket client not available. Install it: npm install ws");
@@ -6414,8 +2741,10 @@ function loadDailySpending(walletDir) {
6414
2741
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
6415
2742
  const budgetPath = getBudgetPath(walletDir);
6416
2743
  try {
6417
- const data = JSON.parse(fs13.readFileSync(budgetPath, "utf-8"));
6418
- if (data.date === today) return data;
2744
+ if (fs13.existsSync(budgetPath)) {
2745
+ const data = JSON.parse(fs13.readFileSync(budgetPath, "utf-8"));
2746
+ if (data.date === today) return data;
2747
+ }
6419
2748
  } catch {
6420
2749
  }
6421
2750
  return { date: today, totalSats: 0, transactions: [] };
@@ -6443,7 +2772,18 @@ function applyConfigToEnv(config) {
6443
2772
  process["env"].AGENT_NAME = config.agentName || "openclaw-agent";
6444
2773
  setNoExit(true);
6445
2774
  }
6446
- async function startAutoImport(config, api) {
2775
+ function wakeAgent(text, logger, port, token, options = {}) {
2776
+ const sessionKey = options.sessionKey || `hook:openclaw-overlay:${Date.now()}`;
2777
+ if (!token) return;
2778
+ const target = `http://localhost:${port}/hooks/agent`;
2779
+ fetch(target, {
2780
+ method: "POST",
2781
+ headers: { "Content-Type": "application/json", "x-openclaw-token": token },
2782
+ body: JSON.stringify({ prompt: text, sessionKey })
2783
+ }).catch(() => {
2784
+ });
2785
+ }
2786
+ async function startAutoImport(config, api, port, token) {
6447
2787
  try {
6448
2788
  applyConfigToEnv(config);
6449
2789
  const addrOutput = await cmdAddress();
@@ -6475,7 +2815,7 @@ async function startAutoImport(config, api) {
6475
2815
 
6476
2816
  Auto-imported ${utxo.value} sats from transaction ${utxo.tx_hash.slice(0, 16)}...
6477
2817
 
6478
- Notify the user their wallet has been funded.`, api.logger, { sessionKey: "hook:openclaw-overlay:import" });
2818
+ Notify the user their wallet has been funded.`, api.logger, port, token, { sessionKey: "hook:openclaw-overlay:import" });
6479
2819
  try {
6480
2820
  const regPath = path4.join(os2.homedir(), ".openclaw", "openclaw-overlay", "registration.json");
6481
2821
  if (!fs13.existsSync(regPath)) {
@@ -6523,19 +2863,7 @@ async function autoAdvertiseServices(config, logger) {
6523
2863
  logger?.warn?.("[openclaw-overlay] Auto-advertising failed:", err.message);
6524
2864
  }
6525
2865
  }
6526
- function wakeAgent(text, logger, options = {}) {
6527
- const sessionKey = options.sessionKey || `hook:openclaw-overlay:${Date.now()}`;
6528
- const gatewayPort = process["env"].OPENCLAW_GATEWAY_PORT || "18789";
6529
- const httpToken = process["env"].OPENCLAW_HOOKS_TOKEN || null;
6530
- if (!httpToken) return;
6531
- fetch(`http://localhost:${gatewayPort}/hooks/agent`, {
6532
- method: "POST",
6533
- headers: { "Content-Type": "application/json", "x-openclaw-token": httpToken },
6534
- body: JSON.stringify({ prompt: text, sessionKey })
6535
- }).catch(() => {
6536
- });
6537
- }
6538
- async function startBackgroundService(config, api) {
2866
+ async function startBackgroundService(config, api, port, token) {
6539
2867
  if (serviceRunning) return;
6540
2868
  serviceRunning = true;
6541
2869
  abortController = new AbortController();
@@ -6558,7 +2886,7 @@ Fulfill it now:
6558
2886
  1. overlay({ action: "pending-requests" })
6559
2887
  2. Process the request
6560
2888
  3. overlay({ action: "fulfill", requestId: "${event.id}", recipientKey: "${event.from}", serviceId: "${event.serviceId}", result: { ... } })`;
6561
- wakeAgent(wakeText, api.logger, { sessionKey: `hook:openclaw-overlay:${rid}` });
2889
+ wakeAgent(wakeText, api.logger, port, token, { sessionKey: `hook:openclaw-overlay:${rid}` });
6562
2890
  }
6563
2891
  if (event.type === "service-response" && event.action === "received") {
6564
2892
  const wakeText = `\u{1F4EC} Overlay service response received!
@@ -6569,7 +2897,7 @@ Status: ${event.status}
6569
2897
 
6570
2898
  Full result:
6571
2899
  ${JSON.stringify(event.result, null, 2)}`;
6572
- wakeAgent(wakeText, api.logger, { sessionKey: `hook:openclaw-overlay:resp-${event.requestId || Date.now()}` });
2900
+ wakeAgent(wakeText, api.logger, port, token, { sessionKey: `hook:openclaw-overlay:resp-${event.requestId || Date.now()}` });
6573
2901
  }
6574
2902
  }, abortController.signal).catch((err) => {
6575
2903
  if (serviceRunning && !abortController?.signal.aborted) {
@@ -6594,7 +2922,7 @@ function stopBackgroundService() {
6594
2922
  }
6595
2923
  }
6596
2924
  function register(api) {
6597
- const version = "0.8.15";
2925
+ const version = "0.8.17";
6598
2926
  if (isInitialized) return;
6599
2927
  isInitialized = true;
6600
2928
  api.logger?.info?.(`[openclaw-overlay] Initializing Plugin v${version}`);
@@ -6620,6 +2948,7 @@ function register(api) {
6620
2948
  required: ["action"]
6621
2949
  },
6622
2950
  async execute(_id, params) {
2951
+ log3("Executing tool action: %s with params: %O", params.action, params);
6623
2952
  try {
6624
2953
  return await executeOverlayAction(params, pluginConfig, api);
6625
2954
  } catch (error) {
@@ -6652,8 +2981,10 @@ ${typeof result === "string" ? result : JSON.stringify(result, null, 2)}` };
6652
2981
  await initializeServiceSystem();
6653
2982
  } catch {
6654
2983
  }
6655
- await startBackgroundService(pluginConfig, api);
6656
- await startAutoImport(pluginConfig, api);
2984
+ const gatewayPort = process["env"].OPENCLAW_GATEWAY_PORT || "18789";
2985
+ const httpToken = process["env"].OPENCLAW_HOOKS_TOKEN || "";
2986
+ await startBackgroundService(pluginConfig, api, gatewayPort, httpToken);
2987
+ await startAutoImport(pluginConfig, api, gatewayPort, httpToken);
6657
2988
  },
6658
2989
  stop: () => stopBackgroundService()
6659
2990
  });
@@ -6681,7 +3012,6 @@ ${typeof result === "string" ? result : JSON.stringify(result, null, 2)}` };
6681
3012
  }
6682
3013
  async function executeOverlayAction(params, config, api) {
6683
3014
  const { action } = params;
6684
- log3("Executing action: %s with params: %O", action, params);
6685
3015
  applyConfigToEnv(config);
6686
3016
  switch (action) {
6687
3017
  case "request": {