@waku/core 0.0.33-acef1ac.0 → 0.0.33-b7bdb60.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 (36) hide show
  1. package/bundle/base_protocol-BDjsZTsQ.js +275 -0
  2. package/bundle/{index-tdQNdKHx.js → index-CeEH6b9b.js} +24 -450
  3. package/bundle/index.js +100 -420
  4. package/bundle/lib/base_protocol.js +2 -2
  5. package/bundle/lib/message/version_0.js +2 -2
  6. package/bundle/{version_0-BrbNEwD-.js → version_0-BYg0O3M-.js} +451 -2
  7. package/dist/.tsbuildinfo +1 -1
  8. package/dist/index.d.ts +1 -2
  9. package/dist/index.js +1 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/lib/base_protocol.d.ts +4 -6
  12. package/dist/lib/base_protocol.js +9 -14
  13. package/dist/lib/base_protocol.js.map +1 -1
  14. package/dist/lib/filter/index.d.ts +1 -2
  15. package/dist/lib/filter/index.js +1 -4
  16. package/dist/lib/filter/index.js.map +1 -1
  17. package/dist/lib/metadata/index.js +1 -1
  18. package/dist/lib/metadata/index.js.map +1 -1
  19. package/dist/lib/stream_manager/stream_manager.d.ts +12 -9
  20. package/dist/lib/stream_manager/stream_manager.js +87 -56
  21. package/dist/lib/stream_manager/stream_manager.js.map +1 -1
  22. package/dist/lib/stream_manager/utils.d.ts +1 -1
  23. package/dist/lib/stream_manager/utils.js +5 -17
  24. package/dist/lib/stream_manager/utils.js.map +1 -1
  25. package/package.json +1 -1
  26. package/src/index.ts +1 -3
  27. package/src/lib/base_protocol.ts +12 -29
  28. package/src/lib/filter/index.ts +0 -2
  29. package/src/lib/metadata/index.ts +1 -1
  30. package/src/lib/stream_manager/stream_manager.ts +124 -66
  31. package/src/lib/stream_manager/utils.ts +5 -17
  32. package/bundle/base_protocol-BS9mxaB7.js +0 -336
  33. package/dist/lib/wait_for_remote_peer.d.ts +0 -22
  34. package/dist/lib/wait_for_remote_peer.js +0 -142
  35. package/dist/lib/wait_for_remote_peer.js.map +0 -1
  36. package/src/lib/wait_for_remote_peer.ts +0 -200
package/bundle/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { v as version_0, e as encodingLength, a as encode$1, d as decode$1, M as MessagePush, F as FilterSubscribeRequest, b as FilterSubscribeResponse$1, P as PushRpc$1, c as PushResponse, S as StoreQueryRequest$1, f as StoreQueryResponse$1, g as createEncoder, W as WakuMetadataRequest, h as WakuMetadataResponse } from './version_0-BrbNEwD-.js';
2
- export { i as createDecoder } from './version_0-BrbNEwD-.js';
3
- import { a as allocUnsafe, b as alloc, L as Logger, P as ProtocolError, c as Protocols, u as utf8ToBytes, p as pubsubTopicToSingleShardInfo, T as Tags, E as EPeersByDiscoveryEvents, s as shardInfoToPubsubTopics, d as EConnectionStateEvents, H as HealthStatus, e as pubsubTopicsToShardInfo } from './index-tdQNdKHx.js';
4
- import { B as BaseProtocol, d as decodeRelayShard, e as encodeRelayShard } from './base_protocol-BS9mxaB7.js';
5
- export { S as StreamManager } from './base_protocol-BS9mxaB7.js';
1
+ import { v as version_0, e as encodingLength, a as encode$1, d as decode$1, M as MessagePush, F as FilterSubscribeRequest, b as FilterSubscribeResponse$1, P as PushRpc$1, c as PushResponse, S as StoreQueryRequest$1, f as StoreQueryResponse$1, g as createEncoder, p as pubsubTopicToSingleShardInfo, s as shardInfoToPubsubTopics, W as WakuMetadataRequest, h as pubsubTopicsToShardInfo, i as WakuMetadataResponse } from './version_0-BYg0O3M-.js';
2
+ export { j as createDecoder } from './version_0-BYg0O3M-.js';
3
+ import { a as allocUnsafe, b as alloc, L as Logger, P as ProtocolError, u as utf8ToBytes, T as Tags, E as EPeersByDiscoveryEvents, c as EConnectionStateEvents, H as HealthStatus, d as Protocols } from './index-CeEH6b9b.js';
4
+ import { B as BaseProtocol } from './base_protocol-BDjsZTsQ.js';
5
+ export { S as StreamManager } from './base_protocol-BDjsZTsQ.js';
6
6
 
7
7
  const MB = 1024 ** 2;
8
8
  const SIZE_CAP_IN_MB = 1;
