@waku/core 0.0.1

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 (235) hide show
  1. package/CHANGELOG.md +614 -0
  2. package/README.md +56 -0
  3. package/bundle/browser-1e1a2f27.js +722 -0
  4. package/bundle/crypto-8551d579.js +2585 -0
  5. package/bundle/crypto-b00764b7.js +1772 -0
  6. package/bundle/enr-564d4a51.js +20785 -0
  7. package/bundle/enr-9fc5eed8.js +20786 -0
  8. package/bundle/enr-f6e82a53.js +20785 -0
  9. package/bundle/events-158407bb.js +1929 -0
  10. package/bundle/events-fcbda4dc.js +76 -0
  11. package/bundle/index-02d21809.js +20 -0
  12. package/bundle/index-0a4bdddc.js +2976 -0
  13. package/bundle/index-2ae915be.js +1854 -0
  14. package/bundle/index-64ce43f0.js +69 -0
  15. package/bundle/index-691c0be6.js +4059 -0
  16. package/bundle/index-a013a259.js +20 -0
  17. package/bundle/index-ba42b4fc.js +862 -0
  18. package/bundle/index.js +13428 -0
  19. package/bundle/lib/enr.js +8 -0
  20. package/bundle/lib/peer_discovery_dns.js +5018 -0
  21. package/bundle/lib/peer_discovery_static_list.js +75 -0
  22. package/bundle/lib/predefined_bootstrap_nodes.js +59 -0
  23. package/bundle/lib/utils.js +1 -0
  24. package/bundle/lib/wait_for_remote_peer.js +327 -0
  25. package/bundle/lib/waku_message/topic_only_message.js +4 -0
  26. package/bundle/lib/waku_message/version_0.js +4 -0
  27. package/bundle/lib/waku_message/version_1.js +463 -0
  28. package/bundle/message-e2db79d7.js +8393 -0
  29. package/bundle/multiaddr_to_peer_info-c406b1e1.js +19 -0
  30. package/bundle/multiaddr_to_peer_info-fd1de516.js +19 -0
  31. package/bundle/random_subset-75d1c511.js +26 -0
  32. package/bundle/topic_only_message-34f36fa6.js +82 -0
  33. package/bundle/utils-9a3221f2.js +815 -0
  34. package/bundle/version_0-e6fe440c.js +317 -0
  35. package/dist/index.d.ts +16 -0
  36. package/dist/index.js +17 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/lib/constants.d.ts +4 -0
  39. package/dist/lib/constants.js +5 -0
  40. package/dist/lib/constants.js.map +1 -0
  41. package/dist/lib/crypto.d.ts +34 -0
  42. package/dist/lib/crypto.js +79 -0
  43. package/dist/lib/crypto.js.map +1 -0
  44. package/dist/lib/enr/constants.d.ts +4 -0
  45. package/dist/lib/enr/constants.js +8 -0
  46. package/dist/lib/enr/constants.js.map +1 -0
  47. package/dist/lib/enr/enr.d.ts +90 -0
  48. package/dist/lib/enr/enr.js +432 -0
  49. package/dist/lib/enr/enr.js.map +1 -0
  50. package/dist/lib/enr/index.d.ts +5 -0
  51. package/dist/lib/enr/index.js +6 -0
  52. package/dist/lib/enr/index.js.map +1 -0
  53. package/dist/lib/enr/keypair/index.d.ts +8 -0
  54. package/dist/lib/enr/keypair/index.js +53 -0
  55. package/dist/lib/enr/keypair/index.js.map +1 -0
  56. package/dist/lib/enr/keypair/secp256k1.d.ts +13 -0
  57. package/dist/lib/enr/keypair/secp256k1.js +57 -0
  58. package/dist/lib/enr/keypair/secp256k1.js.map +1 -0
  59. package/dist/lib/enr/keypair/types.d.ts +13 -0
  60. package/dist/lib/enr/keypair/types.js +7 -0
  61. package/dist/lib/enr/keypair/types.js.map +1 -0
  62. package/dist/lib/enr/multiaddr_from_fields.d.ts +2 -0
  63. package/dist/lib/enr/multiaddr_from_fields.js +8 -0
  64. package/dist/lib/enr/multiaddr_from_fields.js.map +1 -0
  65. package/dist/lib/enr/multiaddrs_codec.d.ts +3 -0
  66. package/dist/lib/enr/multiaddrs_codec.js +32 -0
  67. package/dist/lib/enr/multiaddrs_codec.js.map +1 -0
  68. package/dist/lib/enr/types.d.ts +8 -0
  69. package/dist/lib/enr/types.js +3 -0
  70. package/dist/lib/enr/types.js.map +1 -0
  71. package/dist/lib/enr/v4.d.ts +3 -0
  72. package/dist/lib/enr/v4.js +14 -0
  73. package/dist/lib/enr/v4.js.map +1 -0
  74. package/dist/lib/enr/waku2_codec.d.ts +8 -0
  75. package/dist/lib/enr/waku2_codec.js +36 -0
  76. package/dist/lib/enr/waku2_codec.js.map +1 -0
  77. package/dist/lib/group_by.d.ts +3 -0
  78. package/dist/lib/group_by.js +13 -0
  79. package/dist/lib/group_by.js.map +1 -0
  80. package/dist/lib/multiaddr_to_peer_info.d.ts +3 -0
  81. package/dist/lib/multiaddr_to_peer_info.js +15 -0
  82. package/dist/lib/multiaddr_to_peer_info.js.map +1 -0
  83. package/dist/lib/peer_discovery_dns/dns.d.ts +48 -0
  84. package/dist/lib/peer_discovery_dns/dns.js +158 -0
  85. package/dist/lib/peer_discovery_dns/dns.js.map +1 -0
  86. package/dist/lib/peer_discovery_dns/dns_over_https.d.ts +32 -0
  87. package/dist/lib/peer_discovery_dns/dns_over_https.js +87 -0
  88. package/dist/lib/peer_discovery_dns/dns_over_https.js.map +1 -0
  89. package/dist/lib/peer_discovery_dns/enrtree.d.ts +33 -0
  90. package/dist/lib/peer_discovery_dns/enrtree.js +76 -0
  91. package/dist/lib/peer_discovery_dns/enrtree.js.map +1 -0
  92. package/dist/lib/peer_discovery_dns/fetch_nodes.d.ts +14 -0
  93. package/dist/lib/peer_discovery_dns/fetch_nodes.js +133 -0
  94. package/dist/lib/peer_discovery_dns/fetch_nodes.js.map +1 -0
  95. package/dist/lib/peer_discovery_dns/index.d.ts +30 -0
  96. package/dist/lib/peer_discovery_dns/index.js +54 -0
  97. package/dist/lib/peer_discovery_dns/index.js.map +1 -0
  98. package/dist/lib/peer_discovery_static_list.d.ts +44 -0
  99. package/dist/lib/peer_discovery_static_list.js +72 -0
  100. package/dist/lib/peer_discovery_static_list.js.map +1 -0
  101. package/dist/lib/predefined_bootstrap_nodes.d.ts +35 -0
  102. package/dist/lib/predefined_bootstrap_nodes.js +56 -0
  103. package/dist/lib/predefined_bootstrap_nodes.js.map +1 -0
  104. package/dist/lib/push_or_init_map.d.ts +1 -0
  105. package/dist/lib/push_or_init_map.js +9 -0
  106. package/dist/lib/push_or_init_map.js.map +1 -0
  107. package/dist/lib/random_subset.d.ts +4 -0
  108. package/dist/lib/random_subset.js +25 -0
  109. package/dist/lib/random_subset.js.map +1 -0
  110. package/dist/lib/select_connection.d.ts +2 -0
  111. package/dist/lib/select_connection.js +19 -0
  112. package/dist/lib/select_connection.js.map +1 -0
  113. package/dist/lib/select_peer.d.ts +15 -0
  114. package/dist/lib/select_peer.js +59 -0
  115. package/dist/lib/select_peer.js.map +1 -0
  116. package/dist/lib/to_proto_message.d.ts +3 -0
  117. package/dist/lib/to_proto_message.js +11 -0
  118. package/dist/lib/to_proto_message.js.map +1 -0
  119. package/dist/lib/utils.d.ts +22 -0
  120. package/dist/lib/utils.js +40 -0
  121. package/dist/lib/utils.js.map +1 -0
  122. package/dist/lib/wait_for_remote_peer.d.ts +22 -0
  123. package/dist/lib/wait_for_remote_peer.js +113 -0
  124. package/dist/lib/wait_for_remote_peer.js.map +1 -0
  125. package/dist/lib/waku.d.ts +61 -0
  126. package/dist/lib/waku.js +174 -0
  127. package/dist/lib/waku.js.map +1 -0
  128. package/dist/lib/waku_filter/filter_rpc.d.ts +25 -0
  129. package/dist/lib/waku_filter/filter_rpc.js +44 -0
  130. package/dist/lib/waku_filter/filter_rpc.js.map +1 -0
  131. package/dist/lib/waku_filter/index.d.ts +50 -0
  132. package/dist/lib/waku_filter/index.js +181 -0
  133. package/dist/lib/waku_filter/index.js.map +1 -0
  134. package/dist/lib/waku_light_push/index.d.ts +38 -0
  135. package/dist/lib/waku_light_push/index.js +83 -0
  136. package/dist/lib/waku_light_push/index.js.map +1 -0
  137. package/dist/lib/waku_light_push/push_rpc.d.ts +11 -0
  138. package/dist/lib/waku_light_push/push_rpc.js +31 -0
  139. package/dist/lib/waku_light_push/push_rpc.js.map +1 -0
  140. package/dist/lib/waku_message/constants.d.ts +12 -0
  141. package/dist/lib/waku_message/constants.js +10 -0
  142. package/dist/lib/waku_message/constants.js.map +1 -0
  143. package/dist/lib/waku_message/ecies.d.ts +17 -0
  144. package/dist/lib/waku_message/ecies.js +126 -0
  145. package/dist/lib/waku_message/ecies.js.map +1 -0
  146. package/dist/lib/waku_message/symmetric.d.ts +3 -0
  147. package/dist/lib/waku_message/symmetric.js +18 -0
  148. package/dist/lib/waku_message/symmetric.js.map +1 -0
  149. package/dist/lib/waku_message/topic_only_message.d.ts +15 -0
  150. package/dist/lib/waku_message/topic_only_message.js +31 -0
  151. package/dist/lib/waku_message/topic_only_message.js.map +1 -0
  152. package/dist/lib/waku_message/version_0.d.ts +26 -0
  153. package/dist/lib/waku_message/version_0.js +96 -0
  154. package/dist/lib/waku_message/version_0.js.map +1 -0
  155. package/dist/lib/waku_message/version_1.d.ts +93 -0
  156. package/dist/lib/waku_message/version_1.js +325 -0
  157. package/dist/lib/waku_message/version_1.js.map +1 -0
  158. package/dist/lib/waku_relay/constants.d.ts +63 -0
  159. package/dist/lib/waku_relay/constants.js +67 -0
  160. package/dist/lib/waku_relay/constants.js.map +1 -0
  161. package/dist/lib/waku_relay/index.d.ts +65 -0
  162. package/dist/lib/waku_relay/index.js +111 -0
  163. package/dist/lib/waku_relay/index.js.map +1 -0
  164. package/dist/lib/waku_store/history_rpc.d.ts +27 -0
  165. package/dist/lib/waku_store/history_rpc.js +71 -0
  166. package/dist/lib/waku_store/history_rpc.js.map +1 -0
  167. package/dist/lib/waku_store/index.d.ts +126 -0
  168. package/dist/lib/waku_store/index.js +218 -0
  169. package/dist/lib/waku_store/index.js.map +1 -0
  170. package/dist/proto/filter.d.ts +65 -0
  171. package/dist/proto/filter.js +425 -0
  172. package/dist/proto/filter.js.map +1 -0
  173. package/dist/proto/light_push.d.ts +57 -0
  174. package/dist/proto/light_push.js +369 -0
  175. package/dist/proto/light_push.js.map +1 -0
  176. package/dist/proto/message.d.ts +29 -0
  177. package/dist/proto/message.js +215 -0
  178. package/dist/proto/message.js.map +1 -0
  179. package/dist/proto/store.d.ts +104 -0
  180. package/dist/proto/store.js +602 -0
  181. package/dist/proto/store.js.map +1 -0
  182. package/dist/proto/topic_only_message.d.ts +10 -0
  183. package/dist/proto/topic_only_message.js +46 -0
  184. package/dist/proto/topic_only_message.js.map +1 -0
  185. package/package.json +292 -0
  186. package/src/index.ts +33 -0
  187. package/src/lib/constants.ts +4 -0
  188. package/src/lib/crypto.ts +100 -0
  189. package/src/lib/enr/constants.ts +10 -0
  190. package/src/lib/enr/enr.ts +516 -0
  191. package/src/lib/enr/index.ts +5 -0
  192. package/src/lib/enr/keypair/index.ts +76 -0
  193. package/src/lib/enr/keypair/secp256k1.ts +69 -0
  194. package/src/lib/enr/keypair/types.ts +14 -0
  195. package/src/lib/enr/multiaddr_from_fields.ts +18 -0
  196. package/src/lib/enr/multiaddrs_codec.ts +50 -0
  197. package/src/lib/enr/types.ts +11 -0
  198. package/src/lib/enr/v4.ts +22 -0
  199. package/src/lib/enr/waku2_codec.ts +39 -0
  200. package/src/lib/group_by.ts +14 -0
  201. package/src/lib/multiaddr_to_peer_info.ts +17 -0
  202. package/src/lib/peer_discovery_dns/dns.ts +223 -0
  203. package/src/lib/peer_discovery_dns/dns_over_https.ts +98 -0
  204. package/src/lib/peer_discovery_dns/enrtree.ts +123 -0
  205. package/src/lib/peer_discovery_dns/fetch_nodes.ts +180 -0
  206. package/src/lib/peer_discovery_dns/index.ts +84 -0
  207. package/src/lib/peer_discovery_static_list.ts +118 -0
  208. package/src/lib/predefined_bootstrap_nodes.ts +72 -0
  209. package/src/lib/push_or_init_map.ts +13 -0
  210. package/src/lib/random_subset.ts +30 -0
  211. package/src/lib/select_connection.ts +24 -0
  212. package/src/lib/select_peer.ts +77 -0
  213. package/src/lib/to_proto_message.ts +15 -0
  214. package/src/lib/utils.ts +50 -0
  215. package/src/lib/wait_for_remote_peer.ts +151 -0
  216. package/src/lib/waku.ts +258 -0
  217. package/src/lib/waku_filter/filter_rpc.ts +57 -0
  218. package/src/lib/waku_filter/index.ts +291 -0
  219. package/src/lib/waku_light_push/index.ts +137 -0
  220. package/src/lib/waku_light_push/push_rpc.ts +39 -0
  221. package/src/lib/waku_message/constants.ts +10 -0
  222. package/src/lib/waku_message/ecies.ts +194 -0
  223. package/src/lib/waku_message/symmetric.ts +33 -0
  224. package/src/lib/waku_message/topic_only_message.ts +40 -0
  225. package/src/lib/waku_message/version_0.ts +121 -0
  226. package/src/lib/waku_message/version_1.ts +457 -0
  227. package/src/lib/waku_relay/constants.ts +77 -0
  228. package/src/lib/waku_relay/index.ts +189 -0
  229. package/src/lib/waku_store/history_rpc.ts +94 -0
  230. package/src/lib/waku_store/index.ts +372 -0
  231. package/src/proto/filter.ts +602 -0
  232. package/src/proto/light_push.ts +526 -0
  233. package/src/proto/message.ts +304 -0
  234. package/src/proto/store.ts +844 -0
  235. package/src/proto/topic_only_message.ts +67 -0
