@waku/core 0.0.33 → 0.0.34-00f2e75.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 (84) hide show
  1. package/bundle/base_protocol-Bp5a9PNG.js +152 -0
  2. package/bundle/{index-BIW3qNYx.js → index-G1eRBjeI.js} +118 -204
  3. package/bundle/index.js +1895 -179
  4. package/bundle/lib/base_protocol.js +2 -2
  5. package/bundle/lib/message/version_0.js +2 -2
  6. package/bundle/{version_0-CdmZMfkQ.js → version_0-DJZG2fB2.js} +283 -45
  7. package/dist/.tsbuildinfo +1 -1
  8. package/dist/index.d.ts +1 -3
  9. package/dist/index.js +1 -3
  10. package/dist/index.js.map +1 -1
  11. package/dist/lib/base_protocol.d.ts +3 -23
  12. package/dist/lib/base_protocol.js +3 -47
  13. package/dist/lib/base_protocol.js.map +1 -1
  14. package/dist/lib/connection_manager/connection_manager.d.ts +118 -0
  15. package/dist/lib/{connection_manager.js → connection_manager/connection_manager.js} +136 -36
  16. package/dist/lib/connection_manager/connection_manager.js.map +1 -0
  17. package/dist/lib/connection_manager/index.d.ts +1 -0
  18. package/dist/lib/connection_manager/index.js +2 -0
  19. package/dist/lib/connection_manager/index.js.map +1 -0
  20. package/dist/lib/{keep_alive_manager.d.ts → connection_manager/keep_alive_manager.d.ts} +4 -2
  21. package/dist/lib/{keep_alive_manager.js → connection_manager/keep_alive_manager.js} +2 -2
  22. package/dist/lib/connection_manager/keep_alive_manager.js.map +1 -0
  23. package/dist/lib/connection_manager/utils.d.ts +7 -0
  24. package/dist/lib/connection_manager/utils.js +22 -0
  25. package/dist/lib/connection_manager/utils.js.map +1 -0
  26. package/dist/lib/filter/filter.d.ts +18 -0
  27. package/dist/lib/filter/filter.js +209 -0
  28. package/dist/lib/filter/filter.js.map +1 -0
  29. package/dist/lib/filter/index.d.ts +1 -18
  30. package/dist/lib/filter/index.js +1 -208
  31. package/dist/lib/filter/index.js.map +1 -1
  32. package/dist/lib/light_push/index.d.ts +1 -15
  33. package/dist/lib/light_push/index.js +1 -143
  34. package/dist/lib/light_push/index.js.map +1 -1
  35. package/dist/lib/light_push/light_push.d.ts +15 -0
  36. package/dist/lib/light_push/light_push.js +144 -0
  37. package/dist/lib/light_push/light_push.js.map +1 -0
  38. package/dist/lib/light_push/utils.d.ts +0 -2
  39. package/dist/lib/light_push/utils.js +9 -17
  40. package/dist/lib/light_push/utils.js.map +1 -1
  41. package/dist/lib/metadata/index.d.ts +1 -3
  42. package/dist/lib/metadata/index.js +1 -118
  43. package/dist/lib/metadata/index.js.map +1 -1
  44. package/dist/lib/metadata/metadata.d.ts +3 -0
  45. package/dist/lib/metadata/metadata.js +119 -0
  46. package/dist/lib/metadata/metadata.js.map +1 -0
  47. package/dist/lib/store/index.d.ts +1 -9
  48. package/dist/lib/store/index.js +1 -82
  49. package/dist/lib/store/index.js.map +1 -1
  50. package/dist/lib/store/store.d.ts +9 -0
  51. package/dist/lib/store/store.js +83 -0
  52. package/dist/lib/store/store.js.map +1 -0
  53. package/dist/lib/stream_manager/stream_manager.d.ts +2 -2
  54. package/dist/lib/stream_manager/stream_manager.js +16 -17
  55. package/dist/lib/stream_manager/stream_manager.js.map +1 -1
  56. package/package.json +1 -126
  57. package/src/index.ts +1 -4
  58. package/src/lib/base_protocol.ts +3 -76
  59. package/src/lib/{connection_manager.ts → connection_manager/connection_manager.ts} +168 -63
  60. package/src/lib/connection_manager/index.ts +1 -0
  61. package/src/lib/{keep_alive_manager.ts → connection_manager/keep_alive_manager.ts} +7 -3
  62. package/src/lib/connection_manager/utils.ts +25 -0
  63. package/src/lib/filter/filter.ts +315 -0
  64. package/src/lib/filter/index.ts +1 -315
  65. package/src/lib/light_push/index.ts +1 -188
  66. package/src/lib/light_push/light_push.ts +188 -0
  67. package/src/lib/light_push/utils.ts +13 -21
  68. package/src/lib/metadata/index.ts +1 -182
  69. package/src/lib/metadata/metadata.ts +182 -0
  70. package/src/lib/store/index.ts +1 -136
  71. package/src/lib/store/store.ts +136 -0
  72. package/src/lib/stream_manager/stream_manager.ts +16 -18
  73. package/bundle/base_protocol-Dzv-QHPR.js +0 -275
  74. package/dist/lib/connection_manager.d.ts +0 -62
  75. package/dist/lib/connection_manager.js.map +0 -1
  76. package/dist/lib/filterPeers.d.ts +0 -13
  77. package/dist/lib/filterPeers.js +0 -38
  78. package/dist/lib/filterPeers.js.map +0 -1
  79. package/dist/lib/health_manager.d.ts +0 -14
  80. package/dist/lib/health_manager.js +0 -70
  81. package/dist/lib/health_manager.js.map +0 -1
  82. package/dist/lib/keep_alive_manager.js.map +0 -1
  83. package/src/lib/filterPeers.ts +0 -51
  84. package/src/lib/health_manager.ts +0 -90
