@waku/core 0.0.34-c43cec2.0 → 0.0.34-c86e056.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 (60) hide show
  1. package/bundle/{base_protocol-DxFKDXX2.js → base_protocol-CCK9RCtH.js} +19 -20
  2. package/bundle/{index-yLOEQnIE.js → index-Db7LxDrL.js} +75 -39
  3. package/bundle/index.js +1815 -133
  4. package/bundle/lib/base_protocol.js +2 -2
  5. package/bundle/lib/message/version_0.js +2 -2
  6. package/bundle/{version_0-Che4t3mN.js → version_0-ANFNAdFD.js} +163 -42
  7. package/dist/.tsbuildinfo +1 -1
  8. package/dist/index.d.ts +0 -1
  9. package/dist/index.js +0 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/lib/base_protocol.d.ts +2 -2
  12. package/dist/lib/base_protocol.js +2 -2
  13. package/dist/lib/base_protocol.js.map +1 -1
  14. package/dist/lib/connection_manager/connection_manager.d.ts +56 -3
  15. package/dist/lib/connection_manager/connection_manager.js +96 -13
  16. package/dist/lib/connection_manager/connection_manager.js.map +1 -1
  17. package/dist/lib/filter/filter.d.ts +18 -0
  18. package/dist/lib/filter/filter.js +209 -0
  19. package/dist/lib/filter/filter.js.map +1 -0
  20. package/dist/lib/filter/index.d.ts +1 -18
  21. package/dist/lib/filter/index.js +1 -208
  22. package/dist/lib/filter/index.js.map +1 -1
  23. package/dist/lib/light_push/index.d.ts +1 -15
  24. package/dist/lib/light_push/index.js +1 -144
  25. package/dist/lib/light_push/index.js.map +1 -1
  26. package/dist/lib/light_push/light_push.d.ts +15 -0
  27. package/dist/lib/light_push/light_push.js +144 -0
  28. package/dist/lib/light_push/light_push.js.map +1 -0
  29. package/dist/lib/metadata/index.d.ts +1 -3
  30. package/dist/lib/metadata/index.js +1 -118
  31. package/dist/lib/metadata/index.js.map +1 -1
  32. package/dist/lib/metadata/metadata.d.ts +3 -0
  33. package/dist/lib/metadata/metadata.js +119 -0
  34. package/dist/lib/metadata/metadata.js.map +1 -0
  35. package/dist/lib/store/index.d.ts +1 -9
  36. package/dist/lib/store/index.js +1 -82
  37. package/dist/lib/store/index.js.map +1 -1
  38. package/dist/lib/store/store.d.ts +9 -0
  39. package/dist/lib/store/store.js +83 -0
  40. package/dist/lib/store/store.js.map +1 -0
  41. package/dist/lib/stream_manager/stream_manager.d.ts +2 -2
  42. package/dist/lib/stream_manager/stream_manager.js +16 -17
  43. package/dist/lib/stream_manager/stream_manager.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/index.ts +0 -2
  46. package/src/lib/base_protocol.ts +3 -3
  47. package/src/lib/connection_manager/connection_manager.ts +114 -20
  48. package/src/lib/filter/filter.ts +315 -0
  49. package/src/lib/filter/index.ts +1 -315
  50. package/src/lib/light_push/index.ts +1 -189
  51. package/src/lib/light_push/light_push.ts +188 -0
  52. package/src/lib/metadata/index.ts +1 -182
  53. package/src/lib/metadata/metadata.ts +182 -0
  54. package/src/lib/store/index.ts +1 -136
  55. package/src/lib/store/store.ts +136 -0
  56. package/src/lib/stream_manager/stream_manager.ts +16 -18
  57. package/dist/lib/health_manager.d.ts +0 -14
  58. package/dist/lib/health_manager.js +0 -70
  59. package/dist/lib/health_manager.js.map +0 -1
  60. package/src/lib/health_manager.ts +0 -90
