libp2p 0.46.15 → 0.46.16-69581367

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.
package/README.md CHANGED
@@ -1,48 +1,3 @@
1
- # libp2p <!-- omit in toc -->
2
-
3
- [![libp2p.io](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://libp2p.io/)
4
- [![Discuss](https://img.shields.io/discourse/https/discuss.libp2p.io/posts.svg?style=flat-square)](https://discuss.libp2p.io)
5
- [![codecov](https://img.shields.io/codecov/c/github/libp2p/js-libp2p.svg?style=flat-square)](https://codecov.io/gh/libp2p/js-libp2p)
6
- [![CI](https://img.shields.io/github/actions/workflow/status/libp2p/js-libp2p/main.yml?branch=master\&style=flat-square)](https://github.com/libp2p/js-libp2p/actions/workflows/main.yml?query=branch%3Amaster)
7
-
8
- > JavaScript implementation of libp2p, a modular peer to peer network stack
9
-
10
- ## Table of contents <!-- omit in toc -->
11
-
12
- - [Install](#install)
13
- - [Browser `<script>` tag](#browser-script-tag)
14
- - [Project status](#project-status)
15
- - [Background](#background)
16
- - [Roadmap](#roadmap)
17
- - [Usage](#usage)
18
- - [Configuration](#configuration)
19
- - [Limits](#limits)
20
- - [Getting started](#getting-started)
21
- - [Tutorials and Examples](#tutorials-and-examples)
22
- - [Development](#development)
23
- - [Tests](#tests)
24
- - [Run unit tests](#run-unit-tests)
25
- - [Packages](#packages)
26
- - [Used by](#used-by)
27
- - [Contribute](#contribute)
28
- - [API Docs](#api-docs)
29
- - [License](#license)
30
- - [Contribution](#contribution)
31
-
32
- ## Install
33
-
34
- ```console
35
- $ npm i libp2p
36
- ```
37
-
38
- ### Browser `<script>` tag
39
-
40
- Loading this module through a script tag will make it's exports available as `Libp2p` in the global namespace.
41
-
42
- ```html
43
- <script src="https://unpkg.com/libp2p/dist/index.min.js"></script>
44
- ```
45
-
46
1
  <h1 align="center">
47
2
  <a href="https://libp2p.io"><img width="250" src="https://github.com/libp2p/js-libp2p/blob/master/img/libp2p.png?raw=true" alt="libp2p hex logo" /></a>
48
3
  </h1>
@@ -71,18 +26,20 @@ Loading this module through a script tag will make it's exports available as `Li
71
26
  <br>
72
27
  </p>
73
28
 
74
- ### Project status
29
+ > JavaScript implementation of libp2p, a modular peer to peer network stack
30
+
31
+ # Project status
75
32
 
76
33
  We've come a long way, but this project is still in Alpha, lots of development is happening, API might change, beware of the Dragons 🐉..
77
34
 
78
35
  The documentation in the master branch may contain changes from a pre-release.
79
36
  If you are looking for the documentation of the latest release, you can view the latest release on [**npm**](https://www.npmjs.com/package/libp2p), or select the tag in github that matches the version you are looking for.
80
37
 
81
- **Want to get started?** Check our [GETTING\_STARTED.md](./doc/GETTING_STARTED.md) guide and [examples folder](/examples).
38
+ **Want to get started?** Check our [GETTING\_STARTED.md](./doc/GETTING_STARTED.md) guide and [examples repo](https://github.com/libp2p/js-libp2p-examples).
82
39
 
83
40
  **Want to update libp2p in your project?** Check our [migrations folder](./doc/migrations).
84
41
 
85
- ## Background
42
+ # Background
86
43
 
87
44
  libp2p is the product of a long and arduous quest to understand the evolution of the Internet networking stack. In order to build P2P applications, devs have long had to make custom ad-hoc solutions to fit their needs, sometimes making some hard assumptions about their runtimes and the state of the network at the time of their development. Today, looking back more than 20 years, we see a clear pattern in the types of mechanisms built around the Internet Protocol, IP, which can be found throughout many layers of the OSI layer system, libp2p distils these mechanisms into flat categories and defines clear interfaces that once exposed, enable other protocols and applications to use and swap them, enabling upgradability and adaptability for the runtime, without breaking the API.
88
45
 
@@ -99,7 +56,7 @@ We are in the process of writing better documentation, blog posts, tutorials and
99
56
 
100
57
  To sum up, libp2p is a "network stack" -- a protocol suite -- that cleanly separates concerns, and enables sophisticated applications to only use the protocols they absolutely need, without giving up interoperability and upgradeability. libp2p grew out of IPFS, but it is built so that lots of people can use it, for lots of different projects.
101
58
 
102
- ## Roadmap
59
+ # Roadmap
103
60
 
104
61
  The js-libp2p roadmap can be found here: <https://github.com/libp2p/js-libp2p/blob/master/ROADMAP.md>
105
62
 
@@ -107,25 +64,25 @@ It represents current projects the js-libp2p maintainers are focused on and prov
107
64
 
108
65
  It is complementary to the overarching libp2p project roadmap: <https://github.com/libp2p/specs/blob/master/ROADMAP.md>
109
66
 
110
- ## Usage
67
+ # Usage
111
68
 
112
69
  ### Configuration
113
70
 
114
71
  For all the information on how you can configure libp2p see [CONFIGURATION.md](./doc/CONFIGURATION.md).
115
72
 
116
- ### Limits
73
+ ## Limits
117
74
 
118
75
  For help configuring your node to resist malicious network peers, see [LIMITS.md](./doc/LIMITS.md)
119
76
 
120
- ### Getting started
77
+ ## Getting started
121
78
 
122
79
  If you are starting your journey with `js-libp2p`, read the [GETTING\_STARTED.md](./doc/GETTING_STARTED.md) guide.
123
80
 
124
- ### Tutorials and Examples
81
+ ## Tutorials and Examples
125
82
 
126
- You can find multiple examples on the [examples folder](./examples) that will guide you through using libp2p for several scenarios.
83
+ You can find multiple examples on the [examples repo](https://github.com/libp2p/js-libp2p-examples) that will guide you through using libp2p for several scenarios.
127
84
 
128
- ## Development
85
+ # Development
129
86
 
130
87
  **Clone and install dependencies:**
131
88
 
@@ -136,9 +93,9 @@ You can find multiple examples on the [examples folder](./examples) that will gu
136
93
  > npm run build
137
94
  ```
138
95
 
139
- ### Tests
96
+ # Tests
140
97
 
141
- #### Run unit tests
98
+ ## Run unit tests
142
99
 
143
100
  ```sh
144
101
  # run all the unit tsts
@@ -151,7 +108,7 @@ You can find multiple examples on the [examples folder](./examples) that will gu
151
108
  > npm run test:chrome
152
109
  ```
153
110
 
154
- ### Packages
111
+ # Packages
155
112
 
156
113
  List of packages currently in existence for libp2p
157
114
 
@@ -195,7 +152,7 @@ List of packages currently in existence for libp2p
195
152
  | [`@ChainSafe/libp2p-gossipsub`](//github.com/ChainSafe/js-libp2p-gossipsub) | [![npm](https://img.shields.io/npm/v/%40ChainSafe%2Flibp2p-gossipsub.svg?maxAge=86400\&style=flat-square)](//github.com/ChainSafe/js-libp2p-gossipsub/releases) | [![Deps](https://img.shields.io/librariesio/release/npm/%40ChainSafe%2Flibp2p-gossipsub?logo=Libraries.io\&logoColor=white\&style=flat-square)](//libraries.io/npm/%40ChainSafe%2Flibp2p-gossipsub) | [![GitHub CI](https://img.shields.io/github/actions/workflow/status/ChainSafe/js-libp2p-gossipsub/main.yml?branch=master\&label=ci\&style=flat-square)](//github.com/ChainSafe/js-libp2p-gossipsub/actions?query=branch%3Amaster+workflow%3Aci+) | [![codecov](https://codecov.io/gh/ChainSafe/js-libp2p-gossipsub/branch/master/graph/badge.svg?style=flat-square)](https://codecov.io/gh/ChainSafe/js-libp2p-gossipsub) |
196
153
  | [`@libp2p/floodsub`](//github.com/libp2p/js-libp2p-floodsub) | [![npm](https://img.shields.io/npm/v/%40libp2p%2Ffloodsub.svg?maxAge=86400\&style=flat-square)](//github.com/libp2p/js-libp2p-floodsub/releases) | [![Deps](https://img.shields.io/librariesio/release/npm/%40libp2p%2Ffloodsub?logo=Libraries.io\&logoColor=white\&style=flat-square)](//libraries.io/npm/%40libp2p%2Ffloodsub) | [![GitHub CI](https://img.shields.io/github/actions/workflow/status/libp2p/js-libp2p-floodsub/js-test-and-release.yml?branch=master\&label=ci\&style=flat-square)](//github.com/libp2p/js-libp2p-floodsub/actions?query=branch%3Amaster+workflow%3Aci+) | [![codecov](https://codecov.io/gh/libp2p/js-libp2p-floodsub/branch/master/graph/badge.svg?style=flat-square)](https://codecov.io/gh/libp2p/js-libp2p-floodsub) |
197
154
 
198
- ## Used by
155
+ # Used by
199
156
 
200
157
  <div style="padding: 20px">
201
158
  <p align="middle">
@@ -207,7 +164,7 @@ List of packages currently in existence for libp2p
207
164
 
208
165
  And [many others...](https://github.com/libp2p/js-libp2p/network/dependents)
209
166
 
210
- ## Contribute
167
+ # Contribute
211
168
 
212
169
  The libp2p implementation in JavaScript is a work in progress. As such, there are a few things you can do right now to help out:
213
170
 
@@ -215,17 +172,17 @@ The libp2p implementation in JavaScript is a work in progress. As such, there ar
215
172
  - **Perform code reviews**. Most of this has been developed by @diasdavid, which means that more eyes will help a) speed the project along b) ensure quality and c) reduce possible future bugs.
216
173
  - **Add tests**. There can never be enough tests.
217
174
 
218
- ## API Docs
175
+ # API Docs
219
176
 
220
177
  - <https://libp2p.github.io/js-libp2p/modules/libp2p.html>
221
178
 
222
- ## License
179
+ # License
223
180
 
224
181
  Licensed under either of
225
182
 
226
183
  - Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
227
184
  - MIT ([LICENSE-MIT](LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
228
185
 
229
- ## Contribution
186
+ # Contribution
230
187
 
231
188
  Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
package/dist/index.min.js CHANGED
@@ -18,7 +18,7 @@
18
18
  expire = ?;`,d=[this.dbName,this.tableName,r,n,l,n,l]):(f=`INSERT INTO ??.?? VALUES (?, ?, ?)
19
19
  ON DUPLICATE KEY UPDATE
20
20
  points = IF(expire <= ?, ?, points + (?)),
21
- expire = IF(expire <= ?, ?, expire);`,d=[this.dbName,this.tableName,r,n,l,u,n,n,u,l]),e.query(f,d,p=>{if(p)return e.rollback(),a(p);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,r],(h,m)=>{if(h)return e.rollback(),a(h);e.query("COMMIT",y=>{if(y)return e.rollback(),a(y);o(m)})})})})})}_upsert(e,r,n,i=!1){return this.tableCreated?new Promise((s,o)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,r,n,i).then(c=>{s(c),this._releaseConnection(a)}).catch(c=>{o(c),this._releaseConnection(a)})}).catch(a=>{o(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((r,n)=>{this._getConnection().then(i=>{i.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(s,o)=>{s?n(s):o.length===0?r(null):r(o),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((r,n)=>{this._getConnection().then(i=>{i.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(s,o)=>{s?n(s):r(o.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};Wm.exports=$l});var Zm=V((qL,Xm)=>{var zv=Ri(),Gv=Rt(),Hl=class extends zv{constructor(e,r=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.schemaName=e.schemaName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?typeof r=="function"&&r():this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof r=="function"&&r()}).catch(n=>{if(typeof r=="function")r(n);else throw n})}_getTableIdentifier(){return this.schemaName?`"${this.schemaName}"."${this.tableName}"`:`"${this.tableName}"`}clearExpired(e){return new Promise(r=>{let n={name:"rlflx-clear-expired",text:`DELETE FROM ${this._getTableIdentifier()} WHERE expire < $1`,values:[e]};this._query(n).then(()=>{r()}).catch(()=>{r()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,r)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(n=>{n.code==="23505"?e():r(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this._getTableIdentifier()} (
21
+ expire = IF(expire <= ?, ?, expire);`,d=[this.dbName,this.tableName,r,n,l,u,n,n,u,l]),e.query(f,d,p=>{if(p)return e.rollback(),a(p);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,r],(h,m)=>{if(h)return e.rollback(),a(h);e.query("COMMIT",y=>{if(y)return e.rollback(),a(y);o(m)})})})})})}_upsert(e,r,n,i=!1){return this.tableCreated?new Promise((s,o)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,r,n,i).then(c=>{s(c),this._releaseConnection(a)}).catch(c=>{o(c),this._releaseConnection(a)})}).catch(a=>{o(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((r,n)=>{this._getConnection().then(i=>{i.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(s,o)=>{s?n(s):o.length===0?r(null):r(o),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((r,n)=>{this._getConnection().then(i=>{i.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(s,o)=>{s?n(s):r(o.affectedRows>0),this._releaseConnection(i)})}).catch(i=>{n(i)})}):Promise.reject(Error("Table is not created yet"))}};Wm.exports=$l});var Zm=V((qL,Xm)=>{var zv=Ri(),Gv=Rt(),Hl=class extends zv{constructor(e,r=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.schemaName=e.schemaName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof r=="function"&&r()):this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof r=="function"&&r()}).catch(n=>{if(typeof r=="function")r(n);else throw n})}_getTableIdentifier(){return this.schemaName?`"${this.schemaName}"."${this.tableName}"`:`"${this.tableName}"`}clearExpired(e){return new Promise(r=>{let n={name:"rlflx-clear-expired",text:`DELETE FROM ${this._getTableIdentifier()} WHERE expire < $1`,values:[e]};this._query(n).then(()=>{r()}).catch(()=>{r()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,r)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(n=>{n.code==="23505"?e():r(n)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this._getTableIdentifier()} (
22
22
  key varchar(255) PRIMARY KEY,
23
23
  points integer NOT NULL DEFAULT 0,
24
24
  expire bigint
@@ -45,7 +45,7 @@
45
45
  (?:${Ve}:){1}(?:(?::${Ve}){0,4}:${zt}|(?::${Ve}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
46
46
  (?::(?:(?::${Ve}){0,5}:${zt}|(?::${Ve}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
47
47
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
48
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),mv=new RegExp(`(?:^${zt}$)|(?:^${sa}$)`),yv=new RegExp(`^${zt}$`),gv=new RegExp(`^${sa}$`),Rl=t=>t&&t.exact?mv:new RegExp(`(?:${Qr(t)}${zt}${Qr(t)})|(?:${Qr(t)}${sa}${Qr(t)})`,"g");Rl.v4=t=>t&&t.exact?yv:new RegExp(`${Qr(t)}${zt}${Qr(t)}`,"g");Rl.v6=t=>t&&t.exact?gv:new RegExp(`${Qr(t)}${sa}${Qr(t)}`,"g");var cm=Rl;var dm=ae(lm(),1),{isValid:xv,parse:Ev}=dm.default,bv=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],wv=bv.map(t=>new hm.Netmask(t));function vv(t){for(let e of wv)if(e.contains(t))return!0;return!1}function fm(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}var pm=t=>{if(xv(t)){let e=Ev(t);if(e.kind()==="ipv4")return vv(e.toNormalizedString());if(e.kind()==="ipv6")return fm(t)}else if(Ei(t)&&cm.v6().test(t))return fm(t)};var aa=pm;function mm(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!aa(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}var kB=Symbol.for("@libp2p/transport");var Xr;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Xr||(Xr={}));var _v=t=>t.toString().split("/").slice(1),vs=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),Ue=t=>({match:e=>vs(r=>r===t).match(e),pattern:t}),la=()=>({match:t=>vs(e=>typeof e=="string").match(t),pattern:"{string}"}),ym=()=>({match:t=>vs(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),Dt=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{Te.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),ca=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{wc.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),ir=t=>({match:e=>{let r=t.match(e);return r===!1?e:r},pattern:`optional(${t.pattern})`}),sr=(...t)=>({match:e=>{let r;for(let n of t){let i=n.match(e);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${t.map(e=>e.pattern).join(", ")})`}),Fe=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${t.map(e=>e.pattern).join(", ")})`});function Xe(...t){function e(i){let s=_v(i);for(let o of t){let a=o.match(s);if(a===!1)return!1;s=a}return s}function r(i){return e(i)!==!1}function n(i){let s=e(i);return s===!1?!1:s.length===0}return{matches:r,exactMatch:n}}var Tl=Fe(Ue("dns4"),la()),Bl=Fe(Ue("dns6"),la()),Ll=Fe(Ue("dnsaddr"),la()),gm=Fe(Ue("dns"),la()),VB=Xe(Tl),qB=Xe(Bl),$B=Xe(Ll),HB=Xe(sr(gm,Ll,Tl,Bl)),xm=Fe(Ue("ip4"),vs(Mo)),Em=Fe(Ue("ip6"),vs(Uo)),bm=sr(xm,Em),fa=sr(bm,gm,Tl,Bl,Ll),zB=Xe(xm),GB=Xe(Em),YB=Xe(bm),ha=Fe(fa,Ue("tcp"),ym()),_s=Fe(fa,Ue("udp"),ym()),Sv=sr(ha,_s),WB=Xe(ha),QB=Xe(_s),Pl=Fe(_s,Ue("quic")),da=Fe(_s,Ue("quic-v1")),Av=sr(Pl,da),XB=Xe(Pl),ZB=Xe(da),Cl=sr(fa,ha,_s,Pl,da),wm=sr(Fe(Cl,Ue("ws"),ir(Dt()))),jB=Xe(wm),vm=sr(Fe(Cl,Ue("wss"),ir(Dt())),Fe(Cl,Ue("tls"),Ue("ws"),ir(Dt()))),JB=Xe(vm),_m=Fe(Sv,Ue("webrtc-direct"),ca(),ir(ca()),ir(Dt())),eL=Xe(_m),Sm=Fe(da,Ue("webtransport"),ca(),ca(),ir(Dt())),tL=Xe(Sm),ua=sr(wm,vm,Fe(ha,ir(Dt())),Fe(Av,ir(Dt())),Fe(fa,ir(Dt())),_m,Sm,Dt()),rL=Xe(ua),Iv=Fe(ua,Ue("p2p-circuit"),Dt()),Dl=Xe(Iv),Rv=sr(Fe(ua,Ue("p2p-circuit"),Ue("webrtc"),Dt()),Fe(ua,Ue("webrtc"),ir(Dt())),Ue("webrtc")),nL=Xe(Rv);function Nl(t){try{let{address:e}=t.nodeAddress();return!!aa(e)}catch{return!0}}function Cv(t,e){let r=Nl(t.multiaddr),n=Nl(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function Tv(t,e){return t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function Bv(t,e){let r=Dl.exactMatch(t.multiaddr),n=Dl.exactMatch(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function Ai(t,e){let r=Cv(t,e);if(r!==0)return r;let n=Bv(t,e);return n!==0?n:Tv(t,e)}var Ol=ae(Cu(),1),Ml=ae(Rm(),1);var Cm=globalThis.fetch,Tm=globalThis.Headers,fL=globalThis.Request,hL=globalThis.Response;function pa(t,e,r){return`${t}?name=${e}&type=${r}`}async function Bm(t,e){return await(await Cm(t,{headers:new Tm({accept:"application/dns-json"}),signal:e})).json()}function Nn(t,e){return`${e}_${t}`}var kl=Object.assign((0,Ol.default)("dns-over-http-resolver"),{error:(0,Ol.default)("dns-over-http-resolver:error")}),Ul=class{constructor(e={}){this._cache=new Ml.default({max:e?.maxCache??100}),this._TXTcache=new Ml.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Bm,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>e.abort())}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,r="A"){switch(r){case"A":return await this.resolve4(e);case"AAAA":return await this.resolve6(e);case"TXT":return await this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(Nn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(pa(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Nn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),kl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(Nn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(pa(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Nn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),kl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(Nn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(pa(s,e,r),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(Nn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),kl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},Lm=Ul;var Pm=Lm;var{code:kv}=Ee("dnsaddr");async function Ii(t,e={}){let r=new Pm;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===kv)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var or;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(or||(or={}));var U;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TIMEOUT="ERR_TIMEOUT",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(U||(U={}));var Ov={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Ii},addressSorter:Ai},transportManager:{faultTolerance:Xr.FATAL_ALL}};function Dm(t){let e=qr(Ov,t);if(e.transports==null||e.transports.length<1)throw new w(or.ERR_TRANSPORTS_REQUIRED,U.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new w(or.ERR_PROTECTOR_REQUIRED,U.ERR_PROTECTOR_REQUIRED);return e}var Nm="keep-alive";var Dy=ae(Cy(),1);var x_=re("libp2p:get-peer");function ya(t){if(Co(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:fe(r),t.forEach(n=>{if(!Bn(n))throw x_.error("multiaddr %s was invalid",n),new w("Invalid Multiaddr",U.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new w("Multiaddrs must all have the same peer id or have no peer id",U.ERR_INVALID_PARAMETERS)}else{let s=fe(i);if(e==null||!e.equals(s))throw new w("Multiaddrs must all have the same peer id or have no peer id",U.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function E_(t,e,r){let n=0,i=t.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var ef=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new w("missing peer id",U.ERR_INVALID_PARAMETERS);let s={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(s);return}let o=E_(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(o,0,s)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let r=e.peerId;return this.#e.filter(n=>r.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}},ga=class extends Gr{constructor(e={}){super({...e,queueClass:ef})}hasJob(e){return this.sizeBy({peerId:e})>0}};var xa="last-dial-failure";var Ea=5,ba=100,wa=50,Ty=1e3*60*7;var Ze=re("libp2p:connection-manager:auto-dial"),kn={minConnections:Ea,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Ty,autoDialDiscoveredPeersDebounce:10},va=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??kn.minConnections,this.autoDialPriority=r.autoDialPriority??kn.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??kn.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??kn.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??kn.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??kn.autoDialDiscoveredPeersDebounce,this.started=!1,this.running=!1,this.queue=new ga({concurrency:r.autoDialConcurrency??kn.autoDialConcurrency}),this.queue.addListener("error",i=>{Ze.error("error during auto-dial",i)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(i=>{Ze.error(i)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(i=>{Ze.error(i)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{Ze.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{Ze.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),r=e.size;if(r>=this.minConnections){this.minConnections>0&&Ze.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){Ze("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){Ze("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,Ze("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new Tn(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[u=>u.addresses.length===0?(Ze.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(Ze.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(Ze.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.hasJob(u.id)?(Ze.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=i.sort(()=>Math.random()>.5?1:-1),o=new qt;for(let u of s)o.has(u.id)||o.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=s.sort((u,l)=>{let f=o.get(u.id)??0,d=o.get(l.id)??0;return f>d?-1:f<d?1:0}).filter(u=>{let l=u.metadata.get(xa);if(l==null)return!0;let f=parseInt(X(l));return isNaN(f)?!0:Date.now()-f>this.autoDialPeerRetryThresholdMs});Ze("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){Ze("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}Ze("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(l=>{Ze.error("could not connect to peerStore stored peer",l)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(u=>{Ze.error("error while autodialing",u)})},this.autoDialIntervalMs))}};var Li=re("libp2p:connection-manager:connection-pruner"),By={maxConnections:ba,allow:[]},_a=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??By.maxConnections,this.allow=r.allow??By.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Li.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(Li("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;Li("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new qt;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&Li.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.timeline.open,d=c.timeline.open;return f<d?1:f>d?-1:0}),o=[];for(let a of s)if(Li("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||o.push(a),o.length===n)break;await Promise.all(o.map(async a=>{try{await a.close()}catch(c){Li.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:o})}};var af=ae($n(),1);function Sa(t){let e=new globalThis.AbortController;function r(){e.abort();for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}for(let s of t){if(s?.aborted===!0){r();break}s?.addEventListener!=null&&s.addEventListener("abort",r)}function n(){for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function jr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var sf=ae($n(),1);var Ly=re("libp2p:connection-manager:utils");async function of(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await v_(t,e),o=(await Promise.all(n.map(async a=>of(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return Ly("resolved %s to",t,o.map(a=>a.toString())),o}async function v_(t,e){try{return t=He(t.toString()),await t.resolve(e)}catch(r){return Ly.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function Py(...t){let e=[];for(let n of t)if(n!=null){try{(0,sf.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=Sa(e);try{(0,sf.setMaxListeners)?.(1/0,r)}catch{}return r}var ot=re("libp2p:connection-manager:dial-queue"),As={addressSorter:Ai,maxParallelDials:wa,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:1,dialTimeout:3e4,resolvers:{dnsaddr:Ii}},Aa=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??As.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??As.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??As.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??As.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,af.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))ju.set(n,i);this.queue=new Gr({concurrency:r.maxParallelDials??As.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{ot.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,r={}){let{peerId:n,multiaddrs:i}=ya(e),s=i.map(l=>({multiaddr:l,isCertified:!1})),o=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,s,{...r,signal:o})}catch(l){throw o.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return ot("joining existing dial target for %p",n),o.clear(),c.promise;ot("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:__(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:o}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),o.clear()}).catch(async l=>{if(ot.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),n!=null)try{await this.peerStore.patch(n,{metadata:{[xa]:z(Date.now().toString())}})}catch(f){ot.error("could not update last dial failure key for %p",n,f)}throw o.aborted?new w(l.message,U.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=Sa([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,af.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new w("Tried to dial self",U.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new w("The dial request is blocked by gater.allowDialPeer",U.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){ot("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),ot("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==U.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await of(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(d=>({multiaddr:d,isCertified:!1}))}))).flat(),s=i.filter(l=>{if(this.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let f=l.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),o=new Map;for(let l of s){let f=l.multiaddr.toString(),d=o.get(f);if(d!=null){d.isCertified=d.isCertified||l.isCertified||!1;continue}o.set(f,l)}let a=[...o.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(ot("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),ot("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new w("The dial request has no valid addresses",U.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new w("dial with more addresses than allowed",U.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let d=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:d!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new w("The connection gater denied all addresses in the dial request",U.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Gr({concurrency:this.maxParallelDialsPerPeer});i.on("error",o=>{ot.error("error dialling",o)});let s=await Promise.any(e.multiaddrs.map(async(o,a)=>{let c=n[a];if(c==null)throw new w("dialAction did not come with an AbortController",U.ERR_INVALID_PARAMETERS);let u=Py(c.signal,r.signal);u.addEventListener("abort",()=>{ot("dial to %a aborted",o)});let l=jr();return await i.add(async()=>{if(u.aborted){ot("dial to %a was aborted before reaching the head of the peer dial queue",o),l.reject(new Wn);return}await this.queue.add(async()=>{try{if(u.aborted){ot("dial to %a was aborted before reaching the head of the dial queue",o),l.reject(new Wn);return}e.status="active";let f=await this.transportManager.dial(o,{...r,signal:u});if(c.signal.aborted){ot("multiple dials succeeded, closing superfluous connection"),f.close().catch(d=>{ot.error("error closing superfluous connection",d)}),l.reject(new Wn);return}n[a]=void 0,n.forEach(d=>{d!==void 0&&d.abort()}),ot("dial to %a succeeded",o),l.resolve(f)}catch(f){ot.error("error during dial of %a",o,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(s==null)throw new w("successful dial led to empty object returned from peer dial queue",U.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",s}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function __(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ct=re("libp2p:connection-manager"),I_=50,On={minConnections:Ea,maxConnections:ba,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Ia=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??On.maxConnections;let n=r.minConnections??On.minConnections;if(this.maxConnections<n)throw new w("Connection Manager maxConnections must be greater than minConnections",U.ERR_INVALID_PARAMETERS);this.connections=new qt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>He(i)),this.deny=(r.deny??[]).map(i=>He(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??On.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Dy.RateLimiterMemory({points:r.inboundConnectionThreshold??On.inboundConnectionThreshold,duration:1}),this.autoDial=new va({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??On.autoDialConcurrency,autoDialPriority:r.autoDialPriority??On.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??On.autoDialMaxQueueLength}),this.connectionPruner=new _a({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Aa({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??Ai,maxParallelDials:r.maxParallelDials??wa,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,maxParallelDialsPerPeer:r.maxParallelDialsPerPeer??1,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Ii}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let s=`${i.direction} ${i.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let s={};for(let o of i.streams){let a=`${o.direction} ${o.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[o,a]of Object.entries(s))e[o]=e[o]??[],e[o].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((o,a)=>o-a);let s=Math.floor(i.length*.9);r[n]=i[s]}return r}}),this.autoDial.start(),this.started=!0,Ct("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(Nm)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{Ct.error(n)})}))}).catch(e=>{Ct.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){Ct.error(i)}})());Ct("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),Ct("stopped")}onConnect(e){this._onConnect(e).catch(r=>{Ct.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),s=!1;i!=null?i.push(r):(s=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(s=>s.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new w("Not started",U.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=ya(e);if(n!=null&&r.force!==!0){Ct("dial %p",n);let a=this.getConnections(n);if(a.length>0)return Ct("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??I_}),s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(let a of s)a.id===i.id&&(o=!0);return o||s.push(i),i}async closeConnections(e,r={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(s){i.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return Ct("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return Ct("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return Ct("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(Ct("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var Ra=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Pi=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ra(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Ra(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ff=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Mn(t={}){return R_(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function R_(t,e){e=e??{};let r=e.onEnd,n=new Pi,i,s,o,a=jr(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,g)=>{s=x=>{s=null,n.push(x);try{y(t(n))}catch(b){g(b)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=jr()})}},u=y=>s!=null?s(y):(n.push(y),i),l=y=>(n=new Pi,s!=null?s({error:y}):(n.push({error:y}),i)),f=y=>{if(o)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},d=y=>o?i:(o=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new Pi,d(),{done:!0}),h=y=>(d(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:f,end:d,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,b;g!=null&&(x=new Promise((C,_)=>{b=()=>{_(new ff)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength}},i}function C_(t){return t[Symbol.asyncIterator]!=null}function T_(...t){let e=[];for(let r of t)C_(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=Mn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var Jr=T_;function Un(t,...e){if(t==null)throw new Error("Empty pipeline");if(hf(t)){let n=t;t=()=>n.source}else if(ky(t)||Ny(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&hf(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)hf(r[n])&&(r[n]=L_(r[n]));return B_(...r)}var B_=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Ny=t=>t?.[Symbol.asyncIterator]!=null,ky=t=>t?.[Symbol.iterator]!=null,hf=t=>t==null?!1:t.sink!=null&&t.source!=null,L_=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Mn({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let i,s=t.source;if(Ny(s))i=async function*(){yield*s,n.end()};else if(ky(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Jr(n,i())}return t.source};function P_(t){return t[Symbol.asyncIterator]!=null}function D_(t,e){if(P_(t))return async function*(){for await(let a of t)yield e(a)}();let r=ta(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of r)yield e(a)}();let o=e;return function*(){yield s;for(let a of r)yield o(a)}()}var Oy=D_;async function*Is(t,e){yield*Oy(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Ca(t){let e=new Set;return Ht(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*Ta(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new w(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var Ba=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new w("No content routers available",U.ERR_NO_ROUTERS_AVAILABLE);yield*Un(Jr(...this.routers.map(n=>n.findProviders(e,r))),n=>Is(n,this.components.peerStore),n=>Ca(n),n=>Ta(n))}async provide(e,r={}){if(this.routers.length===0)throw new w("No content routers available",U.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new w(or.NOT_STARTED_YET,U.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new w(or.NOT_STARTED_YET,U.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function N_(t){return t[Symbol.asyncIterator]!=null}function k_(t){if(N_(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var La=k_;var O_=re("libp2p:peer-routing"),Pa=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new w("No peer routers available",U.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new w("Should not try to find self",U.ERR_FIND_SELF);let n=await Un(Jr(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(s){O_.error(s)}}())),i=>Ht(i,Boolean),i=>Is(i,this.components.peerStore),async i=>La(i));if(n!=null)return n;throw new w(or.NOT_FOUND,U.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new w("No peer routers available",U.ERR_NO_ROUTERS_AVAILABLE);yield*Un(Jr(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>Is(n,this.components.peerStore),n=>Ca(n),n=>Ta(n))}};var df=re("libp2p:registrar"),pf=32,mf=64,Da=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new w(`No handler registered for protocol ${e}`,U.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new w(`Handler already registered for protocol ${e}`,U.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=qr.bind({ignoreUndefined:!0})({maxInboundStreams:pf,maxOutboundStreams:mf},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,r){if(r==null)throw new w("invalid topology",U.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect?.(r)}}).catch(n=>{n.code!==U.ERR_NOT_FOUND&&df.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){df("peer %p connected but the connection manager did not have a connection",n);return}for(let s of n.protocols){let o=this.topologies.get(s);if(o!=null)for(let a of o.values())a.onConnect?.(r,i)}}).catch(n=>{n.code!==U.ERR_NOT_FOUND&&df.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!r.protocols.includes(o)),s=r.protocols.filter(o=>!(n?.protocols??[]).includes(o));for(let o of i){let a=this.topologies.get(o);if(a!=null)for(let c of a.values())c.onDisconnect?.(r.id)}for(let o of s){let a=this.topologies.get(o);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect?.(r.id,u)}}}};var yf=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function My(t){let{name:e,metrics:r}=t,n;return r!=null?n=new yf({name:e,metrics:r}):n=new Map,n}var en=re("libp2p:transports"),Na=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=My({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Xr.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new w("Transport must have a valid tag",U.ERR_INVALID_KEY);if(this.transports.has(r))throw new w(`There is already a transport with the tag ${r}`,U.ERR_DUPLICATE_TRANSPORT);en("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[r,n]of this.listeners)for(en("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),en("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new w(`No transport available for address ${String(e)}`,U.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=U.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this.listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(!this.isStarted())throw new w("Not started",U.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){en("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){en("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=f.findIndex(p=>p===l);f.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if((await Promise.allSettled(o)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Xr.NO_FATAL)throw new w(`Transport (${n}) could not listen on any available address`,U.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Xr.FATAL_ALL)throw new w(n,U.ERR_NO_VALID_ADDRESSES);en(`libp2p in dial mode only: ${n}`)}}async remove(e){let r=this.listeners.get(e)??[];en.trace("removing transport %s",e);let n=[];for(en.trace("closing listeners for %s",e);r.length>0;){let i=r.pop();i!=null&&n.push(i.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let r of this.transports.keys())e.push(this.remove(r));await Promise.all(e)}};var bf=ae($n(),1);var Rr="/multistream/1.0.0";function gf(t){let e=async function*(){let r=yield,n=new Qe;for await(let i of t){if(r==null){n.append(i),r=yield n,n=new Qe;continue}for(n.append(i);n.length>=r;){let s=n.sublist(0,r);if(n.consume(r),r=yield s,r==null){n.length>0&&(r=yield n,n=new Qe);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function ka(t){let e=Mn(),r=gf(t.source),n=jr(),i,s=t.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await s},source:r},rest:()=>e.end(),write:e.push,read:async()=>{let a=await r.next();if(a.value!=null)return a.value}}}var Rs=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Uy(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function Fy(t,e,r){let n=r??{},i=Uy(t);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new Rs(l,f)}let u=new Promise((l,f)=>{o=()=>{let{abortMessage:d,abortCode:p}=n;f(new Rs(d,p))}});c=await Promise.race([u,i.next()]),o=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(d=>{n.onReturnError!=null&&n.onReturnError(d)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function Oa(t){return t[Symbol.asyncIterator]!=null}var Ma=t=>{let e=xt(t),r=ct(e);return Pt(t,r),Ma.bytes=e,r};Ma.bytes=0;function Ua(t,e){e=e??{};let r=e.lengthEncoder??Ma;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return Oa(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}Ua.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??Ma;return new Qe(r(t.byteLength),t)};var Di=ae(Sl(),1);var M_=8,U_=1024*1024*4,Fn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Fn||(Fn={}));var xf=t=>{let e=Ar(t);return xf.bytes=xt(e),e};xf.bytes=0;function Cs(t,e){let r=new Qe,n=Fn.LENGTH,i=-1,s=e?.lengthDecoder??xf,o=e?.maxLengthLength??M_,a=e?.maxDataLength??U_;function*c(){for(;r.byteLength>0;){if(n===Fn.LENGTH)try{if(i=s(r),i<0)throw(0,Di.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,Di.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=Fn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,Di.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Fn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=Fn.LENGTH}}}return Oa(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,Di.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,Di.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Cs.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return Cs(n,{...e??{},onLength:s=>{r=s}})};var V_=re("libp2p:mss"),Ky=z(`
48
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),mv=new RegExp(`(?:^${zt}$)|(?:^${sa}$)`),yv=new RegExp(`^${zt}$`),gv=new RegExp(`^${sa}$`),Rl=t=>t&&t.exact?mv:new RegExp(`(?:${Qr(t)}${zt}${Qr(t)})|(?:${Qr(t)}${sa}${Qr(t)})`,"g");Rl.v4=t=>t&&t.exact?yv:new RegExp(`${Qr(t)}${zt}${Qr(t)}`,"g");Rl.v6=t=>t&&t.exact?gv:new RegExp(`${Qr(t)}${sa}${Qr(t)}`,"g");var cm=Rl;var dm=ae(lm(),1),{isValid:xv,parse:Ev}=dm.default,bv=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],wv=bv.map(t=>new hm.Netmask(t));function vv(t){for(let e of wv)if(e.contains(t))return!0;return!1}function fm(t){return/^::$/.test(t)||/^::1$/.test(t)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(t)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(t)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(t)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(t)||/^ff([0-9a-fA-F]{2,2}):/i.test(t)}var pm=t=>{if(xv(t)){let e=Ev(t);if(e.kind()==="ipv4")return vv(e.toNormalizedString());if(e.kind()==="ipv6")return fm(t)}else if(Ei(t)&&cm.v6().test(t))return fm(t)};var aa=pm;function mm(t={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let r=e.stringTuples();return r[0][0]===4||r[0][0]===41?!!aa(`${r[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...t}}var kB=Symbol.for("@libp2p/transport");var Xr;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Xr||(Xr={}));var _v=t=>t.toString().split("/").slice(1),vs=t=>({match:e=>e.length<1?!1:t(e[0])?e.slice(1):!1,pattern:"fn"}),Ue=t=>({match:e=>vs(r=>r===t).match(e),pattern:t}),la=()=>({match:t=>vs(e=>typeof e=="string").match(t),pattern:"{string}"}),ym=()=>({match:t=>vs(e=>!isNaN(parseInt(e))).match(t),pattern:"{number}"}),Dt=()=>({match:t=>{if(t.length<2||t[0]!=="p2p"&&t[0]!=="ipfs")return!1;if(t[1].startsWith("Q")||t[1].startsWith("1"))try{Te.decode(`z${t[1]}`)}catch{return!1}else return!1;return t.slice(2)},pattern:"/p2p/{peerid}"}),ca=()=>({match:t=>{if(t.length<2||t[0]!=="certhash")return!1;try{wc.decode(t[1])}catch{return!1}return t.slice(2)},pattern:"/certhash/{certhash}"}),ir=t=>({match:e=>{let r=t.match(e);return r===!1?e:r},pattern:`optional(${t.pattern})`}),sr=(...t)=>({match:e=>{let r;for(let n of t){let i=n.match(e);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${t.map(e=>e.pattern).join(", ")})`}),Fe=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${t.map(e=>e.pattern).join(", ")})`});function Xe(...t){function e(i){let s=_v(i);for(let o of t){let a=o.match(s);if(a===!1)return!1;s=a}return s}function r(i){return e(i)!==!1}function n(i){let s=e(i);return s===!1?!1:s.length===0}return{matches:r,exactMatch:n}}var Tl=Fe(Ue("dns4"),la()),Bl=Fe(Ue("dns6"),la()),Ll=Fe(Ue("dnsaddr"),la()),gm=Fe(Ue("dns"),la()),VB=Xe(Tl),qB=Xe(Bl),$B=Xe(Ll),HB=Xe(sr(gm,Ll,Tl,Bl)),xm=Fe(Ue("ip4"),vs(Mo)),Em=Fe(Ue("ip6"),vs(Uo)),bm=sr(xm,Em),fa=sr(bm,gm,Tl,Bl,Ll),zB=Xe(xm),GB=Xe(Em),YB=Xe(bm),ha=Fe(fa,Ue("tcp"),ym()),_s=Fe(fa,Ue("udp"),ym()),Sv=sr(ha,_s),WB=Xe(ha),QB=Xe(_s),Pl=Fe(_s,Ue("quic")),da=Fe(_s,Ue("quic-v1")),Av=sr(Pl,da),XB=Xe(Pl),ZB=Xe(da),Cl=sr(fa,ha,_s,Pl,da),wm=sr(Fe(Cl,Ue("ws"),ir(Dt()))),jB=Xe(wm),vm=sr(Fe(Cl,Ue("wss"),ir(Dt())),Fe(Cl,Ue("tls"),Ue("ws"),ir(Dt()))),JB=Xe(vm),_m=Fe(Sv,Ue("webrtc-direct"),ca(),ir(ca()),ir(Dt())),eL=Xe(_m),Sm=Fe(da,Ue("webtransport"),ca(),ca(),ir(Dt())),tL=Xe(Sm),ua=sr(wm,vm,Fe(ha,ir(Dt())),Fe(Av,ir(Dt())),Fe(fa,ir(Dt())),_m,Sm,Dt()),rL=Xe(ua),Iv=Fe(ua,Ue("p2p-circuit"),Dt()),Dl=Xe(Iv),Rv=sr(Fe(ua,Ue("p2p-circuit"),Ue("webrtc"),Dt()),Fe(ua,Ue("webrtc"),ir(Dt())),Ue("webrtc")),nL=Xe(Rv);function Nl(t){try{let{address:e}=t.nodeAddress();return!!aa(e)}catch{return!0}}function Cv(t,e){let r=Nl(t.multiaddr),n=Nl(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function Tv(t,e){return t.isCertified&&!e.isCertified?-1:!t.isCertified&&e.isCertified?1:0}function Bv(t,e){let r=Dl.exactMatch(t.multiaddr),n=Dl.exactMatch(e.multiaddr);return r&&!n?1:!r&&n?-1:0}function Ai(t,e){let r=Cv(t,e);if(r!==0)return r;let n=Bv(t,e);return n!==0?n:Tv(t,e)}var Ol=ae(Cu(),1),Ml=ae(Rm(),1);var Cm=globalThis.fetch,Tm=globalThis.Headers,fL=globalThis.Request,hL=globalThis.Response;function pa(t,e,r){return`${t}?name=${e}&type=${r}`}async function Bm(t,e){return await(await Cm(t,{headers:new Tm({accept:"application/dns-json"}),signal:e})).json()}function Nn(t,e){return`${e}_${t}`}var kl=Object.assign((0,Ol.default)("dns-over-http-resolver"),{error:(0,Ol.default)("dns-over-http-resolver:error")}),Ul=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new Ml.default({max:e?.maxCache??100}),this._TXTcache=new Ml.default({max:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??Bm,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>{e.abort()})}getServers(){return this._servers}_getShuffledServers(){let e=[...this._servers];for(let r=e.length-1;r>0;r--){let n=Math.floor(Math.random()*r),i=e[r];e[r]=e[n],e[n]=i}return e}setServers(e){this._servers=e}async resolve(e,r="A"){switch(r){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${r} is not supported`)}}async resolve4(e){let r="A",n=this._cache.get(Nn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(pa(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Nn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),kl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolve6(e){let r="AAAA",n=this._cache.get(Nn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(pa(s,e,r),o.signal),c=a.Answer.map(l=>l.data),u=Math.min(...a.Answer.map(l=>l.TTL));return this._cache.set(Nn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),kl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}async resolveTxt(e){let r="TXT",n=this._TXTcache.get(Nn(e,r));if(n!=null)return n;let i=!1;for(let s of this._getShuffledServers()){let o=new AbortController;this._abortControllers.push(o);try{let a=await this._request(pa(s,e,r),o.signal),c=a.Answer.map(l=>[l.data.replace(/['"]+/g,"")]),u=Math.min(...a.Answer.map(l=>l.TTL));return this._TXTcache.set(Nn(e,r),c,{ttl:u}),c}catch{o.signal.aborted&&(i=!0),kl.error(`${s} could not resolve ${e} record ${r}`)}finally{this._abortControllers=this._abortControllers.filter(a=>a!==o)}}throw i?Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"}):new Error(`Could not resolve ${e} record ${r}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},Lm=Ul;var Pm=Lm;var{code:kv}=Ee("dnsaddr");async function Ii(t,e={}){let r=new Pm;e.signal!=null&&e.signal.addEventListener("abort",()=>{r.cancel()});let n=t.getPeerId(),[,i]=t.stringTuples().find(([a])=>a===kv)??[];if(i==null)throw new Error("No hostname found in multiaddr");let o=(await r.resolveTxt(`_dnsaddr.${i}`)).flat().map(a=>a.split("=")[1]).filter(Boolean);return n!=null&&(o=o.filter(a=>a.includes(n))),o}var or;(function(t){t.NOT_STARTED_YET="The libp2p node is not started yet",t.DHT_DISABLED="DHT is not available",t.PUBSUB_DISABLED="PubSub is not available",t.CONN_ENCRYPTION_REQUIRED="At least one connection encryption module is required",t.ERR_TRANSPORTS_REQUIRED="At least one transport module is required",t.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",t.NOT_FOUND="Not found"})(or||(or={}));var U;(function(t){t.DHT_DISABLED="ERR_DHT_DISABLED",t.ERR_PUBSUB_DISABLED="ERR_PUBSUB_DISABLED",t.PUBSUB_NOT_STARTED="ERR_PUBSUB_NOT_STARTED",t.DHT_NOT_STARTED="ERR_DHT_NOT_STARTED",t.CONN_ENCRYPTION_REQUIRED="ERR_CONN_ENCRYPTION_REQUIRED",t.ERR_TRANSPORTS_REQUIRED="ERR_TRANSPORTS_REQUIRED",t.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",t.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",t.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",t.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",t.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",t.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",t.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",t.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",t.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",t.ERR_DIALED_SELF="ERR_DIALED_SELF",t.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",t.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",t.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",t.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",t.ERR_INVALID_KEY="ERR_INVALID_KEY",t.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_INVALID_PEER="ERR_INVALID_PEER",t.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",t.ERR_NOT_FOUND="ERR_NOT_FOUND",t.ERR_TIMEOUT="ERR_TIMEOUT",t.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",t.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",t.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",t.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",t.ERR_FIND_SELF="ERR_FIND_SELF",t.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",t.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",t.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",t.ERR_KEYCHAIN_REQUIRED="ERR_KEYCHAIN_REQUIRED",t.ERR_INVALID_CMS="ERR_INVALID_CMS",t.ERR_MISSING_KEYS="ERR_MISSING_KEYS",t.ERR_NO_KEY="ERR_NO_KEY",t.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",t.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",t.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",t.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",t.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",t.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",t.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",t.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",t.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",t.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",t.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",t.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",t.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",t.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",t.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",t.ERR_INVALID_RECORD="ERR_INVALID_RECORD",t.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",t.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",t.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(U||(U={}));var Ov={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:t=>t},connectionManager:{resolvers:{dnsaddr:Ii},addressSorter:Ai},transportManager:{faultTolerance:Xr.FATAL_ALL}};function Dm(t){let e=qr(Ov,t);if(e.transports==null||e.transports.length<1)throw new w(or.ERR_TRANSPORTS_REQUIRED,U.ERR_TRANSPORTS_REQUIRED);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new w(or.ERR_PROTECTOR_REQUIRED,U.ERR_PROTECTOR_REQUIRED);return e}var Nm="keep-alive";var Dy=ae(Cy(),1);var x_=re("libp2p:get-peer");function ya(t){if(Co(t))return{peerId:t,multiaddrs:[]};Array.isArray(t)||(t=[t]);let e;if(t.length>0){let r=t[0].getPeerId();e=r==null?void 0:fe(r),t.forEach(n=>{if(!Bn(n))throw x_.error("multiaddr %s was invalid",n),new w("Invalid Multiaddr",U.ERR_INVALID_MULTIADDR);let i=n.getPeerId();if(i==null){if(e!=null)throw new w("Multiaddrs must all have the same peer id or have no peer id",U.ERR_INVALID_PARAMETERS)}else{let s=fe(i);if(e==null||!e.equals(s))throw new w("Multiaddrs must all have the same peer id or have no peer id",U.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:t}}function E_(t,e,r){let n=0,i=t.length;for(;i>0;){let s=Math.trunc(i/2),o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}var ef=class{#e=[];enqueue(e,r){let n=r?.peerId,i=r?.priority??0;if(n==null)throw new w("missing peer id",U.ERR_INVALID_PARAMETERS);let s={priority:i,peerId:n,run:e};if(this.size>0&&this.#e[this.size-1].priority>=i){this.#e.push(s);return}let o=E_(this.#e,s,(a,c)=>c.priority-a.priority);this.#e.splice(o,0,s)}dequeue(){return this.#e.shift()?.run}filter(e){if(e.peerId!=null){let r=e.peerId;return this.#e.filter(n=>r.equals(n.peerId)).map(n=>n.run)}return this.#e.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this.#e.length}},ga=class extends Gr{constructor(e={}){super({...e,queueClass:ef})}hasJob(e){return this.sizeBy({peerId:e})>0}};var xa="last-dial-failure";var Ea=5,ba=100,wa=50,Ty=1e3*60*7;var Ze=re("libp2p:connection-manager:auto-dial"),kn={minConnections:Ea,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Ty,autoDialDiscoveredPeersDebounce:10},va=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;constructor(e,r){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=r.minConnections??kn.minConnections,this.autoDialPriority=r.autoDialPriority??kn.autoDialPriority,this.autoDialIntervalMs=r.autoDialInterval??kn.autoDialInterval,this.autoDialMaxQueueLength=r.maxQueueLength??kn.maxQueueLength,this.autoDialPeerRetryThresholdMs=r.autoDialPeerRetryThreshold??kn.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=r.autoDialDiscoveredPeersDebounce??kn.autoDialDiscoveredPeersDebounce,this.started=!1,this.running=!1,this.queue=new ga({concurrency:r.autoDialConcurrency??kn.autoDialConcurrency}),this.queue.addListener("error",i=>{Ze.error("error during auto-dial",i)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(i=>{Ze.error(i)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(i=>{Ze.error(i)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{Ze.error("error while autodialing",e)})},this.autoDialIntervalMs),this.started=!0}afterStart(){this.autoDial().catch(e=>{Ze.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started)return;let e=this.connectionManager.getConnectionsMap(),r=e.size;if(r>=this.minConnections){this.minConnections>0&&Ze.trace("have enough connections %d/%d",r,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){Ze("not enough connections %d/%d but auto dial queue is full",r,this.minConnections);return}if(this.running){Ze("not enough connections %d/%d - but skipping autodial as it is already running",r,this.minConnections);return}this.running=!0,Ze("not enough connections %d/%d - will dial peers to increase the number of connections",r,this.minConnections);let n=new Tn(this.connectionManager.getDialQueue().map(u=>u.peerId).filter(Boolean)),i=await this.peerStore.all({filters:[u=>u.addresses.length===0?(Ze.trace("not autodialing %p because they have no addresses",u.id),!1):e.has(u.id)?(Ze.trace("not autodialing %p because they are already connected",u.id),!1):n.has(u.id)?(Ze.trace("not autodialing %p because they are already being dialed",u.id),!1):this.queue.hasJob(u.id)?(Ze.trace("not autodialing %p because they are already being autodialed",u.id),!1):!0]}),s=i.sort(()=>Math.random()>.5?1:-1),o=new qt;for(let u of s)o.has(u.id)||o.set(u.id,[...u.tags.values()].reduce((l,f)=>l+f.value,0));let c=s.sort((u,l)=>{let f=o.get(u.id)??0,d=o.get(l.id)??0;return f>d?-1:f<d?1:0}).filter(u=>{let l=u.metadata.get(xa);if(l==null)return!0;let f=parseInt(X(l));return isNaN(f)?!0:Date.now()-f>this.autoDialPeerRetryThresholdMs});Ze("selected %d/%d peers to dial",c.length,i.length);for(let u of c)this.queue.add(async()=>{let l=this.connectionManager.getConnectionsMap().size;if(l>=this.minConnections){Ze("got enough connections now %d/%d",l,this.minConnections),this.queue.clear();return}Ze("connecting to a peerStore stored peer %p",u.id),await this.connectionManager.openConnection(u.id,{priority:this.autoDialPriority})},{peerId:u.id}).catch(l=>{Ze.error("could not connect to peerStore stored peer",l)});this.running=!1,this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(u=>{Ze.error("error while autodialing",u)})},this.autoDialIntervalMs))}};var Li=re("libp2p:connection-manager:connection-pruner"),By={maxConnections:ba,allow:[]},_a=class{maxConnections;connectionManager;peerStore;allow;events;constructor(e,r={}){this.maxConnections=r.maxConnections??By.maxConnections,this.allow=r.allow??By.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{Li.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),r=e.length,n=Math.max(r-this.maxConnections,0);if(Li("checking max connections limit %d/%d",r,this.maxConnections),r<=this.maxConnections)return;Li("max connections limit exceeded %d/%d, pruning %d connection(s)",r,this.maxConnections,n);let i=new qt;for(let a of e){let c=a.remotePeer;if(!i.has(c)){i.set(c,0);try{let u=await this.peerStore.get(c);i.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.code!=="ERR_NOT_FOUND"&&Li.error("error loading peer tags",u)}}}let s=e.sort((a,c)=>{let u=i.get(a.remotePeer)??0,l=i.get(c.remotePeer)??0;if(u>l)return 1;if(u<l)return-1;let f=a.timeline.open,d=c.timeline.open;return f<d?1:f>d?-1:0}),o=[];for(let a of s)if(Li("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>a.remoteAddr.toString().startsWith(u.toString()))||o.push(a),o.length===n)break;await Promise.all(o.map(async a=>{try{await a.close()}catch(c){Li.error(c)}})),this.events.safeDispatchEvent("connection:prune",{detail:o})}};var af=ae($n(),1);function Sa(t){let e=new globalThis.AbortController;function r(){e.abort();for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}for(let s of t){if(s?.aborted===!0){r();break}s?.addEventListener!=null&&s.addEventListener("abort",r)}function n(){for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}let i=e.signal;return i.clear=n,i}function jr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var sf=ae($n(),1);var Ly=re("libp2p:connection-manager:utils");async function of(t,e){if(!t.protoNames().includes("dnsaddr"))return[t];let n=await v_(t,e),o=(await Promise.all(n.map(async a=>of(a,e)))).flat().reduce((a,c)=>(a.find(u=>u.equals(c))==null&&a.push(c),a),[]);return Ly("resolved %s to",t,o.map(a=>a.toString())),o}async function v_(t,e){try{return t=He(t.toString()),await t.resolve(e)}catch(r){return Ly.error(`multiaddr ${t.toString()} could not be resolved`,r),[]}}function Py(...t){let e=[];for(let n of t)if(n!=null){try{(0,sf.setMaxListeners)?.(1/0,n)}catch{}e.push(n)}let r=Sa(e);try{(0,sf.setMaxListeners)?.(1/0,r)}catch{}return r}var ot=re("libp2p:connection-manager:dial-queue"),As={addressSorter:Ai,maxParallelDials:wa,maxPeerAddrsToDial:25,maxParallelDialsPerPeer:1,dialTimeout:3e4,resolvers:{dnsaddr:Ii}},Aa=class{pendingDials;queue;peerId;peerStore;connectionGater;transportManager;addressSorter;maxPeerAddrsToDial;maxParallelDialsPerPeer;dialTimeout;inProgressDialCount;pendingDialCount;shutDownController;constructor(e,r={}){this.addressSorter=r.addressSorter??As.addressSorter,this.maxPeerAddrsToDial=r.maxPeerAddrsToDial??As.maxPeerAddrsToDial,this.maxParallelDialsPerPeer=r.maxParallelDialsPerPeer??As.maxParallelDialsPerPeer,this.dialTimeout=r.dialTimeout??As.dialTimeout,this.peerId=e.peerId,this.peerStore=e.peerStore,this.connectionGater=e.connectionGater,this.transportManager=e.transportManager,this.shutDownController=new AbortController;try{(0,af.setMaxListeners)?.(1/0,this.shutDownController.signal)}catch{}this.pendingDialCount=e.metrics?.registerMetric("libp2p_dialler_pending_dials"),this.inProgressDialCount=e.metrics?.registerMetric("libp2p_dialler_in_progress_dials"),this.pendingDials=[];for(let[n,i]of Object.entries(r.resolvers??{}))ju.set(n,i);this.queue=new Gr({concurrency:r.maxParallelDials??As.maxParallelDials}),this.queue.on("add",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("active",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("completed",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("error",n=>{ot.error("error in dial queue",n),this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("empty",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)}),this.queue.on("idle",()=>{this.pendingDialCount?.update(this.queue.size),this.inProgressDialCount?.update(this.queue.pending)})}stop(){this.shutDownController.abort()}async dial(e,r={}){let{peerId:n,multiaddrs:i}=ya(e),s=i.map(l=>({multiaddr:l,isCertified:!1})),o=this.createDialAbortControllers(r.signal),a;try{a=await this.calculateMultiaddrs(n,s,{...r,signal:o})}catch(l){throw o.clear(),l}let c=this.pendingDials.find(l=>!!(l.peerId!=null&&n!=null&&l.peerId.equals(n)||a.map(({multiaddr:f})=>f.toString()).join()===l.multiaddrs.map(f=>f.toString()).join()));if(c!=null)return ot("joining existing dial target for %p",n),o.clear(),c.promise;ot("creating dial target for",a.map(({multiaddr:l})=>l.toString()));let u={id:__(),status:"queued",peerId:n,multiaddrs:a.map(({multiaddr:l})=>l)};return u.promise=this.performDial(u,{...r,signal:o}).finally(()=>{this.pendingDials=this.pendingDials.filter(l=>l.id!==u.id),o.clear()}).catch(async l=>{if(ot.error("dial failed to %s",u.multiaddrs.map(f=>f.toString()).join(", "),l),n!=null)try{await this.peerStore.patch(n,{metadata:{[xa]:z(Date.now().toString())}})}catch(f){ot.error("could not update last dial failure key for %p",n,f)}throw o.aborted?new w(l.message,U.ERR_TIMEOUT):l}),this.pendingDials.push(u),u.promise}createDialAbortControllers(e){let r=Sa([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);try{(0,af.setMaxListeners)?.(1/0,r)}catch{}return r}async calculateMultiaddrs(e,r=[],n={}){if(e!=null){if(this.peerId.equals(e))throw new w("Tried to dial self",U.ERR_DIALED_SELF);if(await this.connectionGater.denyDialPeer?.(e)===!0)throw new w("The dial request is blocked by gater.allowDialPeer",U.ERR_PEER_DIAL_INTERCEPTED);if(r.length===0){ot("loading multiaddrs for %p",e);try{let l=await this.peerStore.get(e);r.push(...l.addresses),ot("loaded multiaddrs for %p",e,r.map(({multiaddr:f})=>f.toString()))}catch(l){if(l.code!==U.ERR_NOT_FOUND)throw l}}}let i=(await Promise.all(r.map(async l=>{let f=await of(l.multiaddr,n);return f.length===1&&f[0].equals(l.multiaddr)?l:f.map(d=>({multiaddr:d,isCertified:!1}))}))).flat(),s=i.filter(l=>{if(this.transportManager.transportForMultiaddr(l.multiaddr)==null)return!1;let f=l.multiaddr.getPeerId();return e!=null&&f!=null?e.equals(f):!0}),o=new Map;for(let l of s){let f=l.multiaddr.toString(),d=o.get(f);if(d!=null){d.isCertified=d.isCertified||l.isCertified||!1;continue}o.set(f,l)}let a=[...o.values()];if((a.length===0||a.length>this.maxPeerAddrsToDial)&&(ot("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:l})=>l.toString())),ot("addresses for %p after filtering",e??"unknown peer",a.map(({multiaddr:l})=>l.toString()))),a.length===0)throw new w("The dial request has no valid addresses",U.ERR_NO_VALID_ADDRESSES);if(a.length>this.maxPeerAddrsToDial)throw new w("dial with more addresses than allowed",U.ERR_TOO_MANY_ADDRESSES);if(e!=null){let l=`/p2p/${e.toString()}`;a=a.map(f=>{let d=f.multiaddr.getPeerId();return f.multiaddr.protos().pop()?.path===!0?f:d!==e.toString()?{multiaddr:f.multiaddr.encapsulate(l),isCertified:f.isCertified}:f})}let c=[];for(let l of a)this.connectionGater.denyDialMultiaddr!=null&&await this.connectionGater.denyDialMultiaddr(l.multiaddr)||c.push(l);let u=c.sort(this.addressSorter);if(u.length===0)throw new w("The connection gater denied all addresses in the dial request",U.ERR_NO_VALID_ADDRESSES);return u}async performDial(e,r={}){let n=e.multiaddrs.map(()=>new AbortController);try{let i=new Gr({concurrency:this.maxParallelDialsPerPeer});i.on("error",o=>{ot.error("error dialling",o)});let s=await Promise.any(e.multiaddrs.map(async(o,a)=>{let c=n[a];if(c==null)throw new w("dialAction did not come with an AbortController",U.ERR_INVALID_PARAMETERS);let u=Py(c.signal,r.signal);u.addEventListener("abort",()=>{ot("dial to %a aborted",o)});let l=jr();return await i.add(async()=>{if(u.aborted){ot("dial to %a was aborted before reaching the head of the peer dial queue",o),l.reject(new Wn);return}await this.queue.add(async()=>{try{if(u.aborted){ot("dial to %a was aborted before reaching the head of the dial queue",o),l.reject(new Wn);return}e.status="active";let f=await this.transportManager.dial(o,{...r,signal:u});if(c.signal.aborted){ot("multiple dials succeeded, closing superfluous connection"),f.close().catch(d=>{ot.error("error closing superfluous connection",d)}),l.reject(new Wn);return}n[a]=void 0,n.forEach(d=>{d!==void 0&&d.abort()}),ot("dial to %a succeeded",o),l.resolve(f)}catch(f){ot.error("error during dial of %a",o,f),l.reject(f)}},{...r,signal:u}).catch(f=>{l.reject(f)})},{signal:u}).catch(f=>{l.reject(f)}).finally(()=>{u.clear()}),l.promise}));if(s==null)throw new w("successful dial led to empty object returned from peer dial queue",U.ERR_TRANSPORT_DIAL_FAILED);return e.status="success",s}catch(i){throw e.status="error",e.multiaddrs.length===1&&i.name==="AggregateError"?i.errors[0]:i}}};function __(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ct=re("libp2p:connection-manager"),I_=50,On={minConnections:Ea,maxConnections:ba,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100},Ia=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;constructor(e,r={}){this.maxConnections=r.maxConnections??On.maxConnections;let n=r.minConnections??On.minConnections;if(this.maxConnections<n)throw new w("Connection Manager maxConnections must be greater than minConnections",U.ERR_INVALID_PARAMETERS);this.connections=new qt,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(r.allow??[]).map(i=>He(i)),this.deny=(r.deny??[]).map(i=>He(i)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=r.maxIncomingPendingConnections??On.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Dy.RateLimiterMemory({points:r.inboundConnectionThreshold??On.inboundConnectionThreshold,duration:1}),this.autoDial=new va({connectionManager:this,peerStore:e.peerStore,events:e.events},{minConnections:n,autoDialConcurrency:r.autoDialConcurrency??On.autoDialConcurrency,autoDialPriority:r.autoDialPriority??On.autoDialPriority,maxQueueLength:r.autoDialMaxQueueLength??On.autoDialMaxQueueLength}),this.connectionPruner=new _a({connectionManager:this,peerStore:e.peerStore,events:e.events},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Aa({peerId:e.peerId,metrics:e.metrics,peerStore:e.peerStore,transportManager:e.transportManager,connectionGater:e.connectionGater},{addressSorter:r.addressSorter??Ai,maxParallelDials:r.maxParallelDials??wa,maxPeerAddrsToDial:r.maxPeerAddrsToDial??25,maxParallelDialsPerPeer:r.maxParallelDialsPerPeer??1,dialTimeout:r.dialTimeout??3e4,resolvers:r.resolvers??{dnsaddr:Ii}})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let r of this.connections.values())for(let n of r)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let r of this.connections.values())for(let n of r)for(let i of n.streams){let s=`${i.direction} ${i.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let s={};for(let o of i.streams){let a=`${o.direction} ${o.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[o,a]of Object.entries(s))e[o]=e[o]??[],e[o].push(a)}let r={};for(let[n,i]of Object.entries(e)){i=i.sort((o,a)=>o-a);let s=Math.floor(i.length*.9);r[n]=i[s]}return r}}),this.autoDial.start(),this.started=!0,Ct("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[r=>r.tags.has(Nm)]});await Promise.all(e.map(async r=>{await this.openConnection(r.id).catch(n=>{Ct.error(n)})}))}).catch(e=>{Ct.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let r of this.connections.values())for(let n of r)e.push((async()=>{try{await n.close()}catch(i){Ct.error(i)}})());Ct("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),Ct("stopped")}onConnect(e){this._onConnect(e).catch(r=>{Ct.error(r)})}async _onConnect(e){let{detail:r}=e;if(!this.started){await r.close();return}let n=r.remotePeer,i=this.connections.get(n),s=!1;i!=null?i.push(r):(s=!0,this.connections.set(n,[r])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:r.remotePeer})}onDisconnect(e){let{detail:r}=e;if(!this.started)return;let n=r.remotePeer,i=this.connections.get(n);i!=null&&i.length>1?(i=i.filter(s=>s.id!==r.id),this.connections.set(n,i)):i!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let r=[];for(let n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}async openConnection(e,r={}){if(!this.isStarted())throw new w("Not started",U.ERR_NODE_NOT_STARTED);r.signal?.throwIfAborted();let{peerId:n}=ya(e);if(n!=null&&r.force!==!0){Ct("dial %p",n);let a=this.getConnections(n);if(a.length>0)return Ct("had an existing connection to %p",n),a[0]}let i=await this.dialQueue.dial(e,{...r,priority:r.priority??I_}),s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let o=!1;for(let a of s)a.id===i.id&&(o=!0);return o||s.push(i),i}async closeConnections(e,r={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(r)}catch(s){i.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return Ct("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>e.remoteAddr.toString().startsWith(i.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return Ct("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return Ct("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(Ct("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){return this.dialQueue.pendingDials}};var Ra=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Pi=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ra(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Ra(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var ff=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Mn(t={}){return R_(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function R_(t,e){e=e??{};let r=e.onEnd,n=new Pi,i,s,o,a=jr(),c=async()=>{try{return n.isEmpty()?o?{done:!0}:await new Promise((y,g)=>{s=x=>{s=null,n.push(x);try{y(t(n))}catch(b){g(b)}return i}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=jr()})}},u=y=>s!=null?s(y):(n.push(y),i),l=y=>(n=new Pi,s!=null?s({error:y}):(n.push({error:y}),i)),f=y=>{if(o)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},d=y=>o?i:(o=!0,y!=null?l(y):u({done:!0})),p=()=>(n=new Pi,d(),{done:!0}),h=y=>(d(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:p,throw:h,push:f,end:d,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,b;g!=null&&(x=new Promise((C,_)=>{b=()=>{_(new ff)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},r==null)return i;let m=i;return i={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return m.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return m.readableLength}},i}function C_(t){return t[Symbol.asyncIterator]!=null}function T_(...t){let e=[];for(let r of t)C_(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=Mn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var Jr=T_;function Un(t,...e){if(t==null)throw new Error("Empty pipeline");if(hf(t)){let n=t;t=()=>n.source}else if(ky(t)||Ny(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&hf(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)hf(r[n])&&(r[n]=L_(r[n]));return B_(...r)}var B_=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Ny=t=>t?.[Symbol.asyncIterator]!=null,ky=t=>t?.[Symbol.iterator]!=null,hf=t=>t==null?!1:t.sink!=null&&t.source!=null,L_=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Mn({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let i,s=t.source;if(Ny(s))i=async function*(){yield*s,n.end()};else if(ky(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Jr(n,i())}return t.source};function P_(t){return t[Symbol.asyncIterator]!=null}function D_(t,e){if(P_(t))return async function*(){for await(let a of t)yield e(a)}();let r=ta(t),{value:n,done:i}=r.next();if(i===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of r)yield e(a)}();let o=e;return function*(){yield s;for(let a of r)yield o(a)}()}var Oy=D_;async function*Is(t,e){yield*Oy(t,async r=>(await e.merge(r.id,{multiaddrs:r.multiaddrs}),r))}function Ca(t){let e=new Set;return Ht(t,r=>e.has(r.id.toString())?!1:(e.add(r.id.toString()),!0))}async function*Ta(t,e=1){let r=0;for await(let n of t)r++,yield n;if(r<e)throw new w(`more peers required, seen: ${r} min: ${e}`,"NOT_FOUND")}var Ba=class{routers;started;components;constructor(e,r){this.routers=r.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,r={}){if(this.routers.length===0)throw new w("No content routers available",U.ERR_NO_ROUTERS_AVAILABLE);yield*Un(Jr(...this.routers.map(n=>n.findProviders(e,r))),n=>Is(n,this.components.peerStore),n=>Ca(n),n=>Ta(n))}async provide(e,r={}){if(this.routers.length===0)throw new w("No content routers available",U.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,r)}))}async put(e,r,n){if(!this.isStarted())throw new w(or.NOT_STARTED_YET,U.DHT_NOT_STARTED);await Promise.all(this.routers.map(async i=>{await i.put(e,r,n)}))}async get(e,r){if(!this.isStarted())throw new w(or.NOT_STARTED_YET,U.DHT_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,r)))}};function N_(t){return t[Symbol.asyncIterator]!=null}function k_(t){if(N_(t))return(async()=>{for await(let e of t)return e})();for(let e of t)return e}var La=k_;var O_=re("libp2p:peer-routing"),Pa=class{components;routers;constructor(e,r){this.components=e,this.routers=r.routers??[]}async findPeer(e,r){if(this.routers.length===0)throw new w("No peer routers available",U.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.components.peerId.toString())throw new w("Should not try to find self",U.ERR_FIND_SELF);let n=await Un(Jr(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,r)}catch(s){O_.error(s)}}())),i=>Ht(i,Boolean),i=>Is(i,this.components.peerStore),async i=>La(i));if(n!=null)return n;throw new w(or.NOT_FOUND,U.ERR_NOT_FOUND)}async*getClosestPeers(e,r){if(this.routers.length===0)throw new w("No peer routers available",U.ERR_NO_ROUTERS_AVAILABLE);yield*Un(Jr(...this.routers.map(n=>n.getClosestPeers(e,r))),n=>Is(n,this.components.peerStore),n=>Ca(n),n=>Ta(n))}};var df=re("libp2p:registrar"),pf=32,mf=64,Da=class{topologies;handlers;components;constructor(e){this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onConnect=this._onConnect.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:connect",this._onConnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let r=this.handlers.get(e);if(r==null)throw new w(`No handler registered for protocol ${e}`,U.ERR_NO_HANDLER_FOR_PROTOCOL);return r}getTopologies(e){let r=this.topologies.get(e);return r==null?[]:[...r.values()]}async handle(e,r,n){if(this.handlers.has(e))throw new w(`Handler already registered for protocol ${e}`,U.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let i=qr.bind({ignoreUndefined:!0})({maxInboundStreams:pf,maxOutboundStreams:mf},n);this.handlers.set(e,{handler:r,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,r){if(r==null)throw new w("invalid topology",U.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,r),n}unregister(e){for(let[r,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(r))}_onDisconnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{for(let i of n.protocols){let s=this.topologies.get(i);if(s!=null)for(let o of s.values())o.onDisconnect?.(r)}}).catch(n=>{n.code!==U.ERR_NOT_FOUND&&df.error("could not inform topologies of disconnecting peer %p",r,n)})}_onConnect(e){let r=e.detail;this.components.peerStore.get(r).then(n=>{let i=this.components.connectionManager.getConnections(n.id)[0];if(i==null){df("peer %p connected but the connection manager did not have a connection",n);return}for(let s of n.protocols){let o=this.topologies.get(s);if(o!=null)for(let a of o.values())a.onConnect?.(r,i)}}).catch(n=>{n.code!==U.ERR_NOT_FOUND&&df.error("could not inform topologies of connecting peer %p",r,n)})}_onPeerUpdate(e){let{peer:r,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!r.protocols.includes(o)),s=r.protocols.filter(o=>!(n?.protocols??[]).includes(o));for(let o of i){let a=this.topologies.get(o);if(a!=null)for(let c of a.values())c.onDisconnect?.(r.id)}for(let o of s){let a=this.topologies.get(o);if(a!=null)for(let c of a.values()){let u=this.components.connectionManager.getConnections(r.id)[0];u!=null&&c.onConnect?.(r.id,u)}}}};var yf=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function My(t){let{name:e,metrics:r}=t,n;return r!=null?n=new yf({name:e,metrics:r}):n=new Map,n}var en=re("libp2p:transports"),Na=class{components;transports;listeners;faultTolerance;started;constructor(e,r={}){this.components=e,this.started=!1,this.transports=new Map,this.listeners=My({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=r.faultTolerance??Xr.FATAL_ALL}add(e){let r=e[Symbol.toStringTag];if(r==null)throw new w("Transport must have a valid tag",U.ERR_INVALID_KEY);if(this.transports.has(r))throw new w(`There is already a transport with the tag ${r}`,U.ERR_DUPLICATE_TRANSPORT);en("adding transport %s",r),this.transports.set(r,e),this.listeners.has(r)||this.listeners.set(r,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[r,n]of this.listeners)for(en("closing listeners for %s",r);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),en("all listeners closed");for(let r of this.listeners.keys())this.listeners.set(r,[]);this.started=!1}async dial(e,r){let n=this.transportForMultiaddr(e);if(n==null)throw new w(`No transport available for address ${String(e)}`,U.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...r,upgrader:this.components.upgrader})}catch(i){throw i.code==null&&(i.code=U.ERR_TRANSPORT_DIAL_FAILED),i}}getAddrs(){let e=[];for(let r of this.listeners.values())for(let n of r)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}transportForMultiaddr(e){for(let r of this.transports.values())if(r.filter([e]).length>0)return r}async listen(e){if(!this.isStarted())throw new w("Not started",U.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){en("no addresses were provided for listening, this node is dial only");return}let r=[];for(let[n,i]of this.transports.entries()){let s=i.filter(e),o=[];for(let u of s){en("creating listener for %s on %a",n,u);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(n)??[];f==null&&(f=[],this.listeners.set(n,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=f.findIndex(p=>p===l);f.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),o.push(l.listen(u))}if(o.length===0){r.push(n);continue}if((await Promise.allSettled(o)).find(u=>u.status==="fulfilled")==null&&this.faultTolerance!==Xr.NO_FATAL)throw new w(`Transport (${n}) could not listen on any available address`,U.ERR_NO_VALID_ADDRESSES)}if(r.length===this.transports.size){let n=`no valid addresses were provided for transports [${r.join(", ")}]`;if(this.faultTolerance===Xr.FATAL_ALL)throw new w(n,U.ERR_NO_VALID_ADDRESSES);en(`libp2p in dial mode only: ${n}`)}}async remove(e){let r=this.listeners.get(e)??[];en.trace("removing transport %s",e);let n=[];for(en.trace("closing listeners for %s",e);r.length>0;){let i=r.pop();i!=null&&n.push(i.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let r of this.transports.keys())e.push(this.remove(r));await Promise.all(e)}};var bf=ae($n(),1);var Rr="/multistream/1.0.0";function gf(t){let e=async function*(){let r=yield,n=new Qe;for await(let i of t){if(r==null){n.append(i),r=yield n,n=new Qe;continue}for(n.append(i);n.length>=r;){let s=n.sublist(0,r);if(n.consume(r),r=yield s,r==null){n.length>0&&(r=yield n,n=new Qe);break}}}if(r!=null)throw Object.assign(new Error(`stream ended before ${r} bytes became available`),{code:"ERR_UNDER_READ",buffer:n})}();return e.next(),e}function ka(t){let e=Mn(),r=gf(t.source),n=jr(),i,s=t.sink(async function*(){yield*e,yield*await n.promise}());return s.catch(a=>{i=a}),{reader:r,writer:e,stream:{sink:async a=>{if(i!=null){await Promise.reject(i);return}n.resolve(a),await s},source:r},rest:()=>e.end(),write:e.push,read:async()=>{let a=await r.next();if(a.value!=null)return a.value}}}var Rs=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Uy(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function Fy(t,e,r){let n=r??{},i=Uy(t);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:l,abortCode:f}=n;throw new Rs(l,f)}let u=new Promise((l,f)=>{o=()=>{let{abortMessage:d,abortCode:p}=n;f(new Rs(d,p))}});c=await Promise.race([u,i.next()]),o=null}catch(u){e.removeEventListener("abort",a);let l=u.type==="aborted"&&e.aborted;if(l&&n.onAbort!=null&&n.onAbort(t),typeof i.return=="function")try{let f=i.return();f instanceof Promise&&f.catch(d=>{n.onReturnError!=null&&n.onReturnError(d)})}catch(f){n.onReturnError!=null&&n.onReturnError(f)}if(l&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function Oa(t){return t[Symbol.asyncIterator]!=null}var Ma=t=>{let e=xt(t),r=ct(e);return Pt(t,r),Ma.bytes=e,r};Ma.bytes=0;function Ua(t,e){e=e??{};let r=e.lengthEncoder??Ma;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return Oa(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}Ua.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??Ma;return new Qe(r(t.byteLength),t)};var Di=ae(Sl(),1);var M_=8,U_=1024*1024*4,Fn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Fn||(Fn={}));var xf=t=>{let e=Ar(t);return xf.bytes=xt(e),e};xf.bytes=0;function Cs(t,e){let r=new Qe,n=Fn.LENGTH,i=-1,s=e?.lengthDecoder??xf,o=e?.maxLengthLength??M_,a=e?.maxDataLength??U_;function*c(){for(;r.byteLength>0;){if(n===Fn.LENGTH)try{if(i=s(r),i<0)throw(0,Di.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,Di.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=Fn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,Di.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Fn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=Fn.LENGTH}}}return Oa(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,Di.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,Di.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Cs.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return Cs(n,{...e??{},onLength:s=>{r=s}})};var V_=re("libp2p:mss"),Ky=z(`
49
49
  `);function Ts(t){let e=new Qe(t,Ky);return Ua.single(e)}function Kn(t,e,r={}){let n=Ts(e);r.writeBytes===!0?t.push(n.subarray()):t.push(n)}function Vy(t,e,r={}){let n=new Qe;for(let i of e)n.append(Ts(i));r.writeBytes===!0?t.push(n.subarray()):t.push(n)}async function q_(t,e){let r=1,n={[Symbol.asyncIterator]:()=>n,next:async()=>t.next(r)},i=n;e?.signal!=null&&(i=Fy(n,e.signal));let s=a=>{r=a},o=await Un(i,a=>Cs(a,{onLength:s,maxDataLength:1024}),async a=>La(a));if(o==null||o.length===0)throw new w("no buffer returned","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");if(o.get(o.byteLength-1)!==Ky[0])throw V_.error("Invalid mss message - missing newline - %s",o.subarray()),new w("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return o.sublist(0,-1)}async function Ni(t,e){let r=await q_(t,e);return X(r.subarray())}var Bs=re("libp2p:mss:select");async function Ls(t,e,r={}){e=Array.isArray(e)?[...e]:[e];let{reader:n,writer:i,rest:s,stream:o}=ka(t),a=e.shift();if(a==null)throw new Error("At least one protocol must be specified");Bs.trace('select: write ["%s", "%s"]',Rr,a);let c=z(Rr),u=z(a);Vy(i,[c,u],r);let l=await Ni(n,r);if(Bs.trace('select: read "%s"',l),l===Rr&&(l=await Ni(n,r),Bs.trace('select: read "%s"',l)),l===a)return s(),{stream:o,protocol:a};for(let f of e){Bs.trace('select: write "%s"',f),Kn(i,z(f),r);let d=await Ni(n,r);if(Bs.trace('select: read "%s" for "%s"',d,f),d===f)return s(),{stream:o,protocol:f}}throw s(),new w("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}var Ps=re("libp2p:mss:handle");async function Ds(t,e,r){e=Array.isArray(e)?e:[e];let{writer:n,reader:i,rest:s,stream:o}=ka(t);for(;;){let a=await Ni(i,r);if(Ps.trace('read "%s"',a),a===Rr){Ps.trace('respond with "%s" for "%s"',Rr,a),Kn(n,z(Rr),r);continue}if(e.includes(a))return Kn(n,z(a),r),Ps.trace('respond with "%s" for "%s"',a,a),s(),{stream:o,protocol:a};if(a==="ls"){Kn(n,new Qe(...e.map(c=>Ts(z(c)))),r),Ps.trace('respond with "%s" for %s',e,a);continue}Kn(n,z("na"),r),Ps('respond with "na" for "%s"',a)}}var Hy=ae($n(),1);var $y=Symbol.for("@libp2p/connection");var Vn=re("libp2p:connection"),H_=500,Ef=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:r,remotePeer:n,newStream:i,close:s,abort:o,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=r,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this._newStream=i,this._close=s,this._abort=o,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[$y]=!0;get streams(){return this._getStreams()}async newStream(e,r){if(this.status==="closing")throw new w("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new w("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&r?.runOnTransientConnection!==!0)throw new w("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,r);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){Vn("closing connection to %a",this.remoteAddr),this.status="closing",e.signal=e?.signal??AbortSignal.timeout(H_);try{(0,Hy.setMaxListeners)?.(1/0,e.signal)}catch{}try{Vn.trace("closing all streams"),await Promise.all(this.streams.map(async r=>r.close(e))),Vn.trace("closing underlying transport"),await this._close(e),Vn.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(r){Vn.error("error encountered during graceful close of connection to %a",this.remoteAddr,r),this.abort(r)}}}abort(e){Vn.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(r=>{r.abort(e)}),Vn.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function zy(t){return new Ef(t)}var be=re("libp2p:upgrader");function G_(t,e){try{let{options:r}=e.getHandler(t);return r.maxInboundStreams}catch(r){if(r.code!==U.ERR_NO_HANDLER_FOR_PROTOCOL)throw r}return pf}function Y_(t,e,r={}){try{let{options:n}=e.getHandler(t);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==U.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return r.maxOutboundStreams??mf}function Gy(t,e,r){let n=0;return r.streams.forEach(i=>{i.direction===e&&i.protocol===t&&n++}),n}var Fa=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,r){this.components=e,this.connectionEncryption=new Map,r.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,r.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=r.inboundUpgradeTimeout??3e4,this.events=e.events}async shouldBlockConnection(e,r,n){let i=this.components.connectionGater[n];if(i!==void 0&&await i(e,r))throw new w(`The multiaddr connection is blocked by gater.${n}`,U.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,r){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new w("connection denied",U.ERR_CONNECTION_DENIED);let i,s,o,a,c,u=AbortSignal.timeout(this.inboundUpgradeTimeout),l=()=>{e.abort(new w("inbound upgrade timeout",U.ERR_TIMEOUT))};u.addEventListener("abort",l,{once:!0});try{(0,bf.setMaxListeners)?.(1/0,u)}catch{}try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new w("The multiaddr connection is blocked by gater.acceptConnection",U.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),be("starting the inbound connection upgrade");let f=e;if(r?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(be("protecting the inbound connection"),f=await d.protect(e))}try{if(i=f,r?.skipEncryption!==!0){({conn:i,remotePeer:s,protocol:c}=await this._encryptInbound(f));let d={...f,...i};await this.shouldBlockConnection(s,d,"denyInboundEncryptedConnection")}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new w("inbound connection that skipped encryption must have a peer id",U.ERR_INVALID_MULTIADDR);let p=fe(d);c="native",s=p}if(o=i,r?.muxerFactory!=null)a=r.muxerFactory;else if(this.muxers.size>0){let d=await this._multiplexInbound({...f,...i},this.muxers);a=d.muxerFactory,o=d.stream}}catch(d){throw be.error("Failed to upgrade inbound connection",d),d}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),be("Successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:o,muxerFactory:a,remotePeer:s,transient:r?.transient})}finally{u.removeEventListener("abort",l),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,r){let n=e.remoteAddr.getPeerId(),i;n!=null&&(i=fe(n),await this.shouldBlockConnection(i,e,"denyOutboundConnection"));let s,o,a,c,u;this.components.metrics?.trackMultiaddrConnection(e),be("Starting the outbound connection upgrade");let l=e;if(r?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(l=await f.protect(e))}try{if(s=l,r?.skipEncryption!==!0){({conn:s,remotePeer:o,protocol:c}=await this._encryptOutbound(l,i));let f={...l,...s};await this.shouldBlockConnection(o,f,"denyOutboundEncryptedConnection")}else{if(i==null)throw new w("Encryption was skipped but no peer id was passed",U.ERR_INVALID_PEER);c="native",o=i}if(a=s,r?.muxerFactory!=null)u=r.muxerFactory;else if(this.muxers.size>0){let f=await this._multiplexOutbound({...l,...s},this.muxers);u=f.muxerFactory,a=f.stream}}catch(f){throw be.error("Failed to upgrade outbound connection",f),await e.close(f),f}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),be("Successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:u,remotePeer:o,transient:r?.transient})}_createConnection(e){let{cryptoProtocol:r,direction:n,maConn:i,upgradedConn:s,remotePeer:o,muxerFactory:a,transient:c}=e,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:h=>{f!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:y,protocol:g}=await Ds(h,m);if(be("%s: incoming stream opened on %s",n,g),f==null)return;let x=G_(g,this.components.registrar);if(Gy(g,"inbound",f)===x){let C=new w(`Too many inbound protocol streams for protocol "${g}" - limit ${x}`,U.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw h.abort(C),C}h.source=y.source,h.sink=y.sink,h.protocol=g,await this.components.peerStore.merge(o,{protocols:[g]}),this.components.metrics?.trackProtocolStream(h,f),this._onStream({connection:f,stream:h,protocol:g})}).catch(async m=>{be.error(m),h.timeline.close==null&&await h.close()})}}),l=async(h,m={})=>{if(u==null)throw new w("Stream is not multiplexed",U.ERR_MUXER_UNAVAILABLE);be("%s: starting new stream on %s",n,h);let y=await u.newStream();try{if(m.signal==null){be("No abort signal was passed while trying to negotiate protocols %s falling back to default timeout",h),m.signal=AbortSignal.timeout(3e4);try{(0,bf.setMaxListeners)?.(1/0,m.signal)}catch{}}let{stream:g,protocol:x}=await Ls(y,h,m),b=Y_(x,this.components.registrar,m);if(Gy(x,"outbound",f)>=b){let _=new w(`Too many outbound protocol streams for protocol "${x}" - limit ${b}`,U.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(_),_}return await this.components.peerStore.merge(o,{protocols:[x]}),y.source=g.source,y.sink=g.sink,y.protocol=x,this.components.metrics?.trackProtocolStream(y,f),y}catch(g){throw be.error("could not create new stream for protocols %s on connection with address %a",h,f.remoteAddr,g),y.timeline.close==null&&y.abort(g),g.code!=null?g:new w(String(g),U.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(h=>{be.error(h)}));let d=i.timeline;i.timeline=new Proxy(d,{set:(...h)=>(f!=null&&h[1]==="close"&&h[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(m){be.error(m)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(m=>{be.error(m)}),Reflect.set(...h))}),i.timeline.upgraded=Date.now();let p=()=>{throw new w("connection is not multiplexed",U.ERR_CONNECTION_NOT_MULTIPLEXED)};return f=zy({remoteAddr:i.remoteAddr,remotePeer:o,status:"open",direction:n,timeline:i.timeline,multiplexer:u?.protocol,encryption:r,transient:c,newStream:l??p,getStreams:()=>u!=null?u.streams:[],close:async h=>{u!=null&&(be.trace("close muxer"),await u.close(h)),be.trace("close maconn"),await i.close(h),be.trace("closed maconn")},abort:h=>{i.abort(h),u?.abort(h)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f}_onStream(e){let{connection:r,stream:n,protocol:i}=e,{handler:s,options:o}=this.components.registrar.getHandler(i);if(r.transient&&o.runOnTransientConnection!==!0)throw new w("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:r,stream:n})}async _encryptInbound(e){let r=Array.from(this.connectionEncryption.keys());be("handling inbound crypto protocol selection",r);try{let{stream:n,protocol:i}=await Ds(e,r,{writeBytes:!0}),s=this.connectionEncryption.get(i);if(s==null)throw new Error(`no crypto module found for ${i}`);return be("encrypting inbound connection..."),{...await s.secureInbound(this.components.peerId,n),protocol:i}}catch(n){throw new w(String(n),U.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,r){let n=Array.from(this.connectionEncryption.keys());be("selecting outbound crypto protocol",n);try{let{stream:i,protocol:s}=await Ls(e,n,{writeBytes:!0}),o=this.connectionEncryption.get(s);if(o==null)throw new Error(`no crypto module found for ${s}`);return be("encrypting outbound connection to %p",r),{...await o.secureOutbound(this.components.peerId,i,r),protocol:s}}catch(i){throw new w(String(i),U.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,r){let n=Array.from(r.keys());be("outbound selecting muxer %s",n);try{let{stream:i,protocol:s}=await Ls(e,n,{writeBytes:!0});be("%s selected as muxer protocol",s);let o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw be.error("error multiplexing outbound stream",i),new w(String(i),U.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,r){let n=Array.from(r.keys());be("inbound handling muxers %s",n);try{let{stream:i,protocol:s}=await Ds(e,n,{writeBytes:!0}),o=r.get(s);return{stream:i,muxerFactory:o}}catch(i){throw be.error("error multiplexing inbound stream",i),new w(String(i),U.ERR_MUXER_UNAVAILABLE)}}};var Et=re("libp2p"),wf=class extends as{peerId;peerStore;contentRouting;peerRouting;keychain;metrics;services;components;#e;constructor(e){super();let r=new as,n=r.dispatchEvent.bind(r);r.dispatchEvent=c=>{let u=n(c),l=this.dispatchEvent(new Su(c.type,{detail:c.detail}));return u||l};try{(0,Yy.setMaxListeners)?.(1/0,r)}catch{}this.#e=!1,this.peerId=e.peerId,this.services={};let i=this.components=sm({peerId:e.peerId,events:r,datastore:e.datastore??new na,connectionGater:mm(e.connectionGater)});this.peerStore=this.configureComponent("peerStore",new ea(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",c=>{if(c.detail.previous==null){let u={id:c.detail.peer.id,multiaddrs:c.detail.peer.addresses.map(l=>l.multiaddr),protocols:c.detail.peer.protocols};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Fa(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((c,u)=>this.configureComponent(`connection-encryption-${u}`,c(this.components))),muxers:(e.streamMuxers??[]).map((c,u)=>this.configureComponent(`stream-muxers-${u}`,c(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Na(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ia(this.components,e.connectionManager)),this.configureComponent("registrar",new Da(this.components)),this.configureComponent("addressManager",new ia(this.components,e.addresses));let s=Cn.generateOptions();this.keychain=this.configureComponent("keyChain",new Cn(this.components,{...s,...e.keychain}));let o=(e.peerRouters??[]).map((c,u)=>this.configureComponent(`peer-router-${u}`,c(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Pa(this.components,{routers:o}));let a=(e.contentRouters??[]).map((c,u)=>this.configureComponent(`content-router-${u}`,c(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ba(this.components,{routers:a})),(e.peerDiscovery??[]).forEach((c,u)=>{this.configureComponent(`peer-discovery-${u}`,c(this.components)).addEventListener("peer",f=>{this.#t(f)})}),e.transports.forEach((c,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,c(this.components)))}),e.services!=null)for(let c of Object.keys(e.services)){let u=e.services[c],l=u(this.components);if(l==null){Et.error("service factory %s returned null or undefined instance",c);continue}this.services[c]=l,this.configureComponent(c,l),l[vu]!=null&&(Et("registering service %s for content routing",c),a.push(l[vu])),l[Iu]!=null&&(Et("registering service %s for peer routing",c),o.push(l[Iu])),l[Au]!=null&&(Et("registering service %s for peer discovery",c),l[Au].addEventListener("peer",f=>{this.#t(f)}))}}configureComponent(e,r){return r==null&&Et.error("component %s was null or undefined",e),this.components[e]=r,r}async start(){if(this.#e)return;this.#e=!0,Et("libp2p is starting"),(await this.keychain.listKeys()).find(r=>r.name==="self")==null&&(Et("importing self key into keychain"),await this.keychain.importPeer("self",this.components.peerId));try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.safeDispatchEvent("start",{detail:this}),Et("libp2p has started")}catch(r){throw Et.error("An error occurred starting libp2p",r),await this.stop(),r}}async stop(){this.#e&&(Et("libp2p is stopping"),this.#e=!1,await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.safeDispatchEvent("stop",{detail:this}),Et("libp2p has stopped"))}isStarted(){return this.#e}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Tn;for(let r of this.components.connectionManager.getConnections())e.add(r.remotePeer);return Array.from(e)}async dial(e,r={}){return this.components.connectionManager.openConnection(e,r)}async dialProtocol(e,r,n={}){if(r==null)throw new w("no protocols were provided to open a stream",U.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(r=Array.isArray(r)?r:[r],r.length===0)throw new w("no protocols were provided to open a stream",U.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(r,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,r={}){Bn(e)&&(e=fe(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,r)}async getPublicKey(e,r={}){if(Et("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;let n=await this.peerStore.get(e);if(n.id.publicKey!=null)return n.id.publicKey;let i=Oe([z("/pk/"),e.multihash.digest]),s=await this.contentRouting.get(i,r);return ss(s),await this.peerStore.patch(e,{publicKey:s}),s}async handle(e,r,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async i=>{await this.components.registrar.handle(i,r,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async r=>{await this.components.registrar.unhandle(r)}))}async register(e,r){return this.components.registrar.register(e,r)}unregister(e){this.components.registrar.unregister(e)}#t(e){let{detail:r}=e;if(r.id.toString()===this.peerId.toString()){Et.error(new Error(U.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(r.id,{multiaddrs:r.multiaddrs,protocols:r.protocols}).catch(n=>{Et.error(n)})}};async function Wy(t){if(t.peerId==null){let e=t.datastore;if(e!=null)try{let r=new Cn({datastore:e},qr(Cn.generateOptions(),t.keychain));t.peerId=await r.exportPeerId("self")}catch(r){if(r.code!=="ERR_NOT_FOUND")throw r}}return t.peerId==null&&(t.peerId=await fp()),new wf(Dm(t))}async function W_(t){let e=await Wy(t);return t.start!==!1&&await e.start(),e}return cg(Q_);})();
50
50
  /*! Bundled license information:
51
51
 
@@ -1,5 +1,5 @@
1
1
  export declare const PROTOCOL_VERSION = "ipfs/0.1.0";
2
- export declare const AGENT_VERSION = "js-libp2p/0.46.15";
2
+ export declare const AGENT_VERSION = "js-libp2p/0.46.16-69581367";
3
3
  export declare const MULTICODEC_IDENTIFY = "/ipfs/id/1.0.0";
4
4
  export declare const MULTICODEC_IDENTIFY_PUSH = "/ipfs/id/push/1.0.0";
5
5
  export declare const IDENTIFY_PROTOCOL_VERSION = "0.1.0";
@@ -1 +1 @@
1
- {"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../../../src/identify/consts.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,gBAAgB,eAAe,CAAA;AAC5C,eAAO,MAAM,aAAa,sBAAyB,CAAA;AACnD,eAAO,MAAM,mBAAmB,mBAAmB,CAAA;AACnD,eAAO,MAAM,wBAAwB,wBAAwB,CAAA;AAE7D,eAAO,MAAM,yBAAyB,UAAU,CAAA;AAChD,eAAO,MAAM,iCAAiC,OAAO,CAAA;AACrD,eAAO,MAAM,sCAAsC,YAAY,CAAA;AAC/D,eAAO,MAAM,oCAAoC,UAAU,CAAA;AAC3D,eAAO,MAAM,yCAAyC,UAAU,CAAA"}
1
+ {"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../../../src/identify/consts.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,gBAAgB,eAAe,CAAA;AAC5C,eAAO,MAAM,aAAa,+BAAyB,CAAA;AACnD,eAAO,MAAM,mBAAmB,mBAAmB,CAAA;AACnD,eAAO,MAAM,wBAAwB,wBAAwB,CAAA;AAE7D,eAAO,MAAM,yBAAyB,UAAU,CAAA;AAChD,eAAO,MAAM,iCAAiC,OAAO,CAAA;AACrD,eAAO,MAAM,sCAAsC,YAAY,CAAA;AAC/D,eAAO,MAAM,oCAAoC,UAAU,CAAA;AAC3D,eAAO,MAAM,yCAAyC,UAAU,CAAA"}
@@ -1,3 +1,3 @@
1
- export declare const version = "0.46.15";
1
+ export declare const version = "0.46.16-69581367";
2
2
  export declare const name = "libp2p";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,YAAY,CAAA;AAChC,eAAO,MAAM,IAAI,WAAW,CAAA"}
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,OAAO,qBAAqB,CAAA;AACzC,eAAO,MAAM,IAAI,WAAW,CAAA"}
@@ -1,3 +1,3 @@
1
- export const version = '0.46.15';
1
+ export const version = '0.46.16-69581367';
2
2
  export const name = 'libp2p';
3
3
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,SAAS,CAAA;AAChC,MAAM,CAAC,MAAM,IAAI,GAAG,QAAQ,CAAA"}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,kBAAkB,CAAA;AACzC,MAAM,CAAC,MAAM,IAAI,GAAG,QAAQ,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2p",
3
- "version": "0.46.15",
3
+ "version": "0.46.16-69581367",
4
4
  "description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/master/packages/libp2p#readme",
@@ -121,18 +121,18 @@
121
121
  },
122
122
  "dependencies": {
123
123
  "@achingbrain/nat-port-mapper": "^1.0.9",
124
- "@libp2p/crypto": "^2.0.5",
125
- "@libp2p/interface": "^0.1.3",
126
- "@libp2p/interface-internal": "^0.1.6",
127
- "@libp2p/keychain": "^3.0.5",
128
- "@libp2p/logger": "^3.0.3",
129
- "@libp2p/multistream-select": "^4.0.3",
130
- "@libp2p/peer-collections": "^4.0.5",
131
- "@libp2p/peer-id": "^3.0.3",
132
- "@libp2p/peer-id-factory": "^3.0.5",
133
- "@libp2p/peer-record": "^6.0.6",
134
- "@libp2p/peer-store": "^9.0.6",
135
- "@libp2p/utils": "^4.0.4",
124
+ "@libp2p/crypto": "2.0.6-69581367",
125
+ "@libp2p/interface": "0.1.4-69581367",
126
+ "@libp2p/interface-internal": "0.1.7-69581367",
127
+ "@libp2p/keychain": "3.0.6-69581367",
128
+ "@libp2p/logger": "3.0.4-69581367",
129
+ "@libp2p/multistream-select": "4.0.4-69581367",
130
+ "@libp2p/peer-collections": "4.0.6-69581367",
131
+ "@libp2p/peer-id": "3.0.4-69581367",
132
+ "@libp2p/peer-id-factory": "3.0.6-69581367",
133
+ "@libp2p/peer-record": "6.0.7-69581367",
134
+ "@libp2p/peer-store": "9.0.7-69581367",
135
+ "@libp2p/utils": "4.0.5-69581367",
136
136
  "@multiformats/mafmt": "^12.1.2",
137
137
  "@multiformats/multiaddr": "^12.1.5",
138
138
  "@multiformats/multiaddr-matcher": "^1.0.0",
@@ -171,17 +171,17 @@
171
171
  "@chainsafe/libp2p-gossipsub": "^10.0.0",
172
172
  "@chainsafe/libp2p-noise": "^13.0.0",
173
173
  "@chainsafe/libp2p-yamux": "^5.0.0",
174
- "@libp2p/bootstrap": "^9.0.8",
174
+ "@libp2p/bootstrap": "9.0.9-69581367",
175
175
  "@libp2p/daemon-client": "^7.0.0",
176
176
  "@libp2p/daemon-server": "^6.0.0",
177
- "@libp2p/floodsub": "^8.0.9",
178
- "@libp2p/interface-compliance-tests": "^4.1.1",
177
+ "@libp2p/floodsub": "8.0.10-69581367",
178
+ "@libp2p/interface-compliance-tests": "4.1.2-69581367",
179
179
  "@libp2p/interop": "^9.0.0",
180
- "@libp2p/kad-dht": "^10.0.10",
181
- "@libp2p/mdns": "^9.0.10",
182
- "@libp2p/mplex": "^9.0.8",
183
- "@libp2p/tcp": "^8.0.9",
184
- "@libp2p/websockets": "^7.0.9",
180
+ "@libp2p/kad-dht": "10.0.11-69581367",
181
+ "@libp2p/mdns": "9.0.11-69581367",
182
+ "@libp2p/mplex": "9.0.9-69581367",
183
+ "@libp2p/tcp": "8.0.10-69581367",
184
+ "@libp2p/websockets": "7.0.10-69581367",
185
185
  "@types/xsalsa20": "^1.1.0",
186
186
  "aegir": "^41.0.2",
187
187
  "execa": "^8.0.1",
@@ -8,7 +8,6 @@ js-libp2p-pnet <!-- omit in toc -->
8
8
  ## Table of Contents <!-- omit in toc -->
9
9
 
10
10
  - [Usage](#usage)
11
- - [Examples](#examples)
12
11
  - [Private Shared Keys](#private-shared-keys)
13
12
  - [PSK Generation](#psk-generation)
14
13
  - [From a module using libp2p](#from-a-module-using-libp2p)
@@ -32,9 +31,6 @@ const node = await createLibp2p({
32
31
  })
33
32
  ```
34
33
 
35
- ## Examples
36
- [Private Networks with IPFS](../../examples/pnet-ipfs)
37
-
38
34
  ## Private Shared Keys
39
35
 
40
36
  Private Shared Keys are expected to be in the following format:
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '0.46.15'
1
+ export const version = '0.46.16-69581367'
2
2
  export const name = 'libp2p'
@@ -1,71 +0,0 @@
1
- {
2
- "AutoNATComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.autonat.AutoNATComponents.html",
3
- "./autonat:AutoNATComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.autonat.AutoNATComponents.html",
4
- "AutoNATServiceInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.autonat.AutoNATServiceInit.html",
5
- "./autonat:AutoNATServiceInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.autonat.AutoNATServiceInit.html",
6
- "autoNATService": "https://libp2p.github.io/js-libp2p/functions/libp2p.autonat.autoNATService.html",
7
- "./autonat:autoNATService": "https://libp2p.github.io/js-libp2p/functions/libp2p.autonat.autoNATService.html",
8
- "CircuitRelayService": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.circuit_relay.CircuitRelayService.html",
9
- "./circuit-relay:CircuitRelayService": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.circuit_relay.CircuitRelayService.html",
10
- "CircuitRelayServiceEvents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.circuit_relay.CircuitRelayServiceEvents.html",
11
- "./circuit-relay:CircuitRelayServiceEvents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.circuit_relay.CircuitRelayServiceEvents.html",
12
- "RelayReservation": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.circuit_relay.RelayReservation.html",
13
- "./circuit-relay:RelayReservation": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.circuit_relay.RelayReservation.html",
14
- "circuitRelayServer": "https://libp2p.github.io/js-libp2p/functions/libp2p.circuit_relay.circuitRelayServer.html",
15
- "circuitRelayTransport": "https://libp2p.github.io/js-libp2p/functions/libp2p.circuit_relay.circuitRelayTransport.html",
16
- "FetchService": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.FetchService.html",
17
- "./fetch:FetchService": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.FetchService.html",
18
- "FetchServiceComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.FetchServiceComponents.html",
19
- "./fetch:FetchServiceComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.FetchServiceComponents.html",
20
- "FetchServiceInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.FetchServiceInit.html",
21
- "./fetch:FetchServiceInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.FetchServiceInit.html",
22
- "HandleMessageOptions": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.HandleMessageOptions.html",
23
- "./fetch:HandleMessageOptions": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.HandleMessageOptions.html",
24
- "LookupFunction": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.LookupFunction.html",
25
- "./fetch:LookupFunction": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.fetch.LookupFunction.html",
26
- "fetchService": "https://libp2p.github.io/js-libp2p/functions/libp2p.fetch.fetchService-1.html",
27
- "./fetch:fetchService": "https://libp2p.github.io/js-libp2p/functions/libp2p.fetch.fetchService-1.html",
28
- "IdentifyService": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.identify.IdentifyService.html",
29
- "./identify:IdentifyService": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.identify.IdentifyService.html",
30
- "IdentifyServiceComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.identify.IdentifyServiceComponents.html",
31
- "./identify:IdentifyServiceComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.identify.IdentifyServiceComponents.html",
32
- "IdentifyServiceInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.identify.IdentifyServiceInit.html",
33
- "./identify:IdentifyServiceInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.identify.IdentifyServiceInit.html",
34
- "Message": "https://libp2p.github.io/js-libp2p/variables/libp2p.identify.Message.html",
35
- "./identify:Message": "https://libp2p.github.io/js-libp2p/variables/libp2p.identify.Message.html",
36
- "multicodecs": "https://libp2p.github.io/js-libp2p/variables/libp2p.identify.multicodecs.html",
37
- "./identify:multicodecs": "https://libp2p.github.io/js-libp2p/variables/libp2p.identify.multicodecs.html",
38
- "identifyService": "https://libp2p.github.io/js-libp2p/functions/libp2p.identify.identifyService-1.html",
39
- "./identify:identifyService": "https://libp2p.github.io/js-libp2p/functions/libp2p.identify.identifyService-1.html",
40
- "Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
41
- ".:Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
42
- "Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
43
- ".:Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
44
- "ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
45
- ".:ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
46
- "createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
47
- ".:createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
48
- "plaintext": "https://libp2p.github.io/js-libp2p/functions/libp2p.insecure.plaintext.html",
49
- "./insecure:plaintext": "https://libp2p.github.io/js-libp2p/functions/libp2p.insecure.plaintext.html",
50
- "PingService": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.ping.PingService.html",
51
- "./ping:PingService": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.ping.PingService.html",
52
- "PingServiceComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.ping.PingServiceComponents.html",
53
- "./ping:PingServiceComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.ping.PingServiceComponents.html",
54
- "PingServiceInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.ping.PingServiceInit.html",
55
- "./ping:PingServiceInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.ping.PingServiceInit.html",
56
- "pingService": "https://libp2p.github.io/js-libp2p/functions/libp2p.ping.pingService-1.html",
57
- "./ping:pingService": "https://libp2p.github.io/js-libp2p/functions/libp2p.ping.pingService-1.html",
58
- "ProtectorInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.pnet.ProtectorInit.html",
59
- "./pnet:ProtectorInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.pnet.ProtectorInit.html",
60
- "generateKey": "https://libp2p.github.io/js-libp2p/functions/libp2p.pnet.generateKey.html",
61
- "preSharedKey": "https://libp2p.github.io/js-libp2p/functions/libp2p.pnet.preSharedKey.html",
62
- "./pnet:preSharedKey": "https://libp2p.github.io/js-libp2p/functions/libp2p.pnet.preSharedKey.html",
63
- "PMPOptions": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.upnp_nat.PMPOptions.html",
64
- "./upnp-nat:PMPOptions": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.upnp_nat.PMPOptions.html",
65
- "UPnPNATComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.upnp_nat.UPnPNATComponents.html",
66
- "./upnp-nat:UPnPNATComponents": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.upnp_nat.UPnPNATComponents.html",
67
- "UPnPNATInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.upnp_nat.UPnPNATInit.html",
68
- "./upnp-nat:UPnPNATInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.upnp_nat.UPnPNATInit.html",
69
- "uPnPNATService": "https://libp2p.github.io/js-libp2p/functions/libp2p.upnp_nat.uPnPNATService.html",
70
- "./upnp-nat:uPnPNATService": "https://libp2p.github.io/js-libp2p/functions/libp2p.upnp_nat.uPnPNATService.html"
71
- }