@@ -0,0 +1,152 @@
1
+ import { L as Logger } from './index-G1eRBjeI.js';
2
+
3
+ function selectOpenConnection(connections) {
4
+ return connections
5
+ .filter((c) => c.status === "open")
6
+ .sort((left, right) => right.timeline.open - left.timeline.open)
7
+ .at(0);
8
+ }
9
+
10
+ const STREAM_LOCK_KEY = "consumed";
11
+ class StreamManager {
12
+ multicodec;
13
+ getConnections;
14
+ addEventListener;
15
+ log;
16
+ ongoingCreation = new Set();
17
+ streamPool = new Map();
18
+ constructor(multicodec, getConnections, addEventListener) {
19
+ this.multicodec = multicodec;
20
+ this.getConnections = getConnections;
21
+ this.addEventListener = addEventListener;
22
+ this.log = new Logger(`stream-manager:${multicodec}`);
23
+ this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
24
+ }
25
+ async getStream(peerId) {
26
+ const peerIdStr = peerId.toString();
27
+ const scheduledStream = this.streamPool.get(peerIdStr);
28
+ if (scheduledStream) {
29
+ this.streamPool.delete(peerIdStr);
30
+ await scheduledStream;
31
+ }
32
+ let stream = this.getOpenStreamForCodec(peerId);
33
+ if (stream) {
34
+ this.log.info(`Found existing stream peerId=${peerIdStr} multicodec=${this.multicodec}`);
35
+ this.lockStream(peerIdStr, stream);
36
+ return stream;
37
+ }
38
+ stream = await this.createStream(peerId);
39
+ this.lockStream(peerIdStr, stream);
40
+ return stream;
41
+ }
42
+ async createStream(peerId, retries = 0) {
43
+ const connections = this.getConnections(peerId);
44
+ const connection = selectOpenConnection(connections);
45
+ if (!connection) {
46
+ throw new Error(`Failed to get a connection to the peer peerId=${peerId.toString()} multicodec=${this.multicodec}`);
47
+ }
48
+ let lastError;
49
+ let stream;
50
+ for (let i = 0; i < retries + 1; i++) {
51
+ try {
52
+ this.log.info(`Attempting to create a stream for peerId=${peerId.toString()} multicodec=${this.multicodec}`);
53
+ stream = await connection.newStream(this.multicodec);
54
+ this.log.info(`Created stream for peerId=${peerId.toString()} multicodec=${this.multicodec}`);
55
+ break;
56
+ }
57
+ catch (error) {
58
+ lastError = error;
59
+ }
60
+ }
61
+ if (!stream) {
62
+ throw new Error(`Failed to create a new stream for ${peerId.toString()} -- ` + lastError);
63
+ }
64
+ return stream;
65
+ }
66
+ async createStreamWithLock(peer) {
67
+ const peerId = peer.id.toString();
68
+ if (this.ongoingCreation.has(peerId)) {
69
+ this.log.info(`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`);
70
+ return;
71
+ }
72
+ try {
73
+ this.ongoingCreation.add(peerId);
74
+ await this.createStream(peer.id);
75
+ }
76
+ catch (error) {
77
+ this.log.error(`Failed to createStreamWithLock:`, error);
78
+ }
79
+ finally {
80
+ this.ongoingCreation.delete(peerId);
81
+ }
82
+ return;
83
+ }
84
+ handlePeerUpdateStreamPool = (evt) => {
85
+ const { peer } = evt.detail;
86
+ if (!peer.protocols.includes(this.multicodec)) {
87
+ return;
88
+ }
89
+ const stream = this.getOpenStreamForCodec(peer.id);
90
+ if (stream) {
91
+ return;
92
+ }
93
+ this.scheduleNewStream(peer);
94
+ };
95
+ scheduleNewStream(peer) {
96
+ this.log.info(`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
97
+ // abandon previous attempt
98
+ if (this.streamPool.has(peer.id.toString())) {
99
+ this.streamPool.delete(peer.id.toString());
100
+ }
101
+ this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));
102
+ }
103
+ getOpenStreamForCodec(peerId) {
104
+ const connections = this.getConnections(peerId);
105
+ const connection = selectOpenConnection(connections);
106
+ if (!connection) {
107
+ return;
108
+ }
109
+ const stream = connection.streams.find((s) => s.protocol === this.multicodec);
110
+ if (!stream) {
111
+ return;
112
+ }
113
+ const isStreamUnusable = ["done", "closed", "closing"].includes(stream.writeStatus || "");
114
+ if (isStreamUnusable || this.isStreamLocked(stream)) {
115
+ return;
116
+ }
117
+ return stream;
118
+ }
119
+ lockStream(peerId, stream) {
120
+ this.log.info(`Locking stream for peerId:${peerId}\tstreamId:${stream.id}`);
121
+ stream.metadata[STREAM_LOCK_KEY] = true;
122
+ }
123
+ isStreamLocked(stream) {
124
+ return !!stream.metadata[STREAM_LOCK_KEY];
125
+ }
126
+ }
127
+
128
+ /**
129
+ * A class with predefined helpers, to be used as a base to implement Waku
130
+ * Protocols.
131
+ */
132
+ class BaseProtocol {
133
+ multicodec;
134
+ components;
135
+ pubsubTopics;
136
+ addLibp2pEventListener;
137
+ removeLibp2pEventListener;
138
+ streamManager;
139
+ constructor(multicodec, components, pubsubTopics) {
140
+ this.multicodec = multicodec;
141
+ this.components = components;
142
+ this.pubsubTopics = pubsubTopics;
143
+ this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);
144
+ this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
145
+ this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
146
+ }
147
+ async getStream(peerId) {
148
+ return this.streamManager.getStream(peerId);
149
+ }
150
+ }
151
+
152
+ export { BaseProtocol as B, StreamManager as S };
@@ -1,19 +1,16 @@
1
- /**
2
- * Returns a `Uint8Array` of the requested size. Referenced memory will
3
- * be initialized to 0.
4
- */
5
- function alloc(size = 0) {
6
- return new Uint8Array(size);
7
- }
8
- /**
9
- * Where possible returns a Uint8Array of the requested size that references
10
- * uninitialized memory. Only use if you are certain you will immediately
11
- * overwrite every value in the returned `Uint8Array`.
12
- */
13
- function allocUnsafe(size = 0) {
14
- return new Uint8Array(size);
1
+ function equals(aa, bb) {
2
+ if (aa === bb)
3
+ return true;
4
+ if (aa.byteLength !== bb.byteLength) {
5
+ return false;
6
+ }
7
+ for (let ii = 0; ii < aa.byteLength; ii++) {
8
+ if (aa[ii] !== bb[ii]) {
9
+ return false;
10
+ }
11
+ }
12
+ return true;
15
13
  }
16
-
17
14
  function coerce(o) {
18
15
  if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')
19
16
  return o;
@@ -24,10 +21,10 @@ function coerce(o) {
24
21
  }
25
22
  throw new Error('Unknown type, must be binary type');
26
23
  }
27
- function fromString$1(str) {
24
+ function fromString(str) {
28
25
  return new TextEncoder().encode(str);
29
26
  }
30
- function toString$1(b) {
27
+ function toString(b) {
31
28
  return new TextDecoder().decode(b);
32
29
  }
33
30
 
@@ -636,8 +633,8 @@ var base8$1 = /*#__PURE__*/Object.freeze({
636
633
  const identity = from({
637
634
  prefix: '\x00',
638
635
  name: 'identity',
639
- encode: (buf) => toString$1(buf),
640
- decode: (str) => fromString$1(str)
636
+ encode: (buf) => toString(buf),
637
+ decode: (str) => fromString(str)
641
638
  });
642
639
 
643
640
  var identityBase = /*#__PURE__*/Object.freeze({
@@ -648,69 +645,6 @@ var identityBase = /*#__PURE__*/Object.freeze({
648
645
  new TextEncoder();
649
646
  new TextDecoder();
650
647
 
651
- const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 };
652
-
653
- function createCodec(name, prefix, encode, decode) {
654
- return {
655
- name,
656
- prefix,
657
- encoder: {
658
- name,
659
- prefix,
660
- encode
661
- },
662
- decoder: {
663
- decode
664
- }
665
- };
666
- }
667
- const string = createCodec('utf8', 'u', (buf) => {
668
- const decoder = new TextDecoder('utf8');
669
- return 'u' + decoder.decode(buf);
670
- }, (str) => {
671
- const encoder = new TextEncoder();
672
- return encoder.encode(str.substring(1));
673
- });
674
- const ascii = createCodec('ascii', 'a', (buf) => {
675
- let string = 'a';
676
- for (let i = 0; i < buf.length; i++) {
677
- string += String.fromCharCode(buf[i]);
678
- }
679
- return string;
680
- }, (str) => {
681
- str = str.substring(1);
682
- const buf = allocUnsafe(str.length);
683
- for (let i = 0; i < str.length; i++) {
684
- buf[i] = str.charCodeAt(i);
685
- }
686
- return buf;
687
- });
688
- const BASES = {
689
- utf8: string,
690
- 'utf-8': string,
691
- hex: bases.base16,
692
- latin1: ascii,
693
- ascii,
694
- binary: ascii,
695
- ...bases
696
- };
697
-
698
- /**
699
- * Create a `Uint8Array` from the passed string
700
- *
701
- * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
702
- *
703
- * Also `ascii` which is similar to node's 'binary' encoding.
704
- */
705
- function fromString(string, encoding = 'utf8') {
706
- const base = BASES[encoding];
707
- if (base == null) {
708
- throw new Error(`Unsupported encoding "${encoding}"`);
709
- }
710
- // add multibase prefix
711
- return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
712
- }
713
-
714
648
  var Protocols;
715
649
  (function (Protocols) {
716
650
  Protocols["Relay"] = "relay";
@@ -720,43 +654,24 @@ var Protocols;
720
654
  })(Protocols || (Protocols = {}));
721
655
  var ProtocolError;
722
656
  (function (ProtocolError) {
723
- /** Could not determine the origin of the fault. Best to check connectivity and try again */
657
+ //
658
+ // GENERAL ERRORS SECTION
659
+ //
660
+ /**
661
+ * Could not determine the origin of the fault. Best to check connectivity and try again
662
+ * */
724
663
  ProtocolError["GENERIC_FAIL"] = "Generic error";
725
664
  /**
726
- * Failure to protobuf encode the message. This is not recoverable and needs
727
- * further investigation.
665
+ * The remote peer rejected the message. Information provided by the remote peer
666
+ * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`
667
+ * or `DECODE_FAILED` can be used.
728
668
  */
729
- ProtocolError["ENCODE_FAILED"] = "Failed to encode";
669
+ ProtocolError["REMOTE_PEER_REJECTED"] = "Remote peer rejected";
730
670
  /**
731
671
  * Failure to protobuf decode the message. May be due to a remote peer issue,
732
672
  * ensuring that messages are sent via several peer enable mitigation of this error.
733
673
  */
734
674
  ProtocolError["DECODE_FAILED"] = "Failed to decode";
735
- /**
736
- * The message payload is empty, making the message invalid. Ensure that a non-empty
737
- * payload is set on the outgoing message.
738
- */
739
- ProtocolError["EMPTY_PAYLOAD"] = "Payload is empty";
740
- /**
741
- * The message size is above the maximum message size allowed on the Waku Network.
742
- * Compressing the message or using an alternative strategy for large messages is recommended.
743
- */
744
- ProtocolError["SIZE_TOO_BIG"] = "Size is too big";
745
- /**
746
- * The PubsubTopic passed to the send function is not configured on the Waku node.
747
- * Please ensure that the PubsubTopic is used when initializing the Waku node.
748
- */
749
- ProtocolError["TOPIC_NOT_CONFIGURED"] = "Topic not configured";
750
- /**
751
- * The pubsub topic configured on the decoder does not match the pubsub topic setup on the protocol.
752
- * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.
753
- */
754
- ProtocolError["TOPIC_DECODER_MISMATCH"] = "Topic decoder mismatch";
755
- /**
756
- * The topics passed in the decoders do not match each other, or don't exist at all.
757
- * Ensure that all the pubsub topics used in the decoders are valid and match each other.
758
- */
759
- ProtocolError["INVALID_DECODER_TOPICS"] = "Invalid decoder topics";
760
675
  /**
761
676
  * Failure to find a peer with suitable protocols. This may due to a connection issue.
762
677
  * Mitigation can be: retrying after a given time period, display connectivity issue
@@ -774,37 +689,51 @@ var ProtocolError;
774
689
  * or `DECODE_FAILED` can be used.
775
690
  */
776
691
  ProtocolError["NO_RESPONSE"] = "No response received";
692
+ //
693
+ // SEND ERRORS SECTION
694
+ //
777
695
  /**
778
- * The remote peer rejected the message. Information provided by the remote peer
779
- * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`
780
- * or `DECODE_FAILED` can be used.
696
+ * Failure to protobuf encode the message. This is not recoverable and needs
697
+ * further investigation.
781
698
  */
782
- ProtocolError["REMOTE_PEER_REJECTED"] = "Remote peer rejected";
699
+ ProtocolError["ENCODE_FAILED"] = "Failed to encode";
783
700
  /**
784
- * The protocol request timed out without a response. This may be due to a connection issue.
785
- * Mitigation can be: retrying after a given time period
701
+ * The message payload is empty, making the message invalid. Ensure that a non-empty
702
+ * payload is set on the outgoing message.
786
703
  */
787
- ProtocolError["REQUEST_TIMEOUT"] = "Request timeout";
704
+ ProtocolError["EMPTY_PAYLOAD"] = "Payload is empty";
788
705
  /**
789
- * Missing credentials info message.
790
- * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L186
706
+ * The message size is above the maximum message size allowed on the Waku Network.
707
+ * Compressing the message or using an alternative strategy for large messages is recommended.
791
708
  */
792
- ProtocolError["RLN_IDENTITY_MISSING"] = "Identity credentials are not set";
709
+ ProtocolError["SIZE_TOO_BIG"] = "Size is too big";
793
710
  /**
794
- * Membership index missing info message.
795
- * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L188
711
+ * The PubsubTopic passed to the send function is not configured on the Waku node.
712
+ * Please ensure that the PubsubTopic is used when initializing the Waku node.
796
713
  */
797
- ProtocolError["RLN_MEMBERSHIP_INDEX"] = "Membership index is not set";
714
+ ProtocolError["TOPIC_NOT_CONFIGURED"] = "Topic not configured";
798
715
  /**
799
- * Message limit is missing.
800
- * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L190
716
+ * Fails when
801
717
  */
802
- ProtocolError["RLN_LIMIT_MISSING"] = "User message limit is not set";
718
+ ProtocolError["STREAM_ABORTED"] = "Stream aborted";
803
719
  /**
804
720
  * General proof generation error message.
805
721
  * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L201C19-L201C42
806
722
  */
807
723
  ProtocolError["RLN_PROOF_GENERATION"] = "Proof generation failed";
724
+ //
725
+ // RECEIVE ERRORS SECTION
726
+ //
727
+ /**
728
+ * The pubsub topic configured on the decoder does not match the pubsub topic setup on the protocol.
729
+ * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.
730
+ */
731
+ ProtocolError["TOPIC_DECODER_MISMATCH"] = "Topic decoder mismatch";
732
+ /**
733
+ * The topics passed in the decoders do not match each other, or don't exist at all.
734
+ * Ensure that all the pubsub topics used in the decoders are valid and match each other.
735
+ */
736
+ ProtocolError["INVALID_DECODER_TOPICS"] = "Invalid decoder topics";
808
737
  })(ProtocolError || (ProtocolError = {}));
809
738
 
810
739
  var Tags;
@@ -825,6 +754,10 @@ var EConnectionStateEvents;
825
754
  EConnectionStateEvents["CONNECTION_STATUS"] = "waku:connection";
826
755
  })(EConnectionStateEvents || (EConnectionStateEvents = {}));