@@ -23,6 +23,60 @@ const isWireSizeUnderCap = (buf) => buf.length / MB <= SIZE_CAP_IN_MB;
23
23
 
24
24
  const DNS_DISCOVERY_TAG = "@waku/bootstrap";
25
25
 
26
+ const decodeRelayShard = (bytes) => {
27
+ // explicitly converting to Uint8Array to avoid Buffer
28
+ // https://github.com/libp2p/js-libp2p/issues/2146
29
+ bytes = new Uint8Array(bytes);
30
+ if (bytes.length < 3)
31
+ throw new Error("Insufficient data");
32
+ const view = new DataView(bytes.buffer);
33
+ const clusterId = view.getUint16(0);
34
+ const shards = [];
35
+ if (bytes.length === 130) {
36
+ // rsv format (Bit Vector)
37
+ for (let i = 0; i < 1024; i++) {
38
+ const byteIndex = Math.floor(i / 8) + 2; // Adjusted for the 2-byte cluster field
39
+ const bitIndex = 7 - (i % 8);
40
+ if (view.getUint8(byteIndex) & (1 << bitIndex)) {
41
+ shards.push(i);
42
+ }
43
+ }
44
+ }
45
+ else {
46
+ // rs format (Index List)
47
+ const numIndices = view.getUint8(2);
48
+ for (let i = 0, offset = 3; i < numIndices; i++, offset += 2) {
49
+ if (offset + 1 >= bytes.length)
50
+ throw new Error("Unexpected end of data");
51
+ shards.push(view.getUint16(offset));
52
+ }
53
+ }
54
+ return { clusterId, shards };
55
+ };
56
+ const encodeRelayShard = (shardInfo) => {
57
+ const { clusterId, shards } = shardInfo;
58
+ const totalLength = shards.length >= 64 ? 130 : 3 + 2 * shards.length;
59
+ const buffer = new ArrayBuffer(totalLength);
60
+ const view = new DataView(buffer);
61
+ view.setUint16(0, clusterId);
62
+ if (shards.length >= 64) {
63
+ // rsv format (Bit Vector)
64
+ for (const index of shards) {
65
+ const byteIndex = Math.floor(index / 8) + 2; // Adjusted for the 2-byte cluster field
66
+ const bitIndex = 7 - (index % 8);
67
+ view.setUint8(byteIndex, view.getUint8(byteIndex) | (1 << bitIndex));
68
+ }
69
+ }
70
+ else {
71
+ // rs format (Index List)
72
+ view.setUint8(2, shards.length);
73
+ for (let i = 0, offset = 3; i < shards.length; i++, offset += 2) {
74
+ view.setUint16(offset, shards[i]);
75
+ }
76
+ }
77
+ return new Uint8Array(buffer);
78
+ };
79
+
26
80
  var index$3 = /*#__PURE__*/Object.freeze({
27
81
  __proto__: null,
28
82
  version_0: version_0
@@ -1040,7 +1094,7 @@ class FIFO {
1040
1094
  * // [ [1, 2, 3] ]
1041
1095
  * ```
1042
1096
  */
1043
- let AbortError$1 = class AbortError extends Error {
1097
+ class AbortError extends Error {
1044
1098
  type;
1045
1099
  code;
1046
1100
  constructor(message, code) {
@@ -1048,7 +1102,7 @@ let AbortError$1 = class AbortError extends Error {
1048
1102
  this.type = 'aborted';
1049
1103
  this.code = code ?? 'ABORT_ERR';
1050
1104
  }
1051
- };
1105
+ }
1052
1106
  function pushable(options = {}) {
1053
1107
  const getNext = (buffer) => {
1054
1108
  const next = buffer.shift();
@@ -1168,7 +1222,7 @@ function _pushable(getNext, options) {
1168
1222
  if (signal != null) {
1169
1223
  cancel = new Promise((resolve, reject) => {
1170
1224
  listener = () => {
1171
- reject(new AbortError$1());
1225
+ reject(new AbortError());
1172
1226
  };
1173
1227
  signal.addEventListener('abort', listener);
1174
1228
  });
@@ -1557,26 +1611,24 @@ class FilterSubscribeResponse {
1557
1611
  }
1558
1612
  }
1559
1613
 
1560
- const log$6 = new Logger("filter:v2");
1614
+ const log$5 = new Logger("filter:v2");
1561
1615
  const FilterCodecs = {
1562
1616
  SUBSCRIBE: "/vac/waku/filter-subscribe/2.0.0-beta1",
1563
1617
  PUSH: "/vac/waku/filter-push/2.0.0-beta1"
1564
1618
  };
1565
1619
  class FilterCore extends BaseProtocol {
1566
1620
  handleIncomingMessage;
1567
- handleError;
1568
1621
  pubsubTopics;
1569
- constructor(handleIncomingMessage, handleError, pubsubTopics, libp2p) {
1570
- super(FilterCodecs.SUBSCRIBE, libp2p.components, log$6, pubsubTopics);
1622
+ constructor(handleIncomingMessage, pubsubTopics, libp2p) {
1623
+ super(FilterCodecs.SUBSCRIBE, libp2p.components, log$5, pubsubTopics);
1571
1624
  this.handleIncomingMessage = handleIncomingMessage;
1572
- this.handleError = handleError;
1573
1625
  this.pubsubTopics = pubsubTopics;
1574
1626
  libp2p
1575
1627
  .handle(FilterCodecs.PUSH, this.onRequest.bind(this), {
1576
1628
  maxInboundStreams: 100
1577
1629
  })
1578
1630
  .catch((e) => {
1579
- log$6.error("Failed to register ", FilterCodecs.PUSH, e);
1631
+ log$5.error("Failed to register ", FilterCodecs.PUSH, e);
1580
1632
  });
1581
1633
  }
1582
1634
  async subscribe(pubsubTopic, peer, contentTopics) {
@@ -1587,7 +1639,7 @@ class FilterCore extends BaseProtocol {
1587
1639
  res = await pipe([request.encode()], encode, stream, decode, async (source) => await all(source));
1588
1640
  }
1589
1641
  catch (error) {
1590
- log$6.error("Failed to send subscribe request", error);
1642
+ log$5.error("Failed to send subscribe request", error);
1591
1643
  return {
1592
1644
  success: null,
1593
1645
  failure: {
@@ -1598,7 +1650,7 @@ class FilterCore extends BaseProtocol {
1598
1650
  }
1599
1651
  const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());
1600
1652
  if (statusCode < 200 || statusCode >= 300) {
1601
- log$6.error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1653
+ log$5.error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1602
1654
  return {
1603
1655
  failure: {
1604
1656
  error: ProtocolError.REMOTE_PEER_REJECTED,
@@ -1618,7 +1670,7 @@ class FilterCore extends BaseProtocol {
1618
1670
  stream = await this.getStream(peer);
1619
1671
  }
1620
1672
  catch (error) {
1621
- log$6.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
1673
+ log$5.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
1622
1674
  return {
1623
1675
  success: null,
1624
1676
  failure: {
@@ -1632,7 +1684,7 @@ class FilterCore extends BaseProtocol {
1632
1684
  await pipe([unsubscribeRequest.encode()], encode, stream.sink);
1633
1685
  }
1634
1686
  catch (error) {
1635
- log$6.error("Failed to send unsubscribe request", error);
1687
+ log$5.error("Failed to send unsubscribe request", error);
1636
1688
  return {
1637
1689
  success: null,
1638
1690
  failure: {
@@ -1661,7 +1713,7 @@ class FilterCore extends BaseProtocol {
1661
1713
  }
1662
1714
  const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());
1663
1715
  if (statusCode < 200 || statusCode >= 300) {
1664
- log$6.error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1716
+ log$5.error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1665
1717
  return {
1666
1718
  failure: {
1667
1719
  error: ProtocolError.REMOTE_PEER_REJECTED,
@@ -1681,7 +1733,7 @@ class FilterCore extends BaseProtocol {
1681
1733
  stream = await this.getStream(peer);
1682
1734
  }
1683
1735
  catch (error) {
1684
- log$6.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
1736
+ log$5.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
1685
1737
  return {
1686
1738
  success: null,
1687
1739
  failure: {
@@ -1696,7 +1748,7 @@ class FilterCore extends BaseProtocol {
1696
1748
  res = await pipe([request.encode()], encode, stream, decode, async (source) => await all(source));
1697
1749
  }
1698
1750
  catch (error) {
1699
- log$6.error("Failed to send ping request", error);
1751
+ log$5.error("Failed to send ping request", error);
1700
1752
  return {
1701
1753
  success: null,
1702
1754
  failure: {
@@ -1716,7 +1768,7 @@ class FilterCore extends BaseProtocol {
1716
1768
  }
1717
1769
  const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());
1718
1770
  if (statusCode < 200 || statusCode >= 300) {
1719
- log$6.error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1771
+ log$5.error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);
1720
1772
  return {
1721
1773
  success: null,
1722
1774
  failure: {
@@ -1733,31 +1785,30 @@ class FilterCore extends BaseProtocol {
1733
1785
  onRequest(streamData) {
1734
1786
  const { connection, stream } = streamData;
1735
1787
  const { remotePeer } = connection;
1736
- log$6.info(`Received message from ${remotePeer.toString()}`);
1788
+ log$5.info(`Received message from ${remotePeer.toString()}`);
1737
1789
  try {
1738
1790
  pipe(stream, decode, async (source) => {
1739
1791
  for await (const bytes of source) {
1740
1792
  const response = FilterPushRpc.decode(bytes.slice());
1741
1793
  const { pubsubTopic, wakuMessage } = response;
1742
1794
  if (!wakuMessage) {
1743
- log$6.error("Received empty message");
1795
+ log$5.error("Received empty message");
1744
1796
  return;
1745
1797
  }
1746
1798
  if (!pubsubTopic) {
1747
- log$6.error("Pubsub topic missing from push message");
1799
+ log$5.error("Pubsub topic missing from push message");
1748
1800
  return;
1749
1801
  }
1750
1802
  await this.handleIncomingMessage(pubsubTopic, wakuMessage, connection.remotePeer.toString());
1751
1803
  }
1752
1804
  }).then(() => {
1753
- log$6.info("Receiving pipe closed.");
1805
+ log$5.info("Receiving pipe closed.");
1754
1806
  }, async (e) => {
1755
- log$6.error("Error with receiving pipe", e, " -- ", "on peer ", connection.remotePeer.toString(), " -- ", "stream ", stream);
1756
- await this.handleError(e);
1807
+ log$5.error("Error with receiving pipe", e, " -- ", "on peer ", connection.remotePeer.toString(), " -- ", "stream ", stream);
1757
1808
  });
1758
1809
  }
1759
1810
  catch (e) {
1760
- log$6.error("Error decoding message", e);
1811
+ log$5.error("Error decoding message", e);
1761
1812
  }
1762
1813
  }
1763
1814
  }
@@ -1823,7 +1874,7 @@ const matchRLNErrorMessage = (info) => {
1823
1874
  return ProtocolError.RLN_PROOF_GENERATION;
1824
1875
  };
1825
1876
 
1826
- const log$5 = new Logger("light-push");
1877
+ const log$4 = new Logger("light-push");
1827
1878
  const LightPushCodec = "/vac/waku/lightpush/2.0.0-beta1";
1828
1879
  /**
1829
1880
  * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).
@@ -1831,22 +1882,22 @@ const LightPushCodec = "/vac/waku/lightpush/2.0.0-beta1";
1831
1882
  class LightPushCore extends BaseProtocol {
1832
1883
  pubsubTopics;
1833
1884
  constructor(pubsubTopics, libp2p) {
1834
- super(LightPushCodec, libp2p.components, log$5, pubsubTopics);
1885
+ super(LightPushCodec, libp2p.components, log$4, pubsubTopics);
1835
1886
  this.pubsubTopics = pubsubTopics;
1836
1887
  }
1837
1888
  async preparePushMessage(encoder, message) {
1838
1889
  try {
1839
1890
  if (!message.payload || message.payload.length === 0) {
1840
- log$5.error("Failed to send waku light push: payload is empty");
1891
+ log$4.error("Failed to send waku light push: payload is empty");
1841
1892
  return { query: null, error: ProtocolError.EMPTY_PAYLOAD };
1842
1893
  }
1843
1894
  if (!(await isMessageSizeUnderCap(encoder, message))) {
1844
- log$5.error("Failed to send waku light push: message is bigger than 1MB");
1895
+ log$4.error("Failed to send waku light push: message is bigger than 1MB");
1845
1896
  return { query: null, error: ProtocolError.SIZE_TOO_BIG };
1846
1897
  }
1847
1898
  const protoMessage = await encoder.toProtoObj(message);
1848
1899
  if (!protoMessage) {
1849
- log$5.error("Failed to encode to protoMessage, aborting push");
1900
+ log$4.error("Failed to encode to protoMessage, aborting push");
1850
1901
  return {
1851
1902
  query: null,
1852
1903
  error: ProtocolError.ENCODE_FAILED
@@ -1856,7 +1907,7 @@ class LightPushCore extends BaseProtocol {
1856
1907
  return { query, error: null };
1857
1908
  }
1858
1909
  catch (error) {
1859
- log$5.error("Failed to prepare push message", error);
1910
+ log$4.error("Failed to prepare push message", error);
1860
1911
  return {
1861
1912
  query: null,
1862
1913
  error: ProtocolError.GENERIC_FAIL
@@ -1879,7 +1930,7 @@ class LightPushCore extends BaseProtocol {
1879
1930
  stream = await this.getStream(peer);
1880
1931
  }
1881
1932
  catch (error) {
1882
- log$5.error("Failed to get stream", error);
1933
+ log$4.error("Failed to get stream", error);
1883
1934
  return {
1884
1935
  success: null,
1885
1936
  failure: {
@@ -1893,7 +1944,7 @@ class LightPushCore extends BaseProtocol {
1893
1944
  res = await pipe([query.encode()], encode, stream, decode, async (source) => await all(source));
1894
1945
  }
1895
1946
  catch (err) {
1896
- log$5.error("Failed to send waku light push request", err);
1947
+ log$4.error("Failed to send waku light push request", err);
1897
1948
  return {
1898
1949
  success: null,
1899
1950
  failure: {
@@ -1911,7 +1962,7 @@ class LightPushCore extends BaseProtocol {
1911
1962
  response = PushRpc.decode(bytes).response;
1912
1963
  }
1913
1964
  catch (err) {
1914
- log$5.error("Failed to decode push reply", err);
1965
+ log$4.error("Failed to decode push reply", err);
1915
1966
  return {
1916
1967
  success: null,
1917
1968
  failure: {
@@ -1921,7 +1972,7 @@ class LightPushCore extends BaseProtocol {
1921
1972
  };
1922
1973
  }
1923
1974
  if (!response) {
1924
- log$5.error("Remote peer fault: No response in PushRPC");
1975
+ log$4.error("Remote peer fault: No response in PushRPC");
1925
1976
  return {
1926
1977
  success: null,
1927
1978
  failure: {
@@ -1932,7 +1983,7 @@ class LightPushCore extends BaseProtocol {
1932
1983
  }
1933
1984
  if (isRLNResponseError(response.info)) {
1934
1985
  const rlnErrorCase = matchRLNErrorMessage(response.info);
1935
- log$5.error("Remote peer rejected the message: ", rlnErrorCase);
1986
+ log$4.error("Remote peer rejected the message: ", rlnErrorCase);
1936
1987
  return {
1937
1988
  success: null,
1938
1989
  failure: {
@@ -1942,7 +1993,7 @@ class LightPushCore extends BaseProtocol {
1942
1993
  };
1943
1994
  }
1944
1995
  if (!response.isSuccess) {
1945
- log$5.error("Remote peer rejected the message: ", response.info);
1996
+ log$4.error("Remote peer rejected the message: ", response.info);
1946
1997
  return {
1947
1998
  success: null,
1948
1999
  failure: {
@@ -2047,12 +2098,12 @@ class StoreQueryResponse {
2047
2098
  }
2048
2099
  }
2049
2100
 
2050
- const log$4 = new Logger("store");
2101
+ const log$3 = new Logger("store");
2051
2102
  const StoreCodec = "/vac/waku/store-query/3.0.0";
2052
2103
  class StoreCore extends BaseProtocol {
2053
2104
  pubsubTopics;
2054
2105
  constructor(pubsubTopics, libp2p) {
2055
- super(StoreCodec, libp2p.components, log$4, pubsubTopics);
2106
+ super(StoreCodec, libp2p.components, log$3, pubsubTopics);
2056
2107
  this.pubsubTopics = pubsubTopics;
2057
2108
  }
2058
2109
  async *queryPerPage(queryOpts, decoders, peer) {
@@ -2071,7 +2122,7 @@ class StoreCore extends BaseProtocol {
2071
2122
  stream = await this.getStream(peer);
2072
2123
  }
2073
2124
  catch (e) {
2074
- log$4.error("Failed to get stream", e);
2125
+ log$3.error("Failed to get stream", e);
2075
2126
  break;
2076
2127
  }
2077
2128
  const res = await pipe([storeQueryRequest.encode()], encode, stream, decode, async (source) => await all(source));
@@ -2083,14 +2134,14 @@ class StoreCore extends BaseProtocol {
2083
2134
  if (!storeQueryResponse.statusCode ||
2084
2135
  storeQueryResponse.statusCode >= 300) {
2085
2136
  const errorMessage = `Store query failed with status code: ${storeQueryResponse.statusCode}, description: ${storeQueryResponse.statusDesc}`;
2086
- log$4.error(errorMessage);
2137
+ log$3.error(errorMessage);
2087
2138
  throw new Error(errorMessage);
2088
2139
  }
2089
2140
  if (!storeQueryResponse.messages || !storeQueryResponse.messages.length) {
2090
- log$4.warn("Stopping pagination due to empty messages in response");
2141
+ log$3.warn("Stopping pagination due to empty messages in response");
2091
2142
  break;
2092
2143
  }
2093
- log$4.info(`${storeQueryResponse.messages.length} messages retrieved from store`);
2144
+ log$3.info(`${storeQueryResponse.messages.length} messages retrieved from store`);
2094
2145
  const decodedMessages = storeQueryResponse.messages.map((protoMsg) => {
2095
2146
  if (!protoMsg.message) {
2096
2147
  return Promise.resolve(undefined);
@@ -2128,377 +2179,6 @@ var index = /*#__PURE__*/Object.freeze({
2128
2179
  StoreCore: StoreCore
2129
2180
  });
2130
2181
 
2131
- class TimeoutError extends Error {
2132
- constructor(message) {
2133
- super(message);
2134
- this.name = 'TimeoutError';
2135
- }
2136
- }
2137
-
2138
- /**
2139
- An error to be thrown when the request is aborted by AbortController.
2140
- DOMException is thrown instead of this Error when DOMException is available.
2141
- */
2142
- class AbortError extends Error {
2143
- constructor(message) {
2144
- super();
2145
- this.name = 'AbortError';
2146
- this.message = message;
2147
- }
2148
- }
2149
-
2150
- /**
2151
- TODO: Remove AbortError and just throw DOMException when targeting Node 18.
2152
- */
2153
- const getDOMException = errorMessage => globalThis.DOMException === undefined
2154
- ? new AbortError(errorMessage)
2155
- : new DOMException(errorMessage);
2156
-
2157
- /**
2158
- TODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.
2159
- */
2160
- const getAbortedReason = signal => {
2161
- const reason = signal.reason === undefined
2162
- ? getDOMException('This operation was aborted.')
2163
- : signal.reason;
2164
-
2165
- return reason instanceof Error ? reason : getDOMException(reason);
2166
- };
2167
-
2168
- function pTimeout(promise, options) {
2169
- const {
2170
- milliseconds,
2171
- fallback,
2172
- message,
2173
- customTimers = {setTimeout, clearTimeout},
2174
- } = options;
2175
-
2176
- let timer;
2177
-
2178
- const wrappedPromise = new Promise((resolve, reject) => {
2179
- if (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {
2180
- throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
2181
- }
2182
-
2183
- if (options.signal) {
2184
- const {signal} = options;
2185
- if (signal.aborted) {
2186
- reject(getAbortedReason(signal));
2187
- }
2188
-
2189
- signal.addEventListener('abort', () => {
2190
- reject(getAbortedReason(signal));
2191
- });
2192
- }
2193
-
2194
- if (milliseconds === Number.POSITIVE_INFINITY) {
2195
- promise.then(resolve, reject);
2196
- return;
2197
- }
2198
-
2199
- // We create the error outside of `setTimeout` to preserve the stack trace.
2200
- const timeoutError = new TimeoutError();
2201
-
2202
- timer = customTimers.setTimeout.call(undefined, () => {
2203
- if (fallback) {
2204
- try {
2205
- resolve(fallback());
2206
- } catch (error) {
2207
- reject(error);
2208
- }
2209
-
2210
- return;
2211
- }
2212
-
2213
- if (typeof promise.cancel === 'function') {
2214
- promise.cancel();
2215
- }
2216
-
2217
- if (message === false) {
2218
- resolve();
2219
- } else if (message instanceof Error) {
2220
- reject(message);
2221
- } else {
2222
- timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
2223
- reject(timeoutError);
2224
- }
2225
- }, milliseconds);
2226
-
2227
- (async () => {
2228
- try {
2229
- resolve(await promise);
2230
- } catch (error) {
2231
- reject(error);
2232
- }
2233
- })();
2234
- });
2235
-
2236
- const cancelablePromise = wrappedPromise.finally(() => {
2237
- cancelablePromise.clear();
2238
- });
2239
-
2240
- cancelablePromise.clear = () => {
2241
- customTimers.clearTimeout.call(undefined, timer);
2242
- timer = undefined;
2243
- };
2244
-
2245
- return cancelablePromise;
2246
- }
2247
-
2248
- const normalizeEmitter = emitter => {
2249
- const addListener = emitter.addEventListener || emitter.on || emitter.addListener;
2250
- const removeListener = emitter.removeEventListener || emitter.off || emitter.removeListener;
2251
-
2252
- if (!addListener || !removeListener) {
2253
- throw new TypeError('Emitter is not compatible');
2254
- }
2255
-
2256
- return {
2257
- addListener: addListener.bind(emitter),
2258
- removeListener: removeListener.bind(emitter),
2259
- };
2260
- };
2261
-
2262
- function pEventMultiple(emitter, event, options) {
2263
- let cancel;
2264
- const returnValue = new Promise((resolve, reject) => {
2265
- options = {
2266
- rejectionEvents: ['error'],
2267
- multiArgs: false,
2268
- resolveImmediately: false,
2269
- ...options,
2270
- };
2271
-
2272
- if (!(options.count >= 0 && (options.count === Number.POSITIVE_INFINITY || Number.isInteger(options.count)))) {
2273
- throw new TypeError('The `count` option should be at least 0 or more');
2274
- }
2275
-
2276
- options.signal?.throwIfAborted();
2277
-
2278
- // Allow multiple events
2279
- const events = [event].flat();
2280
-
2281
- const items = [];
2282
- const {addListener, removeListener} = normalizeEmitter(emitter);
2283
-
2284
- const onItem = (...arguments_) => {
2285
- const value = options.multiArgs ? arguments_ : arguments_[0];
2286
-
2287
- // eslint-disable-next-line unicorn/no-array-callback-reference
2288
- if (options.filter && !options.filter(value)) {
2289
- return;
2290
- }
2291
-
2292
- items.push(value);
2293
-
2294
- if (options.count === items.length) {
2295
- cancel();
2296
- resolve(items);
2297
- }
2298
- };
2299
-
2300
- const rejectHandler = error => {
2301
- cancel();
2302
- reject(error);
2303
- };
2304
-
2305
- cancel = () => {
2306
- for (const event of events) {
2307
- removeListener(event, onItem);
2308
- }
2309
-
2310
- for (const rejectionEvent of options.rejectionEvents) {
2311
- removeListener(rejectionEvent, rejectHandler);
2312
- }
2313
- };
2314
-
2315
- for (const event of events) {
2316
- addListener(event, onItem);
2317
- }
2318
-
2319
- for (const rejectionEvent of options.rejectionEvents) {
2320
- addListener(rejectionEvent, rejectHandler);
2321
- }
2322
-
2323
- if (options.signal) {
2324
- options.signal.addEventListener('abort', () => {
2325
- rejectHandler(options.signal.reason);
2326
- }, {once: true});
2327
- }
2328
-
2329
- if (options.resolveImmediately) {
2330
- resolve(items);
2331
- }
2332
- });
2333
-
2334
- returnValue.cancel = cancel;
2335
-
2336
- if (typeof options.timeout === 'number') {
2337
- const timeout = pTimeout(returnValue, {milliseconds: options.timeout});
2338
- timeout.cancel = cancel;
2339
- return timeout;
2340
- }
2341
-
2342
- return returnValue;
2343
- }
2344
-
2345
- function pEvent(emitter, event, options) {
2346
- if (typeof options === 'function') {
2347
- options = {filter: options};
2348
- }
2349
-
2350
- options = {
2351
- ...options,
2352
- count: 1,
2353
- resolveImmediately: false,
2354
- };
2355
-
2356
- const arrayPromise = pEventMultiple(emitter, event, options);
2357
- const promise = arrayPromise.then(array => array[0]);
2358
- promise.cancel = arrayPromise.cancel;
2359
-
2360
- return promise;
2361
- }
2362
-
2363
- const log$3 = new Logger("wait-for-remote-peer");
2364
- //TODO: move this function within the Waku class: https://github.com/waku-org/js-waku/issues/1761
2365
- /**
2366
- * Wait for a remote peer to be ready given the passed protocols.
2367
- * Must be used after attempting to connect to nodes, using
2368
- * {@link @waku/sdk!WakuNode.dial} or a bootstrap method with
2369
- * {@link @waku/sdk!createLightNode}.
2370
- *
2371
- * If the passed protocols is a GossipSub protocol, then it resolves only once
2372
- * a peer is in a mesh, to help ensure that other peers will send and receive
2373
- * message to us.
2374
- *
2375
- * @param waku The Waku Node
2376
- * @param protocols The protocols that need to be enabled by remote peers.
2377
- * @param timeoutMs A timeout value in milliseconds..
2378
- *
2379
- * @returns A promise that **resolves** if all desired protocols are fulfilled by
2380
- * remote nodes, **rejects** if the timeoutMs is reached.
2381
- * @throws If passing a protocol that is not mounted
2382
- * @default Wait for remote peers with protocols enabled locally and no time out is applied.
2383
- */
2384
- async function waitForRemotePeer(waku, protocols, timeoutMs) {
2385
- protocols = protocols ?? getEnabledProtocols(waku);
2386
- if (!waku.isStarted())
2387
- return Promise.reject("Waku node is not started");
2388
- const promises = [];
2389
- if (protocols.includes(Protocols.Relay)) {
2390
- if (!waku.relay)
2391
- throw new Error("Cannot wait for Relay peer: protocol not mounted");
2392
- promises.push(waitForGossipSubPeerInMesh(waku.relay));
2393
- }
2394
- if (protocols.includes(Protocols.Store)) {
2395
- if (!waku.store)
2396
- throw new Error("Cannot wait for Store peer: protocol not mounted");
2397
- promises.push(waitForConnectedPeer(waku.store.protocol, waku.libp2p.services.metadata));
2398
- }
2399
- if (protocols.includes(Protocols.LightPush)) {
2400
- if (!waku.lightPush)
2401
- throw new Error("Cannot wait for LightPush peer: protocol not mounted");
2402
- promises.push(waitForConnectedPeer(waku.lightPush.protocol, waku.libp2p.services.metadata));
2403
- }
2404
- if (protocols.includes(Protocols.Filter)) {
2405
- if (!waku.filter)
2406
- throw new Error("Cannot wait for Filter peer: protocol not mounted");
2407
- promises.push(waitForConnectedPeer(waku.filter.protocol, waku.libp2p.services.metadata));
2408
- }
2409
- if (timeoutMs) {
2410
- await rejectOnTimeout(Promise.all(promises), timeoutMs, "Timed out waiting for a remote peer.");
2411
- }
2412
- else {
2413
- await Promise.all(promises);
2414
- }
2415
- }
2416
- //TODO: move this function within protocol SDK class: https://github.com/waku-org/js-waku/issues/1761
2417
- /**
2418
- * Wait for a peer with the given protocol to be connected.
2419
- * If sharding is enabled on the node, it will also wait for the peer to be confirmed by the metadata service.
2420
- */
2421
- async function waitForConnectedPeer(protocol, metadataService) {
2422
- const codec = protocol.multicodec;
2423
- const peers = await protocol.connectedPeers();
2424
- if (peers.length) {
2425
- if (!metadataService) {
2426
- log$3.info(`${codec} peer found: `, peers[0].id.toString());
2427
- return;
2428
- }
2429
- // once a peer is connected, we need to confirm the metadata handshake with at least one of those peers if sharding is enabled
2430
- try {
2431
- await Promise.any(peers.map((peer) => metadataService.confirmOrAttemptHandshake(peer.id)));
2432
- return;
2433
- }
2434
- catch (e) {
2435
- if (e.code === "ERR_CONNECTION_BEING_CLOSED")
2436
- log$3.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`);
2437
- log$3.error(`Error waiting for handshake confirmation: ${e}`);
2438
- }
2439
- }
2440
- log$3.info(`Waiting for ${codec} peer`);
2441
- // else we'll just wait for the next peer to connect
2442
- await new Promise((resolve) => {
2443
- const cb = (evt) => {
2444
- if (evt.detail?.protocols?.includes(codec)) {
2445
- if (metadataService) {
2446
- metadataService
2447
- .confirmOrAttemptHandshake(evt.detail.peerId)
2448
- .then(() => {
2449
- protocol.removeLibp2pEventListener("peer:identify", cb);
2450
- resolve();
2451
- })
2452
- .catch((e) => {
2453
- if (e.code === "ERR_CONNECTION_BEING_CLOSED")
2454
- log$3.error(`Connection with the peer was closed and possibly because it's on a different shard. Error: ${e}`);
2455
- log$3.error(`Error waiting for handshake confirmation: ${e}`);
2456
- });
2457
- }
2458
- else {
2459
- protocol.removeLibp2pEventListener("peer:identify", cb);
2460
- resolve();
2461
- }
2462
- }
2463
- };
2464
- protocol.addLibp2pEventListener("peer:identify", cb);
2465
- });
2466
- }
2467
- /**
2468
- * Wait for at least one peer with the given protocol to be connected and in the gossipsub
2469
- * mesh for all pubsubTopics.
2470
- */
2471
- async function waitForGossipSubPeerInMesh(waku) {
2472
- let peers = waku.getMeshPeers();
2473
- const pubsubTopics = waku.pubsubTopics;
2474
- for (const topic of pubsubTopics) {
2475
- while (peers.length == 0) {
2476
- await pEvent(waku.gossipSub, "gossipsub:heartbeat");
2477
- peers = waku.getMeshPeers(topic);
2478
- }
2479
- }
2480
- }
2481
- const awaitTimeout = (ms, rejectReason) => new Promise((_resolve, reject) => setTimeout(() => reject(rejectReason), ms));
2482
- async function rejectOnTimeout(promise, timeoutMs, rejectReason) {
2483
- await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);
2484
- }
2485
- function getEnabledProtocols(waku) {
2486
- const protocols = [];
2487
- if (waku.relay) {
2488
- protocols.push(Protocols.Relay);
2489
- }
2490
- if (waku.filter) {
2491
- protocols.push(Protocols.Filter);
2492
- }
2493
- if (waku.store) {
2494
- protocols.push(Protocols.Store);
2495
- }
2496
- if (waku.lightPush) {
2497
- protocols.push(Protocols.LightPush);
2498
- }
2499
- return protocols;
2500
- }
2501
-
2502
2182
  /** Noop for browser compatibility */