@@ -0,0 +1,2976 @@
1
+ import { e as errCode } from './index-64ce43f0.js';
2
+
3
+ /* eslint-disable @typescript-eslint/no-unsafe-return */
4
+ // We don't care about how the IP is invalid. Save time in the error case by using a single error
5
+ const err = new Error("Invalid IP");
6
+ class Parser {
7
+ index = 0;
8
+ input = "";
9
+ new(input) {
10
+ this.index = 0;
11
+ this.input = input;
12
+ return this;
13
+ }
14
+ /** Run a parser, and restore the pre-parse state if it fails. */
15
+ readAtomically(fn) {
16
+ const index = this.index;
17
+ try {
18
+ return fn();
19
+ }
20
+ catch (e) {
21
+ this.index = index;
22
+ throw e;
23
+ }
24
+ }
25
+ /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */
26
+ parseWith(fn) {
27
+ const result = fn();
28
+ if (this.index !== this.input.length) {
29
+ throw err;
30
+ }
31
+ return result;
32
+ }
33
+ /** Peek the next character from the input */
34
+ peekChar() {
35
+ if (this.index >= this.input.length) {
36
+ throw err;
37
+ }
38
+ return this.input[this.index];
39
+ }
40
+ /** Read the next character from the input */
41
+ readChar() {
42
+ if (this.index >= this.input.length) {
43
+ throw err;
44
+ }
45
+ return this.input[this.index++];
46
+ }
47
+ /** Read the next character from the input if it matches the target. */
48
+ readGivenChar(target) {
49
+ return this.readAtomically(() => {
50
+ const char = this.readChar();
51
+ if (char !== target) {
52
+ throw err;
53
+ }
54
+ });
55
+ }
56
+ /**
57
+ * Helper for reading separators in an indexed loop. Reads the separator
58
+ * character iff index > 0, then runs the parser. When used in a loop,
59
+ * the separator character will only be read on index > 0 (see
60
+ * readIPv4Addr for an example)
61
+ */
62
+ readSeparator(sep, index, inner) {
63
+ return this.readAtomically(() => {
64
+ if (index > 0) {
65
+ this.readGivenChar(sep);
66
+ }
67
+ return inner();
68
+ });
69
+ }
70
+ /**
71
+ * Read a number off the front of the input in the given radix, stopping
72
+ * at the first non-digit character or eof. Fails if the number has more
73
+ * digits than max_digits or if there is no number.
74
+ */
75
+ readNumber(radix, maxDigits, allowZeroPrefix, maxBytes) {
76
+ return this.readAtomically(() => {
77
+ let result = 0;
78
+ let digitCount = 0;
79
+ const hasLeadingZero = this.peekChar() === "0";
80
+ const maxValue = 2 ** (8 * maxBytes) - 1;
81
+ // eslint-disable-next-line no-constant-condition
82
+ while (true) {
83
+ let digit;
84
+ try {
85
+ digit = this.readAtomically(() => {
86
+ const num = Number.parseInt(this.readChar(), radix);
87
+ if (Number.isNaN(num)) {
88
+ throw err;
89
+ }
90
+ return num;
91
+ });
92
+ }
93
+ catch (e) {
94
+ break;
95
+ }
96
+ result *= radix;
97
+ result += digit;
98
+ if (result > maxValue) {
99
+ throw err;
100
+ }
101
+ digitCount += 1;
102
+ if (maxDigits !== undefined) {
103
+ if (digitCount > maxDigits) {
104
+ throw err;
105
+ }
106
+ }
107
+ }
108
+ if (digitCount === 0) {
109
+ throw err;
110
+ }
111
+ else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {
112
+ throw err;
113
+ }
114
+ else {
115
+ return result;
116
+ }
117
+ });
118
+ }
119
+ /** Read an IPv4 address. */
120
+ readIPv4Addr() {
121
+ return this.readAtomically(() => {
122
+ const out = new Uint8Array(4);
123
+ for (let i = 0; i < out.length; i++) {
124
+ out[i] = this.readSeparator(".", i, () => this.readNumber(10, 3, false, 1));
125
+ }
126
+ return out;
127
+ });
128
+ }
129
+ /** Read an IPv6 Address. */
130
+ readIPv6Addr() {
131
+ /**
132
+ * Read a chunk of an IPv6 address into `groups`. Returns the number
133
+ * of groups read, along with a bool indicating if an embedded
134
+ * trailing IPv4 address was read. Specifically, read a series of
135
+ * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional
136
+ * trailing embedded IPv4 address.
137
+ */
138
+ const readGroups = (groups) => {
139
+ for (let i = 0; i < groups.length / 2; i++) {
140
+ const ix = i * 2;
141
+ // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.
142
+ if (i < groups.length - 3) {
143
+ try {
144
+ const ipv4 = this.readSeparator(":", i, () => this.readIPv4Addr());
145
+ groups[ix] = ipv4[0];
146
+ groups[ix + 1] = ipv4[1];
147
+ groups[ix + 2] = ipv4[2];
148
+ groups[ix + 3] = ipv4[3];
149
+ return [ix + 4, true];
150
+ // eslint-disable-next-line no-empty
151
+ }
152
+ catch (e) { }
153
+ }
154
+ try {
155
+ const group = this.readSeparator(":", i, () => this.readNumber(16, 4, true, 2));
156
+ groups[ix] = group >> 8;
157
+ groups[ix + 1] = group & 255;
158
+ }
159
+ catch (e) {
160
+ return [ix, false];
161
+ }
162
+ }
163
+ return [groups.length, false];
164
+ };
165
+ return this.readAtomically(() => {
166
+ // Read the front part of the address; either the whole thing, or up to the first ::
167
+ const head = new Uint8Array(16);
168
+ const [headSize, headIp4] = readGroups(head);
169
+ if (headSize === 16) {
170
+ return head;
171
+ }
172
+ // IPv4 part is not allowed before `::`
173
+ if (headIp4) {
174
+ throw err;
175
+ }
176
+ // Read `::` if previous code parsed less than 8 groups.
177
+ // `::` indicates one or more groups of 16 bits of zeros.
178
+ this.readGivenChar(":");
179
+ this.readGivenChar(":");
180
+ // Read the back part of the address. The :: must contain at least one
181
+ // set of zeroes, so our max length is 7.
182
+ const tail = new Uint8Array(14);
183
+ const limit = 16 - (headSize + 2);
184
+ const [tailSize] = readGroups(tail.subarray(0, limit));
185
+ // Concat the head and tail of the IP address
186
+ head.set(tail.subarray(0, tailSize), 16 - tailSize);
187
+ return head;
188
+ });
189
+ }
190
+ /** Read an IP Address, either IPv4 or IPv6. */
191
+ readIPAddr() {
192
+ try {
193
+ return this.readIPv4Addr();
194
+ }
195
+ catch (e) {
196
+ return this.readIPv6Addr();
197
+ }
198
+ }
199
+ }
200
+
201
+ // See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address
202
+ const MAX_IPV6_LENGTH = 45;
203
+ const MAX_IPV4_LENGTH = 15;
204
+ const parser = new Parser();
205
+ /** Parse `input` into IPv4 bytes. */
206
+ function parseIPv4(input) {
207
+ if (input.length > MAX_IPV4_LENGTH) {
208
+ throw err;
209
+ }
210
+ return parser.new(input).parseWith(() => parser.readIPv4Addr());
211
+ }
212
+ /** Parse `input` into IPv6 bytes. */
213
+ function parseIPv6(input) {
214
+ if (input.length > MAX_IPV6_LENGTH) {
215
+ throw err;
216
+ }
217
+ return parser.new(input).parseWith(() => parser.readIPv6Addr());
218
+ }
219
+ /** Parse `input` into IPv4 or IPv6 bytes. */
220
+ function parseIP(input) {
221
+ if (input.length > MAX_IPV6_LENGTH) {
222
+ throw err;
223
+ }
224
+ return parser.new(input).parseWith(() => parser.readIPAddr());
225
+ }
226
+ /** Check if `input` is IPv4. */
227
+ function isIPv4(input) {
228
+ try {
229
+ parseIPv4(input);
230
+ return true;
231
+ }
232
+ catch (e) {
233
+ return false;
234
+ }
235
+ }
236
+ /** Check if `input` is IPv6. */
237
+ function isIPv6(input) {
238
+ try {
239
+ parseIPv6(input);
240
+ return true;
241
+ }
242
+ catch (e) {
243
+ return false;
244
+ }
245
+ }
246
+ /** Check if `input` is IPv4 or IPv6. */
247
+ function isIP(input) {
248
+ try {
249
+ parseIP(input);
250
+ return true;
251
+ }
252
+ catch (e) {
253
+ return false;
254
+ }
255
+ }
256
+
257
+ // base-x encoding / decoding
258
+ // Copyright (c) 2018 base-x contributors
259
+ // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
260
+ // Distributed under the MIT software license, see the accompanying
261
+ // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
262
+ function base (ALPHABET, name) {
263
+ if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
264
+ var BASE_MAP = new Uint8Array(256);
265
+ for (var j = 0; j < BASE_MAP.length; j++) {
266
+ BASE_MAP[j] = 255;
267
+ }
268
+ for (var i = 0; i < ALPHABET.length; i++) {
269
+ var x = ALPHABET.charAt(i);
270
+ var xc = x.charCodeAt(0);
271
+ if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
272
+ BASE_MAP[xc] = i;
273
+ }
274
+ var BASE = ALPHABET.length;
275
+ var LEADER = ALPHABET.charAt(0);
276
+ var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
277
+ var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
278
+ function encode (source) {
279
+ if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
280
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
281
+ } else if (Array.isArray(source)) {
282
+ source = Uint8Array.from(source);
283
+ }
284
+ if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
285
+ if (source.length === 0) { return '' }
286
+ // Skip & count leading zeroes.
287
+ var zeroes = 0;
288
+ var length = 0;
289
+ var pbegin = 0;
290
+ var pend = source.length;
291
+ while (pbegin !== pend && source[pbegin] === 0) {
292
+ pbegin++;
293
+ zeroes++;
294
+ }
295
+ // Allocate enough space in big-endian base58 representation.
296
+ var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
297
+ var b58 = new Uint8Array(size);
298
+ // Process the bytes.
299
+ while (pbegin !== pend) {
300
+ var carry = source[pbegin];
301
+ // Apply "b58 = b58 * 256 + ch".
302
+ var i = 0;
303
+ for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
304
+ carry += (256 * b58[it1]) >>> 0;
305
+ b58[it1] = (carry % BASE) >>> 0;
306
+ carry = (carry / BASE) >>> 0;
307
+ }
308
+ if (carry !== 0) { throw new Error('Non-zero carry') }
309
+ length = i;
310
+ pbegin++;
311
+ }
312
+ // Skip leading zeroes in base58 result.
313
+ var it2 = size - length;
314
+ while (it2 !== size && b58[it2] === 0) {
315
+ it2++;
316
+ }
317
+ // Translate the result into a string.
318
+ var str = LEADER.repeat(zeroes);
319
+ for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
320
+ return str
321
+ }
322
+ function decodeUnsafe (source) {
323
+ if (typeof source !== 'string') { throw new TypeError('Expected String') }
324
+ if (source.length === 0) { return new Uint8Array() }
325
+ var psz = 0;
326
+ // Skip leading spaces.
327
+ if (source[psz] === ' ') { return }
328
+ // Skip and count leading '1's.
329
+ var zeroes = 0;
330
+ var length = 0;
331
+ while (source[psz] === LEADER) {
332
+ zeroes++;
333
+ psz++;
334
+ }
335
+ // Allocate enough space in big-endian base256 representation.
336
+ var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
337
+ var b256 = new Uint8Array(size);
338
+ // Process the characters.
339
+ while (source[psz]) {
340
+ // Decode character
341
+ var carry = BASE_MAP[source.charCodeAt(psz)];
342
+ // Invalid character
343
+ if (carry === 255) { return }
344
+ var i = 0;
345
+ for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
346
+ carry += (BASE * b256[it3]) >>> 0;
347
+ b256[it3] = (carry % 256) >>> 0;
348
+ carry = (carry / 256) >>> 0;
349
+ }
350
+ if (carry !== 0) { throw new Error('Non-zero carry') }
351
+ length = i;
352
+ psz++;
353
+ }
354
+ // Skip trailing spaces.
355
+ if (source[psz] === ' ') { return }
356
+ // Skip leading zeroes in b256.
357
+ var it4 = size - length;
358
+ while (it4 !== size && b256[it4] === 0) {
359
+ it4++;
360
+ }
361
+ var vch = new Uint8Array(zeroes + (size - it4));
362
+ var j = zeroes;
363
+ while (it4 !== size) {
364
+ vch[j++] = b256[it4++];
365
+ }
366
+ return vch
367
+ }
368
+ function decode (string) {
369
+ var buffer = decodeUnsafe(string);
370
+ if (buffer) { return buffer }
371
+ throw new Error(`Non-${name} character`)
372
+ }
373
+ return {
374
+ encode: encode,
375
+ decodeUnsafe: decodeUnsafe,
376
+ decode: decode
377
+ }
378
+ }
379
+ var src = base;
380
+
381
+ var _brrp__multiformats_scope_baseX = src;
382
+
383
+ /**
384
+ * @param {Uint8Array} aa
385
+ * @param {Uint8Array} bb
386
+ */
387
+ const equals$2 = (aa, bb) => {
388
+ if (aa === bb) return true
389
+ if (aa.byteLength !== bb.byteLength) {
390
+ return false
391
+ }
392
+
393
+ for (let ii = 0; ii < aa.byteLength; ii++) {
394
+ if (aa[ii] !== bb[ii]) {
395
+ return false
396
+ }
397
+ }
398
+
399
+ return true
400
+ };
401
+
402
+ /**
403
+ * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o
404
+ * @returns {Uint8Array}
405
+ */
406
+ const coerce = o => {
407
+ if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o
408
+ if (o instanceof ArrayBuffer) return new Uint8Array(o)
409
+ if (ArrayBuffer.isView(o)) {
410
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)
411
+ }
412
+ throw new Error('Unknown type, must be binary type')
413
+ };
414
+
415
+ /**
416
+ * @param {string} str
417
+ * @returns {Uint8Array}
418
+ */
419
+ const fromString$2 = str => (new TextEncoder()).encode(str);
420
+
421
+ /**
422
+ * @param {Uint8Array} b
423
+ * @returns {string}
424
+ */
425
+ const toString$2 = b => (new TextDecoder()).decode(b);
426
+
427
+ /**
428
+ * Class represents both BaseEncoder and MultibaseEncoder meaning it
429
+ * can be used to encode to multibase or base encode without multibase
430
+ * prefix.
431
+ *
432
+ * @class
433
+ * @template {string} Base
434
+ * @template {string} Prefix
435
+ * @implements {API.MultibaseEncoder<Prefix>}
436
+ * @implements {API.BaseEncoder}
437
+ */
438
+ class Encoder {
439
+ /**
440
+ * @param {Base} name
441
+ * @param {Prefix} prefix
442
+ * @param {(bytes:Uint8Array) => string} baseEncode
443
+ */
444
+ constructor (name, prefix, baseEncode) {
445
+ this.name = name;
446
+ this.prefix = prefix;
447
+ this.baseEncode = baseEncode;
448
+ }
449
+
450
+ /**
451
+ * @param {Uint8Array} bytes
452
+ * @returns {API.Multibase<Prefix>}
453
+ */
454
+ encode (bytes) {
455
+ if (bytes instanceof Uint8Array) {
456
+ return `${this.prefix}${this.baseEncode(bytes)}`
457
+ } else {
458
+ throw Error('Unknown type, must be binary type')
459
+ }
460
+ }
461
+ }
462
+
463
+ /**
464
+ * @template {string} Prefix
465
+ */
466
+ /**
467
+ * Class represents both BaseDecoder and MultibaseDecoder so it could be used
468
+ * to decode multibases (with matching prefix) or just base decode strings
469
+ * with corresponding base encoding.
470
+ *
471
+ * @class
472
+ * @template {string} Base
473
+ * @template {string} Prefix
474
+ * @implements {API.MultibaseDecoder<Prefix>}
475
+ * @implements {API.UnibaseDecoder<Prefix>}
476
+ * @implements {API.BaseDecoder}
477
+ */
478
+ class Decoder {
479
+ /**
480
+ * @param {Base} name
481
+ * @param {Prefix} prefix
482
+ * @param {(text:string) => Uint8Array} baseDecode
483
+ */
484
+ constructor (name, prefix, baseDecode) {
485
+ this.name = name;
486
+ this.prefix = prefix;
487
+ /* c8 ignore next 3 */
488
+ if (prefix.codePointAt(0) === undefined) {
489
+ throw new Error('Invalid prefix character')
490
+ }
491
+ /** @private */
492
+ this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0));
493
+ this.baseDecode = baseDecode;
494
+ }
495
+
496
+ /**
497
+ * @param {string} text
498
+ */
499
+ decode (text) {
500
+ if (typeof text === 'string') {
501
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
502
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)
503
+ }
504
+ return this.baseDecode(text.slice(this.prefix.length))
505
+ } else {
506
+ throw Error('Can only multibase decode strings')
507
+ }
508
+ }
509
+
510
+ /**
511
+ * @template {string} OtherPrefix
512
+ * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
513
+ * @returns {ComposedDecoder<Prefix|OtherPrefix>}
514
+ */
515
+ or (decoder) {
516
+ return or(this, decoder)
517
+ }
518
+ }
519
+
520
+ /**
521
+ * @template {string} Prefix
522
+ * @typedef {Record<Prefix, API.UnibaseDecoder<Prefix>>} Decoders
523
+ */
524
+
525
+ /**
526
+ * @template {string} Prefix
527
+ * @implements {API.MultibaseDecoder<Prefix>}
528
+ * @implements {API.CombobaseDecoder<Prefix>}
529
+ */
530
+ class ComposedDecoder {
531
+ /**
532
+ * @param {Decoders<Prefix>} decoders
533
+ */
534
+ constructor (decoders) {
535
+ this.decoders = decoders;
536
+ }
537
+
538
+ /**
539
+ * @template {string} OtherPrefix
540
+ * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder
541
+ * @returns {ComposedDecoder<Prefix|OtherPrefix>}
542
+ */
543
+ or (decoder) {
544
+ return or(this, decoder)
545
+ }
546
+
547
+ /**
548
+ * @param {string} input
549
+ * @returns {Uint8Array}
550
+ */
551
+ decode (input) {
552
+ const prefix = /** @type {Prefix} */ (input[0]);
553
+ const decoder = this.decoders[prefix];
554
+ if (decoder) {
555
+ return decoder.decode(input)
556
+ } else {
557
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)
558
+ }
559
+ }
560
+ }
561
+
562
+ /**
563
+ * @template {string} L
564
+ * @template {string} R
565
+ * @param {API.UnibaseDecoder<L>|API.CombobaseDecoder<L>} left
566
+ * @param {API.UnibaseDecoder<R>|API.CombobaseDecoder<R>} right
567
+ * @returns {ComposedDecoder<L|R>}
568
+ */
569
+ const or = (left, right) => new ComposedDecoder(/** @type {Decoders<L|R>} */({
570
+ ...(left.decoders || { [/** @type API.UnibaseDecoder<L> */(left).prefix]: left }),
571
+ ...(right.decoders || { [/** @type API.UnibaseDecoder<R> */(right).prefix]: right })
572
+ }));
573
+
574
+ /**
575
+ * @class
576
+ * @template {string} Base
577
+ * @template {string} Prefix
578
+ * @implements {API.MultibaseCodec<Prefix>}
579
+ * @implements {API.MultibaseEncoder<Prefix>}
580
+ * @implements {API.MultibaseDecoder<Prefix>}
581
+ * @implements {API.BaseCodec}
582
+ * @implements {API.BaseEncoder}
583
+ * @implements {API.BaseDecoder}
584
+ */
585
+ class Codec {
586
+ /**
587
+ * @param {Base} name
588
+ * @param {Prefix} prefix
589
+ * @param {(bytes:Uint8Array) => string} baseEncode
590
+ * @param {(text:string) => Uint8Array} baseDecode
591
+ */
592
+ constructor (name, prefix, baseEncode, baseDecode) {
593
+ this.name = name;
594
+ this.prefix = prefix;
595
+ this.baseEncode = baseEncode;
596
+ this.baseDecode = baseDecode;
597
+ this.encoder = new Encoder(name, prefix, baseEncode);
598
+ this.decoder = new Decoder(name, prefix, baseDecode);
599
+ }
600
+
601
+ /**
602
+ * @param {Uint8Array} input
603
+ */
604
+ encode (input) {
605
+ return this.encoder.encode(input)
606
+ }
607
+
608
+ /**
609
+ * @param {string} input
610
+ */
611
+ decode (input) {
612
+ return this.decoder.decode(input)
613
+ }
614
+ }
615
+
616
+ /**
617
+ * @template {string} Base
618
+ * @template {string} Prefix
619
+ * @param {object} options
620
+ * @param {Base} options.name
621
+ * @param {Prefix} options.prefix
622
+ * @param {(bytes:Uint8Array) => string} options.encode
623
+ * @param {(input:string) => Uint8Array} options.decode
624
+ * @returns {Codec<Base, Prefix>}
625
+ */
626
+ const from$1 = ({ name, prefix, encode, decode }) =>
627
+ new Codec(name, prefix, encode, decode);
628
+
629
+ /**
630
+ * @template {string} Base
631
+ * @template {string} Prefix
632
+ * @param {object} options
633
+ * @param {Base} options.name
634
+ * @param {Prefix} options.prefix
635
+ * @param {string} options.alphabet
636
+ * @returns {Codec<Base, Prefix>}
637
+ */
638
+ const baseX = ({ prefix, name, alphabet }) => {
639
+ const { encode, decode } = _brrp__multiformats_scope_baseX(alphabet, name);
640
+ return from$1({
641
+ prefix,
642
+ name,
643
+ encode,
644
+ /**
645
+ * @param {string} text
646
+ */
647
+ decode: text => coerce(decode(text))
648
+ })
649
+ };
650
+
651
+ /**
652
+ * @param {string} string
653
+ * @param {string} alphabet
654
+ * @param {number} bitsPerChar
655
+ * @param {string} name
656
+ * @returns {Uint8Array}
657
+ */
658
+ const decode$5 = (string, alphabet, bitsPerChar, name) => {
659
+ // Build the character lookup table:
660
+ /** @type {Record<string, number>} */
661
+ const codes = {};
662
+ for (let i = 0; i < alphabet.length; ++i) {
663
+ codes[alphabet[i]] = i;
664
+ }
665
+
666
+ // Count the padding bytes:
667
+ let end = string.length;
668
+ while (string[end - 1] === '=') {
669
+ --end;
670
+ }
671
+
672
+ // Allocate the output:
673
+ const out = new Uint8Array((end * bitsPerChar / 8) | 0);
674
+
675
+ // Parse the data:
676
+ let bits = 0; // Number of bits currently in the buffer
677
+ let buffer = 0; // Bits waiting to be written out, MSB first
678
+ let written = 0; // Next byte to write
679
+ for (let i = 0; i < end; ++i) {
680
+ // Read one character from the string:
681
+ const value = codes[string[i]];
682
+ if (value === undefined) {
683
+ throw new SyntaxError(`Non-${name} character`)
684
+ }
685
+
686
+ // Append the bits to the buffer:
687
+ buffer = (buffer << bitsPerChar) | value;
688
+ bits += bitsPerChar;
689
+
690
+ // Write out some bits if the buffer has a byte's worth:
691
+ if (bits >= 8) {
692
+ bits -= 8;
693
+ out[written++] = 0xff & (buffer >> bits);
694
+ }
695
+ }
696
+
697
+ // Verify that we have received just enough bits:
698
+ if (bits >= bitsPerChar || 0xff & (buffer << (8 - bits))) {
699
+ throw new SyntaxError('Unexpected end of data')
700
+ }
701
+
702
+ return out
703
+ };
704
+
705
+ /**
706
+ * @param {Uint8Array} data
707
+ * @param {string} alphabet
708
+ * @param {number} bitsPerChar
709
+ * @returns {string}
710
+ */
711
+ const encode$4 = (data, alphabet, bitsPerChar) => {
712
+ const pad = alphabet[alphabet.length - 1] === '=';
713
+ const mask = (1 << bitsPerChar) - 1;
714
+ let out = '';
715
+
716
+ let bits = 0; // Number of bits currently in the buffer
717
+ let buffer = 0; // Bits waiting to be written out, MSB first
718
+ for (let i = 0; i < data.length; ++i) {
719
+ // Slurp data into the buffer:
720
+ buffer = (buffer << 8) | data[i];
721
+ bits += 8;
722
+
723
+ // Write out as much as we can:
724
+ while (bits > bitsPerChar) {
725
+ bits -= bitsPerChar;
726
+ out += alphabet[mask & (buffer >> bits)];
727
+ }
728
+ }
729
+
730
+ // Partial character:
731
+ if (bits) {
732
+ out += alphabet[mask & (buffer << (bitsPerChar - bits))];
733
+ }
734
+
735
+ // Add padding characters until we hit a byte boundary:
736
+ if (pad) {
737
+ while ((out.length * bitsPerChar) & 7) {
738
+ out += '=';
739
+ }
740
+ }
741
+
742
+ return out
743
+ };
744
+
745
+ /**
746
+ * RFC4648 Factory
747
+ *
748
+ * @template {string} Base
749
+ * @template {string} Prefix
750
+ * @param {object} options
751
+ * @param {Base} options.name
752
+ * @param {Prefix} options.prefix
753
+ * @param {string} options.alphabet
754
+ * @param {number} options.bitsPerChar
755
+ */
756
+ const rfc4648 = ({ name, prefix, bitsPerChar, alphabet }) => {
757
+ return from$1({
758
+ prefix,
759
+ name,
760
+ encode (input) {
761
+ return encode$4(input, alphabet, bitsPerChar)
762
+ },
763
+ decode (input) {
764
+ return decode$5(input, alphabet, bitsPerChar, name)
765
+ }
766
+ })
767
+ };
768
+
769
+ // @ts-check
770
+
771
+ const identity$2 = from$1({
772
+ prefix: '\x00',
773
+ name: 'identity',
774
+ encode: (buf) => toString$2(buf),
775
+ decode: (str) => fromString$2(str)
776
+ });
777
+
778
+ var identityBase = /*#__PURE__*/Object.freeze({
779
+ __proto__: null,
780
+ identity: identity$2
781
+ });
782
+
783
+ // @ts-check
784
+
785
+ const base2 = rfc4648({
786
+ prefix: '0',
787
+ name: 'base2',
788
+ alphabet: '01',
789
+ bitsPerChar: 1
790
+ });
791
+
792
+ var base2$1 = /*#__PURE__*/Object.freeze({
793
+ __proto__: null,
794
+ base2: base2
795
+ });
796
+
797
+ // @ts-check
798
+
799
+ const base8 = rfc4648({
800
+ prefix: '7',
801
+ name: 'base8',
802
+ alphabet: '01234567',
803
+ bitsPerChar: 3
804
+ });
805
+
806
+ var base8$1 = /*#__PURE__*/Object.freeze({
807
+ __proto__: null,
808
+ base8: base8
809
+ });
810
+
811
+ const base10 = baseX({
812
+ prefix: '9',
813
+ name: 'base10',
814
+ alphabet: '0123456789'
815
+ });
816
+
817
+ var base10$1 = /*#__PURE__*/Object.freeze({
818
+ __proto__: null,
819
+ base10: base10
820
+ });
821
+
822
+ // @ts-check
823
+
824
+ const base16 = rfc4648({
825
+ prefix: 'f',
826
+ name: 'base16',
827
+ alphabet: '0123456789abcdef',
828
+ bitsPerChar: 4
829
+ });
830
+
831
+ const base16upper = rfc4648({
832
+ prefix: 'F',
833
+ name: 'base16upper',
834
+ alphabet: '0123456789ABCDEF',
835
+ bitsPerChar: 4
836
+ });
837
+
838
+ var base16$1 = /*#__PURE__*/Object.freeze({
839
+ __proto__: null,
840
+ base16: base16,
841
+ base16upper: base16upper
842
+ });
843
+
844
+ const base32 = rfc4648({
845
+ prefix: 'b',
846
+ name: 'base32',
847
+ alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
848
+ bitsPerChar: 5
849
+ });
850
+
851
+ const base32upper = rfc4648({
852
+ prefix: 'B',
853
+ name: 'base32upper',
854
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
855
+ bitsPerChar: 5
856
+ });
857
+
858
+ const base32pad = rfc4648({
859
+ prefix: 'c',
860
+ name: 'base32pad',
861
+ alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
862
+ bitsPerChar: 5
863
+ });
864
+
865
+ const base32padupper = rfc4648({
866
+ prefix: 'C',
867
+ name: 'base32padupper',
868
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
869
+ bitsPerChar: 5
870
+ });
871
+
872
+ const base32hex = rfc4648({
873
+ prefix: 'v',
874
+ name: 'base32hex',
875
+ alphabet: '0123456789abcdefghijklmnopqrstuv',
876
+ bitsPerChar: 5
877
+ });
878
+
879
+ const base32hexupper = rfc4648({
880
+ prefix: 'V',
881
+ name: 'base32hexupper',
882
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
883
+ bitsPerChar: 5
884
+ });
885
+
886
+ const base32hexpad = rfc4648({
887
+ prefix: 't',
888
+ name: 'base32hexpad',
889
+ alphabet: '0123456789abcdefghijklmnopqrstuv=',
890
+ bitsPerChar: 5
891
+ });
892
+
893
+ const base32hexpadupper = rfc4648({
894
+ prefix: 'T',
895
+ name: 'base32hexpadupper',
896
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
897
+ bitsPerChar: 5
898
+ });
899
+
900
+ const base32z = rfc4648({
901
+ prefix: 'h',
902
+ name: 'base32z',
903
+ alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
904
+ bitsPerChar: 5
905
+ });
906
+
907
+ var base32$1 = /*#__PURE__*/Object.freeze({
908
+ __proto__: null,
909
+ base32: base32,
910
+ base32upper: base32upper,
911
+ base32pad: base32pad,
912
+ base32padupper: base32padupper,
913
+ base32hex: base32hex,
914
+ base32hexupper: base32hexupper,
915
+ base32hexpad: base32hexpad,
916
+ base32hexpadupper: base32hexpadupper,
917
+ base32z: base32z
918
+ });
919
+
920
+ const base36 = baseX({
921
+ prefix: 'k',
922
+ name: 'base36',
923
+ alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
924
+ });
925
+
926
+ const base36upper = baseX({
927
+ prefix: 'K',
928
+ name: 'base36upper',
929
+ alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
930
+ });
931
+
932
+ var base36$1 = /*#__PURE__*/Object.freeze({
933
+ __proto__: null,
934
+ base36: base36,
935
+ base36upper: base36upper
936
+ });
937
+
938
+ const base58btc = baseX({
939
+ name: 'base58btc',
940
+ prefix: 'z',
941
+ alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
942
+ });
943
+
944
+ const base58flickr = baseX({
945
+ name: 'base58flickr',
946
+ prefix: 'Z',
947
+ alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
948
+ });
949
+
950
+ var base58 = /*#__PURE__*/Object.freeze({
951
+ __proto__: null,
952
+ base58btc: base58btc,
953
+ base58flickr: base58flickr
954
+ });
955
+
956
+ // @ts-check
957
+
958
+ const base64 = rfc4648({
959
+ prefix: 'm',
960
+ name: 'base64',
961
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
962
+ bitsPerChar: 6
963
+ });
964
+
965
+ const base64pad = rfc4648({
966
+ prefix: 'M',
967
+ name: 'base64pad',
968
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
969
+ bitsPerChar: 6
970
+ });
971
+
972
+ const base64url = rfc4648({
973
+ prefix: 'u',
974
+ name: 'base64url',
975
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
976
+ bitsPerChar: 6
977
+ });
978
+
979
+ const base64urlpad = rfc4648({
980
+ prefix: 'U',
981
+ name: 'base64urlpad',
982
+ alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
983
+ bitsPerChar: 6
984
+ });
985
+
986
+ var base64$1 = /*#__PURE__*/Object.freeze({
987
+ __proto__: null,
988
+ base64: base64,
989
+ base64pad: base64pad,
990
+ base64url: base64url,
991
+ base64urlpad: base64urlpad
992
+ });
993
+
994
+ const alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');
995
+ const alphabetBytesToChars = /** @type {string[]} */ (alphabet.reduce((p, c, i) => { p[i] = c; return p }, /** @type {string[]} */([])));
996
+ const alphabetCharsToBytes = /** @type {number[]} */ (alphabet.reduce((p, c, i) => { p[/** @type {number} */ (c.codePointAt(0))] = i; return p }, /** @type {number[]} */([])));
997
+
998
+ /**
999
+ * @param {Uint8Array} data
1000
+ * @returns {string}
1001
+ */
1002
+ function encode$3 (data) {
1003
+ return data.reduce((p, c) => {
1004
+ p += alphabetBytesToChars[c];
1005
+ return p
1006
+ }, '')
1007
+ }
1008
+
1009
+ /**
1010
+ * @param {string} str
1011
+ * @returns {Uint8Array}
1012
+ */
1013
+ function decode$4 (str) {
1014
+ const byts = [];
1015
+ for (const char of str) {
1016
+ const byt = alphabetCharsToBytes[/** @type {number} */ (char.codePointAt(0))];
1017
+ if (byt === undefined) {
1018
+ throw new Error(`Non-base256emoji character: ${char}`)
1019
+ }
1020
+ byts.push(byt);
1021
+ }
1022
+ return new Uint8Array(byts)
1023
+ }
1024
+
1025
+ const base256emoji = from$1({
1026
+ prefix: '🚀',
1027
+ name: 'base256emoji',
1028
+ encode: encode$3,
1029
+ decode: decode$4
1030
+ });
1031
+
1032
+ var base256emoji$1 = /*#__PURE__*/Object.freeze({
1033
+ __proto__: null,
1034
+ base256emoji: base256emoji
1035
+ });
1036
+
1037
+ var encode_1$1 = encode$2;
1038
+
1039
+ var MSB$2 = 0x80
1040
+ , REST$2 = 0x7F
1041
+ , MSBALL$1 = ~REST$2
1042
+ , INT$1 = Math.pow(2, 31);
1043
+
1044
+ function encode$2(num, out, offset) {
1045
+ out = out || [];
1046
+ offset = offset || 0;
1047
+ var oldOffset = offset;
1048
+
1049
+ while(num >= INT$1) {
1050
+ out[offset++] = (num & 0xFF) | MSB$2;
1051
+ num /= 128;
1052
+ }
1053
+ while(num & MSBALL$1) {
1054
+ out[offset++] = (num & 0xFF) | MSB$2;
1055
+ num >>>= 7;
1056
+ }
1057
+ out[offset] = num | 0;
1058
+
1059
+ encode$2.bytes = offset - oldOffset + 1;
1060
+
1061
+ return out
1062
+ }
1063
+
1064
+ var decode$3 = read$1;
1065
+
1066
+ var MSB$1$1 = 0x80
1067
+ , REST$1$1 = 0x7F;
1068
+
1069
+ function read$1(buf, offset) {
1070
+ var res = 0
1071
+ , offset = offset || 0
1072
+ , shift = 0
1073
+ , counter = offset
1074
+ , b
1075
+ , l = buf.length;
1076
+
1077
+ do {
1078
+ if (counter >= l) {
1079
+ read$1.bytes = 0;
1080
+ throw new RangeError('Could not decode varint')
1081
+ }
1082
+ b = buf[counter++];
1083
+ res += shift < 28
1084
+ ? (b & REST$1$1) << shift
1085
+ : (b & REST$1$1) * Math.pow(2, shift);
1086
+ shift += 7;
1087
+ } while (b >= MSB$1$1)
1088
+
1089
+ read$1.bytes = counter - offset;
1090
+
1091
+ return res
1092
+ }
1093
+
1094
+ var N1$1 = Math.pow(2, 7);
1095
+ var N2$1 = Math.pow(2, 14);
1096
+ var N3$1 = Math.pow(2, 21);
1097
+ var N4$1 = Math.pow(2, 28);
1098
+ var N5$1 = Math.pow(2, 35);
1099
+ var N6$1 = Math.pow(2, 42);
1100
+ var N7$1 = Math.pow(2, 49);
1101
+ var N8$1 = Math.pow(2, 56);
1102
+ var N9$1 = Math.pow(2, 63);
1103
+
1104
+ var length$1 = function (value) {
1105
+ return (
1106
+ value < N1$1 ? 1
1107
+ : value < N2$1 ? 2
1108
+ : value < N3$1 ? 3
1109
+ : value < N4$1 ? 4
1110
+ : value < N5$1 ? 5
1111
+ : value < N6$1 ? 6
1112
+ : value < N7$1 ? 7
1113
+ : value < N8$1 ? 8
1114
+ : value < N9$1 ? 9
1115
+ : 10
1116
+ )
1117
+ };
1118
+
1119
+ var varint$1 = {
1120
+ encode: encode_1$1
1121
+ , decode: decode$3
1122
+ , encodingLength: length$1
1123
+ };
1124
+
1125
+ var _brrp_varint = varint$1;
1126
+
1127
+ /**
1128
+ * @param {Uint8Array} data
1129
+ * @param {number} [offset=0]
1130
+ * @returns {[number, number]}
1131
+ */
1132
+ const decode$2 = (data, offset = 0) => {
1133
+ const code = _brrp_varint.decode(data, offset);
1134
+ return [code, _brrp_varint.decode.bytes]
1135
+ };
1136
+
1137
+ /**
1138
+ * @param {number} int
1139
+ * @param {Uint8Array} target
1140
+ * @param {number} [offset=0]
1141
+ */
1142
+ const encodeTo = (int, target, offset = 0) => {
1143
+ _brrp_varint.encode(int, target, offset);
1144
+ return target
1145
+ };
1146
+
1147
+ /**
1148
+ * @param {number} int
1149
+ * @returns {number}
1150
+ */
1151
+ const encodingLength = (int) => {
1152
+ return _brrp_varint.encodingLength(int)
1153
+ };
1154
+
1155
+ /**
1156
+ * Creates a multihash digest.
1157
+ *
1158
+ * @template {number} Code
1159
+ * @param {Code} code
1160
+ * @param {Uint8Array} digest
1161
+ */
1162
+ const create = (code, digest) => {
1163
+ const size = digest.byteLength;
1164
+ const sizeOffset = encodingLength(code);
1165
+ const digestOffset = sizeOffset + encodingLength(size);
1166
+
1167
+ const bytes = new Uint8Array(digestOffset + size);
1168
+ encodeTo(code, bytes, 0);
1169
+ encodeTo(size, bytes, sizeOffset);
1170
+ bytes.set(digest, digestOffset);
1171
+
1172
+ return new Digest(code, size, digest, bytes)
1173
+ };
1174
+
1175
+ /**
1176
+ * Turns bytes representation of multihash digest into an instance.
1177
+ *
1178
+ * @param {Uint8Array} multihash
1179
+ * @returns {MultihashDigest}
1180
+ */
1181
+ const decode$1 = (multihash) => {
1182
+ const bytes = coerce(multihash);
1183
+ const [code, sizeOffset] = decode$2(bytes);
1184
+ const [size, digestOffset] = decode$2(bytes.subarray(sizeOffset));
1185
+ const digest = bytes.subarray(sizeOffset + digestOffset);
1186
+
1187
+ if (digest.byteLength !== size) {
1188
+ throw new Error('Incorrect length')
1189
+ }
1190
+
1191
+ return new Digest(code, size, digest, bytes)
1192
+ };
1193
+
1194
+ /**
1195
+ * @param {MultihashDigest} a
1196
+ * @param {unknown} b
1197
+ * @returns {b is MultihashDigest}
1198
+ */
1199
+ const equals$1 = (a, b) => {
1200
+ if (a === b) {
1201
+ return true
1202
+ } else {
1203
+ const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b);
1204
+
1205
+ return (
1206
+ a.code === data.code &&
1207
+ a.size === data.size &&
1208
+ data.bytes instanceof Uint8Array &&
1209
+ equals$2(a.bytes, data.bytes)
1210
+ )
1211
+ }
1212
+ };
1213
+
1214
+ /**
1215
+ * @typedef {import('./interface.js').MultihashDigest} MultihashDigest
1216
+ */
1217
+
1218
+ /**
1219
+ * Represents a multihash digest which carries information about the
1220
+ * hashing alogrithm and an actual hash digest.
1221
+ *
1222
+ * @template {number} Code
1223
+ * @template {number} Size
1224
+ * @class
1225
+ * @implements {MultihashDigest}
1226
+ */
1227
+ class Digest {
1228
+ /**
1229
+ * Creates a multihash digest.
1230
+ *
1231
+ * @param {Code} code
1232
+ * @param {Size} size
1233
+ * @param {Uint8Array} digest
1234
+ * @param {Uint8Array} bytes
1235
+ */
1236
+ constructor (code, size, digest, bytes) {
1237
+ this.code = code;
1238
+ this.size = size;
1239
+ this.digest = digest;
1240
+ this.bytes = bytes;
1241
+ }
1242
+ }
1243
+
1244
+ /**
1245
+ * @template {string} Name
1246
+ * @template {number} Code
1247
+ * @param {object} options
1248
+ * @param {Name} options.name
1249
+ * @param {Code} options.code
1250
+ * @param {(input: Uint8Array) => Await<Uint8Array>} options.encode
1251
+ */
1252
+ const from = ({ name, code, encode }) => new Hasher(name, code, encode);
1253
+
1254
+ /**
1255
+ * Hasher represents a hashing algorithm implementation that produces as
1256
+ * `MultihashDigest`.
1257
+ *
1258
+ * @template {string} Name
1259
+ * @template {number} Code
1260
+ * @class
1261
+ * @implements {MultihashHasher<Code>}
1262
+ */
1263
+ class Hasher {
1264
+ /**
1265
+ *
1266
+ * @param {Name} name
1267
+ * @param {Code} code
1268
+ * @param {(input: Uint8Array) => Await<Uint8Array>} encode
1269
+ */
1270
+ constructor (name, code, encode) {
1271
+ this.name = name;
1272
+ this.code = code;
1273
+ this.encode = encode;
1274
+ }
1275
+
1276
+ /**
1277
+ * @param {Uint8Array} input
1278
+ * @returns {Await<Digest.Digest<Code, number>>}
1279
+ */
1280
+ digest (input) {
1281
+ if (input instanceof Uint8Array) {
1282
+ const result = this.encode(input);
1283
+ return result instanceof Uint8Array
1284
+ ? create(this.code, result)
1285
+ /* c8 ignore next 1 */
1286
+ : result.then(digest => create(this.code, digest))
1287
+ } else {
1288
+ throw Error('Unknown type, must be binary type')
1289
+ /* c8 ignore next 1 */
1290
+ }
1291
+ }
1292
+ }
1293
+
1294
+ /**
1295
+ * @template {number} Alg
1296
+ * @typedef {import('./interface.js').MultihashHasher} MultihashHasher
1297
+ */
1298
+
1299
+ /**
1300
+ * @template T
1301
+ * @typedef {Promise<T>|T} Await
1302
+ */
1303
+
1304
+ /* global crypto */
1305
+
1306
+ /**
1307
+ * @param {AlgorithmIdentifier} name
1308
+ */
1309
+ const sha = name =>
1310
+ /**
1311
+ * @param {Uint8Array} data
1312
+ */
1313
+ async data => new Uint8Array(await crypto.subtle.digest(name, data));
1314
+
1315
+ const sha256 = from({
1316
+ name: 'sha2-256',
1317
+ code: 0x12,
1318
+ encode: sha('SHA-256')
1319
+ });
1320
+
1321
+ const sha512 = from({
1322
+ name: 'sha2-512',
1323
+ code: 0x13,
1324
+ encode: sha('SHA-512')
1325
+ });
1326
+
1327
+ var sha2 = /*#__PURE__*/Object.freeze({
1328
+ __proto__: null,
1329
+ sha256: sha256,
1330
+ sha512: sha512
1331
+ });
1332
+
1333
+ const code = 0x0;
1334
+ const name = 'identity';
1335
+
1336
+ /** @type {(input:Uint8Array) => Uint8Array} */
1337
+ const encode$1 = coerce;
1338
+
1339
+ /**
1340
+ * @param {Uint8Array} input
1341
+ * @returns {Digest.Digest<typeof code, number>}
1342
+ */
1343
+ const digest = (input) => create(code, encode$1(input));
1344
+
1345
+ const identity = { code, name, encode: encode$1, digest };
1346
+
1347
+ var identity$1 = /*#__PURE__*/Object.freeze({
1348
+ __proto__: null,
1349
+ identity: identity
1350
+ });
1351
+
1352
+ // @ts-check
1353
+
1354
+ /**
1355
+ * @template T
1356
+ * @typedef {import('./interface.js').ByteView<T>} ByteView
1357
+ */
1358
+
1359
+ new TextEncoder();
1360
+ new TextDecoder();
1361
+
1362
+ /**
1363
+ * @template {API.Link<unknown, number, number, API.Version>} T
1364
+ * @template {string} Prefix
1365
+ * @param {T} link
1366
+ * @param {API.MultibaseEncoder<Prefix>} [base]
1367
+ * @returns {API.ToString<T, Prefix>}
1368
+ */
1369
+ const format = (link, base) => {
1370
+ const { bytes, version } = link;
1371
+ switch (version) {
1372
+ case 0:
1373
+ return toStringV0(
1374
+ bytes,
1375
+ baseCache(link),
1376
+ /** @type {API.MultibaseEncoder<"z">} */ (base) || base58btc.encoder
1377
+ )
1378
+ default:
1379
+ return toStringV1(
1380
+ bytes,
1381
+ baseCache(link),
1382
+ /** @type {API.MultibaseEncoder<Prefix>} */ (base || base32.encoder)
1383
+ )
1384
+ }
1385
+ };
1386
+
1387
+ /** @type {WeakMap<API.UnknownLink, Map<string, string>>} */
1388
+ const cache = new WeakMap();
1389
+
1390
+ /**
1391
+ * @param {API.UnknownLink} cid
1392
+ * @returns {Map<string, string>}
1393
+ */
1394
+ const baseCache = cid => {
1395
+ const baseCache = cache.get(cid);
1396
+ if (baseCache == null) {
1397
+ const baseCache = new Map();
1398
+ cache.set(cid, baseCache);
1399
+ return baseCache
1400
+ }
1401
+ return baseCache
1402
+ };
1403
+
1404
+ /**
1405
+ * @template {unknown} [Data=unknown]
1406
+ * @template {number} [Format=number]
1407
+ * @template {number} [Alg=number]
1408
+ * @template {API.Version} [Version=API.Version]
1409
+ * @implements {API.Link<Data, Format, Alg, Version>}
1410
+ */
1411
+
1412
+ class CID {
1413
+ /**
1414
+ * @param {Version} version - Version of the CID
1415
+ * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
1416
+ * @param {API.MultihashDigest<Alg>} multihash - (Multi)hash of the of the content.
1417
+ * @param {Uint8Array} bytes
1418
+ *
1419
+ */
1420
+ constructor (version, code, multihash, bytes) {
1421
+ /** @readonly */
1422
+ this.code = code;
1423
+ /** @readonly */
1424
+ this.version = version;
1425
+ /** @readonly */
1426
+ this.multihash = multihash;
1427
+ /** @readonly */
1428
+ this.bytes = bytes;
1429
+
1430
+ // flag to serializers that this is a CID and
1431
+ // should be treated specially
1432
+ /** @readonly */
1433
+ this['/'] = bytes;
1434
+ }
1435
+
1436
+ /**
1437
+ * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
1438
+ * please either use `CID.asCID(cid)` or switch to new signalling mechanism
1439
+ *
1440
+ * @deprecated
1441
+ */
1442
+ get asCID () {
1443
+ return this
1444
+ }
1445
+
1446
+ // ArrayBufferView
1447
+ get byteOffset () {
1448
+ return this.bytes.byteOffset
1449
+ }
1450
+
1451
+ // ArrayBufferView
1452
+ get byteLength () {
1453
+ return this.bytes.byteLength
1454
+ }
1455
+
1456
+ /**
1457
+ * @returns {CID<Data, API.DAG_PB, API.SHA_256, 0>}
1458
+ */
1459
+ toV0 () {
1460
+ switch (this.version) {
1461
+ case 0: {
1462
+ return /** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */ (this)
1463
+ }
1464
+ case 1: {
1465
+ const { code, multihash } = this;
1466
+
1467
+ if (code !== DAG_PB_CODE) {
1468
+ throw new Error('Cannot convert a non dag-pb CID to CIDv0')
1469
+ }
1470
+
1471
+ // sha2-256
1472
+ if (multihash.code !== SHA_256_CODE) {
1473
+ throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')
1474
+ }
1475
+
1476
+ return /** @type {CID<Data, API.DAG_PB, API.SHA_256, 0>} */ (
1477
+ CID.createV0(
1478
+ /** @type {API.MultihashDigest<API.SHA_256>} */ (multihash)
1479
+ )
1480
+ )
1481
+ }
1482
+ default: {
1483
+ throw Error(
1484
+ `Can not convert CID version ${this.version} to version 0. This is a bug please report`
1485
+ )
1486
+ }
1487
+ }
1488
+ }
1489
+
1490
+ /**
1491
+ * @returns {CID<Data, Format, Alg, 1>}
1492
+ */
1493
+ toV1 () {
1494
+ switch (this.version) {
1495
+ case 0: {
1496
+ const { code, digest } = this.multihash;
1497
+ const multihash = create(code, digest);
1498
+ return /** @type {CID<Data, Format, Alg, 1>} */ (
1499
+ CID.createV1(this.code, multihash)
1500
+ )
1501
+ }
1502
+ case 1: {
1503
+ return /** @type {CID<Data, Format, Alg, 1>} */ (this)
1504
+ }
1505
+ default: {
1506
+ throw Error(
1507
+ `Can not convert CID version ${this.version} to version 1. This is a bug please report`
1508
+ )
1509
+ }
1510
+ }
1511
+ }
1512
+
1513
+ /**
1514
+ * @param {unknown} other
1515
+ * @returns {other is CID<Data, Format, Alg, Version>}
1516
+ */
1517
+ equals (other) {
1518
+ return CID.equals(this, other)
1519
+ }
1520
+
1521
+ /**
1522
+ * @template {unknown} Data
1523
+ * @template {number} Format
1524
+ * @template {number} Alg
1525
+ * @template {API.Version} Version
1526
+ * @param {API.Link<Data, Format, Alg, Version>} self
1527
+ * @param {unknown} other
1528
+ * @returns {other is CID}
1529
+ */
1530
+ static equals (self, other) {
1531
+ const unknown =
1532
+ /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ (
1533
+ other
1534
+ );
1535
+ return (
1536
+ unknown &&
1537
+ self.code === unknown.code &&
1538
+ self.version === unknown.version &&
1539
+ equals$1(self.multihash, unknown.multihash)
1540
+ )
1541
+ }
1542
+
1543
+ /**
1544
+ * @param {API.MultibaseEncoder<string>} [base]
1545
+ * @returns {string}
1546
+ */
1547
+ toString (base) {
1548
+ return format(this, base)
1549
+ }
1550
+
1551
+ toJSON () {
1552
+ return {
1553
+ code: this.code,
1554
+ version: this.version,
1555
+ hash: this.multihash.bytes
1556
+ }
1557
+ }
1558
+
1559
+ link () {
1560
+ return this
1561
+ }
1562
+
1563
+ get [Symbol.toStringTag] () {
1564
+ return 'CID'
1565
+ }
1566
+
1567
+ // Legacy
1568
+
1569
+ [Symbol.for('nodejs.util.inspect.custom')] () {
1570
+ return `CID(${this.toString()})`
1571
+ }
1572
+
1573
+ /**
1574
+ * Takes any input `value` and returns a `CID` instance if it was
1575
+ * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
1576
+ * it will return value back. If `value` is not instance of this CID
1577
+ * class, but is compatible CID it will return new instance of this
1578
+ * `CID` class. Otherwise returs null.
1579
+ *
1580
+ * This allows two different incompatible versions of CID library to
1581
+ * co-exist and interop as long as binary interface is compatible.
1582
+ *
1583
+ * @template {unknown} Data
1584
+ * @template {number} Format
1585
+ * @template {number} Alg
1586
+ * @template {API.Version} Version
1587
+ * @template {unknown} U
1588
+ * @param {API.Link<Data, Format, Alg, Version>|U} input
1589
+ * @returns {CID<Data, Format, Alg, Version>|null}
1590
+ */
1591
+ static asCID (input) {
1592
+ if (input == null) {
1593
+ return null
1594
+ }
1595
+
1596
+ const value = /** @type {any} */ (input);
1597
+ if (value instanceof CID) {
1598
+ // If value is instance of CID then we're all set.
1599
+ return value
1600
+ } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
1601
+ // If value isn't instance of this CID class but `this.asCID === this` or
1602
+ // `value['/'] === value.bytes` is true it is CID instance coming from a
1603
+ // different implementation (diff version or duplicate). In that case we
1604
+ // rebase it to this `CID` implementation so caller is guaranteed to get
1605
+ // instance with expected API.
1606
+ const { version, code, multihash, bytes } = value;
1607
+ return new CID(
1608
+ version,
1609
+ code,
1610
+ /** @type {API.MultihashDigest<Alg>} */ (multihash),
1611
+ bytes || encodeCID(version, code, multihash.bytes)
1612
+ )
1613
+ } else if (value[cidSymbol] === true) {
1614
+ // If value is a CID from older implementation that used to be tagged via
1615
+ // symbol we still rebase it to the this `CID` implementation by
1616
+ // delegating that to a constructor.
1617
+ const { version, multihash, code } = value;
1618
+ const digest =
1619
+ /** @type {API.MultihashDigest<Alg>} */
1620
+ (decode$1(multihash));
1621
+ return CID.create(version, code, digest)
1622
+ } else {
1623
+ // Otherwise value is not a CID (or an incompatible version of it) in
1624
+ // which case we return `null`.
1625
+ return null
1626
+ }
1627
+ }
1628
+
1629
+ /**
1630
+ *
1631
+ * @template {unknown} Data
1632
+ * @template {number} Format
1633
+ * @template {number} Alg
1634
+ * @template {API.Version} Version
1635
+ * @param {Version} version - Version of the CID
1636
+ * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
1637
+ * @param {API.MultihashDigest<Alg>} digest - (Multi)hash of the of the content.
1638
+ * @returns {CID<Data, Format, Alg, Version>}
1639
+ */
1640
+ static create (version, code, digest) {
1641
+ if (typeof code !== 'number') {
1642
+ throw new Error('String codecs are no longer supported')
1643
+ }
1644
+
1645
+ if (!(digest.bytes instanceof Uint8Array)) {
1646
+ throw new Error('Invalid digest')
1647
+ }
1648
+
1649
+ switch (version) {
1650
+ case 0: {
1651
+ if (code !== DAG_PB_CODE) {
1652
+ throw new Error(
1653
+ `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`
1654
+ )
1655
+ } else {
1656
+ return new CID(version, code, digest, digest.bytes)
1657
+ }
1658
+ }
1659
+ case 1: {
1660
+ const bytes = encodeCID(version, code, digest.bytes);
1661
+ return new CID(version, code, digest, bytes)
1662
+ }
1663
+ default: {
1664
+ throw new Error('Invalid version')
1665
+ }
1666
+ }
1667
+ }
1668
+
1669
+ /**
1670
+ * Simplified version of `create` for CIDv0.
1671
+ *
1672
+ * @template {unknown} [T=unknown]
1673
+ * @param {API.MultihashDigest<typeof SHA_256_CODE>} digest - Multihash.
1674
+ * @returns {CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0>}
1675
+ */
1676
+ static createV0 (digest) {
1677
+ return CID.create(0, DAG_PB_CODE, digest)
1678
+ }
1679
+
1680
+ /**
1681
+ * Simplified version of `create` for CIDv1.
1682
+ *
1683
+ * @template {unknown} Data
1684
+ * @template {number} Code
1685
+ * @template {number} Alg
1686
+ * @param {Code} code - Content encoding format code.
1687
+ * @param {API.MultihashDigest<Alg>} digest - Miltihash of the content.
1688
+ * @returns {CID<Data, Code, Alg, 1>}
1689
+ */
1690
+ static createV1 (code, digest) {
1691
+ return CID.create(1, code, digest)
1692
+ }
1693
+
1694
+ /**
1695
+ * Decoded a CID from its binary representation. The byte array must contain
1696
+ * only the CID with no additional bytes.
1697
+ *
1698
+ * An error will be thrown if the bytes provided do not contain a valid
1699
+ * binary representation of a CID.
1700
+ *
1701
+ * @template {unknown} Data
1702
+ * @template {number} Code
1703
+ * @template {number} Alg
1704
+ * @template {API.Version} Ver
1705
+ * @param {API.ByteView<API.Link<Data, Code, Alg, Ver>>} bytes
1706
+ * @returns {CID<Data, Code, Alg, Ver>}
1707
+ */
1708
+ static decode (bytes) {
1709
+ const [cid, remainder] = CID.decodeFirst(bytes);
1710
+ if (remainder.length) {
1711
+ throw new Error('Incorrect length')
1712
+ }
1713
+ return cid
1714
+ }
1715
+
1716
+ /**
1717
+ * Decoded a CID from its binary representation at the beginning of a byte
1718
+ * array.
1719
+ *
1720
+ * Returns an array with the first element containing the CID and the second
1721
+ * element containing the remainder of the original byte array. The remainder
1722
+ * will be a zero-length byte array if the provided bytes only contained a
1723
+ * binary CID representation.
1724
+ *
1725
+ * @template {unknown} T
1726
+ * @template {number} C
1727
+ * @template {number} A
1728
+ * @template {API.Version} V
1729
+ * @param {API.ByteView<API.Link<T, C, A, V>>} bytes
1730
+ * @returns {[CID<T, C, A, V>, Uint8Array]}
1731
+ */
1732
+ static decodeFirst (bytes) {
1733
+ const specs = CID.inspectBytes(bytes);
1734
+ const prefixSize = specs.size - specs.multihashSize;
1735
+ const multihashBytes = coerce(
1736
+ bytes.subarray(prefixSize, prefixSize + specs.multihashSize)
1737
+ );
1738
+ if (multihashBytes.byteLength !== specs.multihashSize) {
1739
+ throw new Error('Incorrect length')
1740
+ }
1741
+ const digestBytes = multihashBytes.subarray(
1742
+ specs.multihashSize - specs.digestSize
1743
+ );
1744
+ const digest = new Digest(
1745
+ specs.multihashCode,
1746
+ specs.digestSize,
1747
+ digestBytes,
1748
+ multihashBytes
1749
+ );
1750
+ const cid =
1751
+ specs.version === 0
1752
+ ? CID.createV0(/** @type {API.MultihashDigest<API.SHA_256>} */ (digest))
1753
+ : CID.createV1(specs.codec, digest);
1754
+ return [/** @type {CID<T, C, A, V>} */(cid), bytes.subarray(specs.size)]
1755
+ }
1756
+
1757
+ /**
1758
+ * Inspect the initial bytes of a CID to determine its properties.
1759
+ *
1760
+ * Involves decoding up to 4 varints. Typically this will require only 4 to 6
1761
+ * bytes but for larger multicodec code values and larger multihash digest
1762
+ * lengths these varints can be quite large. It is recommended that at least
1763
+ * 10 bytes be made available in the `initialBytes` argument for a complete
1764
+ * inspection.
1765
+ *
1766
+ * @template {unknown} T
1767
+ * @template {number} C
1768
+ * @template {number} A
1769
+ * @template {API.Version} V
1770
+ * @param {API.ByteView<API.Link<T, C, A, V>>} initialBytes
1771
+ * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }}
1772
+ */
1773
+ static inspectBytes (initialBytes) {
1774
+ let offset = 0;
1775
+ const next = () => {
1776
+ const [i, length] = decode$2(initialBytes.subarray(offset));
1777
+ offset += length;
1778
+ return i
1779
+ };
1780
+
1781
+ let version = /** @type {V} */ (next());
1782
+ let codec = /** @type {C} */ (DAG_PB_CODE);
1783
+ if (/** @type {number} */(version) === 18) {
1784
+ // CIDv0
1785
+ version = /** @type {V} */ (0);
1786
+ offset = 0;
1787
+ } else {
1788
+ codec = /** @type {C} */ (next());
1789
+ }
1790
+
1791
+ if (version !== 0 && version !== 1) {
1792
+ throw new RangeError(`Invalid CID version ${version}`)
1793
+ }
1794
+
1795
+ const prefixSize = offset;
1796
+ const multihashCode = /** @type {A} */ (next()); // multihash code
1797
+ const digestSize = next(); // multihash length
1798
+ const size = offset + digestSize;
1799
+ const multihashSize = size - prefixSize;
1800
+
1801
+ return { version, codec, multihashCode, digestSize, multihashSize, size }
1802
+ }
1803
+
1804
+ /**
1805
+ * Takes cid in a string representation and creates an instance. If `base`
1806
+ * decoder is not provided will use a default from the configuration. It will
1807
+ * throw an error if encoding of the CID is not compatible with supplied (or
1808
+ * a default decoder).
1809
+ *
1810
+ * @template {string} Prefix
1811
+ * @template {unknown} Data
1812
+ * @template {number} Code
1813
+ * @template {number} Alg
1814
+ * @template {API.Version} Ver
1815
+ * @param {API.ToString<API.Link<Data, Code, Alg, Ver>, Prefix>} source
1816
+ * @param {API.MultibaseDecoder<Prefix>} [base]
1817
+ * @returns {CID<Data, Code, Alg, Ver>}
1818
+ */
1819
+ static parse (source, base) {
1820
+ const [prefix, bytes] = parseCIDtoBytes(source, base);
1821
+
1822
+ const cid = CID.decode(bytes);
1823
+
1824
+ // Cache string representation to avoid computing it on `this.toString()`
1825
+ baseCache(cid).set(prefix, source);
1826
+
1827
+ return cid
1828
+ }
1829
+ }
1830
+
1831
+ /**
1832
+ * @template {string} Prefix
1833
+ * @template {unknown} Data
1834
+ * @template {number} Code
1835
+ * @template {number} Alg
1836
+ * @template {API.Version} Ver
1837
+ * @param {API.ToString<API.Link<Data, Code, Alg, Ver>, Prefix>} source
1838
+ * @param {API.MultibaseDecoder<Prefix>} [base]
1839
+ * @returns {[Prefix, API.ByteView<API.Link<Data, Code, Alg, Ver>>]}
1840
+ */
1841
+ const parseCIDtoBytes = (source, base) => {
1842
+ switch (source[0]) {
1843
+ // CIDv0 is parsed differently
1844
+ case 'Q': {
1845
+ const decoder = base || base58btc;
1846
+ return [
1847
+ /** @type {Prefix} */ (base58btc.prefix),
1848
+ decoder.decode(`${base58btc.prefix}${source}`)
1849
+ ]
1850
+ }
1851
+ case base58btc.prefix: {
1852
+ const decoder = base || base58btc;
1853
+ return [/** @type {Prefix} */(base58btc.prefix), decoder.decode(source)]
1854
+ }
1855
+ case base32.prefix: {
1856
+ const decoder = base || base32;
1857
+ return [/** @type {Prefix} */(base32.prefix), decoder.decode(source)]
1858
+ }
1859
+ default: {
1860
+ if (base == null) {
1861
+ throw Error(
1862
+ 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'
1863
+ )
1864
+ }
1865
+ return [/** @type {Prefix} */(source[0]), base.decode(source)]
1866
+ }
1867
+ }
1868
+ };
1869
+
1870
+ /**
1871
+ *
1872
+ * @param {Uint8Array} bytes
1873
+ * @param {Map<string, string>} cache
1874
+ * @param {API.MultibaseEncoder<'z'>} base
1875
+ */
1876
+ const toStringV0 = (bytes, cache, base) => {
1877
+ const { prefix } = base;
1878
+ if (prefix !== base58btc.prefix) {
1879
+ throw Error(`Cannot string encode V0 in ${base.name} encoding`)
1880
+ }
1881
+
1882
+ const cid = cache.get(prefix);
1883
+ if (cid == null) {
1884
+ const cid = base.encode(bytes).slice(1);
1885
+ cache.set(prefix, cid);
1886
+ return cid
1887
+ } else {
1888
+ return cid
1889
+ }
1890
+ };
1891
+
1892
+ /**
1893
+ * @template {string} Prefix
1894
+ * @param {Uint8Array} bytes
1895
+ * @param {Map<string, string>} cache
1896
+ * @param {API.MultibaseEncoder<Prefix>} base
1897
+ */
1898
+ const toStringV1 = (bytes, cache, base) => {
1899
+ const { prefix } = base;
1900
+ const cid = cache.get(prefix);
1901
+ if (cid == null) {
1902
+ const cid = base.encode(bytes);
1903
+ cache.set(prefix, cid);
1904
+ return cid
1905
+ } else {
1906
+ return cid
1907
+ }
1908
+ };
1909
+
1910
+ const DAG_PB_CODE = 0x70;
1911
+ const SHA_256_CODE = 0x12;
1912
+
1913
+ /**
1914
+ * @param {API.Version} version
1915
+ * @param {number} code
1916
+ * @param {Uint8Array} multihash
1917
+ * @returns {Uint8Array}
1918
+ */
1919
+ const encodeCID = (version, code, multihash) => {
1920
+ const codeOffset = encodingLength(version);
1921
+ const hashOffset = codeOffset + encodingLength(code);
1922
+ const bytes = new Uint8Array(hashOffset + multihash.byteLength);
1923
+ encodeTo(version, bytes, 0);
1924
+ encodeTo(code, bytes, codeOffset);
1925
+ bytes.set(multihash, hashOffset);
1926
+ return bytes
1927
+ };
1928
+
1929
+ const cidSymbol = Symbol.for('@ipld/js-cid/CID');
1930
+
1931
+ // @ts-check
1932
+
1933
+ const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 };
1934
+ ({ ...sha2, ...identity$1 });
1935
+
1936
+ /**
1937
+ * To guarantee Uint8Array semantics, convert nodejs Buffers
1938
+ * into vanilla Uint8Arrays
1939
+ */
1940
+ function asUint8Array(buf) {
1941
+ if (globalThis.Buffer != null) {
1942
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
1943
+ }
1944
+ return buf;
1945
+ }
1946
+
1947
+ /**
1948
+ * Where possible returns a Uint8Array of the requested size that references
1949
+ * uninitialized memory. Only use if you are certain you will immediately
1950
+ * overwrite every value in the returned `Uint8Array`.
1951
+ */
1952
+ function allocUnsafe(size = 0) {
1953
+ if (globalThis.Buffer?.allocUnsafe != null) {
1954
+ return asUint8Array(globalThis.Buffer.allocUnsafe(size));
1955
+ }
1956
+ return new Uint8Array(size);
1957
+ }
1958
+
1959
+ function createCodec(name, prefix, encode, decode) {
1960
+ return {
1961
+ name,
1962
+ prefix,
1963
+ encoder: {
1964
+ name,
1965
+ prefix,
1966
+ encode
1967
+ },
1968
+ decoder: {
1969
+ decode
1970
+ }
1971
+ };
1972
+ }
1973
+ const string = createCodec('utf8', 'u', (buf) => {
1974
+ const decoder = new TextDecoder('utf8');
1975
+ return 'u' + decoder.decode(buf);
1976
+ }, (str) => {
1977
+ const encoder = new TextEncoder();
1978
+ return encoder.encode(str.substring(1));
1979
+ });
1980
+ const ascii = createCodec('ascii', 'a', (buf) => {
1981
+ let string = 'a';
1982
+ for (let i = 0; i < buf.length; i++) {
1983
+ string += String.fromCharCode(buf[i]);
1984
+ }
1985
+ return string;
1986
+ }, (str) => {
1987
+ str = str.substring(1);
1988
+ const buf = allocUnsafe(str.length);
1989
+ for (let i = 0; i < str.length; i++) {
1990
+ buf[i] = str.charCodeAt(i);
1991
+ }
1992
+ return buf;
1993
+ });
1994
+ const BASES = {
1995
+ utf8: string,
1996
+ 'utf-8': string,
1997
+ hex: bases.base16,
1998
+ latin1: ascii,
1999
+ ascii: ascii,
2000
+ binary: ascii,
2001
+ ...bases
2002
+ };
2003
+
2004
+ /**
2005
+ * Turns a `Uint8Array` into a string.
2006
+ *
2007
+ * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.
2008
+ *
2009
+ * Also `ascii` which is similar to node's 'binary' encoding.
2010
+ */
2011
+ function toString$1(array, encoding = 'utf8') {
2012
+ const base = BASES[encoding];
2013
+ if (base == null) {
2014
+ throw new Error(`Unsupported encoding "${encoding}"`);
2015
+ }
2016
+ if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
2017
+ return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8');
2018
+ }
2019
+ // strip multibase prefix
2020
+ return base.encoder.encode(array).substring(1);
2021
+ }
2022
+
2023
+ const isV4 = isIPv4;
2024
+ const isV6 = isIPv6;
2025
+ // Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7
2026
+ // but with buf/offset args removed because we don't use them
2027
+ const toBytes = function (ip) {
2028
+ let offset = 0;
2029
+ ip = ip.toString().trim();
2030
+ if (isV4(ip)) {
2031
+ const bytes = new Uint8Array(offset + 4);
2032
+ ip.split(/\./g).forEach((byte) => {
2033
+ bytes[offset++] = parseInt(byte, 10) & 0xff;
2034
+ });
2035
+ return bytes;
2036
+ }
2037
+ if (isV6(ip)) {
2038
+ const sections = ip.split(':', 8);
2039
+ let i;
2040
+ for (i = 0; i < sections.length; i++) {
2041
+ const isv4 = isV4(sections[i]);
2042
+ let v4Buffer;
2043
+ if (isv4) {
2044
+ v4Buffer = toBytes(sections[i]);
2045
+ sections[i] = toString$1(v4Buffer.slice(0, 2), 'base16');
2046
+ }
2047
+ if (v4Buffer != null && ++i < 8) {
2048
+ sections.splice(i, 0, toString$1(v4Buffer.slice(2, 4), 'base16'));
2049
+ }
2050
+ }
2051
+ if (sections[0] === '') {
2052
+ while (sections.length < 8)
2053
+ sections.unshift('0');
2054
+ }
2055
+ else if (sections[sections.length - 1] === '') {
2056
+ while (sections.length < 8)
2057
+ sections.push('0');
2058
+ }
2059
+ else if (sections.length < 8) {
2060
+ for (i = 0; i < sections.length && sections[i] !== ''; i++)
2061
+ ;
2062
+ const argv = [i, 1];
2063
+ for (i = 9 - sections.length; i > 0; i--) {
2064
+ argv.push('0');
2065
+ }
2066
+ sections.splice.apply(sections, argv);
2067
+ }
2068
+ const bytes = new Uint8Array(offset + 16);
2069
+ for (i = 0; i < sections.length; i++) {
2070
+ const word = parseInt(sections[i], 16);
2071
+ bytes[offset++] = (word >> 8) & 0xff;
2072
+ bytes[offset++] = word & 0xff;
2073
+ }
2074
+ return bytes;
2075
+ }
2076
+ throw new Error('invalid ip address');
2077
+ };
2078
+ // Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63
2079
+ const toString = function (buf, offset = 0, length) {
2080
+ offset = ~~offset;
2081
+ length = length ?? (buf.length - offset);
2082
+ const view = new DataView(buf.buffer);
2083
+ if (length === 4) {
2084
+ const result = [];
2085
+ // IPv4
2086
+ for (let i = 0; i < length; i++) {
2087
+ result.push(buf[offset + i]);
2088
+ }
2089
+ return result.join('.');
2090
+ }
2091
+ if (length === 16) {
2092
+ const result = [];
2093
+ // IPv6
2094
+ for (let i = 0; i < length; i += 2) {
2095
+ result.push(view.getUint16(offset + i).toString(16));
2096
+ }
2097
+ return result.join(':')
2098
+ .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')
2099
+ .replace(/:{3,4}/, '::');
2100
+ }
2101
+ return '';
2102
+ };
2103
+
2104
+ const V = -1;
2105
+ const names = {};
2106
+ const codes = {};
2107
+ const table = [
2108
+ [4, 32, 'ip4'],
2109
+ [6, 16, 'tcp'],
2110
+ [33, 16, 'dccp'],
2111
+ [41, 128, 'ip6'],
2112
+ [42, V, 'ip6zone'],
2113
+ [53, V, 'dns', true],
2114
+ [54, V, 'dns4', true],
2115
+ [55, V, 'dns6', true],
2116
+ [56, V, 'dnsaddr', true],
2117
+ [132, 16, 'sctp'],
2118
+ [273, 16, 'udp'],
2119
+ [275, 0, 'p2p-webrtc-star'],
2120
+ [276, 0, 'p2p-webrtc-direct'],
2121
+ [277, 0, 'p2p-stardust'],
2122
+ [280, 0, 'webrtc'],
2123
+ [290, 0, 'p2p-circuit'],
2124
+ [301, 0, 'udt'],
2125
+ [302, 0, 'utp'],
2126
+ [400, V, 'unix', false, true],
2127
+ // `ipfs` is added before `p2p` for legacy support.
2128
+ // All text representations will default to `p2p`, but `ipfs` will
2129
+ // still be supported
2130
+ [421, V, 'ipfs'],
2131
+ // `p2p` is the preferred name for 421, and is now the default
2132
+ [421, V, 'p2p'],
2133
+ [443, 0, 'https'],
2134
+ [444, 96, 'onion'],
2135
+ [445, 296, 'onion3'],
2136
+ [446, V, 'garlic64'],
2137
+ [460, 0, 'quic'],
2138
+ [465, 0, 'webtransport'],
2139
+ [466, V, 'certhash'],
2140
+ [477, 0, 'ws'],
2141
+ [478, 0, 'wss'],
2142
+ [479, 0, 'p2p-websocket-star'],
2143
+ [480, 0, 'http'],
2144
+ [777, V, 'memory']
2145
+ ];
2146
+ // populate tables
2147
+ table.forEach(row => {
2148
+ const proto = createProtocol(...row);
2149
+ codes[proto.code] = proto;
2150
+ names[proto.name] = proto;
2151
+ });
2152
+ function createProtocol(code, size, name, resolvable, path) {
2153
+ return {
2154
+ code,
2155
+ size,
2156
+ name,
2157
+ resolvable: Boolean(resolvable),
2158
+ path: Boolean(path)
2159
+ };
2160
+ }
2161
+ function getProtocol(proto) {
2162
+ if (typeof proto === 'number') {
2163
+ if (codes[proto] != null) {
2164
+ return codes[proto];
2165
+ }
2166
+ throw new Error(`no protocol with code: ${proto}`);
2167
+ }
2168
+ else if (typeof proto === 'string') {
2169
+ if (names[proto] != null) {
2170
+ return names[proto];
2171
+ }
2172
+ throw new Error(`no protocol with name: ${proto}`);
2173
+ }
2174
+ throw new Error(`invalid protocol id type: ${typeof proto}`);
2175
+ }
2176
+
2177
+ var encode_1 = encode;
2178
+
2179
+ var MSB$1 = 0x80
2180
+ , REST$1 = 0x7F
2181
+ , MSBALL = ~REST$1
2182
+ , INT = Math.pow(2, 31);
2183
+
2184
+ function encode(num, out, offset) {
2185
+ if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) {
2186
+ encode.bytes = 0;
2187
+ throw new RangeError('Could not encode varint')
2188
+ }
2189
+ out = out || [];
2190
+ offset = offset || 0;
2191
+ var oldOffset = offset;
2192
+
2193
+ while(num >= INT) {
2194
+ out[offset++] = (num & 0xFF) | MSB$1;
2195
+ num /= 128;
2196
+ }
2197
+ while(num & MSBALL) {
2198
+ out[offset++] = (num & 0xFF) | MSB$1;
2199
+ num >>>= 7;
2200
+ }
2201
+ out[offset] = num | 0;
2202
+
2203
+ encode.bytes = offset - oldOffset + 1;
2204
+
2205
+ return out
2206
+ }
2207
+
2208
+ var decode = read;
2209
+
2210
+ var MSB = 0x80
2211
+ , REST = 0x7F;
2212
+
2213
+ function read(buf, offset) {
2214
+ var res = 0
2215
+ , offset = offset || 0
2216
+ , shift = 0
2217
+ , counter = offset
2218
+ , b
2219
+ , l = buf.length;
2220
+
2221
+ do {
2222
+ if (counter >= l || shift > 49) {
2223
+ read.bytes = 0;
2224
+ throw new RangeError('Could not decode varint')
2225
+ }
2226
+ b = buf[counter++];
2227
+ res += shift < 28
2228
+ ? (b & REST) << shift
2229
+ : (b & REST) * Math.pow(2, shift);
2230
+ shift += 7;
2231
+ } while (b >= MSB)
2232
+
2233
+ read.bytes = counter - offset;
2234
+
2235
+ return res
2236
+ }
2237
+
2238
+ var N1 = Math.pow(2, 7);
2239
+ var N2 = Math.pow(2, 14);
2240
+ var N3 = Math.pow(2, 21);
2241
+ var N4 = Math.pow(2, 28);
2242
+ var N5 = Math.pow(2, 35);
2243
+ var N6 = Math.pow(2, 42);
2244
+ var N7 = Math.pow(2, 49);
2245
+ var N8 = Math.pow(2, 56);
2246
+ var N9 = Math.pow(2, 63);
2247
+
2248
+ var length = function (value) {
2249
+ return (
2250
+ value < N1 ? 1
2251
+ : value < N2 ? 2
2252
+ : value < N3 ? 3
2253
+ : value < N4 ? 4
2254
+ : value < N5 ? 5
2255
+ : value < N6 ? 6
2256
+ : value < N7 ? 7
2257
+ : value < N8 ? 8
2258
+ : value < N9 ? 9
2259
+ : 10
2260
+ )
2261
+ };
2262
+
2263
+ var varint = {
2264
+ encode: encode_1
2265
+ , decode: decode
2266
+ , encodingLength: length
2267
+ };
2268
+
2269
+ /**
2270
+ * Create a `Uint8Array` from the passed string
2271
+ *
2272
+ * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
2273
+ *
2274
+ * Also `ascii` which is similar to node's 'binary' encoding.
2275
+ */
2276
+ function fromString$1(string, encoding = 'utf8') {
2277
+ const base = BASES[encoding];
2278
+ if (base == null) {
2279
+ throw new Error(`Unsupported encoding "${encoding}"`);
2280
+ }
2281
+ if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {
2282
+ return asUint8Array(globalThis.Buffer.from(string, 'utf-8'));
2283
+ }
2284
+ // add multibase prefix
2285
+ return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
2286
+ }
2287
+
2288
+ /**
2289
+ * Returns a new Uint8Array created by concatenating the passed ArrayLikes
2290
+ */
2291
+ function concat(arrays, length) {
2292
+ if (length == null) {
2293
+ length = arrays.reduce((acc, curr) => acc + curr.length, 0);
2294
+ }
2295
+ const output = allocUnsafe(length);
2296
+ let offset = 0;
2297
+ for (const arr of arrays) {
2298
+ output.set(arr, offset);
2299
+ offset += arr.length;
2300
+ }
2301
+ return asUint8Array(output);
2302
+ }
2303
+
2304
+ /**
2305
+ * Convert [code,Uint8Array] to string
2306
+ */
2307
+ function convertToString(proto, buf) {
2308
+ const protocol = getProtocol(proto);
2309
+ switch (protocol.code) {
2310
+ case 4: // ipv4
2311
+ case 41: // ipv6
2312
+ return bytes2ip(buf);
2313
+ case 6: // tcp
2314
+ case 273: // udp
2315
+ case 33: // dccp
2316
+ case 132: // sctp
2317
+ return bytes2port(buf).toString();
2318
+ case 53: // dns
2319
+ case 54: // dns4
2320
+ case 55: // dns6
2321
+ case 56: // dnsaddr
2322
+ case 400: // unix
2323
+ case 777: // memory
2324
+ return bytes2str(buf);
2325
+ case 421: // ipfs
2326
+ return bytes2mh(buf);
2327
+ case 444: // onion
2328
+ return bytes2onion(buf);
2329
+ case 445: // onion3
2330
+ return bytes2onion(buf);
2331
+ case 466: // certhash
2332
+ return bytes2mb(buf);
2333
+ default:
2334
+ return toString$1(buf, 'base16'); // no clue. convert to hex
2335
+ }
2336
+ }
2337
+ function convertToBytes(proto, str) {
2338
+ const protocol = getProtocol(proto);
2339
+ switch (protocol.code) {
2340
+ case 4: // ipv4
2341
+ return ip2bytes(str);
2342
+ case 41: // ipv6
2343
+ return ip2bytes(str);
2344
+ case 6: // tcp
2345
+ case 273: // udp
2346
+ case 33: // dccp
2347
+ case 132: // sctp
2348
+ return port2bytes(parseInt(str, 10));
2349
+ case 53: // dns
2350
+ case 54: // dns4
2351
+ case 55: // dns6
2352
+ case 56: // dnsaddr
2353
+ case 400: // unix
2354
+ case 777: // memory
2355
+ return str2bytes(str);
2356
+ case 421: // ipfs
2357
+ return mh2bytes(str);
2358
+ case 444: // onion
2359
+ return onion2bytes(str);
2360
+ case 445: // onion3
2361
+ return onion32bytes(str);
2362
+ case 466: // certhash
2363
+ return mb2bytes(str);
2364
+ default:
2365
+ return fromString$1(str, 'base16'); // no clue. convert from hex
2366
+ }
2367
+ }
2368
+ const decoders = Object.values(bases).map((c) => c.decoder);
2369
+ const anybaseDecoder = (function () {
2370
+ let acc = decoders[0].or(decoders[1]);
2371
+ decoders.slice(2).forEach((d) => (acc = acc.or(d)));
2372
+ return acc;
2373
+ })();
2374
+ function ip2bytes(ipString) {
2375
+ if (!isIP(ipString)) {
2376
+ throw new Error('invalid ip address');
2377
+ }
2378
+ return toBytes(ipString);
2379
+ }
2380
+ function bytes2ip(ipBuff) {
2381
+ const ipString = toString(ipBuff, 0, ipBuff.length);
2382
+ if (ipString == null) {
2383
+ throw new Error('ipBuff is required');
2384
+ }
2385
+ if (!isIP(ipString)) {
2386
+ throw new Error('invalid ip address');
2387
+ }
2388
+ return ipString;
2389
+ }
2390
+ function port2bytes(port) {
2391
+ const buf = new ArrayBuffer(2);
2392
+ const view = new DataView(buf);
2393
+ view.setUint16(0, port);
2394
+ return new Uint8Array(buf);
2395
+ }
2396
+ function bytes2port(buf) {
2397
+ const view = new DataView(buf.buffer);
2398
+ return view.getUint16(buf.byteOffset);
2399
+ }
2400
+ function str2bytes(str) {
2401
+ const buf = fromString$1(str);
2402
+ const size = Uint8Array.from(varint.encode(buf.length));
2403
+ return concat([size, buf], size.length + buf.length);
2404
+ }
2405
+ function bytes2str(buf) {
2406
+ const size = varint.decode(buf);
2407
+ buf = buf.slice(varint.decode.bytes);
2408
+ if (buf.length !== size) {
2409
+ throw new Error('inconsistent lengths');
2410
+ }
2411
+ return toString$1(buf);
2412
+ }
2413
+ function mh2bytes(hash) {
2414
+ let mh;
2415
+ if (hash[0] === 'Q' || hash[0] === '1') {
2416
+ mh = decode$1(base58btc.decode(`z${hash}`)).bytes;
2417
+ }
2418
+ else {
2419
+ mh = CID.parse(hash).multihash.bytes;
2420
+ }
2421
+ // the address is a varint prefixed multihash string representation
2422
+ const size = Uint8Array.from(varint.encode(mh.length));
2423
+ return concat([size, mh], size.length + mh.length);
2424
+ }
2425
+ function mb2bytes(mbstr) {
2426
+ const mb = anybaseDecoder.decode(mbstr);
2427
+ const size = Uint8Array.from(varint.encode(mb.length));
2428
+ return concat([size, mb], size.length + mb.length);
2429
+ }
2430
+ function bytes2mb(buf) {
2431
+ const size = varint.decode(buf);
2432
+ const hash = buf.slice(varint.decode.bytes);
2433
+ if (hash.length !== size) {
2434
+ throw new Error('inconsistent lengths');
2435
+ }
2436
+ return 'u' + toString$1(hash, 'base64url');
2437
+ }
2438
+ /**
2439
+ * Converts bytes to bas58btc string
2440
+ */
2441
+ function bytes2mh(buf) {
2442
+ const size = varint.decode(buf);
2443
+ const address = buf.slice(varint.decode.bytes);
2444
+ if (address.length !== size) {
2445
+ throw new Error('inconsistent lengths');
2446
+ }
2447
+ return toString$1(address, 'base58btc');
2448
+ }
2449
+ function onion2bytes(str) {
2450
+ const addr = str.split(':');
2451
+ if (addr.length !== 2) {
2452
+ throw new Error(`failed to parse onion addr: ["'${addr.join('", "')}'"]' does not contain a port number`);
2453
+ }
2454
+ if (addr[0].length !== 16) {
2455
+ throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`);
2456
+ }
2457
+ // onion addresses do not include the multibase prefix, add it before decoding
2458
+ const buf = base32.decode('b' + addr[0]);
2459
+ // onion port number
2460
+ const port = parseInt(addr[1], 10);
2461
+ if (port < 1 || port > 65536) {
2462
+ throw new Error('Port number is not in range(1, 65536)');
2463
+ }
2464
+ const portBuf = port2bytes(port);
2465
+ return concat([buf, portBuf], buf.length + portBuf.length);
2466
+ }
2467
+ function onion32bytes(str) {
2468
+ const addr = str.split(':');
2469
+ if (addr.length !== 2) {
2470
+ throw new Error(`failed to parse onion addr: ["'${addr.join('", "')}'"]' does not contain a port number`);
2471
+ }
2472
+ if (addr[0].length !== 56) {
2473
+ throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`);
2474
+ }
2475
+ // onion addresses do not include the multibase prefix, add it before decoding
2476
+ const buf = base32.decode(`b${addr[0]}`);
2477
+ // onion port number
2478
+ const port = parseInt(addr[1], 10);
2479
+ if (port < 1 || port > 65536) {
2480
+ throw new Error('Port number is not in range(1, 65536)');
2481
+ }
2482
+ const portBuf = port2bytes(port);
2483
+ return concat([buf, portBuf], buf.length + portBuf.length);
2484
+ }
2485
+ function bytes2onion(buf) {
2486
+ const addrBytes = buf.slice(0, buf.length - 2);
2487
+ const portBytes = buf.slice(buf.length - 2);
2488
+ const addr = toString$1(addrBytes, 'base32');
2489
+ const port = bytes2port(portBytes);
2490
+ return `${addr}:${port}`;
2491
+ }
2492
+
2493
+ /**
2494
+ * string -> [[str name, str addr]... ]
2495
+ */
2496
+ function stringToStringTuples(str) {
2497
+ const tuples = [];
2498
+ const parts = str.split('/').slice(1); // skip first empty elem
2499
+ if (parts.length === 1 && parts[0] === '') {
2500
+ return [];
2501
+ }
2502
+ for (let p = 0; p < parts.length; p++) {
2503
+ const part = parts[p];
2504
+ const proto = getProtocol(part);
2505
+ if (proto.size === 0) {
2506
+ tuples.push([part]);
2507
+ continue;
2508
+ }
2509
+ p++; // advance addr part
2510
+ if (p >= parts.length) {
2511
+ throw ParseError('invalid address: ' + str);
2512
+ }
2513
+ // if it's a path proto, take the rest
2514
+ if (proto.path === true) {
2515
+ tuples.push([
2516
+ part,
2517
+ // TODO: should we need to check each path part to see if it's a proto?
2518
+ // This would allow for other protocols to be added after a unix path,
2519
+ // however it would have issues if the path had a protocol name in the path
2520
+ cleanPath(parts.slice(p).join('/'))
2521
+ ]);
2522
+ break;
2523
+ }
2524
+ tuples.push([part, parts[p]]);
2525
+ }
2526
+ return tuples;
2527
+ }
2528
+ /**
2529
+ * [[str name, str addr]... ] -> string
2530
+ */
2531
+ function stringTuplesToString(tuples) {
2532
+ const parts = [];
2533
+ tuples.map((tup) => {
2534
+ const proto = protoFromTuple(tup);
2535
+ parts.push(proto.name);
2536
+ if (tup.length > 1 && tup[1] != null) {
2537
+ parts.push(tup[1]);
2538
+ }
2539
+ return null;
2540
+ });
2541
+ return cleanPath(parts.join('/'));
2542
+ }
2543
+ /**
2544
+ * [[str name, str addr]... ] -> [[int code, Uint8Array]... ]
2545
+ */
2546
+ function stringTuplesToTuples(tuples) {
2547
+ return tuples.map((tup) => {
2548
+ if (!Array.isArray(tup)) {
2549
+ tup = [tup];
2550
+ }
2551
+ const proto = protoFromTuple(tup);
2552
+ if (tup.length > 1) {
2553
+ return [proto.code, convertToBytes(proto.code, tup[1])];
2554
+ }
2555
+ return [proto.code];
2556
+ });
2557
+ }
2558
+ /**
2559
+ * Convert tuples to string tuples
2560
+ *
2561
+ * [[int code, Uint8Array]... ] -> [[int code, str addr]... ]
2562
+ */
2563
+ function tuplesToStringTuples(tuples) {
2564
+ return tuples.map(tup => {
2565
+ const proto = protoFromTuple(tup);
2566
+ if (tup[1] != null) {
2567
+ return [proto.code, convertToString(proto.code, tup[1])];
2568
+ }
2569
+ return [proto.code];
2570
+ });
2571
+ }
2572
+ /**
2573
+ * [[int code, Uint8Array ]... ] -> Uint8Array
2574
+ */
2575
+ function tuplesToBytes(tuples) {
2576
+ return fromBytes(concat(tuples.map((tup) => {
2577
+ const proto = protoFromTuple(tup);
2578
+ let buf = Uint8Array.from(varint.encode(proto.code));
2579
+ if (tup.length > 1 && tup[1] != null) {
2580
+ buf = concat([buf, tup[1]]); // add address buffer
2581
+ }
2582
+ return buf;
2583
+ })));
2584
+ }
2585
+ function sizeForAddr(p, addr) {
2586
+ if (p.size > 0) {
2587
+ return p.size / 8;
2588
+ }
2589
+ else if (p.size === 0) {
2590
+ return 0;
2591
+ }
2592
+ else {
2593
+ const size = varint.decode(addr);
2594
+ return size + varint.decode.bytes;
2595
+ }
2596
+ }
2597
+ function bytesToTuples(buf) {
2598
+ const tuples = [];
2599
+ let i = 0;
2600
+ while (i < buf.length) {
2601
+ const code = varint.decode(buf, i);
2602
+ const n = varint.decode.bytes;
2603
+ const p = getProtocol(code);
2604
+ const size = sizeForAddr(p, buf.slice(i + n));
2605
+ if (size === 0) {
2606
+ tuples.push([code]);
2607
+ i += n;
2608
+ continue;
2609
+ }
2610
+ const addr = buf.slice(i + n, i + n + size);
2611
+ i += (size + n);
2612
+ if (i > buf.length) { // did not end _exactly_ at buffer.length
2613
+ throw ParseError('Invalid address Uint8Array: ' + toString$1(buf, 'base16'));
2614
+ }
2615
+ // ok, tuple seems good.
2616
+ tuples.push([code, addr]);
2617
+ }
2618
+ return tuples;
2619
+ }
2620
+ /**
2621
+ * Uint8Array -> String
2622
+ */
2623
+ function bytesToString(buf) {
2624
+ const a = bytesToTuples(buf);
2625
+ const b = tuplesToStringTuples(a);
2626
+ return stringTuplesToString(b);
2627
+ }
2628
+ /**
2629
+ * String -> Uint8Array
2630
+ */
2631
+ function stringToBytes(str) {
2632
+ str = cleanPath(str);
2633
+ const a = stringToStringTuples(str);
2634
+ const b = stringTuplesToTuples(a);
2635
+ return tuplesToBytes(b);
2636
+ }
2637
+ /**
2638
+ * String -> Uint8Array
2639
+ */
2640
+ function fromString(str) {
2641
+ return stringToBytes(str);
2642
+ }
2643
+ /**
2644
+ * Uint8Array -> Uint8Array
2645
+ */
2646
+ function fromBytes(buf) {
2647
+ const err = validateBytes(buf);
2648
+ if (err != null) {
2649
+ throw err;
2650
+ }
2651
+ return Uint8Array.from(buf); // copy
2652
+ }
2653
+ function validateBytes(buf) {
2654
+ try {
2655
+ bytesToTuples(buf); // try to parse. will throw if breaks
2656
+ }
2657
+ catch (err) {
2658
+ return err;
2659
+ }
2660
+ }
2661
+ function cleanPath(str) {
2662
+ return '/' + str.trim().split('/').filter((a) => a).join('/');
2663
+ }
2664
+ function ParseError(str) {
2665
+ return new Error('Error parsing address: ' + str);
2666
+ }
2667
+ function protoFromTuple(tup) {
2668
+ const proto = getProtocol(tup[0]);
2669
+ return proto;
2670
+ }
2671
+
2672
+ /**
2673
+ * Returns true if the two passed Uint8Arrays have the same content
2674
+ */
2675
+ function equals(a, b) {
2676
+ if (a === b) {
2677
+ return true;
2678
+ }
2679
+ if (a.byteLength !== b.byteLength) {
2680
+ return false;
2681
+ }
2682
+ for (let i = 0; i < a.byteLength; i++) {
2683
+ if (a[i] !== b[i]) {
2684
+ return false;
2685
+ }
2686
+ }
2687
+ return true;
2688
+ }
2689
+
2690
+ var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2691
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
2692
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
2693
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
2694
+ };
2695
+ var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2696
+ if (kind === "m") throw new TypeError("Private method is not writable");
2697
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
2698
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
2699
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
2700
+ };
2701
+ var _DefaultMultiaddr_string, _DefaultMultiaddr_tuples, _DefaultMultiaddr_stringTuples, _a;
2702
+ const inspect = Symbol.for('nodejs.util.inspect.custom');
2703
+ const DNS_CODES = [
2704
+ getProtocol('dns').code,
2705
+ getProtocol('dns4').code,
2706
+ getProtocol('dns6').code,
2707
+ getProtocol('dnsaddr').code
2708
+ ];
2709
+ const P2P_CODES = [
2710
+ getProtocol('p2p').code,
2711
+ getProtocol('ipfs').code
2712
+ ];
2713
+ const resolvers = new Map();
2714
+ const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');
2715
+ /**
2716
+ * Check if object is a CID instance
2717
+ */
2718
+ function isMultiaddr(value) {
2719
+ return Boolean(value?.[symbol]);
2720
+ }
2721
+ /**
2722
+ * Creates a [multiaddr](https://github.com/multiformats/multiaddr) from
2723
+ * a Uint8Array, String or another Multiaddr instance
2724
+ * public key.
2725
+ *
2726
+ */
2727
+ class DefaultMultiaddr {
2728
+ /**
2729
+ * @example
2730
+ * ```js
2731
+ * new Multiaddr('/ip4/127.0.0.1/tcp/4001')
2732
+ * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001>
2733
+ * ```
2734
+ *
2735
+ * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)
2736
+ */
2737
+ constructor(addr) {
2738
+ _DefaultMultiaddr_string.set(this, void 0);
2739
+ _DefaultMultiaddr_tuples.set(this, void 0);
2740
+ _DefaultMultiaddr_stringTuples.set(this, void 0);
2741
+ this[_a] = true;
2742
+ // default
2743
+ if (addr == null) {
2744
+ addr = '';
2745
+ }
2746
+ if (addr instanceof Uint8Array) {
2747
+ this.bytes = fromBytes(addr);
2748
+ }
2749
+ else if (typeof addr === 'string') {
2750
+ if (addr.length > 0 && addr.charAt(0) !== '/') {
2751
+ throw new Error(`multiaddr "${addr}" must start with a "/"`);
2752
+ }
2753
+ this.bytes = fromString(addr);
2754
+ }
2755
+ else if (isMultiaddr(addr)) { // Multiaddr
2756
+ this.bytes = fromBytes(addr.bytes); // validate + copy buffer
2757
+ }
2758
+ else {
2759
+ throw new Error('addr must be a string, Buffer, or another Multiaddr');
2760
+ }
2761
+ }
2762
+ toString() {
2763
+ if (__classPrivateFieldGet(this, _DefaultMultiaddr_string, "f") == null) {
2764
+ __classPrivateFieldSet(this, _DefaultMultiaddr_string, bytesToString(this.bytes), "f");
2765
+ }
2766
+ return __classPrivateFieldGet(this, _DefaultMultiaddr_string, "f");
2767
+ }
2768
+ toJSON() {
2769
+ return this.toString();
2770
+ }
2771
+ toOptions() {
2772
+ const codes = this.protoCodes();
2773
+ const parts = this.toString().split('/').slice(1);
2774
+ let transport;
2775
+ let port;
2776
+ if (parts.length > 2) {
2777
+ // default to https when protocol & port are omitted from DNS addrs
2778
+ if (DNS_CODES.includes(codes[0]) && P2P_CODES.includes(codes[1])) {
2779
+ transport = getProtocol('tcp').name;
2780
+ port = 443;
2781
+ }
2782
+ else {
2783
+ transport = getProtocol(parts[2]).name;
2784
+ port = parseInt(parts[3]);
2785
+ }
2786
+ }
2787
+ else if (DNS_CODES.includes(codes[0])) {
2788
+ transport = getProtocol('tcp').name;
2789
+ port = 443;
2790
+ }
2791
+ else {
2792
+ throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');
2793
+ }
2794
+ const opts = {
2795
+ family: (codes[0] === 41 || codes[0] === 55) ? 6 : 4,
2796
+ host: parts[1],
2797
+ transport,
2798
+ port
2799
+ };
2800
+ return opts;
2801
+ }
2802
+ protos() {
2803
+ return this.protoCodes().map(code => Object.assign({}, getProtocol(code)));
2804
+ }
2805
+ protoCodes() {
2806
+ const codes = [];
2807
+ const buf = this.bytes;
2808
+ let i = 0;
2809
+ while (i < buf.length) {
2810
+ const code = varint.decode(buf, i);
2811
+ const n = varint.decode.bytes;
2812
+ const p = getProtocol(code);
2813
+ const size = sizeForAddr(p, buf.slice(i + n));
2814
+ i += (size + n);
2815
+ codes.push(code);
2816
+ }
2817
+ return codes;
2818
+ }
2819
+ protoNames() {
2820
+ return this.protos().map(proto => proto.name);
2821
+ }
2822
+ tuples() {
2823
+ if (__classPrivateFieldGet(this, _DefaultMultiaddr_tuples, "f") == null) {
2824
+ __classPrivateFieldSet(this, _DefaultMultiaddr_tuples, bytesToTuples(this.bytes), "f");
2825
+ }
2826
+ return __classPrivateFieldGet(this, _DefaultMultiaddr_tuples, "f");
2827
+ }
2828
+ stringTuples() {
2829
+ if (__classPrivateFieldGet(this, _DefaultMultiaddr_stringTuples, "f") == null) {
2830
+ __classPrivateFieldSet(this, _DefaultMultiaddr_stringTuples, tuplesToStringTuples(this.tuples()), "f");
2831
+ }
2832
+ return __classPrivateFieldGet(this, _DefaultMultiaddr_stringTuples, "f");
2833
+ }
2834
+ encapsulate(addr) {
2835
+ addr = new DefaultMultiaddr(addr);
2836
+ return new DefaultMultiaddr(this.toString() + addr.toString());
2837
+ }
2838
+ decapsulate(addr) {
2839
+ const addrString = addr.toString();
2840
+ const s = this.toString();
2841
+ const i = s.lastIndexOf(addrString);
2842
+ if (i < 0) {
2843
+ throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`);
2844
+ }
2845
+ return new DefaultMultiaddr(s.slice(0, i));
2846
+ }
2847
+ decapsulateCode(code) {
2848
+ const tuples = this.tuples();
2849
+ for (let i = tuples.length - 1; i >= 0; i--) {
2850
+ if (tuples[i][0] === code) {
2851
+ return new DefaultMultiaddr(tuplesToBytes(tuples.slice(0, i)));
2852
+ }
2853
+ }
2854
+ return this;
2855
+ }
2856
+ getPeerId() {
2857
+ try {
2858
+ const tuples = this.stringTuples().filter((tuple) => {
2859
+ if (tuple[0] === names.ipfs.code) {
2860
+ return true;
2861
+ }
2862
+ return false;
2863
+ });
2864
+ // Get the last ipfs tuple ['ipfs', 'peerid string']
2865
+ const tuple = tuples.pop();
2866
+ if (tuple?.[1] != null) {
2867
+ const peerIdStr = tuple[1];
2868
+ // peer id is base58btc encoded string but not multibase encoded so add the `z`
2869
+ // prefix so we can validate that it is correctly encoded
2870
+ if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {
2871
+ return toString$1(base58btc.decode(`z${peerIdStr}`), 'base58btc');
2872
+ }
2873
+ // try to parse peer id as CID
2874
+ return toString$1(CID.parse(peerIdStr).multihash.bytes, 'base58btc');
2875
+ }
2876
+ return null;
2877
+ }
2878
+ catch (e) {
2879
+ return null;
2880
+ }
2881
+ }
2882
+ getPath() {
2883
+ let path = null;
2884
+ try {
2885
+ path = this.stringTuples().filter((tuple) => {
2886
+ const proto = getProtocol(tuple[0]);
2887
+ if (proto.path === true) {
2888
+ return true;
2889
+ }
2890
+ return false;
2891
+ })[0][1];
2892
+ if (path == null) {
2893
+ path = null;
2894
+ }
2895
+ }
2896
+ catch {
2897
+ path = null;
2898
+ }
2899
+ return path;
2900
+ }
2901
+ equals(addr) {
2902
+ return equals(this.bytes, addr.bytes);
2903
+ }
2904
+ async resolve(options) {
2905
+ const resolvableProto = this.protos().find((p) => p.resolvable);
2906
+ // Multiaddr is not resolvable?
2907
+ if (resolvableProto == null) {
2908
+ return [this];
2909
+ }
2910
+ const resolver = resolvers.get(resolvableProto.name);
2911
+ if (resolver == null) {
2912
+ throw errCode(new Error(`no available resolver for ${resolvableProto.name}`), 'ERR_NO_AVAILABLE_RESOLVER');
2913
+ }
2914
+ const addresses = await resolver(this, options);
2915
+ return addresses.map((a) => new DefaultMultiaddr(a));
2916
+ }
2917
+ nodeAddress() {
2918
+ const options = this.toOptions();
2919
+ if (options.transport !== 'tcp' && options.transport !== 'udp') {
2920
+ throw new Error(`multiaddr must have a valid format - no protocol with name: "${options.transport}". Must have a valid transport protocol: "{tcp, udp}"`);
2921
+ }
2922
+ return {
2923
+ family: options.family,
2924
+ address: options.host,
2925
+ port: options.port
2926
+ };
2927
+ }
2928
+ isThinWaistAddress(addr) {
2929
+ const protos = (addr ?? this).protos();
2930
+ if (protos.length !== 2) {
2931
+ return false;
2932
+ }
2933
+ if (protos[0].code !== 4 && protos[0].code !== 41) {
2934
+ return false;
2935
+ }
2936
+ if (protos[1].code !== 6 && protos[1].code !== 273) {
2937
+ return false;
2938
+ }
2939
+ return true;
2940
+ }
2941
+ /**
2942
+ * Returns Multiaddr as a human-readable string.
2943
+ * For post Node.js v10.0.0.
2944
+ * https://nodejs.org/api/deprecations.html#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect
2945
+ *
2946
+ * @example
2947
+ * ```js
2948
+ * console.log(new Multiaddr('/ip4/127.0.0.1/tcp/4001'))
2949
+ * // '<Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001>'
2950
+ * ```
2951
+ */
2952
+ [(_DefaultMultiaddr_string = new WeakMap(), _DefaultMultiaddr_tuples = new WeakMap(), _DefaultMultiaddr_stringTuples = new WeakMap(), _a = symbol, inspect)]() {
2953
+ return this.inspect();
2954
+ }
2955
+ inspect() {
2956
+ return '<Multiaddr ' +
2957
+ toString$1(this.bytes, 'base16') + ' - ' +
2958
+ bytesToString(this.bytes) + '>';
2959
+ }
2960
+ }
2961
+ /**
2962
+ * Static factory
2963
+ *
2964
+ * @example
2965
+ * ```js
2966
+ * new Multiaddr('/ip4/127.0.0.1/tcp/4001')
2967
+ * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001>
2968
+ * ```
2969
+ *
2970
+ * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)
2971
+ */
2972
+ function multiaddr(addr) {
2973
+ return new DefaultMultiaddr(addr);
2974
+ }
2975
+
2976
+ export { convertToBytes as a, convertToString as c, multiaddr as m };