package/bundle/index.js CHANGED
@@ -1,8 +1,518 @@
1
- import { v as version_0, a as allocUnsafe, b as alloc, e as encodingLength, c as encode$1, d as decode$1, M as MessagePush, F as FilterSubscribeRequest, f as FilterSubscribeResponse$1, P as PushRpc$1, g as PushResponse, S as StoreQueryRequest$1, h as StoreQueryResponse$1, u as utf8ToBytes, i as createEncoder, p as pubsubTopicToSingleShardInfo, j as bytesToUtf8, s as shardInfoToPubsubTopics, W as WakuMetadataRequest, k as pubsubTopicsToShardInfo, l as WakuMetadataResponse } from './version_0-Che4t3mN.js';
2
- export { m as createDecoder } from './version_0-Che4t3mN.js';
3
- import { L as Logger, P as ProtocolError, T as Tags, E as EPeersByDiscoveryEvents, a as EConnectionStateEvents, H as HealthStatus, b as Protocols } from './index-yLOEQnIE.js';
4
- import { B as BaseProtocol } from './base_protocol-DxFKDXX2.js';
5
- export { S as StreamManager } from './base_protocol-DxFKDXX2.js';
1
+ import { v as version_0, a as allocUnsafe, b as alloc, e as encodingLength$1, c as encode$2, d as decode$4, M as MessagePush, F as FilterSubscribeRequest, f as FilterSubscribeResponse$1, P as PushRpc$1, g as PushResponse, S as StoreQueryRequest$1, h as StoreQueryResponse$1, t as toString$1, i as bases, j as fromString, u as utf8ToBytes, k as createEncoder, p as pubsubTopicToSingleShardInfo, l as bytesToUtf8, s as shardInfoToPubsubTopics, W as WakuMetadataRequest, m as pubsubTopicsToShardInfo, n as WakuMetadataResponse } from './version_0-ANFNAdFD.js';
2
+ export { o as createDecoder } from './version_0-ANFNAdFD.js';
3
+ import { c as coerce, e as equals$2, b as base36, a as base32, d as base58btc, L as Logger, P as ProtocolError, T as Tags, E as EPeersByDiscoveryEvents, f as EConnectionStateEvents } from './index-Db7LxDrL.js';
4
+ import { B as BaseProtocol } from './base_protocol-CCK9RCtH.js';
5
+ export { S as StreamManager } from './base_protocol-CCK9RCtH.js';
6
+
7
+ /* eslint-disable */
8
+ var encode_1 = encode$1;
9
+ var MSB = 0x80, MSBALL = -128, INT = Math.pow(2, 31);
10
+ /**
11
+ * @param {number} num
12
+ * @param {number[]} out
13
+ * @param {number} offset
14
+ */
15
+ function encode$1(num, out, offset) {
16
+ out = out || [];
17
+ offset = offset || 0;
18
+ var oldOffset = offset;
19
+ while (num >= INT) {
20
+ out[offset++] = (num & 0xFF) | MSB;
21
+ num /= 128;
22
+ }
23
+ while (num & MSBALL) {
24
+ out[offset++] = (num & 0xFF) | MSB;
25
+ num >>>= 7;
26
+ }
27
+ out[offset] = num | 0;
28
+ // @ts-ignore
29
+ encode$1.bytes = offset - oldOffset + 1;
30
+ return out;
31
+ }
32
+ var decode$3 = read;
33
+ var MSB$1 = 0x80, REST$1 = 0x7F;
34
+ /**
35
+ * @param {string | any[]} buf
36
+ * @param {number} offset
37
+ */
38
+ function read(buf, offset) {
39
+ var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
40
+ do {
41
+ if (counter >= l) {
42
+ // @ts-ignore
43
+ read.bytes = 0;
44
+ throw new RangeError('Could not decode varint');
45
+ }
46
+ b = buf[counter++];
47
+ res += shift < 28
48
+ ? (b & REST$1) << shift
49
+ : (b & REST$1) * Math.pow(2, shift);
50
+ shift += 7;
51
+ } while (b >= MSB$1);
52
+ // @ts-ignore
53
+ read.bytes = counter - offset;
54
+ return res;
55
+ }
56
+ var N1 = Math.pow(2, 7);
57
+ var N2 = Math.pow(2, 14);
58
+ var N3 = Math.pow(2, 21);
59
+ var N4 = Math.pow(2, 28);
60
+ var N5 = Math.pow(2, 35);
61
+ var N6 = Math.pow(2, 42);
62
+ var N7 = Math.pow(2, 49);
63
+ var N8 = Math.pow(2, 56);
64
+ var N9 = Math.pow(2, 63);
65
+ var length = function (/** @type {number} */ value) {
66
+ return (value < N1 ? 1
67
+ : value < N2 ? 2
68
+ : value < N3 ? 3
69
+ : value < N4 ? 4
70
+ : value < N5 ? 5
71
+ : value < N6 ? 6
72
+ : value < N7 ? 7
73
+ : value < N8 ? 8
74
+ : value < N9 ? 9
75
+ : 10);
76
+ };
77
+ var varint = {
78
+ encode: encode_1,
79
+ decode: decode$3,
80
+ encodingLength: length
81
+ };
82
+ var _brrp_varint = varint;
83
+
84
+ function decode$2(data, offset = 0) {
85
+ const code = _brrp_varint.decode(data, offset);
86
+ return [code, _brrp_varint.decode.bytes];
87
+ }
88
+ function encodeTo(int, target, offset = 0) {
89
+ _brrp_varint.encode(int, target, offset);
90
+ return target;
91
+ }
92
+ function encodingLength(int) {
93
+ return _brrp_varint.encodingLength(int);
94
+ }
95
+
96
+ /**
97
+ * Creates a multihash digest.
98
+ */
99
+ function create(code, digest) {
100
+ const size = digest.byteLength;
101
+ const sizeOffset = encodingLength(code);
102
+ const digestOffset = sizeOffset + encodingLength(size);
103
+ const bytes = new Uint8Array(digestOffset + size);
104
+ encodeTo(code, bytes, 0);
105
+ encodeTo(size, bytes, sizeOffset);
106
+ bytes.set(digest, digestOffset);
107
+ return new Digest(code, size, digest, bytes);
108
+ }
109
+ /**
110
+ * Turns bytes representation of multihash digest into an instance.
111
+ */
112
+ function decode$1(multihash) {
113
+ const bytes = coerce(multihash);
114
+ const [code, sizeOffset] = decode$2(bytes);
115
+ const [size, digestOffset] = decode$2(bytes.subarray(sizeOffset));
116
+ const digest = bytes.subarray(sizeOffset + digestOffset);
117
+ if (digest.byteLength !== size) {
118
+ throw new Error('Incorrect length');
119
+ }
120
+ return new Digest(code, size, digest, bytes);
121
+ }
122
+ function equals$1(a, b) {
123
+ if (a === b) {
124
+ return true;
125
+ }
126
+ else {
127
+ const data = b;
128
+ return (a.code === data.code &&
129
+ a.size === data.size &&
130
+ data.bytes instanceof Uint8Array &&
131
+ equals$2(a.bytes, data.bytes));
132
+ }
133
+ }
134
+ /**
135
+ * Represents a multihash digest which carries information about the
136
+ * hashing algorithm and an actual hash digest.
137
+ */
138
+ class Digest {
139
+ code;
140
+ size;
141
+ digest;
142
+ bytes;
143
+ /**
144
+ * Creates a multihash digest.
145
+ */
146
+ constructor(code, size, digest, bytes) {
147
+ this.code = code;
148
+ this.size = size;
149
+ this.digest = digest;
150
+ this.bytes = bytes;
151
+ }
152
+ }
153
+
154
+ function format(link, base) {
155
+ const { bytes, version } = link;
156
+ switch (version) {
157
+ case 0:
158
+ return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
159
+ default:
160
+ return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
161
+ }
162
+ }
163
+ const cache = new WeakMap();
164
+ function baseCache(cid) {
165
+ const baseCache = cache.get(cid);
166
+ if (baseCache == null) {
167
+ const baseCache = new Map();
168
+ cache.set(cid, baseCache);
169
+ return baseCache;
170
+ }
171
+ return baseCache;
172
+ }
173
+ class CID {
174
+ code;
175
+ version;
176
+ multihash;
177
+ bytes;
178
+ '/';
179
+ /**
180
+ * @param version - Version of the CID
181
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
182
+ * @param multihash - (Multi)hash of the of the content.
183
+ */
184
+ constructor(version, code, multihash, bytes) {
185
+ this.code = code;
186
+ this.version = version;
187
+ this.multihash = multihash;
188
+ this.bytes = bytes;
189
+ // flag to serializers that this is a CID and
190
+ // should be treated specially
191
+ this['/'] = bytes;
192
+ }
193
+ /**
194
+ * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
195
+ * please either use `CID.asCID(cid)` or switch to new signalling mechanism
196
+ *
197
+ * @deprecated
198
+ */
199
+ get asCID() {
200
+ return this;
201
+ }
202
+ // ArrayBufferView
203
+ get byteOffset() {
204
+ return this.bytes.byteOffset;
205
+ }
206
+ // ArrayBufferView
207
+ get byteLength() {
208
+ return this.bytes.byteLength;
209
+ }
210
+ toV0() {
211
+ switch (this.version) {
212
+ case 0: {
213
+ return this;
214
+ }
215
+ case 1: {
216
+ const { code, multihash } = this;
217
+ if (code !== DAG_PB_CODE) {
218
+ throw new Error('Cannot convert a non dag-pb CID to CIDv0');
219
+ }
220
+ // sha2-256
221
+ if (multihash.code !== SHA_256_CODE) {
222
+ throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
223
+ }
224
+ return (CID.createV0(multihash));
225
+ }
226
+ default: {
227
+ throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
228
+ }
229
+ }
230
+ }
231
+ toV1() {
232
+ switch (this.version) {
233
+ case 0: {
234
+ const { code, digest } = this.multihash;
235
+ const multihash = create(code, digest);
236
+ return (CID.createV1(this.code, multihash));
237
+ }
238
+ case 1: {
239
+ return this;
240
+ }
241
+ default: {
242
+ throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
243
+ }
244
+ }
245
+ }
246
+ equals(other) {
247
+ return CID.equals(this, other);
248
+ }
249
+ static equals(self, other) {
250
+ const unknown = other;
251
+ return (unknown != null &&
252
+ self.code === unknown.code &&
253
+ self.version === unknown.version &&
254
+ equals$1(self.multihash, unknown.multihash));
255
+ }
256
+ toString(base) {
257
+ return format(this, base);
258
+ }
259
+ toJSON() {
260
+ return { '/': format(this) };
261
+ }
262
+ link() {
263
+ return this;
264
+ }
265
+ [Symbol.toStringTag] = 'CID';
266
+ // Legacy
267
+ [Symbol.for('nodejs.util.inspect.custom')]() {
268
+ return `CID(${this.toString()})`;
269
+ }
270
+ /**
271
+ * Takes any input `value` and returns a `CID` instance if it was
272
+ * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
273
+ * it will return value back. If `value` is not instance of this CID
274
+ * class, but is compatible CID it will return new instance of this
275
+ * `CID` class. Otherwise returns null.
276
+ *
277
+ * This allows two different incompatible versions of CID library to
278
+ * co-exist and interop as long as binary interface is compatible.
279
+ */
280
+ static asCID(input) {
281
+ if (input == null) {
282
+ return null;
283
+ }
284
+ const value = input;
285
+ if (value instanceof CID) {
286
+ // If value is instance of CID then we're all set.
287
+ return value;
288
+ }
289
+ else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
290
+ // If value isn't instance of this CID class but `this.asCID === this` or
291
+ // `value['/'] === value.bytes` is true it is CID instance coming from a
292
+ // different implementation (diff version or duplicate). In that case we
293
+ // rebase it to this `CID` implementation so caller is guaranteed to get
294
+ // instance with expected API.
295
+ const { version, code, multihash, bytes } = value;
296
+ return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
297
+ }
298
+ else if (value[cidSymbol] === true) {
299
+ // If value is a CID from older implementation that used to be tagged via
300
+ // symbol we still rebase it to the this `CID` implementation by
301
+ // delegating that to a constructor.
302
+ const { version, multihash, code } = value;
303
+ const digest = decode$1(multihash);
304
+ return CID.create(version, code, digest);
305
+ }
306
+ else {
307
+ // Otherwise value is not a CID (or an incompatible version of it) in
308
+ // which case we return `null`.
309
+ return null;
310
+ }
311
+ }
312
+ /**
313
+ * @param version - Version of the CID
314
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
315
+ * @param digest - (Multi)hash of the of the content.
316
+ */
317
+ static create(version, code, digest) {
318
+ if (typeof code !== 'number') {
319
+ throw new Error('String codecs are no longer supported');
320
+ }
321
+ if (!(digest.bytes instanceof Uint8Array)) {
322
+ throw new Error('Invalid digest');
323
+ }
324
+ switch (version) {
325
+ case 0: {
326
+ if (code !== DAG_PB_CODE) {
327
+ throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
328
+ }
329
+ else {
330
+ return new CID(version, code, digest, digest.bytes);
331
+ }
332
+ }
333
+ case 1: {
334
+ const bytes = encodeCID(version, code, digest.bytes);
335
+ return new CID(version, code, digest, bytes);
336
+ }
337
+ default: {
338
+ throw new Error('Invalid version');
339
+ }
340
+ }
341
+ }
342
+ /**
343
+ * Simplified version of `create` for CIDv0.
344
+ */
345
+ static createV0(digest) {
346
+ return CID.create(0, DAG_PB_CODE, digest);
347
+ }
348
+ /**
349
+ * Simplified version of `create` for CIDv1.
350
+ *
351
+ * @param code - Content encoding format code.
352
+ * @param digest - Multihash of the content.
353
+ */
354
+ static createV1(code, digest) {
355
+ return CID.create(1, code, digest);
356
+ }
357
+ /**
358
+ * Decoded a CID from its binary representation. The byte array must contain
359
+ * only the CID with no additional bytes.
360
+ *
361
+ * An error will be thrown if the bytes provided do not contain a valid
362
+ * binary representation of a CID.
363
+ */
364
+ static decode(bytes) {
365
+ const [cid, remainder] = CID.decodeFirst(bytes);
366
+ if (remainder.length !== 0) {
367
+ throw new Error('Incorrect length');
368
+ }
369
+ return cid;
370
+ }
371
+ /**
372
+ * Decoded a CID from its binary representation at the beginning of a byte
373
+ * array.
374
+ *
375
+ * Returns an array with the first element containing the CID and the second
376
+ * element containing the remainder of the original byte array. The remainder
377
+ * will be a zero-length byte array if the provided bytes only contained a
378
+ * binary CID representation.
379
+ */
380
+ static decodeFirst(bytes) {
381
+ const specs = CID.inspectBytes(bytes);
382
+ const prefixSize = specs.size - specs.multihashSize;
383
+ const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
384
+ if (multihashBytes.byteLength !== specs.multihashSize) {
385
+ throw new Error('Incorrect length');
386
+ }
387
+ const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
388
+ const digest = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
389
+ const cid = specs.version === 0
390
+ ? CID.createV0(digest)
391
+ : CID.createV1(specs.codec, digest);
392
+ return [cid, bytes.subarray(specs.size)];
393
+ }
394
+ /**
395
+ * Inspect the initial bytes of a CID to determine its properties.
396
+ *
397
+ * Involves decoding up to 4 varints. Typically this will require only 4 to 6
398
+ * bytes but for larger multicodec code values and larger multihash digest
399
+ * lengths these varints can be quite large. It is recommended that at least
400
+ * 10 bytes be made available in the `initialBytes` argument for a complete
401
+ * inspection.
402
+ */
403
+ static inspectBytes(initialBytes) {
404
+ let offset = 0;
405
+ const next = () => {
406
+ const [i, length] = decode$2(initialBytes.subarray(offset));
407
+ offset += length;
408
+ return i;
409
+ };
410
+ let version = next();
411
+ let codec = DAG_PB_CODE;
412
+ if (version === 18) {
413
+ // CIDv0
414
+ version = 0;
415
+ offset = 0;
416
+ }
417
+ else {
418
+ codec = next();
419
+ }
420
+ if (version !== 0 && version !== 1) {
421
+ throw new RangeError(`Invalid CID version ${version}`);
422
+ }
423
+ const prefixSize = offset;
424
+ const multihashCode = next(); // multihash code
425
+ const digestSize = next(); // multihash length
426
+ const size = offset + digestSize;
427
+ const multihashSize = size - prefixSize;
428
+ return { version, codec, multihashCode, digestSize, multihashSize, size };
429
+ }
430
+ /**
431
+ * Takes cid in a string representation and creates an instance. If `base`
432
+ * decoder is not provided will use a default from the configuration. It will
433
+ * throw an error if encoding of the CID is not compatible with supplied (or
434
+ * a default decoder).
435
+ */
436
+ static parse(source, base) {
437
+ const [prefix, bytes] = parseCIDtoBytes(source, base);
438
+ const cid = CID.decode(bytes);
439
+ if (cid.version === 0 && source[0] !== 'Q') {
440
+ throw Error('Version 0 CID string must not include multibase prefix');
441
+ }
442
+ // Cache string representation to avoid computing it on `this.toString()`
443
+ baseCache(cid).set(prefix, source);
444
+ return cid;
445
+ }
446
+ }
447
+ function parseCIDtoBytes(source, base) {
448
+ switch (source[0]) {
449
+ // CIDv0 is parsed differently
450
+ case 'Q': {
451
+ const decoder = base ?? base58btc;
452
+ return [
453
+ base58btc.prefix,
454
+ decoder.decode(`${base58btc.prefix}${source}`)
455
+ ];
456
+ }
457
+ case base58btc.prefix: {
458
+ const decoder = base ?? base58btc;
459
+ return [base58btc.prefix, decoder.decode(source)];
460
+ }
461
+ case base32.prefix: {
462
+ const decoder = base ?? base32;
463
+ return [base32.prefix, decoder.decode(source)];
464
+ }
465
+ case base36.prefix: {
466
+ const decoder = base ?? base36;
467
+ return [base36.prefix, decoder.decode(source)];
468
+ }
469
+ default: {
470
+ if (base == null) {
471
+ throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
472
+ }
473
+ return [source[0], base.decode(source)];
474
+ }
475
+ }
476
+ }
477
+ function toStringV0(bytes, cache, base) {
478
+ const { prefix } = base;
479
+ if (prefix !== base58btc.prefix) {
480
+ throw Error(`Cannot string encode V0 in ${base.name} encoding`);
481
+ }
482
+ const cid = cache.get(prefix);
483
+ if (cid == null) {
484
+ const cid = base.encode(bytes).slice(1);
485
+ cache.set(prefix, cid);
486
+ return cid;
487
+ }
488
+ else {
489
+ return cid;
490
+ }
491
+ }
492
+ function toStringV1(bytes, cache, base) {
493
+ const { prefix } = base;
494
+ const cid = cache.get(prefix);
495
+ if (cid == null) {
496
+ const cid = base.encode(bytes);
497
+ cache.set(prefix, cid);
498
+ return cid;
499
+ }
500
+ else {
501
+ return cid;
502
+ }
503
+ }
504
+ const DAG_PB_CODE = 0x70;
505
+ const SHA_256_CODE = 0x12;
506
+ function encodeCID(version, code, multihash) {
507
+ const codeOffset = encodingLength(version);
508
+ const hashOffset = codeOffset + encodingLength(code);
509
+ const bytes = new Uint8Array(hashOffset + multihash.byteLength);
510
+ encodeTo(version, bytes, 0);
511
+ encodeTo(code, bytes, codeOffset);
512
+ bytes.set(multihash, hashOffset);
513
+ return bytes;
514
+ }
515
+ const cidSymbol = Symbol.for('@ipld/js-cid/CID');
6
516
 
