@waku/core 0.0.26-4c5a8a9.0 → 0.0.26-7eb3375.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/bundle/base_protocol-46017f51.js +468 -0
  2. package/bundle/{base_protocol-4bcf7514.js → browser-9a6558bb.js} +742 -451
  3. package/bundle/{index-27b91e3b.js → index-7581d519.js} +1 -1
  4. package/bundle/index.js +3742 -4917
  5. package/bundle/lib/base_protocol.js +3 -3
  6. package/bundle/lib/message/version_0.js +3 -3
  7. package/bundle/lib/predefined_bootstrap_nodes.js +1 -1
  8. package/bundle/{version_0-2f1176e3.js → version_0-7190df43.js} +7 -7
  9. package/dist/.tsbuildinfo +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/lib/connection_manager.d.ts +8 -4
  13. package/dist/lib/connection_manager.js +34 -12
  14. package/dist/lib/connection_manager.js.map +1 -1
  15. package/dist/lib/constants.d.ts +2 -2
  16. package/dist/lib/constants.js +2 -2
  17. package/dist/lib/filter/index.js +4 -4
  18. package/dist/lib/keep_alive_manager.d.ts +1 -0
  19. package/dist/lib/keep_alive_manager.js +4 -1
  20. package/dist/lib/keep_alive_manager.js.map +1 -1
  21. package/dist/lib/light_push/index.js +2 -2
  22. package/dist/lib/message/version_0.d.ts +6 -6
  23. package/dist/lib/message/version_0.js +3 -3
  24. package/dist/lib/store/index.js +11 -11
  25. package/dist/lib/waku.d.ts +4 -3
  26. package/dist/lib/waku.js +3 -0
  27. package/dist/lib/waku.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/index.ts +1 -1
  30. package/src/lib/connection_manager.ts +44 -13
  31. package/src/lib/constants.ts +2 -2
  32. package/src/lib/filter/index.ts +11 -11
  33. package/src/lib/keep_alive_manager.ts +7 -1
  34. package/src/lib/light_push/index.ts +4 -4
  35. package/src/lib/message/version_0.ts +6 -6
  36. package/src/lib/store/index.ts +13 -13
  37. package/src/lib/waku.ts +6 -2
  38. package/bundle/browser-90197c87.js +0 -754
@@ -1,5 +1,3 @@
1
- import { L as Logger } from './index-27b91e3b.js';
2
-
3
1
  // base-x encoding / decoding
4
2
  // Copyright (c) 2018 base-x contributors
5
3
  // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