827
756
 
757
+ var HealthStatusChangeEvents;
758
+ (function (HealthStatusChangeEvents) {
759
+ HealthStatusChangeEvents["StatusChange"] = "health:change";
760
+ })(HealthStatusChangeEvents || (HealthStatusChangeEvents = {}));
828
761
  var HealthStatus;
829
762
  (function (HealthStatus) {
830
763
  HealthStatus["Unhealthy"] = "Unhealthy";
@@ -832,44 +765,6 @@ var HealthStatus;
832
765
  HealthStatus["SufficientlyHealthy"] = "SufficientlyHealthy";
833
766
  })(HealthStatus || (HealthStatus = {}));
834
767
 
835
- /**
836
- * Turns a `Uint8Array` into a string.
837
- *
838
- * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.
839
- *
840
- * Also `ascii` which is similar to node's 'binary' encoding.
841
- */
842
- function toString(array, encoding = 'utf8') {
843
- const base = BASES[encoding];
844
- if (base == null) {
845
- throw new Error(`Unsupported encoding "${encoding}"`);
846
- }
847
- // strip multibase prefix
848
- return base.encoder.encode(array).substring(1);
849
- }
850
-
851
- /**
852
- * Decode byte array to utf-8 string.
853
- */
854
- const bytesToUtf8 = (b) => toString(b, "utf8");
855
- /**
856
- * Encode utf-8 string to byte array.
857
- */
858
- const utf8ToBytes = (s) => fromString(s, "utf8");
859
- /**
860
- * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`
861
- */
862
- function concat(byteArrays, totalLength) {
863
- const len = byteArrays.reduce((acc, curr) => acc + curr.length, 0);
864
- const res = new Uint8Array(len);
865
- let offset = 0;
866
- for (const bytes of byteArrays) {
867
- res.set(bytes, offset);
868
- offset += bytes.length;
869
- }
870
- return res;
871
- }
872
-
873
768
  function getDefaultExportFromCjs (x) {
874
769
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
875
770
  }