7
517
  const MB = 1024 ** 2;
8
518
  const SIZE_CAP_IN_MB = 1;
@@ -258,7 +768,7 @@ function equals(a, b) {
258
768
  *
259
769
  * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.
260
770
  */
261
- const symbol = Symbol.for('@achingbrain/uint8arraylist');
771
+ const symbol$1 = Symbol.for('@achingbrain/uint8arraylist');
262
772
  function findBufAndOffset(bufs, index) {
263
773
  if (index == null || index < 0) {
264
774
  throw new RangeError('index is out of bounds');
@@ -290,12 +800,12 @@ function findBufAndOffset(bufs, index) {
290
800
  * ```
291
801
  */
292
802
  function isUint8ArrayList(value) {
293
- return Boolean(value?.[symbol]);
803
+ return Boolean(value?.[symbol$1]);
294
804
  }
295
805
  class Uint8ArrayList {
296
806
  bufs;
297
807
  length;
298
- [symbol] = true;
808
+ [symbol$1] = true;
299
809
  constructor(...data) {
300
810
  this.bufs = [];
301
811
  this.length = 0;
@@ -751,9 +1261,9 @@ function isAsyncIterable$2(thing) {
751
1261
  }
752
1262
 
753
1263
  const defaultEncoder = (length) => {
754
- const lengthLength = encodingLength(length);
1264
+ const lengthLength = encodingLength$1(length);
755
1265
  const lengthBuf = allocUnsafe(lengthLength);
756
- encode$1(length, lengthBuf);
1266
+ encode$2(length, lengthBuf);
757
1267
  defaultEncoder.bytes = lengthLength;
758
1268
  return lengthBuf;
759
1269
  };
@@ -840,8 +1350,8 @@ var ReadMode;
840
1350
  ReadMode[ReadMode["DATA"] = 1] = "DATA";
841
1351
  })(ReadMode || (ReadMode = {}));
842
1352
  const defaultDecoder = (buf) => {
843
- const length = decode$1(buf);
844
- defaultDecoder.bytes = encodingLength(length);
1353
+ const length = decode$4(buf);
1354
+ defaultDecoder.bytes = encodingLength$1(length);
845
1355
  return length;
846
1356
  };
847
1357
  defaultDecoder.bytes = 0;
@@ -1491,7 +2001,7 @@ var native = {
1491
2001
  };
1492
2002
 
1493
2003
  function v4(options, buf, offset) {
1494
- if (native.randomUUID && !buf && !options) {
2004
+ if (native.randomUUID && true && !options) {
1495
2005
  return native.randomUUID();
1496
2006
  }
1497
2007
 
@@ -1631,8 +2141,8 @@ class FilterCore extends BaseProtocol {
1631
2141
  log$5.error("Failed to register ", FilterCodecs.PUSH, e);
1632
2142
  });
1633
2143
  }
1634
- async subscribe(pubsubTopic, peer, contentTopics) {
1635
- const stream = await this.getStream(peer);
2144
+ async subscribe(pubsubTopic, peerId, contentTopics) {
2145
+ const stream = await this.getStream(peerId);
1636
2146
  const request = FilterSubscribeRpc.createSubscribeRequest(pubsubTopic, contentTopics);
1637
2147
  let res;
1638
2148
  try {
@@ -1644,7 +2154,7 @@ class FilterCore extends BaseProtocol {
1644
2154
  success: null,
1645
2155
  failure: {
1646
2156
  error: ProtocolError.GENERIC_FAIL,
1647
- peerId: peer.id
2157
+ peerId: peerId
1648
2158
  }
1649
2159
  };
1650
2160
  }
@@ -1654,28 +2164,28 @@ class FilterCore extends BaseProtocol {
1654
2164
  return {
1655
2165
  failure: {
1656
2166
  error: ProtocolError.REMOTE_PEER_REJECTED,
1657
- peerId: peer.id
2167
+ peerId: peerId
1658
2168
  },
1659
2169
  success: null
1660
2170
  };
1661
2171
  }
1662
2172
  return {
1663
2173
  failure: null,
1664
- success: peer.id
2174
+ success: peerId
1665
2175
  };
1666
2176
  }
1667
- async unsubscribe(pubsubTopic, peer, contentTopics) {
2177
+ async unsubscribe(pubsubTopic, peerId, contentTopics) {
1668
2178
  let stream;
1669
2179
  try {
1670
- stream = await this.getStream(peer);
2180
+ stream = await this.getStream(peerId);
1671
2181
  }
1672
2182
  catch (error) {
1673
- log$5.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
2183
+ log$5.error(`Failed to get a stream for remote peer${peerId.toString()}`, error);
1674
2184
  return {
1675
2185
  success: null,
1676
2186
  failure: {
1677
2187
  error: ProtocolError.NO_STREAM_AVAILABLE,
1678
- peerId: peer.id
2188
+ peerId: peerId
1679
2189
  }
1680
2190
  };
1681
2191
  }
@@ -1689,24 +2199,24 @@ class FilterCore extends BaseProtocol {
1689
2199
  success: null,
1690
2200
  failure: {
1691
2201
  error: ProtocolError.GENERIC_FAIL,
1692
- peerId: peer.id
2202
+ peerId: peerId
1693
2203
  }
1694
2204
  };
1695
2205
  }
1696
2206
  return {
1697
- success: peer.id,
2207
+ success: peerId,
1698
2208
  failure: null
1699
2209
  };
1700
2210
  }
1701
- async unsubscribeAll(pubsubTopic, peer) {
1702
- const stream = await this.getStream(peer);
2211
+ async unsubscribeAll(pubsubTopic, peerId) {
2212
+ const stream = await this.getStream(peerId);
1703
2213
  const request = FilterSubscribeRpc.createUnsubscribeAllRequest(pubsubTopic);
1704
2214
  const res = await pipe([request.encode()], encode, stream, decode, async (source) => await all(source));
1705
2215
  if (!res || !res.length) {
1706
2216
  return {
1707
2217
  failure: {
1708
2218
  error: ProtocolError.NO_RESPONSE,
1709
- peerId: peer.id
2219
+ peerId: peerId
1710
2220
  },
1711
2221
  success: null
1712
2222
  };
@@ -1717,28 +2227,28 @@ class FilterCore extends BaseProtocol {
1717
2227
  return {
1718
2228
  failure: {
1719
2229
  error: ProtocolError.REMOTE_PEER_REJECTED,
1720
- peerId: peer.id
2230
+ peerId: peerId
1721
2231
  },
1722
2232
  success: null
1723
2233
  };
1724
2234
  }
1725
2235
  return {
1726
2236
  failure: null,
1727
- success: peer.id
2237
+ success: peerId
1728
2238
  };
1729
2239
  }
1730
- async ping(peer) {
2240
+ async ping(peerId) {
1731
2241
  let stream;
1732
2242
  try {
1733
- stream = await this.getStream(peer);
2243
+ stream = await this.getStream(peerId);
1734
2244
  }
1735
2245
  catch (error) {
1736
- log$5.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);
2246
+ log$5.error(`Failed to get a stream for remote peer${peerId.toString()}`, error);
1737
2247
  return {
1738
2248
  success: null,
1739
2249
  failure: {
1740
2250
  error: ProtocolError.NO_STREAM_AVAILABLE,
1741
- peerId: peer.id
2251
+ peerId: peerId
1742
2252
  }
1743
2253
  };
1744
2254
  }
@@ -1753,7 +2263,7 @@ class FilterCore extends BaseProtocol {
1753
2263
  success: null,
1754
2264
  failure: {
1755
2265
  error: ProtocolError.GENERIC_FAIL,
1756
- peerId: peer.id
2266
+ peerId: peerId
1757
2267
  }
1758
2268
  };
1759
2269
  }
@@ -1762,7 +2272,7 @@ class FilterCore extends BaseProtocol {
1762
2272
  success: null,
1763
2273
  failure: {
1764
2274
  error: ProtocolError.NO_RESPONSE,
1765
- peerId: peer.id
2275
+ peerId: peerId
1766
2276
  }
1767
2277
  };
1768
2278
  }
@@ -1773,12 +2283,12 @@ class FilterCore extends BaseProtocol {
1773
2283
  success: null,
1774
2284
  failure: {
1775
2285
  error: ProtocolError.REMOTE_PEER_REJECTED,
1776
- peerId: peer.id
2286
+ peerId: peerId
1777
2287
  }
1778
2288
  };
1779
2289
  }
1780
2290
  return {
1781
- success: peer.id,
2291
+ success: peerId,
1782
2292
  failure: null
1783
2293
  };
1784
2294
  }
@@ -1914,21 +2424,20 @@ class LightPushCore extends BaseProtocol {
1914
2424
  };
1915
2425
  }
1916
2426
  }
1917
- // TODO(weboko): use peer.id as parameter instead
1918
- async send(encoder, message, peer) {
2427
+ async send(encoder, message, peerId) {
1919
2428
  const { query, error: preparationError } = await this.preparePushMessage(encoder, message);
1920
2429
  if (preparationError || !query) {
1921
2430
  return {
1922
2431
  success: null,
1923
2432
  failure: {
1924
2433
  error: preparationError,
1925
- peerId: peer.id
2434
+ peerId
1926
2435
  }
1927
2436
  };
1928
2437
  }
1929
2438
  let stream;
1930
2439
  try {
1931
- stream = await this.getStream(peer);
2440
+ stream = await this.getStream(peerId);
1932
2441
  }
1933
2442
  catch (error) {
1934
2443
  log$4.error("Failed to get stream", error);
@@ -1936,7 +2445,7 @@ class LightPushCore extends BaseProtocol {
1936
2445
  success: null,
1937
2446
  failure: {
1938
2447
  error: ProtocolError.NO_STREAM_AVAILABLE,
1939
- peerId: peer.id
2448
+ peerId: peerId
1940
2449
  }
1941
2450
  };
1942
2451
  }
@@ -1950,7 +2459,7 @@ class LightPushCore extends BaseProtocol {
1950
2459
  success: null,
1951
2460
  failure: {
1952
2461
  error: ProtocolError.GENERIC_FAIL,
1953
- peerId: peer.id
2462
+ peerId: peerId
1954
2463
  }
1955
2464
  };
1956
2465
  }
@@ -1968,7 +2477,7 @@ class LightPushCore extends BaseProtocol {
1968
2477
  success: null,
1969
2478
  failure: {
1970
2479
  error: ProtocolError.DECODE_FAILED,
1971
- peerId: peer.id
2480
+ peerId: peerId
1972
2481
  }
1973
2482
  };
1974
2483
  }
@@ -1978,7 +2487,7 @@ class LightPushCore extends BaseProtocol {
1978
2487
  success: null,
1979
2488
  failure: {
1980
2489
  error: ProtocolError.NO_RESPONSE,
1981
- peerId: peer.id
2490
+ peerId: peerId
1982
2491
  }
1983
2492
  };
1984
2493
  }
@@ -1989,7 +2498,7 @@ class LightPushCore extends BaseProtocol {
1989
2498
  success: null,
1990
2499
  failure: {
1991
2500
  error: rlnErrorCase,
1992
- peerId: peer.id
2501
+ peerId: peerId
1993
2502
  }
1994
2503
  };
1995
2504
  }
@@ -1999,11 +2508,11 @@ class LightPushCore extends BaseProtocol {
1999
2508
  success: null,
2000
2509
  failure: {
2001
2510
  error: ProtocolError.REMOTE_PEER_REJECTED,
2002
- peerId: peer.id
2511
+ peerId: peerId
2003
2512
  }
2004
2513
  };
2005
2514
  }
2006
- return { success: peer.id, failure: null };
2515
+ return { success: peerId, failure: null };
2007
2516
  }
2008
2517
  }
2009
2518
 
@@ -2107,7 +2616,7 @@ class StoreCore extends BaseProtocol {
2107
2616
  super(StoreCodec, libp2p.components, pubsubTopics);
2108
2617
  this.pubsubTopics = pubsubTopics;
2109
2618
  }
2110
- async *queryPerPage(queryOpts, decoders, peer) {
2619
+ async *queryPerPage(queryOpts, decoders, peerId) {
2111
2620
  if (queryOpts.contentTopics.toString() !==
2112
2621
  Array.from(decoders.keys()).toString()) {
2113
2622
  throw new Error("Internal error, the decoders should match the query's content topics");
@@ -2120,7 +2629,7 @@ class StoreCore extends BaseProtocol {
2120
2629
  });
2121
2630
  let stream;
2122
2631
  try {
2123
- stream = await this.getStream(peer);
2632
+ stream = await this.getStream(peerId);
2124
2633
  }
2125
2634
  catch (e) {
2126
2635
  log$3.error("Failed to get stream", e);
@@ -2180,6 +2689,18 @@ var index = /*#__PURE__*/Object.freeze({
2180
2689
  StoreCore: StoreCore
2181
2690
  });
2182
2691
 
2692
+ /**
2693
+ * All PeerId implementations must use this symbol as the name of a property
2694
+ * with a boolean `true` value
2695
+ */
2696
+ const peerIdSymbol = Symbol.for('@libp2p/peer-id');
2697
+ /**
2698
+ * Returns true if the passed argument is a PeerId implementation
2699
+ */
2700
+ function isPeerId(other) {
2701
+ return Boolean(other?.[peerIdSymbol]);
2702
+ }
2703
+
2183
2704
  /**
2184
2705
  * Noop for browser compatibility
2185
2706
  */
@@ -2252,6 +2773,1154 @@ class TypedEventEmitter extends EventTarget {
2252
2773
  }
2253
2774
  }
2254
2775
 
2776
+ /* eslint-disable @typescript-eslint/no-unsafe-return */
2777
+ class Parser {
2778
+ index = 0;
2779
+ input = "";
2780
+ new(input) {
2781
+ this.index = 0;
2782
+ this.input = input;
2783
+ return this;
2784
+ }
2785
+ /** Run a parser, and restore the pre-parse state if it fails. */
2786
+ readAtomically(fn) {
2787
+ const index = this.index;
2788
+ const result = fn();
2789
+ if (result === undefined) {
2790
+ this.index = index;
2791
+ }
2792
+ return result;
2793
+ }
2794
+ /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */
2795
+ parseWith(fn) {
2796
+ const result = fn();
2797
+ if (this.index !== this.input.length) {
2798
+ return undefined;
2799
+ }
2800
+ return result;
2801
+ }
2802
+ /** Peek the next character from the input */
2803
+ peekChar() {
2804
+ if (this.index >= this.input.length) {
2805
+ return undefined;
2806
+ }
2807
+ return this.input[this.index];
2808
+ }
2809
+ /** Read the next character from the input */
2810
+ readChar() {
2811
+ if (this.index >= this.input.length) {
2812
+ return undefined;
2813
+ }
2814
+ return this.input[this.index++];
2815
+ }
2816
+ /** Read the next character from the input if it matches the target. */
2817
+ readGivenChar(target) {
2818
+ return this.readAtomically(() => {
2819
+ const char = this.readChar();
2820
+ if (char !== target) {
2821
+ return undefined;
2822
+ }
2823
+ return char;
2824
+ });
2825
+ }
2826
+ /**
2827
+ * Helper for reading separators in an indexed loop. Reads the separator
2828
+ * character iff index > 0, then runs the parser. When used in a loop,
2829
+ * the separator character will only be read on index > 0 (see
2830
+ * readIPv4Addr for an example)
2831
+ */
2832
+ readSeparator(sep, index, inner) {
2833
+ return this.readAtomically(() => {
2834
+ if (index > 0) {
2835
+ if (this.readGivenChar(sep) === undefined) {
2836
+ return undefined;
2837
+ }
2838
+ }
2839
+ return inner();
2840
+ });
2841
+ }
2842
+ /**
2843
+ * Read a number off the front of the input in the given radix, stopping
2844
+ * at the first non-digit character or eof. Fails if the number has more
2845
+ * digits than max_digits or if there is no number.
2846
+ */
2847
+ readNumber(radix, maxDigits, allowZeroPrefix, maxBytes) {
2848
+ return this.readAtomically(() => {
2849
+ let result = 0;
2850
+ let digitCount = 0;
2851
+ const leadingChar = this.peekChar();
2852
+ if (leadingChar === undefined) {
2853
+ return undefined;
2854
+ }
2855
+ const hasLeadingZero = leadingChar === "0";
2856
+ const maxValue = 2 ** (8 * maxBytes) - 1;
2857
+ // eslint-disable-next-line no-constant-condition
2858
+ while (true) {
2859
+ const digit = this.readAtomically(() => {
2860
+ const char = this.readChar();
2861
+ if (char === undefined) {
2862
+ return undefined;
2863
+ }
2864
+ const num = Number.parseInt(char, radix);
2865
+ if (Number.isNaN(num)) {
2866
+ return undefined;
2867
+ }
2868
+ return num;
2869
+ });
2870
+ if (digit === undefined) {
2871
+ break;
2872
+ }
2873
+ result *= radix;
2874
+ result += digit;
2875
+ if (result > maxValue) {
2876
+ return undefined;
2877
+ }
2878
+ digitCount += 1;
2879
+ if (maxDigits !== undefined) {
2880
+ if (digitCount > maxDigits) {
2881
+ return undefined;
2882
+ }
2883
+ }
2884
+ }
2885
+ if (digitCount === 0) {
2886
+ return undefined;
2887
+ }
2888
+ else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {
2889
+ return undefined;
2890
+ }
2891
+ else {
2892
+ return result;
2893
+ }
2894
+ });
2895
+ }
2896
+ /** Read an IPv4 address. */
2897
+ readIPv4Addr() {
2898
+ return this.readAtomically(() => {
2899
+ const out = new Uint8Array(4);
2900
+ for (let i = 0; i < out.length; i++) {
2901
+ const ix = this.readSeparator(".", i, () => this.readNumber(10, 3, false, 1));
2902
+ if (ix === undefined) {
2903
+ return undefined;
2904
+ }
2905
+ out[i] = ix;
2906
+ }
2907
+ return out;
2908
+ });
2909
+ }
2910
+ /** Read an IPv6 Address. */
2911
+ readIPv6Addr() {
2912
+ /**
2913
+ * Read a chunk of an IPv6 address into `groups`. Returns the number
2914
+ * of groups read, along with a bool indicating if an embedded
2915
+ * trailing IPv4 address was read. Specifically, read a series of
2916
+ * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional
2917
+ * trailing embedded IPv4 address.
2918
+ */
2919
+ const readGroups = (groups) => {
2920
+ for (let i = 0; i < groups.length / 2; i++) {
2921
+ const ix = i * 2;
2922
+ // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.
2923
+ if (i < groups.length - 3) {
2924
+ const ipv4 = this.readSeparator(":", i, () => this.readIPv4Addr());
2925
+ if (ipv4 !== undefined) {
2926
+ groups[ix] = ipv4[0];
2927
+ groups[ix + 1] = ipv4[1];
2928
+ groups[ix + 2] = ipv4[2];
2929
+ groups[ix + 3] = ipv4[3];
2930
+ return [ix + 4, true];
2931
+ }
2932
+ }
2933
+ const group = this.readSeparator(":", i, () => this.readNumber(16, 4, true, 2));
2934
+ if (group === undefined) {
2935
+ return [ix, false];
2936
+ }
2937
+ groups[ix] = group >> 8;
2938
+ groups[ix + 1] = group & 255;
2939
+ }
2940
+ return [groups.length, false];
2941
+ };
2942
+ return this.readAtomically(() => {
2943
+ // Read the front part of the address; either the whole thing, or up to the first ::
2944
+ const head = new Uint8Array(16);
2945
+ const [headSize, headIp4] = readGroups(head);
2946
+ if (headSize === 16) {
2947
+ return head;
2948
+ }
2949
+ // IPv4 part is not allowed before `::`
2950
+ if (headIp4) {
2951
+ return undefined;
2952
+ }
2953
+ // Read `::` if previous code parsed less than 8 groups.
2954
+ // `::` indicates one or more groups of 16 bits of zeros.
2955
+ if (this.readGivenChar(":") === undefined) {
2956
+ return undefined;
2957
+ }
2958
+ if (this.readGivenChar(":") === undefined) {
2959
+ return undefined;
2960
+ }
2961
+ // Read the back part of the address. The :: must contain at least one
2962
+ // set of zeroes, so our max length is 7.
2963
+ const tail = new Uint8Array(14);
2964
+ const limit = 16 - (headSize + 2);
2965
+ const [tailSize] = readGroups(tail.subarray(0, limit));
2966
+ // Concat the head and tail of the IP address
2967
+ head.set(tail.subarray(0, tailSize), 16 - tailSize);
2968
+ return head;
2969
+ });
2970
+ }
2971
+ /** Read an IP Address, either IPv4 or IPv6. */
2972
+ readIPAddr() {
2973
+ return this.readIPv4Addr() ?? this.readIPv6Addr();
2974
+ }
2975
+ }
2976
+
2977
+ // See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address
2978
+ const MAX_IPV6_LENGTH = 45;
2979
+ const MAX_IPV4_LENGTH = 15;
2980
+ const parser = new Parser();
2981
+ /** Parse `input` into IPv4 bytes. */
2982
+ function parseIPv4(input) {
2983
+ if (input.length > MAX_IPV4_LENGTH) {
2984
+ return undefined;
2985
+ }
2986
+ return parser.new(input).parseWith(() => parser.readIPv4Addr());
2987
+ }
2988
+ /** Parse `input` into IPv6 bytes. */
2989
+ function parseIPv6(input) {
2990
+ // strip zone index if it is present
2991
+ if (input.includes("%")) {
2992
+ input = input.split("%")[0];
2993
+ }
2994
+ if (input.length > MAX_IPV6_LENGTH) {
2995
+ return undefined;
2996
+ }
2997
+ return parser.new(input).parseWith(() => parser.readIPv6Addr());
2998
+ }
2999
+ /** Parse `input` into IPv4 or IPv6 bytes. */
3000
+ function parseIP(input, mapIPv4ToIPv6 = false) {
3001
+ // strip zone index if it is present
3002
+ if (input.includes("%")) {
3003
+ input = input.split("%")[0];
3004
+ }
3005
+ if (input.length > MAX_IPV6_LENGTH) {
3006
+ return undefined;
3007
+ }
3008
+ const addr = parser.new(input).parseWith(() => parser.readIPAddr());
3009
+ if (!addr) {
3010
+ return undefined;
3011
+ }
3012
+ if (mapIPv4ToIPv6 && addr.length === 4) {
3013
+ return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, addr[0], addr[1], addr[2], addr[3]]);
3014
+ }
3015
+ return addr;
3016
+ }
3017
+
3018
+ /** Check if `input` is IPv4. */
3019
+ function isIPv4(input) {
3020
+ return Boolean(parseIPv4(input));
3021
+ }
3022
+ /** Check if `input` is IPv6. */
3023
+ function isIPv6(input) {
3024
+ return Boolean(parseIPv6(input));
3025
+ }
3026
+ /** Check if `input` is IPv4 or IPv6. */
3027
+ function isIP(input) {
3028
+ return Boolean(parseIP(input));
3029
+ }
3030
+
3031
+ const isV4 = isIPv4;
3032
+ const isV6 = isIPv6;
3033
+ // Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7
3034
+ // but with buf/offset args removed because we don't use them
3035
+ const toBytes = function (ip) {
3036
+ let offset = 0;
3037
+ ip = ip.toString().trim();
3038
+ if (isV4(ip)) {
3039
+ const bytes = new Uint8Array(offset + 4);
3040
+ ip.split(/\./g).forEach((byte) => {
3041
+ bytes[offset++] = parseInt(byte, 10) & 0xff;
3042
+ });
3043
+ return bytes;
3044
+ }
3045
+ if (isV6(ip)) {
3046
+ const sections = ip.split(':', 8);
3047
+ let i;
3048
+ for (i = 0; i < sections.length; i++) {
3049
+ const isv4 = isV4(sections[i]);
3050
+ let v4Buffer;
3051
+ if (isv4) {
3052
+ v4Buffer = toBytes(sections[i]);
3053
+ sections[i] = toString$1(v4Buffer.slice(0, 2), 'base16');
3054
+ }
3055
+ if (v4Buffer != null && ++i < 8) {
3056
+ sections.splice(i, 0, toString$1(v4Buffer.slice(2, 4), 'base16'));
3057
+ }
3058
+ }
3059
+ if (sections[0] === '') {
3060
+ while (sections.length < 8)
3061
+ sections.unshift('0');
3062
+ }
3063
+ else if (sections[sections.length - 1] === '') {
3064
+ while (sections.length < 8)
3065
+ sections.push('0');
3066
+ }
3067
+ else if (sections.length < 8) {
3068
+ for (i = 0; i < sections.length && sections[i] !== ''; i++)
3069
+ ;
3070
+ const argv = [i, 1];
3071
+ for (i = 9 - sections.length; i > 0; i--) {
3072
+ argv.push('0');
3073
+ }
3074
+ sections.splice.apply(sections, argv);
3075
+ }
3076
+ const bytes = new Uint8Array(offset + 16);
3077
+ for (i = 0; i < sections.length; i++) {
3078
+ const word = parseInt(sections[i], 16);
3079
+ bytes[offset++] = (word >> 8) & 0xff;
3080
+ bytes[offset++] = word & 0xff;
3081
+ }
3082
+ return bytes;
3083
+ }
3084
+ throw new Error('invalid ip address');
3085
+ };
3086
+ // Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63
3087
+ const toString = function (buf, offset = 0, length) {
3088
+ offset = ~~offset;
3089
+ length = length ?? (buf.length - offset);
3090
+ const view = new DataView(buf.buffer);
3091
+ if (length === 4) {
3092
+ const result = [];
3093
+ // IPv4
3094
+ for (let i = 0; i < length; i++) {
3095
+ result.push(buf[offset + i]);
3096
+ }
3097
+ return result.join('.');
3098
+ }
3099
+ if (length === 16) {
3100
+ const result = [];
3101
+ // IPv6
3102
+ for (let i = 0; i < length; i += 2) {
3103
+ result.push(view.getUint16(offset + i).toString(16));
3104
+ }
3105
+ return result.join(':')
3106
+ .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')
3107
+ .replace(/:{3,4}/, '::');
3108
+ }
3109
+ return '';
3110
+ };
3111
+
3112
+ const V = -1;
3113
+ const names = {};
3114
+ const codes = {};
3115
+ const table = [
3116
+ [4, 32, 'ip4'],
3117
+ [6, 16, 'tcp'],
3118
+ [33, 16, 'dccp'],
3119
+ [41, 128, 'ip6'],
3120
+ [42, V, 'ip6zone'],
3121
+ [43, 8, 'ipcidr'],
3122
+ [53, V, 'dns', true],
3123
+ [54, V, 'dns4', true],
3124
+ [55, V, 'dns6', true],
3125
+ [56, V, 'dnsaddr', true],
3126
+ [132, 16, 'sctp'],
3127
+ [273, 16, 'udp'],
3128
+ [275, 0, 'p2p-webrtc-star'],
3129
+ [276, 0, 'p2p-webrtc-direct'],
3130
+ [277, 0, 'p2p-stardust'],
3131
+ [280, 0, 'webrtc-direct'],
3132
+ [281, 0, 'webrtc'],
3133
+ [290, 0, 'p2p-circuit'],
3134
+ [301, 0, 'udt'],
3135
+ [302, 0, 'utp'],
3136
+ [400, V, 'unix', false, true],
3137
+ // `ipfs` is added before `p2p` for legacy support.
3138
+ // All text representations will default to `p2p`, but `ipfs` will
3139
+ // still be supported
3140
+ [421, V, 'ipfs'],
3141
+ // `p2p` is the preferred name for 421, and is now the default
3142
+ [421, V, 'p2p'],
3143
+ [443, 0, 'https'],
3144
+ [444, 96, 'onion'],
3145
+ [445, 296, 'onion3'],
3146
+ [446, V, 'garlic64'],
3147
+ [448, 0, 'tls'],
3148
+ [449, V, 'sni'],
3149
+ [460, 0, 'quic'],
3150
+ [461, 0, 'quic-v1'],
3151
+ [465, 0, 'webtransport'],
3152
+ [466, V, 'certhash'],
3153
+ [477, 0, 'ws'],
3154
+ [478, 0, 'wss'],
3155
+ [479, 0, 'p2p-websocket-star'],
3156
+ [480, 0, 'http'],
3157
+ [481, V, 'http-path'],
3158
+ [777, V, 'memory']
3159
+ ];
3160
+ // populate tables
3161
+ table.forEach(row => {
3162
+ const proto = createProtocol(...row);
3163
+ codes[proto.code] = proto;
3164
+ names[proto.name] = proto;
3165
+ });
3166
+ function createProtocol(code, size, name, resolvable, path) {
3167
+ return {
3168
+ code,
3169
+ size,
3170
+ name,
3171
+ resolvable: Boolean(resolvable),
3172
+ path: Boolean(path)
3173
+ };
3174
+ }
3175
+ /**
3176
+ * For the passed proto string or number, return a {@link Protocol}
3177
+ *
3178
+ * @example
3179
+ *
3180
+ * ```js
3181
+ * import { protocol } from '@multiformats/multiaddr'
3182
+ *
3183
+ * console.info(protocol(4))
3184
+ * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }
3185
+ * ```
3186
+ */
3187
+ function getProtocol(proto) {
3188
+ if (typeof proto === 'number') {
3189
+ if (codes[proto] != null) {
3190
+ return codes[proto];
3191
+ }
3192
+ throw new Error(`no protocol with code: ${proto}`);
3193
+ }
3194
+ else if (typeof proto === 'string') {
3195
+ if (names[proto] != null) {
3196
+ return names[proto];
3197
+ }
3198
+ throw new Error(`no protocol with name: ${proto}`);
3199
+ }
3200
+ throw new Error(`invalid protocol id type: ${typeof proto}`);
3201
+ }
3202
+
3203
+ getProtocol('ip4');
3204
+ getProtocol('ip6');
3205
+ getProtocol('ipcidr');
3206
+ /**
3207
+ * Convert [code,Uint8Array] to string
3208
+ */
3209
+ // eslint-disable-next-line complexity
3210
+ function convertToString(proto, buf) {
3211
+ const protocol = getProtocol(proto);
3212
+ switch (protocol.code) {
3213
+ case 4: // ipv4
3214
+ case 41: // ipv6
3215
+ return bytes2ip(buf);
3216
+ case 42: // ipv6zone
3217
+ return bytes2str(buf);
3218
+ case 43: // ipcidr
3219
+ return toString$1(buf, 'base10');
3220
+ case 6: // tcp
3221
+ case 273: // udp
3222
+ case 33: // dccp
3223
+ case 132: // sctp
3224
+ return bytes2port(buf).toString();
3225
+ case 53: // dns
3226
+ case 54: // dns4
3227
+ case 55: // dns6
3228
+ case 56: // dnsaddr
3229
+ case 400: // unix
3230
+ case 449: // sni
3231
+ case 777: // memory
3232
+ return bytes2str(buf);
3233
+ case 421: // ipfs
3234
+ return bytes2mh(buf);
3235
+ case 444: // onion
3236
+ return bytes2onion(buf);
3237
+ case 445: // onion3
3238
+ return bytes2onion(buf);
3239
+ case 466: // certhash
3240
+ return bytes2mb(buf);
3241
+ case 481: // http-path
3242
+ return globalThis.encodeURIComponent(bytes2str(buf));
3243
+ default:
3244
+ return toString$1(buf, 'base16'); // no clue. convert to hex
3245
+ }
3246
+ }
3247
+ // eslint-disable-next-line complexity
3248
+ function convertToBytes(proto, str) {
3249
+ const protocol = getProtocol(proto);
3250
+ switch (protocol.code) {
3251
+ case 4: // ipv4
3252
+ return ip2bytes(str);
3253
+ case 41: // ipv6
3254
+ return ip2bytes(str);
3255
+ case 42: // ipv6zone
3256
+ return str2bytes(str);
3257
+ case 43: // ipcidr
3258
+ return fromString(str, 'base10');
3259
+ case 6: // tcp
3260
+ case 273: // udp
3261
+ case 33: // dccp
3262
+ case 132: // sctp
3263
+ return port2bytes(parseInt(str, 10));
3264
+ case 53: // dns
3265
+ case 54: // dns4
3266
+ case 55: // dns6
3267
+ case 56: // dnsaddr
3268
+ case 400: // unix
3269
+ case 449: // sni
3270
+ case 777: // memory
3271
+ return str2bytes(str);
3272
+ case 421: // ipfs
3273
+ return mh2bytes(str);
3274
+ case 444: // onion
3275
+ return onion2bytes(str);
3276
+ case 445: // onion3
3277
+ return onion32bytes(str);
3278
+ case 466: // certhash
3279
+ return mb2bytes(str);
3280
+ case 481: // http-path
3281
+ return str2bytes(globalThis.decodeURIComponent(str));
3282
+ default:
3283
+ return fromString(str, 'base16'); // no clue. convert from hex
3284
+ }
3285
+ }
3286
+ const decoders = Object.values(bases).map((c) => c.decoder);
3287
+ const anybaseDecoder = (function () {
3288
+ let acc = decoders[0].or(decoders[1]);
3289
+ decoders.slice(2).forEach((d) => (acc = acc.or(d)));
3290
+ return acc;
3291
+ })();
3292
+ function ip2bytes(ipString) {
3293
+ if (!isIP(ipString)) {
3294
+ throw new Error('invalid ip address');
3295
+ }
3296
+ return toBytes(ipString);
3297
+ }
3298
+ function bytes2ip(ipBuff) {
3299
+ const ipString = toString(ipBuff, 0, ipBuff.length);
3300
+ if (ipString == null) {
3301
+ throw new Error('ipBuff is required');
3302
+ }
3303
+ if (!isIP(ipString)) {
3304
+ throw new Error('invalid ip address');
3305
+ }
3306
+ return ipString;
3307
+ }
3308
+ function port2bytes(port) {
3309
+ const buf = new ArrayBuffer(2);
3310
+ const view = new DataView(buf);
3311
+ view.setUint16(0, port);
3312
+ return new Uint8Array(buf);
3313
+ }
3314
+ function bytes2port(buf) {
3315
+ const view = new DataView(buf.buffer);
3316
+ return view.getUint16(buf.byteOffset);
3317
+ }
3318
+ function str2bytes(str) {
3319
+ const buf = fromString(str);
3320
+ const size = Uint8Array.from(encode$2(buf.length));
3321
+ return concat([size, buf], size.length + buf.length);
3322
+ }
3323
+ function bytes2str(buf) {
3324
+ const size = decode$4(buf);
3325
+ buf = buf.slice(encodingLength$1(size));
3326
+ if (buf.length !== size) {
3327
+ throw new Error('inconsistent lengths');
3328
+ }
3329
+ return toString$1(buf);
3330
+ }
3331
+ function mh2bytes(hash) {
3332
+ let mh;
3333
+ if (hash[0] === 'Q' || hash[0] === '1') {
3334
+ mh = decode$1(base58btc.decode(`z${hash}`)).bytes;
3335
+ }
3336
+ else {
3337
+ mh = CID.parse(hash).multihash.bytes;
3338
+ }
3339
+ // the address is a varint prefixed multihash string representation
3340
+ const size = Uint8Array.from(encode$2(mh.length));
3341
+ return concat([size, mh], size.length + mh.length);
3342
+ }
3343
+ function mb2bytes(mbstr) {
3344
+ const mb = anybaseDecoder.decode(mbstr);
3345
+ const size = Uint8Array.from(encode$2(mb.length));
3346
+ return concat([size, mb], size.length + mb.length);
3347
+ }
3348
+ function bytes2mb(buf) {
3349
+ const size = decode$4(buf);
3350
+ const hash = buf.slice(encodingLength$1(size));
3351
+ if (hash.length !== size) {
3352
+ throw new Error('inconsistent lengths');
3353
+ }
3354
+ return 'u' + toString$1(hash, 'base64url');
3355
+ }
3356
+ /**
3357
+ * Converts bytes to bas58btc string
3358
+ */
3359
+ function bytes2mh(buf) {
3360
+ const size = decode$4(buf);
3361
+ const address = buf.slice(encodingLength$1(size));
3362
+ if (address.length !== size) {
3363
+ throw new Error('inconsistent lengths');
3364
+ }
3365
+ return toString$1(address, 'base58btc');
3366
+ }
3367
+ function onion2bytes(str) {
3368
+ const addr = str.split(':');
3369
+ if (addr.length !== 2) {
3370
+ throw new Error(`failed to parse onion addr: ["'${addr.join('", "')}'"]' does not contain a port number`);
3371
+ }
3372
+ if (addr[0].length !== 16) {
3373
+ throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`);
3374
+ }
3375
+ // onion addresses do not include the multibase prefix, add it before decoding
3376
+ const buf = base32.decode('b' + addr[0]);
3377
+ // onion port number
3378
+ const port = parseInt(addr[1], 10);
3379
+ if (port < 1 || port > 65536) {
3380
+ throw new Error('Port number is not in range(1, 65536)');
3381
+ }
3382
+ const portBuf = port2bytes(port);
3383
+ return concat([buf, portBuf], buf.length + portBuf.length);
3384
+ }
3385
+ function onion32bytes(str) {
3386
+ const addr = str.split(':');
3387
+ if (addr.length !== 2) {
3388
+ throw new Error(`failed to parse onion addr: ["'${addr.join('", "')}'"]' does not contain a port number`);
3389
+ }
3390
+ if (addr[0].length !== 56) {
3391
+ throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`);
3392
+ }
3393
+ // onion addresses do not include the multibase prefix, add it before decoding
3394
+ const buf = base32.decode(`b${addr[0]}`);
3395
+ // onion port number
3396
+ const port = parseInt(addr[1], 10);
3397
+ if (port < 1 || port > 65536) {
3398
+ throw new Error('Port number is not in range(1, 65536)');
3399
+ }
3400
+ const portBuf = port2bytes(port);
3401
+ return concat([buf, portBuf], buf.length + portBuf.length);
3402
+ }
3403
+ function bytes2onion(buf) {
3404
+ const addrBytes = buf.slice(0, buf.length - 2);
3405
+ const portBytes = buf.slice(buf.length - 2);
3406
+ const addr = toString$1(addrBytes, 'base32');
3407
+ const port = bytes2port(portBytes);
3408
+ return `${addr}:${port}`;
3409
+ }
3410
+
3411
+ function stringToMultiaddrParts(str) {
3412
+ str = cleanPath(str);
3413
+ const tuples = [];
3414
+ const stringTuples = [];
3415
+ let path = null;
3416
+ const parts = str.split('/').slice(1);
3417
+ if (parts.length === 1 && parts[0] === '') {
3418
+ return {
3419
+ bytes: new Uint8Array(),
3420
+ string: '/',
3421
+ tuples: [],
3422
+ stringTuples: [],
3423
+ path: null
3424
+ };
3425
+ }
3426
+ for (let p = 0; p < parts.length; p++) {
3427
+ const part = parts[p];
3428
+ const proto = getProtocol(part);
3429
+ if (proto.size === 0) {
3430
+ tuples.push([proto.code]);
3431
+ stringTuples.push([proto.code]);
3432
+ // eslint-disable-next-line no-continue
3433
+ continue;
3434
+ }
3435
+ p++; // advance addr part
3436
+ if (p >= parts.length) {
3437
+ throw ParseError('invalid address: ' + str);
3438
+ }
3439
+ // if it's a path proto, take the rest
3440
+ if (proto.path === true) {
3441
+ // should we need to check each path part to see if it's a proto?
3442
+ // This would allow for other protocols to be added after a unix path,
3443
+ // however it would have issues if the path had a protocol name in the path
3444
+ path = cleanPath(parts.slice(p).join('/'));
3445
+ tuples.push([proto.code, convertToBytes(proto.code, path)]);
3446
+ stringTuples.push([proto.code, path]);
3447
+ break;
3448
+ }
3449
+ const bytes = convertToBytes(proto.code, parts[p]);
3450
+ tuples.push([proto.code, bytes]);
3451
+ stringTuples.push([proto.code, convertToString(proto.code, bytes)]);
3452
+ }
3453
+ return {
3454
+ string: stringTuplesToString(stringTuples),
3455
+ bytes: tuplesToBytes(tuples),
3456
+ tuples,
3457
+ stringTuples,
3458
+ path
3459
+ };
3460
+ }
3461
+ function bytesToMultiaddrParts(bytes) {
3462
+ const tuples = [];
3463
+ const stringTuples = [];
3464
+ let path = null;
3465
+ let i = 0;
3466
+ while (i < bytes.length) {
3467
+ const code = decode$4(bytes, i);
3468
+ const n = encodingLength$1(code);
3469
+ const p = getProtocol(code);
3470
+ const size = sizeForAddr(p, bytes.slice(i + n));
3471
+ if (size === 0) {
3472
+ tuples.push([code]);
3473
+ stringTuples.push([code]);
3474
+ i += n;
3475
+ // eslint-disable-next-line no-continue
3476
+ continue;
3477
+ }
3478
+ const addr = bytes.slice(i + n, i + n + size);
3479
+ i += (size + n);
3480
+ if (i > bytes.length) { // did not end _exactly_ at buffer.length
3481
+ throw ParseError('Invalid address Uint8Array: ' + toString$1(bytes, 'base16'));
3482
+ }
3483
+ // ok, tuple seems good.
3484
+ tuples.push([code, addr]);
3485
+ const stringAddr = convertToString(code, addr);
3486
+ stringTuples.push([code, stringAddr]);
3487
+ if (p.path === true) {
3488
+ // should we need to check each path part to see if it's a proto?
3489
+ // This would allow for other protocols to be added after a unix path,
3490
+ // however it would have issues if the path had a protocol name in the path
3491
+ path = stringAddr;
3492
+ break;
3493
+ }
3494
+ }
3495
+ return {
3496
+ bytes: Uint8Array.from(bytes),
3497
+ string: stringTuplesToString(stringTuples),
3498
+ tuples,
3499
+ stringTuples,
3500
+ path
3501
+ };
3502
+ }
3503
+ /**
3504
+ * [[str name, str addr]... ] -> string
3505
+ */
3506
+ function stringTuplesToString(tuples) {
3507
+ const parts = [];
3508
+ tuples.map((tup) => {
3509
+ const proto = getProtocol(tup[0]);
3510
+ parts.push(proto.name);
3511
+ if (tup.length > 1 && tup[1] != null) {
3512
+ parts.push(tup[1]);
3513
+ }
3514
+ return null;
3515
+ });
3516
+ return cleanPath(parts.join('/'));
3517
+ }
3518
+ /**
3519
+ * [[int code, Uint8Array ]... ] -> Uint8Array
3520
+ */
3521
+ function tuplesToBytes(tuples) {
3522
+ return concat(tuples.map((tup) => {
3523
+ const proto = getProtocol(tup[0]);
3524
+ let buf = Uint8Array.from(encode$2(proto.code));
3525
+ if (tup.length > 1 && tup[1] != null) {
3526
+ buf = concat([buf, tup[1]]); // add address buffer
3527
+ }
3528
+ return buf;
3529
+ }));
3530
+ }
3531
+ /**
3532
+ * For the passed address, return the serialized size
3533
+ */
3534
+ function sizeForAddr(p, addr) {
3535
+ if (p.size > 0) {
3536
+ return p.size / 8;
3537
+ }
3538
+ else if (p.size === 0) {
3539
+ return 0;
3540
+ }
3541
+ else {
3542
+ const size = decode$4(addr instanceof Uint8Array ? addr : Uint8Array.from(addr));
3543
+ return size + encodingLength$1(size);
3544
+ }
3545
+ }
3546
+ function cleanPath(str) {
3547
+ return '/' + str.trim().split('/').filter((a) => a).join('/');
3548
+ }
3549
+ function ParseError(str) {
3550
+ return new Error('Error parsing address: ' + str);
3551
+ }
3552
+
3553
+ const inspect = Symbol.for('nodejs.util.inspect.custom');
3554
+ const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');
3555
+ const DNS_CODES = [
3556
+ getProtocol('dns').code,
3557
+ getProtocol('dns4').code,
3558
+ getProtocol('dns6').code,
3559
+ getProtocol('dnsaddr').code
3560
+ ];
3561
+ class NoAvailableResolverError extends Error {
3562
+ constructor(message = 'No available resolver') {
3563
+ super(message);
3564
+ this.name = 'NoAvailableResolverError';
3565
+ }
3566
+ }
3567
+ /**
3568
+ * Creates a {@link Multiaddr} from a {@link MultiaddrInput}
3569
+ */
3570
+ class Multiaddr {
3571
+ bytes;
3572
+ #string;
3573
+ #tuples;
3574
+ #stringTuples;
3575
+ #path;
3576
+ [symbol] = true;
3577
+ constructor(addr) {
3578
+ // default
3579
+ if (addr == null) {
3580
+ addr = '';
3581
+ }
3582
+ let parts;
3583
+ if (addr instanceof Uint8Array) {
3584
+ parts = bytesToMultiaddrParts(addr);
3585
+ }
3586
+ else if (typeof addr === 'string') {
3587
+ if (addr.length > 0 && addr.charAt(0) !== '/') {
3588
+ throw new Error(`multiaddr "${addr}" must start with a "/"`);
3589
+ }
3590
+ parts = stringToMultiaddrParts(addr);
3591
+ }
3592
+ else if (isMultiaddr(addr)) { // Multiaddr
3593
+ parts = bytesToMultiaddrParts(addr.bytes);
3594
+ }
3595
+ else {
3596
+ throw new Error('addr must be a string, Buffer, or another Multiaddr');
3597
+ }
3598
+ this.bytes = parts.bytes;
3599
+ this.#string = parts.string;
3600
+ this.#tuples = parts.tuples;
3601
+ this.#stringTuples = parts.stringTuples;
3602
+ this.#path = parts.path;
3603
+ }
3604
+ toString() {
3605
+ return this.#string;
3606
+ }
3607
+ toJSON() {
3608
+ return this.toString();
3609
+ }
3610
+ toOptions() {
3611
+ let family;
3612
+ let transport;
3613
+ let host;
3614
+ let port;
3615
+ let zone = '';
3616
+ const tcp = getProtocol('tcp');
3617
+ const udp = getProtocol('udp');
3618
+ const ip4 = getProtocol('ip4');
3619
+ const ip6 = getProtocol('ip6');
3620
+ const dns6 = getProtocol('dns6');
3621
+ const ip6zone = getProtocol('ip6zone');
3622
+ for (const [code, value] of this.stringTuples()) {
3623
+ if (code === ip6zone.code) {
3624
+ zone = `%${value ?? ''}`;
3625
+ }
3626
+ // default to https when protocol & port are omitted from DNS addrs
3627
+ if (DNS_CODES.includes(code)) {
3628
+ transport = tcp.name;
3629
+ port = 443;
3630
+ host = `${value ?? ''}${zone}`;
3631
+ family = code === dns6.code ? 6 : 4;
3632
+ }
3633
+ if (code === tcp.code || code === udp.code) {
3634
+ transport = getProtocol(code).name;
3635
+ port = parseInt(value ?? '');
3636
+ }
3637
+ if (code === ip4.code || code === ip6.code) {
3638
+ transport = getProtocol(code).name;
3639
+ host = `${value ?? ''}${zone}`;
3640
+ family = code === ip6.code ? 6 : 4;
3641
+ }
3642
+ }
3643
+ if (family == null || transport == null || host == null || port == null) {
3644
+ throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');
3645
+ }
3646
+ const opts = {
3647
+ family,
3648
+ host,
3649
+ transport,
3650
+ port
3651
+ };
3652
+ return opts;
3653
+ }
3654
+ protos() {
3655
+ return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)));
3656
+ }
3657
+ protoCodes() {
3658
+ return this.#tuples.map(([code]) => code);
3659
+ }
3660
+ protoNames() {
3661
+ return this.#tuples.map(([code]) => getProtocol(code).name);
3662
+ }
3663
+ tuples() {
3664
+ return this.#tuples.map(([code, value]) => {
3665
+ if (value == null) {
3666
+ return [code];
3667
+ }
3668
+ return [code, value];
3669
+ });
3670
+ }
3671
+ stringTuples() {
3672
+ return this.#stringTuples.map(([code, value]) => {
3673
+ if (value == null) {
3674
+ return [code];
3675
+ }
3676
+ return [code, value];
3677
+ });
3678
+ }
3679
+ encapsulate(addr) {
3680
+ addr = new Multiaddr(addr);
3681
+ return new Multiaddr(this.toString() + addr.toString());
3682
+ }
3683
+ decapsulate(addr) {
3684
+ const addrString = addr.toString();
3685
+ const s = this.toString();
3686
+ const i = s.lastIndexOf(addrString);
3687
+ if (i < 0) {
3688
+ throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`);
3689
+ }
3690
+ return new Multiaddr(s.slice(0, i));
3691
+ }
3692
+ decapsulateCode(code) {
3693
+ const tuples = this.tuples();
3694
+ for (let i = tuples.length - 1; i >= 0; i--) {
3695
+ if (tuples[i][0] === code) {
3696
+ return new Multiaddr(tuplesToBytes(tuples.slice(0, i)));
3697
+ }
3698
+ }
3699
+ return this;
3700
+ }
3701
+ getPeerId() {
3702
+ try {
3703
+ let tuples = [];
3704
+ this.stringTuples().forEach(([code, name]) => {
3705
+ if (code === names.p2p.code) {
3706
+ tuples.push([code, name]);
3707
+ }
3708
+ // if this is a p2p-circuit address, return the target peer id if present
3709
+ // not the peer id of the relay
3710
+ if (code === names['p2p-circuit'].code) {
3711
+ tuples = [];
3712
+ }
3713
+ });
3714
+ // Get the last ipfs tuple ['p2p', 'peerid string']
3715
+ const tuple = tuples.pop();
3716
+ if (tuple?.[1] != null) {
3717
+ const peerIdStr = tuple[1];
3718
+ // peer id is base58btc encoded string but not multibase encoded so add the `z`
3719
+ // prefix so we can validate that it is correctly encoded
3720
+ if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {
3721
+ return toString$1(base58btc.decode(`z${peerIdStr}`), 'base58btc');
3722
+ }
3723
+ // try to parse peer id as CID
3724
+ return toString$1(CID.parse(peerIdStr).multihash.bytes, 'base58btc');
3725
+ }
3726
+ return null;
3727
+ }
3728
+ catch (e) {
3729
+ return null;
3730
+ }
3731
+ }
3732
+ getPath() {
3733
+ return this.#path;
3734
+ }
3735
+ equals(addr) {
3736
+ return equals(this.bytes, addr.bytes);
3737
+ }
3738
+ async resolve(options) {
3739
+ const resolvableProto = this.protos().find((p) => p.resolvable);
3740
+ // Multiaddr is not resolvable?
3741
+ if (resolvableProto == null) {
3742
+ return [this];
3743
+ }
3744
+ const resolver = resolvers.get(resolvableProto.name);
3745
+ if (resolver == null) {
3746
+ throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`);
3747
+ }
3748
+ const result = await resolver(this, options);
3749
+ return result.map(str => multiaddr(str));
3750
+ }
3751
+ nodeAddress() {
3752
+ const options = this.toOptions();
3753
+ if (options.transport !== 'tcp' && options.transport !== 'udp') {
3754
+ throw new Error(`multiaddr must have a valid format - no protocol with name: "${options.transport}". Must have a valid transport protocol: "{tcp, udp}"`);
3755
+ }
3756
+ return {
3757
+ family: options.family,
3758
+ address: options.host,
3759
+ port: options.port
3760
+ };
3761
+ }
3762
+ isThinWaistAddress(addr) {
3763
+ const protos = (addr ?? this).protos();
3764
+ if (protos.length !== 2) {
3765
+ return false;
3766
+ }
3767
+ if (protos[0].code !== 4 && protos[0].code !== 41) {
3768
+ return false;
3769
+ }
3770
+ if (protos[1].code !== 6 && protos[1].code !== 273) {
3771
+ return false;
3772
+ }
3773
+ return true;
3774
+ }
3775
+ /**
3776
+ * Returns Multiaddr as a human-readable string
3777
+ * https://nodejs.org/api/util.html#utilinspectcustom
3778
+ *
3779
+ * @example
3780
+ * ```js
3781
+ * import { multiaddr } from '@multiformats/multiaddr'
3782
+ *
3783
+ * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))
3784
+ * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'
3785
+ * ```
3786
+ */
3787
+ [inspect]() {
3788
+ return `Multiaddr(${this.#string})`;
3789
+ }
3790
+ }
3791
+
3792
+ /**
3793
+ * @packageDocumentation
3794
+ *
3795
+ * A standard way to represent addresses that
3796
+ *
3797
+ * - support any standard network protocol
3798
+ * - are self-describing
3799
+ * - have a binary packed format
3800
+ * - have a nice string representation
3801
+ * - encapsulate well
3802
+ *
3803
+ * @example
3804
+ *
3805
+ * ```TypeScript
3806
+ * import { multiaddr } from '@multiformats/multiaddr'
3807
+ *
3808
+ * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')
3809
+ * // Multiaddr(/ip4/127.0.0.1/udp/1234)
3810
+ *
3811
+ * addr.bytes
3812
+ * // <Uint8Array 04 7f 00 00 01 11 04 d2>
3813
+ *
3814
+ * addr.toString()
3815
+ * // '/ip4/127.0.0.1/udp/1234'
3816
+ *
3817
+ * addr.protos()
3818
+ * // [
3819
+ * // {code: 4, name: 'ip4', size: 32},
3820
+ * // {code: 273, name: 'udp', size: 16}
3821
+ * // ]
3822
+ *
3823
+ * // gives you an object that is friendly with what Node.js core modules expect for addresses
3824
+ * addr.nodeAddress()
3825
+ * // {
3826
+ * // family: 4,
3827
+ * // port: 1234,
3828
+ * // address: "127.0.0.1"
3829
+ * // }
3830
+ *
3831
+ * addr.encapsulate('/sctp/5678')
3832
+ * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)
3833
+ * ```
3834
+ *
3835
+ * ## Resolving DNSADDR addresses
3836
+ *
3837
+ * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.
3838
+ *
3839
+ * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.
3840
+ *
3841
+ * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.
3842
+ *
3843
+ * @example Resolving DNSADDR Multiaddrs
3844
+ *
3845
+ * ```TypeScript
3846
+ * import { multiaddr, resolvers } from '@multiformats/multiaddr'
3847
+ * import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'
3848
+ *
3849
+ * resolvers.set('dnsaddr', dnsaddrResolver)
3850
+ *
3851
+ * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
3852
+ *
3853
+ * // resolve with a 5s timeout
3854
+ * const resolved = await ma.resolve({
3855
+ * signal: AbortSignal.timeout(5000)
3856
+ * })
3857
+ *
3858
+ * console.info(resolved)
3859
+ * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]
3860
+ * ```
3861
+ *
3862
+ * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs
3863
+ *
3864
+ * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.
3865
+ *
3866
+ * ```TypeScript
3867
+ * import { multiaddr } from '@multiformats/multiaddr'
3868
+ * import { dns } from '@multiformats/dns'
3869
+ * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'
3870
+ *
3871
+ * const resolver = dns({
3872
+ * resolvers: {
3873
+ * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')
3874
+ * }
3875
+ * })
3876
+ *
3877
+ * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')
3878
+ * const resolved = await ma.resolve({
3879
+ * dns: resolver
3880
+ * })
3881
+ *
3882
+ * console.info(resolved)
3883
+ * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]
3884
+ * ```
3885
+ */
3886
+ /**
3887
+ * All configured {@link Resolver}s
3888
+ */
3889
+ const resolvers = new Map();
3890
+ /**
3891
+ * Check if object is a {@link Multiaddr} instance
3892
+ *
3893
+ * @example
3894
+ *
3895
+ * ```js
3896
+ * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'
3897
+ *
3898
+ * isMultiaddr(5)
3899
+ * // false
3900
+ * isMultiaddr(multiaddr('/ip4/127.0.0.1'))
3901
+ * // true
3902
+ * ```
3903
+ */
3904
+ function isMultiaddr(value) {
3905
+ return Boolean(value?.[symbol]);
3906
+ }
3907
+ /**
3908
+ * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}
3909
+ *
3910
+ * @example
3911
+ * ```js
3912
+ * import { multiaddr } from '@libp2p/multiaddr'
3913
+ *
3914
+ * multiaddr('/ip4/127.0.0.1/tcp/4001')
3915
+ * // Multiaddr(/ip4/127.0.0.1/tcp/4001)
3916
+ * ```
3917
+ *
3918
+ * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)
3919
+ */
3920
+ function multiaddr(addr) {
3921
+ return new Multiaddr(addr);
3922
+ }
3923
+
2255
3924
  const RelayPingContentTopic = "/relay-ping/1/ping/null";