@@ -162,13 +160,13 @@ const coerce = o => {
162
160
  * @param {string} str
163
161
  * @returns {Uint8Array}
164
162
  */
165
- const fromString$1 = str => (new TextEncoder()).encode(str);
163
+ const fromString = str => (new TextEncoder()).encode(str);
166
164
 
167
165
  /**
168
166
  * @param {Uint8Array} b
169
167
  * @returns {string}
170
168
  */
171
- const toString$1 = b => (new TextDecoder()).decode(b);
169
+ const toString = b => (new TextDecoder()).decode(b);
172
170
 
173
171
  /**
174
172
  * Class represents both BaseEncoder and MultibaseEncoder meaning it
@@ -776,8 +774,8 @@ var base8$1 = /*#__PURE__*/Object.freeze({
776
774
  const identity = from({
777
775
  prefix: '\x00',
778
776
  name: 'identity',
779
- encode: (buf) => toString$1(buf),
780
- decode: (str) => fromString$1(str)
777
+ encode: (buf) => toString(buf),
778
+ decode: (str) => fromString(str)
781
779
  });
782
780
 
783
781
  var identityBase = /*#__PURE__*/Object.freeze({
@@ -795,464 +793,757 @@ var identityBase = /*#__PURE__*/Object.freeze({
795
793
  new TextEncoder();
796
794
  new TextDecoder();
797
795
 
798
- // @ts-check
799
-
800
-
801
- const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 };
796
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
802
797
 
803
- /**
804
- * To guarantee Uint8Array semantics, convert nodejs Buffers
805
- * into vanilla Uint8Arrays
806
- */
807
- function asUint8Array(buf) {
808
- if (globalThis.Buffer != null) {
809
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
810
- }
811
- return buf;
798
+ function getDefaultExportFromCjs (x) {
799
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
812
800
  }
813
801
 
814
- /**
815
- * Returns a `Uint8Array` of the requested size. Referenced memory will
816
- * be initialized to 0.
817
- */
818
- function alloc(size = 0) {
819
- if (globalThis.Buffer?.alloc != null) {
820
- return asUint8Array(globalThis.Buffer.alloc(size));
821
- }
822
- return new Uint8Array(size);
802
+ function getAugmentedNamespace(n) {
803
+ if (n.__esModule) return n;
804
+ var f = n.default;
805
+ if (typeof f == "function") {
806
+ var a = function a () {
807
+ if (this instanceof a) {
808
+ return Reflect.construct(f, arguments, this.constructor);
809
+ }
810
+ return f.apply(this, arguments);
811
+ };
812
+ a.prototype = f.prototype;
813
+ } else a = {};
814
+ Object.defineProperty(a, '__esModule', {value: true});
815
+ Object.keys(n).forEach(function (k) {
816
+ var d = Object.getOwnPropertyDescriptor(n, k);
817
+ Object.defineProperty(a, k, d.get ? d : {
818
+ enumerable: true,
819
+ get: function () {
820
+ return n[k];
821
+ }
822
+ });
823
+ });
824
+ return a;
823
825
  }
824
- /**
825
- * Where possible returns a Uint8Array of the requested size that references
826
- * uninitialized memory. Only use if you are certain you will immediately
827
- * overwrite every value in the returned `Uint8Array`.
828
- */
829
- function allocUnsafe(size = 0) {
830
- if (globalThis.Buffer?.allocUnsafe != null) {
831
- return asUint8Array(globalThis.Buffer.allocUnsafe(size));
832
- }
833
- return new Uint8Array(size);
834
- }
835
-
836
- function createCodec(name, prefix, encode, decode) {
837
- return {
838
- name,
839
- prefix,
840
- encoder: {
841
- name,
842
- prefix,
843
- encode
844
- },
845
- decoder: {
846
- decode
847
- }
848
- };
849
- }
850
- const string = createCodec('utf8', 'u', (buf) => {
851
- const decoder = new TextDecoder('utf8');
852
- return 'u' + decoder.decode(buf);
853
- }, (str) => {
854
- const encoder = new TextEncoder();
855
- return encoder.encode(str.substring(1));
856
- });
857
- const ascii = createCodec('ascii', 'a', (buf) => {
858
- let string = 'a';
859
- for (let i = 0; i < buf.length; i++) {
860
- string += String.fromCharCode(buf[i]);
861
- }
862
- return string;
863
- }, (str) => {
864
- str = str.substring(1);
865
- const buf = allocUnsafe(str.length);
866
- for (let i = 0; i < str.length; i++) {
867
- buf[i] = str.charCodeAt(i);
868
- }
869
- return buf;
870
- });
871
- const BASES = {
872
- utf8: string,
873
- 'utf-8': string,
874
- hex: bases.base16,
875
- latin1: ascii,
876
- ascii,
877
- binary: ascii,
878
- ...bases
879
- };
880
826
 
881
- /**
882
- * Turns a `Uint8Array` into a string.
883
- *
884
- * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.
885
- *
886
- * Also `ascii` which is similar to node's 'binary' encoding.
887
- */
888
- function toString(array, encoding = 'utf8') {
889
- const base = BASES[encoding];
890
- if (base == null) {
891
- throw new Error(`Unsupported encoding "${encoding}"`);
892
- }
893
- if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
894
- return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');
895
- }
896
- // strip multibase prefix
897
- return base.encoder.encode(array).substring(1);
898
- }
899
-
900
- /**
901
- * Create a `Uint8Array` from the passed string
902
- *
903
- * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
904
- *
905
- * Also `ascii` which is similar to node's 'binary' encoding.
906
- */
907
- function fromString(string, encoding = 'utf8') {
908
- const base = BASES[encoding];
909
- if (base == null) {
910
- throw new Error(`Unsupported encoding "${encoding}"`);
911
- }
912
- if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
913
- return asUint8Array(globalThis.Buffer.from(string, 'utf-8'));
914
- }
915
- // add multibase prefix
916
- return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
917
- }
918
-
919
- var Protocols;
920
- (function (Protocols) {
921
- Protocols["Relay"] = "relay";
922
- Protocols["Store"] = "store";
923
- Protocols["LightPush"] = "lightpush";
924
- Protocols["Filter"] = "filter";
925
- })(Protocols || (Protocols = {}));
926
- var SendError;
927
- (function (SendError) {
928
- /** Could not determine the origin of the fault. Best to check connectivity and try again */
929
- SendError["GENERIC_FAIL"] = "Generic error";
930
- /**
931
- * Failure to protobuf encode the message. This is not recoverable and needs
932
- * further investigation.
933
- */
934
- SendError["ENCODE_FAILED"] = "Failed to encode";
935
- /**
936
- * Failure to protobuf decode the message. May be due to a remote peer issue,
937
- * ensuring that messages are sent via several peer enable mitigation of this error.
938
- */
939
- SendError["DECODE_FAILED"] = "Failed to decode";
940
- /**
941
- * The message payload is empty, making the message invalid. Ensure that a non-empty
942
- * payload is set on the outgoing message.
943
- */
944
- SendError["EMPTY_PAYLOAD"] = "Payload is empty";
945
- /**
946
- * The message size is above the maximum message size allowed on the Waku Network.
947
- * Compressing the message or using an alternative strategy for large messages is recommended.
948
- */
949
- SendError["SIZE_TOO_BIG"] = "Size is too big";
950
- /**
951
- * The PubSubTopic passed to the send function is not configured on the Waku node.
952
- * Please ensure that the PubSubTopic is used when initializing the Waku node.
953
- */
954
- SendError["TOPIC_NOT_CONFIGURED"] = "Topic not configured";
955
- /**
956
- * Failure to find a peer with suitable protocols. This may due to a connection issue.
957
- * Mitigation can be: retrying after a given time period, display connectivity issue
958
- * to user or listening for `peer:connected:bootstrap` or `peer:connected:peer-exchange`
959
- * on the connection manager before retrying.
960
- */
961
- SendError["NO_PEER_AVAILABLE"] = "No peer available";
962
- /**
963
- * The remote peer did not behave as expected. Mitigation for `NO_PEER_AVAILABLE`
964
- * or `DECODE_FAILED` can be used.
965
- */
966
- SendError["REMOTE_PEER_FAULT"] = "Remote peer fault";
967
- /**
968
- * The remote peer rejected the message. Information provided by the remote peer
969
- * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`
970
- * or `DECODE_FAILED` can be used.
971
- */
972
- SendError["REMOTE_PEER_REJECTED"] = "Remote peer rejected";
973
- })(SendError || (SendError = {}));
974
-
975
- var PageDirection;
976
- (function (PageDirection) {
977
- PageDirection["BACKWARD"] = "backward";
978
- PageDirection["FORWARD"] = "forward";
979
- })(PageDirection || (PageDirection = {}));
980
-
981
- var Tags;
982
- (function (Tags) {
983
- Tags["BOOTSTRAP"] = "bootstrap";
984
- Tags["PEER_EXCHANGE"] = "peer-exchange";
985
- })(Tags || (Tags = {}));
986
- var EPeersByDiscoveryEvents;
987
- (function (EPeersByDiscoveryEvents) {
988
- EPeersByDiscoveryEvents["PEER_DISCOVERY_BOOTSTRAP"] = "peer:discovery:bootstrap";
989
- EPeersByDiscoveryEvents["PEER_DISCOVERY_PEER_EXCHANGE"] = "peer:discovery:peer-exchange";
990
- EPeersByDiscoveryEvents["PEER_CONNECT_BOOTSTRAP"] = "peer:connected:bootstrap";
991
- EPeersByDiscoveryEvents["PEER_CONNECT_PEER_EXCHANGE"] = "peer:connected:peer-exchange";
992
- })(EPeersByDiscoveryEvents || (EPeersByDiscoveryEvents = {}));
827
+ var browser = {exports: {}};
993
828
 
994
829
  /**
995
- * Decode byte array to utf-8 string.
830
+ * Helpers.
996
831
  */
997
- const bytesToUtf8 = (b) => toString(b, "utf8");
998
- /**
999
- * Encode utf-8 string to byte array.
1000
- */
1001
- const utf8ToBytes = (s) => fromString(s, "utf8");
1002
- /**
1003
- * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`
1004
- */
1005
- function concat(byteArrays, totalLength) {
1006
- const len = totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);
1007
- const res = new Uint8Array(len);
1008
- let offset = 0;
1009
- for (const bytes of byteArrays) {
1010
- res.set(bytes, offset);
1011
- offset += bytes.length;
1012
- }
1013
- return res;
1014
- }
1015
832
 
1016
- /**
1017
- * Returns a pseudo-random peer that supports the given protocol.
1018
- * Useful for protocols such as store and light push
1019
- */
1020
- function selectRandomPeer(peers) {
1021
- if (peers.length === 0)
1022
- return;
1023
- const index = Math.round(Math.random() * (peers.length - 1));
1024
- return peers[index];
1025
- }
1026
- /**
1027
- * Returns the peer with the lowest latency.
1028
- * @param peerStore - The Libp2p PeerStore
1029
- * @param peers - The list of peers to choose from
1030
- * @returns The peer with the lowest latency, or undefined if no peer could be reached
1031
- */
1032
- async function selectLowestLatencyPeer(peerStore, peers) {
1033
- if (peers.length === 0)
1034
- return;
1035
- const results = await Promise.all(peers.map(async (peer) => {
1036
- const pingBytes = (await peerStore.get(peer.id)).metadata.get("ping");
1037
- if (!pingBytes)
1038
- return { peer, ping: Infinity };
1039
- const ping = Number(bytesToUtf8(pingBytes)) ?? Infinity;
1040
- return { peer, ping };
1041
- }));
1042
- const lowestLatencyResult = results.sort((a, b) => a.ping - b.ping)[0];
1043
- if (!lowestLatencyResult) {
1044
- return undefined;
1045
- }
1046
- return lowestLatencyResult.ping !== Infinity
1047
- ? lowestLatencyResult.peer
1048
- : undefined;
1049
- }
1050
- /**
1051
- * Returns the list of peers that supports the given protocol.
1052
- */
1053
- async function getPeersForProtocol(peerStore, protocols) {
1054
- const peers = [];
1055
- await peerStore.forEach((peer) => {
1056
- for (let i = 0; i < protocols.length; i++) {
1057
- if (peer.protocols.includes(protocols[i])) {
1058
- peers.push(peer);
1059
- break;
1060
- }
1061
- }
1062
- });
1063
- return peers;
1064
- }
1065
- /**
1066
- * Returns a peer that supports the given protocol.
1067
- * If peerId is provided, the peer with that id is returned.
1068
- * Otherwise, the peer with the lowest latency is returned.
1069
- * If no peer is found from the above criteria, a random peer is returned.
1070
- */
1071
- async function selectPeerForProtocol(peerStore, protocols, peerId) {
1072
- let peer;
1073
- if (peerId) {
1074
- peer = await peerStore.get(peerId);
1075
- if (!peer) {
1076
- throw new Error(`Failed to retrieve connection details for provided peer in peer store: ${peerId.toString()}`);
1077
- }
1078
- }
1079
- else {
1080
- const peers = await getPeersForProtocol(peerStore, protocols);
1081
- peer = await selectLowestLatencyPeer(peerStore, peers);
1082
- if (!peer) {
1083
- peer = selectRandomPeer(peers);
1084
- if (!peer)
1085
- throw new Error(`Failed to find known peer that registers protocols: ${protocols}`);
1086
- }
1087
- }
1088
- let protocol;
1089
- for (const codec of protocols) {
1090
- if (peer.protocols.includes(codec)) {
1091
- protocol = codec;
1092
- // Do not break as we want to keep the last value
1093
- }
1094
- }
1095
- if (!protocol) {
1096
- throw new Error(`Peer does not register required protocols (${peer.id.toString()}): ${protocols}`);
1097
- }
1098
- return { peer, protocol };
1099
- }
1100
- function selectConnection(connections) {
1101
- if (!connections.length)
1102
- return;
1103
- if (connections.length === 1)
1104
- return connections[0];
1105
- let latestConnection;
1106
- connections.forEach((connection) => {
1107
- if (connection.status === "open") {
1108
- if (!latestConnection) {
1109
- latestConnection = connection;
1110
- }
1111
- else if (connection.timeline.open > latestConnection.timeline.open) {
1112
- latestConnection = connection;
1113
- }
1114
- }
1115
- });
1116
- return latestConnection;
833
+ var ms;
834
+ var hasRequiredMs;
835
+
836
+ function requireMs () {
837
+ if (hasRequiredMs) return ms;
838
+ hasRequiredMs = 1;
839
+ var s = 1000;
840
+ var m = s * 60;
841
+ var h = m * 60;
842
+ var d = h * 24;
843
+ var w = d * 7;
844
+ var y = d * 365.25;
845
+
846
+ /**
847
+ * Parse or format the given `val`.
848
+ *
849
+ * Options:
850
+ *
851
+ * - `long` verbose formatting [false]
852
+ *
853
+ * @param {String|Number} val
854
+ * @param {Object} [options]
855
+ * @throws {Error} throw an error if val is not a non-empty string or a number
856
+ * @return {String|Number}
857
+ * @api public
858
+ */
859
+
860
+ ms = function(val, options) {
861
+ options = options || {};
862
+ var type = typeof val;
863
+ if (type === 'string' && val.length > 0) {
864
+ return parse(val);
865
+ } else if (type === 'number' && isFinite(val)) {
866
+ return options.long ? fmtLong(val) : fmtShort(val);
867
+ }
868
+ throw new Error(
869
+ 'val is not a non-empty string or a valid number. val=' +
870
+ JSON.stringify(val)
871
+ );
872
+ };
873
+
874
+ /**
875
+ * Parse the given `str` and return milliseconds.
876
+ *
877
+ * @param {String} str
878
+ * @return {Number}
879
+ * @api private
880
+ */
881
+
882
+ function parse(str) {
883
+ str = String(str);
884
+ if (str.length > 100) {
885
+ return;
886
+ }
887
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
888
+ str
889
+ );
890
+ if (!match) {
891
+ return;
892
+ }
893
+ var n = parseFloat(match[1]);
894
+ var type = (match[2] || 'ms').toLowerCase();
895
+ switch (type) {
896
+ case 'years':
897
+ case 'year':
898
+ case 'yrs':
899
+ case 'yr':
900
+ case 'y':
901
+ return n * y;
902
+ case 'weeks':
903
+ case 'week':
904
+ case 'w':
905
+ return n * w;
906
+ case 'days':
907
+ case 'day':
908
+ case 'd':
909
+ return n * d;
910
+ case 'hours':
911
+ case 'hour':
912
+ case 'hrs':
913
+ case 'hr':
914
+ case 'h':
915
+ return n * h;
916
+ case 'minutes':
917
+ case 'minute':
918
+ case 'mins':
919
+ case 'min':
920
+ case 'm':
921
+ return n * m;
922
+ case 'seconds':
923
+ case 'second':
924
+ case 'secs':
925
+ case 'sec':
926
+ case 's':
927
+ return n * s;
928
+ case 'milliseconds':
929
+ case 'millisecond':
930
+ case 'msecs':
931
+ case 'msec':
932
+ case 'ms':
933
+ return n;
934
+ default:
935
+ return undefined;
936
+ }
937
+ }
938
+
939
+ /**
940
+ * Short format for `ms`.
941
+ *
942
+ * @param {Number} ms
943
+ * @return {String}
944
+ * @api private
945
+ */
946
+
947
+ function fmtShort(ms) {
948
+ var msAbs = Math.abs(ms);
949
+ if (msAbs >= d) {
950
+ return Math.round(ms / d) + 'd';
951
+ }
952
+ if (msAbs >= h) {
953
+ return Math.round(ms / h) + 'h';
954
+ }
955
+ if (msAbs >= m) {
956
+ return Math.round(ms / m) + 'm';
957
+ }
958
+ if (msAbs >= s) {
959
+ return Math.round(ms / s) + 's';
960
+ }
961
+ return ms + 'ms';
962
+ }
963
+
964
+ /**
965
+ * Long format for `ms`.
966
+ *
967
+ * @param {Number} ms
968
+ * @return {String}
969
+ * @api private
970
+ */
971
+
972
+ function fmtLong(ms) {
973
+ var msAbs = Math.abs(ms);
974
+ if (msAbs >= d) {
975
+ return plural(ms, msAbs, d, 'day');
976
+ }
977
+ if (msAbs >= h) {
978
+ return plural(ms, msAbs, h, 'hour');
979
+ }
980
+ if (msAbs >= m) {
981
+ return plural(ms, msAbs, m, 'minute');
982
+ }
983
+ if (msAbs >= s) {
984
+ return plural(ms, msAbs, s, 'second');
985
+ }
986
+ return ms + ' ms';
987
+ }
988
+
989
+ /**
990
+ * Pluralization helper.
991
+ */
992
+
993
+ function plural(ms, msAbs, n, name) {
994
+ var isPlural = msAbs >= n * 1.5;
995
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
996
+ }
997
+ return ms;
1117
998
  }
1118
999
 
1119
1000
  /**
1120
- * Retrieves a list of peers based on the specified criteria.
1121
- *
1122
- * @param peers - The list of peers to filter from.
1123
- * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
1124
- * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
1125
- * @returns A Promise that resolves to an array of peers based on the specified criteria.
1001
+ * This is the common logic for both the Node.js and web browser
1002
+ * implementations of `debug()`.
1126
1003
  */
1127
- async function filterPeers(peers, numPeers, maxBootstrapPeers) {
1128
- // Collect the bootstrap peers up to the specified maximum
1129
- const bootstrapPeers = peers
1130
- .filter((peer) => peer.tags.has(Tags.BOOTSTRAP))
1131
- .slice(0, maxBootstrapPeers);
1132
- // Collect non-bootstrap peers
1133
- const nonBootstrapPeers = peers.filter((peer) => !peer.tags.has(Tags.BOOTSTRAP));
1134
- // If numPeers is 0, return all peers
1135
- if (numPeers === 0) {
1136
- return [...bootstrapPeers, ...nonBootstrapPeers];
1137
- }
1138
- // Initialize the list of selected peers with the bootstrap peers
1139
- const selectedPeers = [...bootstrapPeers];
1140
- // Fill up to numPeers with remaining random peers if needed
1141
- while (selectedPeers.length < numPeers && nonBootstrapPeers.length > 0) {
1142
- const randomIndex = Math.floor(Math.random() * nonBootstrapPeers.length);
1143
- const randomPeer = nonBootstrapPeers.splice(randomIndex, 1)[0];
1144
- selectedPeers.push(randomPeer);
1145
- }
1146
- return selectedPeers;
1147
- }
1148
-
1149
- class StreamManager {
1150
- multicodec;
1151
- getConnections;
1152
- addEventListener;
1153
- streamPool;
1154
- log;
1155
- constructor(multicodec, getConnections, addEventListener) {
1156
- this.multicodec = multicodec;
1157
- this.getConnections = getConnections;
1158
- this.addEventListener = addEventListener;
1159
- this.log = new Logger(`stream-manager:${multicodec}`);
1160
- this.addEventListener("peer:update", this.handlePeerUpdateStreamPool.bind(this));
1161
- this.getStream = this.getStream.bind(this);
1162
- this.streamPool = new Map();
1163
- }
1164
- async getStream(peer) {
1165
- const peerIdStr = peer.id.toString();
1166
- const streamPromise = this.streamPool.get(peerIdStr);
1167
- if (!streamPromise) {
1168
- return this.newStream(peer); // fallback by creating a new stream on the spot
1169
- }
1170
- // We have the stream, let's remove it from the map
1171
- this.streamPool.delete(peerIdStr);
1172
- this.prepareNewStream(peer);
1173
- const stream = await streamPromise;
1174
- if (!stream || stream.status === "closed") {
1175
- return this.newStream(peer); // fallback by creating a new stream on the spot
1176
- }
1177
- return stream;
1178
- }
1179
- async newStream(peer) {
1180
- const connections = this.getConnections(peer.id);
1181
- const connection = selectConnection(connections);
1182
- if (!connection) {
1183
- throw new Error("Failed to get a connection to the peer");
1184
- }
1185
- return connection.newStream(this.multicodec);
1186
- }
1187
- prepareNewStream(peer) {
1188
- const streamPromise = this.newStream(peer).catch(() => {
1189
- // No error thrown as this call is not triggered by the user
1190
- this.log.error(`Failed to prepare a new stream for ${peer.id.toString()}`);
1191
- });
1192
- this.streamPool.set(peer.id.toString(), streamPromise);
1193
- }
1194
- handlePeerUpdateStreamPool = (evt) => {
1195
- const peer = evt.detail.peer;
1196
- if (peer.protocols.includes(this.multicodec)) {
1197
- this.log.info(`Preemptively opening a stream to ${peer.id.toString()}`);
1198
- this.prepareNewStream(peer);
1199
- }
1200
- };
1201
- }
1202
1004
 
1203
- /**
1204
- * A class with predefined helpers, to be used as a base to implement Waku
1205
- * Protocols.
1206
- */
1207
- class BaseProtocol {
1208
- multicodec;
1209
- components;
1210
- addLibp2pEventListener;
1211
- removeLibp2pEventListener;
1212
- streamManager;
1213
- constructor(multicodec, components) {
1214
- this.multicodec = multicodec;
1215
- this.components = components;
1216
- this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);
1217
- this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
1218
- this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
1219
- }
1220
- async getStream(peer) {
1221
- return this.streamManager.getStream(peer);
1222
- }
1223
- get peerStore() {
1224
- return this.components.peerStore;
1225
- }
1226
- /**
1227
- * Returns known peers from the address book (`libp2p.peerStore`) that support
1228
- * the class protocol. Waku may or may not be currently connected to these
1229
- * peers.
1230
- */
1231
- async peers() {
1232
- return getPeersForProtocol(this.peerStore, [this.multicodec]);
1233
- }
1234
- async getPeer(peerId) {
1235
- const { peer } = await selectPeerForProtocol(this.peerStore, [this.multicodec], peerId);
1236
- return peer;
1237
- }
1238
- /**
1239
- * Retrieves a list of peers based on the specified criteria.
1240
- *
1241
- * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
1242
- * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
1243
- * @returns A Promise that resolves to an array of peers based on the specified criteria.
1244
- */
1245
- async getPeers({ numPeers, maxBootstrapPeers } = {
1246
- maxBootstrapPeers: 1,
1247
- numPeers: 0
1248
- }) {
1249
- // Retrieve all peers that support the protocol
1250
- const allPeersForProtocol = await getPeersForProtocol(this.peerStore, [
1251
- this.multicodec
1252
- ]);
1253
- // Filter the peers based on the specified criteria
1254
- return filterPeers(allPeersForProtocol, numPeers, maxBootstrapPeers);
1255
- }
1005
+ function setup(env) {
1006
+ createDebug.debug = createDebug;
1007
+ createDebug.default = createDebug;
1008
+ createDebug.coerce = coerce;
1009
+ createDebug.disable = disable;
1010
+ createDebug.enable = enable;
1011
+ createDebug.enabled = enabled;
1012
+ createDebug.humanize = requireMs();
1013
+ createDebug.destroy = destroy;
1014
+
1015
+ Object.keys(env).forEach(key => {
1016
+ createDebug[key] = env[key];
1017
+ });
1018
+
1019
+ /**
1020
+ * The currently active debug mode names, and names to skip.
1021
+ */
1022
+
1023
+ createDebug.names = [];
1024
+ createDebug.skips = [];
1025
+
1026
+ /**
1027
+ * Map of special "%n" handling functions, for the debug "format" argument.
1028
+ *
1029
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
1030
+ */
1031
+ createDebug.formatters = {};
1032
+
1033
+ /**
1034
+ * Selects a color for a debug namespace
1035
+ * @param {String} namespace The namespace string for the debug instance to be colored
1036
+ * @return {Number|String} An ANSI color code for the given namespace
1037
+ * @api private
1038
+ */
1039
+ function selectColor(namespace) {
1040
+ let hash = 0;
1041
+
1042
+ for (let i = 0; i < namespace.length; i++) {
1043
+ hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
1044
+ hash |= 0; // Convert to 32bit integer
1045
+ }
1046
+
1047
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
1048
+ }
1049
+ createDebug.selectColor = selectColor;
1050
+
1051
+ /**
1052
+ * Create a debugger with the given `namespace`.
1053
+ *
1054
+ * @param {String} namespace
1055
+ * @return {Function}
1056
+ * @api public
1057
+ */
1058
+ function createDebug(namespace) {
1059
+ let prevTime;
1060
+ let enableOverride = null;
1061
+ let namespacesCache;
1062
+ let enabledCache;
1063
+
1064
+ function debug(...args) {
1065
+ // Disabled?
1066
+ if (!debug.enabled) {
1067
+ return;
1068
+ }
1069
+
1070
+ const self = debug;
1071
+
1072
+ // Set `diff` timestamp
1073
+ const curr = Number(new Date());
1074
+ const ms = curr - (prevTime || curr);
1075
+ self.diff = ms;
1076
+ self.prev = prevTime;
1077
+ self.curr = curr;
1078
+ prevTime = curr;
1079
+
1080
+ args[0] = createDebug.coerce(args[0]);
1081
+
1082
+ if (typeof args[0] !== 'string') {
1083
+ // Anything else let's inspect with %O
1084
+ args.unshift('%O');
1085
+ }
1086
+
1087
+ // Apply any `formatters` transformations
1088
+ let index = 0;
1089
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
1090
+ // If we encounter an escaped % then don't increase the array index
1091
+ if (match === '%%') {
1092
+ return '%';
1093
+ }
1094
+ index++;
1095
+ const formatter = createDebug.formatters[format];
1096
+ if (typeof formatter === 'function') {
1097
+ const val = args[index];
1098
+ match = formatter.call(self, val);
1099
+
1100
+ // Now we need to remove `args[index]` since it's inlined in the `format`
1101
+ args.splice(index, 1);
1102
+ index--;
1103
+ }
1104
+ return match;
1105
+ });
1106
+
1107
+ // Apply env-specific formatting (colors, etc.)
1108
+ createDebug.formatArgs.call(self, args);
1109
+
1110
+ const logFn = self.log || createDebug.log;
1111
+ logFn.apply(self, args);
1112
+ }
1113
+
1114
+ debug.namespace = namespace;
1115
+ debug.useColors = createDebug.useColors();
1116
+ debug.color = createDebug.selectColor(namespace);
1117
+ debug.extend = extend;
1118
+ debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
1119
+
1120
+ Object.defineProperty(debug, 'enabled', {
1121
+ enumerable: true,
1122
+ configurable: false,
1123
+ get: () => {
1124
+ if (enableOverride !== null) {
1125
+ return enableOverride;
1126
+ }
1127
+ if (namespacesCache !== createDebug.namespaces) {
1128
+ namespacesCache = createDebug.namespaces;
1129
+ enabledCache = createDebug.enabled(namespace);
1130
+ }
1131
+
1132
+ return enabledCache;
1133
+ },
1134
+ set: v => {
1135
+ enableOverride = v;
1136
+ }
1137
+ });
1138
+
1139
+ // Env-specific initialization logic for debug instances
1140
+ if (typeof createDebug.init === 'function') {
1141
+ createDebug.init(debug);
1142
+ }
1143
+
1144
+ return debug;
1145
+ }
1146
+
1147
+ function extend(namespace, delimiter) {
1148
+ const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
1149
+ newDebug.log = this.log;
1150
+ return newDebug;
1151
+ }
1152
+
1153
+ /**
1154
+ * Enables a debug mode by namespaces. This can include modes
1155
+ * separated by a colon and wildcards.
1156
+ *
1157
+ * @param {String} namespaces
1158
+ * @api public
1159
+ */
1160
+ function enable(namespaces) {
1161
+ createDebug.save(namespaces);
1162
+ createDebug.namespaces = namespaces;
1163
+
1164
+ createDebug.names = [];
1165
+ createDebug.skips = [];
1166
+
1167
+ let i;
1168
+ const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
1169
+ const len = split.length;
1170
+
1171
+ for (i = 0; i < len; i++) {
1172
+ if (!split[i]) {
1173
+ // ignore empty strings
1174
+ continue;
1175
+ }
1176
+
1177
+ namespaces = split[i].replace(/\*/g, '.*?');
1178
+
1179
+ if (namespaces[0] === '-') {
1180
+ createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
1181
+ } else {
1182
+ createDebug.names.push(new RegExp('^' + namespaces + '$'));
1183
+ }
1184
+ }
1185
+ }
1186
+
1187
+ /**
1188
+ * Disable debug output.
1189
+ *
1190
+ * @return {String} namespaces
1191
+ * @api public
1192
+ */
1193
+ function disable() {
1194
+ const namespaces = [
1195
+ ...createDebug.names.map(toNamespace),
1196
+ ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
1197
+ ].join(',');
1198
+ createDebug.enable('');
1199
+ return namespaces;
1200
+ }
1201
+
1202
+ /**
1203
+ * Returns true if the given mode name is enabled, false otherwise.
1204
+ *
1205
+ * @param {String} name
1206
+ * @return {Boolean}
1207
+ * @api public
1208
+ */
1209
+ function enabled(name) {
1210
+ if (name[name.length - 1] === '*') {
1211
+ return true;
1212
+ }
1213
+
1214
+ let i;
1215
+ let len;
1216
+
1217
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
1218
+ if (createDebug.skips[i].test(name)) {
1219
+ return false;
1220
+ }
1221
+ }
1222
+
1223
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
1224
+ if (createDebug.names[i].test(name)) {
1225
+ return true;
1226
+ }
1227
+ }
1228
+
1229
+ return false;
1230
+ }
1231
+
1232
+ /**
1233
+ * Convert regexp to namespace
1234
+ *
1235
+ * @param {RegExp} regxep
1236
+ * @return {String} namespace
1237
+ * @api private
1238
+ */
1239
+ function toNamespace(regexp) {
1240
+ return regexp.toString()
1241
+ .substring(2, regexp.toString().length - 2)
1242
+ .replace(/\.\*\?$/, '*');
1243
+ }
1244
+
1245
+ /**
1246
+ * Coerce `val`.
1247
+ *
1248
+ * @param {Mixed} val
1249
+ * @return {Mixed}
1250
+ * @api private
1251
+ */
1252
+ function coerce(val) {
1253
+ if (val instanceof Error) {
1254
+ return val.stack || val.message;
1255
+ }
1256
+ return val;
1257
+ }
1258
+
1259
+ /**
1260
+ * XXX DO NOT USE. This is a temporary stub function.
1261
+ * XXX It WILL be removed in the next major release.
1262
+ */
1263
+ function destroy() {
1264
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
1265
+ }
1266
+
1267
+ createDebug.enable(createDebug.load());
1268
+
1269
+ return createDebug;
1256
1270
  }
1257
1271
 
1258
- export { BaseProtocol as B, EPeersByDiscoveryEvents as E, Protocols as P, SendError as S, Tags as T, base58btc as a, base32 as b, coerce as c, allocUnsafe as d, equals as e, asUint8Array as f, bases as g, fromString as h, alloc as i, concat as j, StreamManager as k, toString as t, utf8ToBytes as u };
1272
+ var common = setup;
1273
+
1274
+ /* eslint-env browser */
1275
+
1276
+ (function (module, exports) {
1277
+ /**
1278
+ * This is the web browser implementation of `debug()`.
1279
+ */
1280
+
1281
+ exports.formatArgs = formatArgs;
1282
+ exports.save = save;
1283
+ exports.load = load;
1284
+ exports.useColors = useColors;
1285
+ exports.storage = localstorage();
1286
+ exports.destroy = (() => {
1287
+ let warned = false;
1288
+
1289
+ return () => {
1290
+ if (!warned) {
1291
+ warned = true;
1292
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
1293
+ }
1294
+ };
1295
+ })();
1296
+
1297
+ /**
1298
+ * Colors.
1299
+ */
1300
+
1301
+ exports.colors = [
1302
+ '#0000CC',
1303
+ '#0000FF',
1304
+ '#0033CC',
1305
+ '#0033FF',
1306
+ '#0066CC',
1307
+ '#0066FF',
1308
+ '#0099CC',
1309
+ '#0099FF',
1310
+ '#00CC00',
1311
+ '#00CC33',
1312
+ '#00CC66',
1313
+ '#00CC99',
1314
+ '#00CCCC',
1315
+ '#00CCFF',
1316
+ '#3300CC',
1317
+ '#3300FF',
1318
+ '#3333CC',
1319
+ '#3333FF',
1320
+ '#3366CC',
1321
+ '#3366FF',
1322
+ '#3399CC',
1323
+ '#3399FF',
1324
+ '#33CC00',
1325
+ '#33CC33',
1326
+ '#33CC66',
1327
+ '#33CC99',
1328
+ '#33CCCC',
1329
+ '#33CCFF',
1330
+ '#6600CC',
1331
+ '#6600FF',
1332
+ '#6633CC',
1333
+ '#6633FF',
1334
+ '#66CC00',
1335
+ '#66CC33',
1336
+ '#9900CC',
1337
+ '#9900FF',
1338
+ '#9933CC',
1339
+ '#9933FF',
1340
+ '#99CC00',
1341
+ '#99CC33',
1342
+ '#CC0000',
1343
+ '#CC0033',
1344
+ '#CC0066',
1345
+ '#CC0099',
1346
+ '#CC00CC',
1347
+ '#CC00FF',
1348
+ '#CC3300',
1349
+ '#CC3333',
1350
+ '#CC3366',
1351
+ '#CC3399',
1352
+ '#CC33CC',
1353
+ '#CC33FF',
1354
+ '#CC6600',
1355
+ '#CC6633',
1356
+ '#CC9900',
1357
+ '#CC9933',
1358
+ '#CCCC00',
1359
+ '#CCCC33',
1360
+ '#FF0000',
1361
+ '#FF0033',
1362
+ '#FF0066',
1363
+ '#FF0099',
1364
+ '#FF00CC',
1365
+ '#FF00FF',
1366
+ '#FF3300',
1367
+ '#FF3333',
1368
+ '#FF3366',
1369
+ '#FF3399',
1370
+ '#FF33CC',
1371
+ '#FF33FF',
1372
+ '#FF6600',
1373
+ '#FF6633',
1374
+ '#FF9900',
1375
+ '#FF9933',
1376
+ '#FFCC00',
1377
+ '#FFCC33'
1378
+ ];
1379
+
1380
+ /**
1381
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
1382
+ * and the Firebug extension (any Firefox version) are known
1383
+ * to support "%c" CSS customizations.
1384
+ *
1385
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
1386
+ */
1387
+
1388
+ // eslint-disable-next-line complexity
1389
+ function useColors() {
1390
+ // NB: In an Electron preload script, document will be defined but not fully
1391
+ // initialized. Since we know we're in Chrome, we'll just detect this case
1392
+ // explicitly
1393
+ if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
1394
+ return true;
1395
+ }
1396
+
1397
+ // Internet Explorer and Edge do not support colors.
1398
+ if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
1399
+ return false;
1400
+ }
1401
+
1402
+ // Is webkit? http://stackoverflow.com/a/16459606/376773
1403
+ // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
1404
+ return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
1405
+ // Is firebug? http://stackoverflow.com/a/398120/376773
1406
+ (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
1407
+ // Is firefox >= v31?
1408
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
1409
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
1410
+ // Double check webkit in userAgent just in case we are in a worker
1411
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
1412
+ }
1413
+
1414
+ /**
1415
+ * Colorize log arguments if enabled.
1416
+ *
1417
+ * @api public
1418
+ */
1419
+
1420
+ function formatArgs(args) {
1421
+ args[0] = (this.useColors ? '%c' : '') +
1422
+ this.namespace +
1423
+ (this.useColors ? ' %c' : ' ') +
1424
+ args[0] +
1425
+ (this.useColors ? '%c ' : ' ') +
1426
+ '+' + module.exports.humanize(this.diff);
1427
+
1428
+ if (!this.useColors) {
1429
+ return;
1430
+ }
1431
+
1432
+ const c = 'color: ' + this.color;
1433
+ args.splice(1, 0, c, 'color: inherit');
1434
+
1435
+ // The final "%c" is somewhat tricky, because there could be other
1436
+ // arguments passed either before or after the %c, so we need to
1437
+ // figure out the correct index to insert the CSS into
1438
+ let index = 0;
1439
+ let lastC = 0;
1440
+ args[0].replace(/%[a-zA-Z%]/g, match => {
1441
+ if (match === '%%') {
1442
+ return;
1443
+ }
1444
+ index++;
1445
+ if (match === '%c') {
1446
+ // We only are interested in the *last* %c
1447
+ // (the user may have provided their own)
1448
+ lastC = index;
1449
+ }
1450
+ });
1451
+
1452
+ args.splice(lastC, 0, c);
1453
+ }
1454
+
1455
+ /**
1456
+ * Invokes `console.debug()` when available.
1457
+ * No-op when `console.debug` is not a "function".
1458
+ * If `console.debug` is not available, falls back
1459
+ * to `console.log`.
1460
+ *
1461
+ * @api public
1462
+ */
1463
+ exports.log = console.debug || console.log || (() => {});
1464
+
1465
+ /**
1466
+ * Save `namespaces`.
1467
+ *
1468
+ * @param {String} namespaces
1469
+ * @api private
1470
+ */
1471
+ function save(namespaces) {
1472
+ try {
1473
+ if (namespaces) {
1474
+ exports.storage.setItem('debug', namespaces);
1475
+ } else {
1476
+ exports.storage.removeItem('debug');
1477
+ }
1478
+ } catch (error) {
1479
+ // Swallow
1480
+ // XXX (@Qix-) should we be logging these?
1481
+ }
1482
+ }
1483
+
1484
+ /**
1485
+ * Load `namespaces`.
1486
+ *
1487
+ * @return {String} returns the previously persisted debug modes
1488
+ * @api private
1489
+ */
1490
+ function load() {
1491
+ let r;
1492
+ try {
1493
+ r = exports.storage.getItem('debug');
1494
+ } catch (error) {
1495
+ // Swallow
1496
+ // XXX (@Qix-) should we be logging these?
1497
+ }
1498
+
1499
+ // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
1500
+ if (!r && typeof process !== 'undefined' && 'env' in process) {
1501
+ r = process.env.DEBUG;
1502
+ }
1503
+
1504
+ return r;
1505
+ }
1506
+
1507
+ /**
1508
+ * Localstorage attempts to return the localstorage.
1509
+ *
1510
+ * This is necessary because safari throws
1511
+ * when a user disables cookies/localstorage
1512
+ * and you attempt to access it.
1513
+ *
1514
+ * @return {LocalStorage}
1515
+ * @api private
1516
+ */
1517
+
1518
+ function localstorage() {
1519
+ try {
1520
+ // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
1521
+ // The Browser also has localStorage in the global context.
1522
+ return localStorage;
1523
+ } catch (error) {
1524
+ // Swallow
1525
+ // XXX (@Qix-) should we be logging these?
1526
+ }
1527
+ }
1528
+
1529
+ module.exports = common(exports);
1530
+
1531
+ const {formatters} = module.exports;
1532
+
1533
+ /**
1534
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
1535
+ */
1536
+
1537
+ formatters.j = function (v) {
1538
+ try {
1539
+ return JSON.stringify(v);
1540
+ } catch (error) {
1541
+ return '[UnexpectedJSONParseError]: ' + error.message;
1542
+ }
1543
+ };
1544
+ } (browser, browser.exports));
1545
+
1546
+ var browserExports = browser.exports;
1547
+ var debug = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
1548
+
1549
+ export { base58btc as a, base32 as b, coerce as c, commonjsGlobal as d, equals as e, getDefaultExportFromCjs as f, getAugmentedNamespace as g, base2$1 as h, identityBase as i, base8$1 as j, base10$1 as k, base16$1 as l, base32$1 as m, base36$1 as n, base58 as o, base64$1 as p, base256emoji$1 as q, debug as r };