@@ -1214,24 +1109,62 @@ function setup(env) {
1214
1109
  createDebug.names = [];
1215
1110
  createDebug.skips = [];
1216
1111
 
1217
- let i;
1218
- const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
1219
- const len = split.length;
1112
+ const split = (typeof namespaces === 'string' ? namespaces : '')
1113
+ .trim()
1114
+ .replace(' ', ',')
1115
+ .split(',')
1116
+ .filter(Boolean);
1220
1117
 
1221
- for (i = 0; i < len; i++) {
1222
- if (!split[i]) {
1223
- // ignore empty strings
1224
- continue;
1118
+ for (const ns of split) {
1119
+ if (ns[0] === '-') {
1120
+ createDebug.skips.push(ns.slice(1));
1121
+ } else {
1122
+ createDebug.names.push(ns);
1225
1123
  }
1124
+ }
1125
+ }
1226
1126
 
1227
- namespaces = split[i].replace(/\*/g, '.*?');
1228
-
1229
- if (namespaces[0] === '-') {
1230
- createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
1127
+ /**
1128
+ * Checks if the given string matches a namespace template, honoring
1129
+ * asterisks as wildcards.
1130
+ *
1131
+ * @param {String} search
1132
+ * @param {String} template
1133
+ * @return {Boolean}
1134
+ */
1135
+ function matchesTemplate(search, template) {
1136
+ let searchIndex = 0;
1137
+ let templateIndex = 0;
1138
+ let starIndex = -1;
1139
+ let matchIndex = 0;
1140
+
1141
+ while (searchIndex < search.length) {
1142
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
1143
+ // Match character or proceed with wildcard
1144
+ if (template[templateIndex] === '*') {
1145
+ starIndex = templateIndex;
1146
+ matchIndex = searchIndex;
1147
+ templateIndex++; // Skip the '*'
1148
+ } else {
1149
+ searchIndex++;
1150
+ templateIndex++;
1151
+ }
1152
+ } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
1153
+ // Backtrack to the last '*' and try to match more characters
1154
+ templateIndex = starIndex + 1;
1155
+ matchIndex++;
1156
+ searchIndex = matchIndex;
1231
1157
  } else {
1232
- createDebug.names.push(new RegExp('^' + namespaces + '$'));
1158
+ return false; // No match
1233
1159
  }
1234
1160
  }
1161
+
1162
+ // Handle trailing '*' in template
1163
+ while (templateIndex < template.length && template[templateIndex] === '*') {
1164
+ templateIndex++;
1165
+ }
1166
+
1167
+ return templateIndex === template.length;
1235
1168
  }
1236
1169
 
1237
1170
  /**
@@ -1242,8 +1175,8 @@ function setup(env) {
1242
1175
  */
1243
1176
  function disable() {
1244
1177
  const namespaces = [
1245
- ...createDebug.names.map(toNamespace),
1246
- ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
1178
+ ...createDebug.names,
1179
+ ...createDebug.skips.map(namespace => '-' + namespace)
1247
1180
  ].join(',');
1248
1181
  createDebug.enable('');
1249
1182
  return namespaces;
@@ -1257,21 +1190,14 @@ function setup(env) {
1257
1190
  * @api public
1258
1191
  */
1259
1192
  function enabled(name) {
1260
- if (name[name.length - 1] === '*') {
1261
- return true;
1262
- }
1263
-
1264
- let i;
1265
- let len;
1266
-
1267
- for (i = 0, len = createDebug.skips.length; i < len; i++) {
1268
- if (createDebug.skips[i].test(name)) {
1193
+ for (const skip of createDebug.skips) {
1194
+ if (matchesTemplate(name, skip)) {
1269
1195
  return false;
1270
1196
  }
1271
1197
  }
1272
1198
 
1273
- for (i = 0, len = createDebug.names.length; i < len; i++) {
1274
- if (createDebug.names[i].test(name)) {
1199
+ for (const ns of createDebug.names) {
1200
+ if (matchesTemplate(name, ns)) {
1275
1201
  return true;
1276
1202
  }
1277
1203
  }
@@ -1279,19 +1205,6 @@ function setup(env) {
1279
1205
  return false;
1280
1206
  }
1281
1207
 
1282
- /**
1283
- * Convert regexp to namespace
1284
- *
1285
- * @param {RegExp} regxep
1286
- * @return {String} namespace
1287
- * @api private
1288
- */
1289
- function toNamespace(regexp) {
1290
- return regexp.toString()
1291
- .substring(2, regexp.toString().length - 2)
1292
- .replace(/\.\*\?$/, '*');
1293
- }
1294
-
1295
1208
  /**
1296
1209
  * Coerce `val`.
1297
1210
  *
@@ -1453,6 +1366,7 @@ var common = setup;
1453
1366
 
1454
1367
  // Is webkit? http://stackoverflow.com/a/16459606/376773
1455
1368
  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
1369
+ // eslint-disable-next-line no-return-assign
1456
1370
  return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
1457
1371
  // Is firebug? http://stackoverflow.com/a/398120/376773
1458
1372
  (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
@@ -1626,4 +1540,4 @@ class Logger {
1626
1540
  }
1627
1541
  }
1628
1542
 
1629
- export { EPeersByDiscoveryEvents as E, HealthStatus as H, Logger as L, ProtocolError as P, Tags as T, allocUnsafe as a, alloc as b, EConnectionStateEvents as c, Protocols as d, concat as e, fromString as f, bytesToUtf8 as g, utf8ToBytes as u };
1543
+ export { EPeersByDiscoveryEvents as E, Logger as L, ProtocolError as P, Tags as T, base32 as a, base36 as b, coerce as c, base58btc as d, equals as e, EConnectionStateEvents as f, base2$1 as g, base8$1 as h, identityBase as i, base10$1 as j, base16$1 as k, base32$1 as l, base36$1 as m, base58 as n, base64$1 as o, base256emoji$1 as p };