2256
3925
  const log$2 = new Logger("keep-alive");
2257
3926
  class KeepAliveManager {
@@ -2538,13 +4207,59 @@ class ConnectionManager extends TypedEventEmitter {
2538
4207
  this.startPeerDisconnectionListener();
2539
4208
  this.startNetworkStatusListener();
2540
4209
  }
2541
- async dialPeer(peerId) {
4210
+ /**
4211
+ * Attempts to establish a connection with a peer and set up specified protocols.
4212
+ * The method handles both PeerId and Multiaddr inputs, manages connection attempts,
4213
+ * and maintains the connection state.
4214
+ *
4215
+ * The dialing process includes:
4216
+ * 1. Converting input to dialable peer info
4217
+ * 2. Managing parallel dial attempts
4218
+ * 3. Attempting to establish protocol-specific connections
4219
+ * 4. Handling connection failures and retries
4220
+ * 5. Updating the peer store and connection state
4221
+ *
4222
+ * @param {PeerId | MultiaddrInput} peer - The peer to connect to, either as a PeerId or multiaddr
4223
+ * @param {string[]} [protocolCodecs] - Optional array of protocol-specific codec strings to establish
4224
+ * (e.g., for LightPush, Filter, Store protocols)
4225
+ *
4226
+ * @throws {Error} If the multiaddr is missing a peer ID
4227
+ * @throws {Error} If the maximum dial attempts are reached and the peer cannot be dialed
4228
+ * @throws {Error} If there's an error deleting an undialable peer from the peer store
4229
+ *
4230
+ * @example
4231
+ * ```typescript
4232
+ * // Dial using PeerId
4233
+ * await connectionManager.dialPeer(peerId);
4234
+ *
4235
+ * // Dial using multiaddr with specific protocols
4236
+ * await connectionManager.dialPeer(multiaddr, [
4237
+ * "/vac/waku/relay/2.0.0",
4238
+ * "/vac/waku/lightpush/2.0.0-beta1"
4239
+ * ]);
4240
+ * ```
4241
+ *
4242
+ * @remarks
4243
+ * - The method implements exponential backoff through multiple dial attempts
4244
+ * - Maintains a queue for parallel dial attempts (limited by maxParallelDials)
4245
+ * - Integrates with the KeepAliveManager for connection maintenance
4246
+ * - Updates the peer store and connection state after successful/failed attempts
4247
+ * - If all dial attempts fail, triggers DNS discovery as a fallback
4248
+ */
4249
+ async dialPeer(peer) {
4250
+ let connection;
4251
+ let peerId;
4252
+ const peerDialInfo = this.getDialablePeerInfo(peer);
4253
+ const peerIdStr = isPeerId(peerDialInfo)
4254
+ ? peerDialInfo.toString()
4255
+ : peerDialInfo.getPeerId();
2542
4256
  this.currentActiveParallelDialCount += 1;
2543
4257
  let dialAttempt = 0;
2544
4258
  while (dialAttempt < this.options.maxDialAttemptsForPeer) {
2545
4259
  try {
2546
- log$1.info(`Dialing peer ${peerId.toString()} on attempt ${dialAttempt + 1}`);
2547
- await this.libp2p.dial(peerId);
4260
+ log$1.info(`Dialing peer ${peerDialInfo} on attempt ${dialAttempt + 1}`);
4261
+ connection = await this.libp2p.dial(peerDialInfo);
4262
+ peerId = connection.remotePeer;
2548
4263
  const tags = await this.getTagNamesForPeer(peerId);
2549
4264
  // add tag to connection describing discovery mechanism
2550
4265
  // don't add duplicate tags
@@ -2561,15 +4276,15 @@ class ConnectionManager extends TypedEventEmitter {
2561
4276
  catch (error) {
2562
4277
  if (error instanceof AggregateError) {
2563
4278
  // Handle AggregateError
2564
- log$1.error(`Error dialing peer ${peerId.toString()} - ${error.errors}`);
4279
+ log$1.error(`Error dialing peer ${peerIdStr} - ${error.errors}`);
2565
4280
  }
2566
4281
  else {
2567
4282
  // Handle generic error
2568
- log$1.error(`Error dialing peer ${peerId.toString()} - ${error.message}`);
4283
+ log$1.error(`Error dialing peer ${peerIdStr} - ${error.message}`);
2569
4284
  }
2570
- this.dialErrorsForPeer.set(peerId.toString(), error);
4285
+ this.dialErrorsForPeer.set(peerIdStr, error);
2571
4286
  dialAttempt++;
2572
- this.dialAttemptsForPeer.set(peerId.toString(), dialAttempt);
4287
+ this.dialAttemptsForPeer.set(peerIdStr, dialAttempt);
2573
4288
  }
2574
4289
  }
2575
4290
  // Always decrease the active dial count and process the dial queue
@@ -2578,7 +4293,7 @@ class ConnectionManager extends TypedEventEmitter {
2578
4293
  // If max dial attempts reached and dialing failed, delete the peer
2579
4294
  if (dialAttempt === this.options.maxDialAttemptsForPeer) {
2580
4295
  try {
2581
- const error = this.dialErrorsForPeer.get(peerId.toString());
4296
+ const error = this.dialErrorsForPeer.get(peerIdStr);
2582
4297
  if (error) {
2583
4298
  let errorMessage;
2584
4299
  if (error instanceof AggregateError) {
@@ -2595,16 +4310,52 @@ class ConnectionManager extends TypedEventEmitter {
2595
4310
  else {
2596
4311
  errorMessage = error.message;
2597
4312
  }
2598
- log$1.info(`Deleting undialable peer ${peerId.toString()} from peer store. Reason: ${errorMessage}`);
4313
+ log$1.info(`Deleting undialable peer ${peerIdStr} from peer store. Reason: ${errorMessage}`);
4314
+ }
4315
+ this.dialErrorsForPeer.delete(peerIdStr);
4316
+ if (peerId) {
4317
+ await this.libp2p.peerStore.delete(peerId);
2599
4318
  }
2600
- this.dialErrorsForPeer.delete(peerId.toString());
2601
- await this.libp2p.peerStore.delete(peerId);
2602
4319
  // if it was last available peer - attempt DNS discovery
2603
4320
  await this.attemptDnsDiscovery();
2604
4321
  }
2605
4322
  catch (error) {
2606
- throw new Error(`Error deleting undialable peer ${peerId.toString()} from peer store - ${error}`);
4323
+ throw new Error(`Error deleting undialable peer ${peerIdStr} from peer store - ${error}`);
4324
+ }
4325
+ }
4326
+ if (!connection) {
4327
+ throw new Error(`Failed to dial peer ${peerDialInfo}`);
4328
+ }
4329
+ return connection;
4330
+ }
4331
+ /**
4332
+ * Dial a peer with specific protocols.
4333
+ * This method is a raw proxy to the libp2p dialProtocol method.
4334
+ * @param peer - The peer to connect to, either as a PeerId or multiaddr
4335
+ * @param protocolCodecs - Optional array of protocol-specific codec strings to establish
4336
+ * @returns A stream to the peer
4337
+ */
4338
+ async rawDialPeerWithProtocols(peer, protocolCodecs) {
4339
+ const peerDialInfo = this.getDialablePeerInfo(peer);
4340
+ return await this.libp2p.dialProtocol(peerDialInfo, protocolCodecs);
4341
+ }
4342
+ /**
4343
+ * Internal utility to extract a PeerId or Multiaddr from a peer input.
4344
+ * This is used internally by the connection manager to handle different peer input formats.
4345
+ * @internal
4346
+ */
4347
+ getDialablePeerInfo(peer) {
4348
+ if (isPeerId(peer)) {
4349
+ return peer;
4350
+ }
4351
+ else {
4352
+ // peer is of MultiaddrInput type
4353
+ const ma = multiaddr(peer);
4354
+ const peerIdStr = ma.getPeerId();
4355
+ if (!peerIdStr) {
4356
+ throw new Error("Failed to dial multiaddr: missing peer ID");
2607
4357
  }
4358
+ return ma;
2608
4359
  }
2609
4360
  }
2610
4361
  async attemptDnsDiscovery() {
@@ -2841,75 +4592,6 @@ class ConnectionManager extends TypedEventEmitter {
2841
4592
  }
2842
4593
  }
2843
4594
 
2844
- class HealthManager {
2845
- static instance;
2846
- health;
2847
- constructor() {
2848
- this.health = {
2849
- overallStatus: HealthStatus.Unhealthy,
2850
- protocolStatuses: new Map()
2851
- };
2852
- }
2853
- static getInstance() {
2854
- if (!HealthManager.instance) {
2855
- HealthManager.instance = new HealthManager();
2856
- }
2857
- return HealthManager.instance;
2858
- }
2859
- getHealthStatus() {
2860
- return this.health.overallStatus;
2861
- }
2862
- getProtocolStatus(protocol) {
2863
- return this.health.protocolStatuses.get(protocol);
2864
- }
2865
- updateProtocolHealth(multicodec, connectedPeers) {
2866
- const protocol = this.getNameFromMulticodec(multicodec);
2867
- let status = HealthStatus.Unhealthy;
2868
- if (connectedPeers == 1) {
2869
- status = HealthStatus.MinimallyHealthy;
2870
- }
2871
- else if (connectedPeers >= 2) {
2872
- status = HealthStatus.SufficientlyHealthy;
2873
- }
2874
- this.health.protocolStatuses.set(protocol, {
2875
- name: protocol,
2876
- status: status,
2877
- lastUpdate: new Date()
2878
- });
2879
- this.updateOverallHealth();
2880
- }
2881
- getNameFromMulticodec(multicodec) {
2882
- let name;
2883
- if (multicodec.includes("filter")) {
2884
- name = Protocols.Filter;
2885
- }
2886
- else if (multicodec.includes("lightpush")) {
2887
- name = Protocols.LightPush;
2888
- }
2889
- else if (multicodec.includes("store")) {
2890
- name = Protocols.Store;
2891
- }
2892
- else {
2893
- throw new Error(`Unknown protocol: ${multicodec}`);
2894
- }
2895
- return name;
2896
- }
2897
- updateOverallHealth() {
2898
- const relevantProtocols = [Protocols.LightPush, Protocols.Filter];
2899
- const statuses = relevantProtocols.map((p) => this.getProtocolStatus(p)?.status);
2900
- if (statuses.some((status) => status === HealthStatus.Unhealthy)) {
2901
- this.health.overallStatus = HealthStatus.Unhealthy;
2902
- }
2903
- else if (statuses.some((status) => status === HealthStatus.MinimallyHealthy)) {
2904
- this.health.overallStatus = HealthStatus.MinimallyHealthy;
2905
- }
2906
- else {
2907
- this.health.overallStatus = HealthStatus.SufficientlyHealthy;
2908
- }
2909
- }
2910
- }
2911
- const getHealthManager = () => HealthManager.getInstance();
2912
-
2913
4595
  const log = new Logger("metadata");
2914
4596
  const MetadataCodec = "/vac/waku/metadata/1.0.0";
2915
4597
  class Metadata extends BaseProtocol {
@@ -2938,7 +4620,7 @@ class Metadata extends BaseProtocol {
2938
4620
  }
2939
4621
  let stream;
2940
4622
  try {
2941
- stream = await this.getStream(peer);
4623
+ stream = await this.getStream(peerId);
2942
4624
  }
2943
4625
  catch (error) {
2944
4626
  log.error("Failed to get stream", error);
@@ -3021,4 +4703,4 @@ function wakuMetadata(pubsubTopics) {
3021
4703
  return (components) => new Metadata(pubsubTopics, components);
3022
4704
  }
3023
4705
 
3024
- export { ConnectionManager, FilterCodecs, FilterCore, 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 };
4706
+ export { ConnectionManager, FilterCodecs, FilterCore, LightPushCodec, LightPushCore, MetadataCodec, StoreCodec, StoreCore, createEncoder, index$3 as message, wakuMetadata, index$2 as waku_filter, index$1 as waku_light_push, index as waku_store };