2503
2183
  function setMaxListeners$1() { }
2504
2184
 
@@ -3208,7 +2888,7 @@ class Metadata extends BaseProtocol {
3208
2888
  */
3209
2889
  async query(peerId) {
3210
2890
  const request = WakuMetadataRequest.encode(pubsubTopicsToShardInfo(this.pubsubTopics));
3211
- const peer = await this.peerStore.get(peerId);
2891
+ const peer = await this.libp2pComponents.peerStore.get(peerId);
3212
2892
  if (!peer) {
3213
2893
  return {
3214
2894
  shardInfo: null,
@@ -3300,4 +2980,4 @@ function wakuMetadata(pubsubTopics) {
3300
2980
  return (components) => new Metadata(pubsubTopics, components);
3301
2981
  }
3302
2982
 
3303
- export { ConnectionManager, FilterCodecs, FilterCore, KeepAliveManager, LightPushCodec, LightPushCore, MetadataCodec, StoreCore, createEncoder, getHealthManager, index$3 as message, waitForRemotePeer, wakuMetadata, index$2 as waku_filter, index$1 as waku_light_push, index as waku_store };
2983
+ export { ConnectionManager, FilterCodecs, FilterCore, KeepAliveManager, LightPushCodec, LightPushCore, MetadataCodec, StoreCodec, StoreCore, createEncoder, getHealthManager, index$3 as message, wakuMetadata, index$2 as waku_filter, index$1 as waku_light_push, index as waku_store };