libp2p 2.9.0 → 2.10.0-8484de8a2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/index.min.js +13 -17
  2. package/dist/index.min.js.map +4 -4
  3. package/dist/src/address-manager/dns-mappings.d.ts +1 -2
  4. package/dist/src/address-manager/dns-mappings.d.ts.map +1 -1
  5. package/dist/src/address-manager/dns-mappings.js +40 -44
  6. package/dist/src/address-manager/dns-mappings.js.map +1 -1
  7. package/dist/src/address-manager/index.d.ts.map +1 -1
  8. package/dist/src/address-manager/index.js +31 -14
  9. package/dist/src/address-manager/index.js.map +1 -1
  10. package/dist/src/address-manager/ip-mappings.d.ts +1 -0
  11. package/dist/src/address-manager/ip-mappings.d.ts.map +1 -1
  12. package/dist/src/address-manager/ip-mappings.js +51 -40
  13. package/dist/src/address-manager/ip-mappings.js.map +1 -1
  14. package/dist/src/address-manager/observed-addresses.d.ts.map +1 -1
  15. package/dist/src/address-manager/observed-addresses.js +1 -3
  16. package/dist/src/address-manager/observed-addresses.js.map +1 -1
  17. package/dist/src/address-manager/transport-addresses.d.ts.map +1 -1
  18. package/dist/src/address-manager/transport-addresses.js +6 -8
  19. package/dist/src/address-manager/transport-addresses.js.map +1 -1
  20. package/dist/src/config/connection-gater.browser.d.ts.map +1 -1
  21. package/dist/src/config/connection-gater.browser.js +3 -9
  22. package/dist/src/config/connection-gater.browser.js.map +1 -1
  23. package/dist/src/config.js +1 -1
  24. package/dist/src/config.js.map +1 -1
  25. package/dist/src/connection-manager/address-sorter.d.ts.map +1 -1
  26. package/dist/src/connection-manager/address-sorter.js +1 -2
  27. package/dist/src/connection-manager/address-sorter.js.map +1 -1
  28. package/dist/src/connection-manager/connection-pruner.d.ts.map +1 -1
  29. package/dist/src/connection-manager/connection-pruner.js +7 -3
  30. package/dist/src/connection-manager/connection-pruner.js.map +1 -1
  31. package/dist/src/connection-manager/constants.defaults.d.ts +4 -0
  32. package/dist/src/connection-manager/constants.defaults.d.ts.map +1 -1
  33. package/dist/src/connection-manager/constants.defaults.js +4 -0
  34. package/dist/src/connection-manager/constants.defaults.js.map +1 -1
  35. package/dist/src/connection-manager/dial-queue.d.ts +2 -2
  36. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  37. package/dist/src/connection-manager/dial-queue.js +13 -25
  38. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  39. package/dist/src/connection-manager/index.d.ts +10 -2
  40. package/dist/src/connection-manager/index.d.ts.map +1 -1
  41. package/dist/src/connection-manager/index.js +45 -27
  42. package/dist/src/connection-manager/index.js.map +1 -1
  43. package/dist/src/connection-manager/reconnect-queue.js +1 -1
  44. package/dist/src/connection-manager/reconnect-queue.js.map +1 -1
  45. package/dist/src/connection-manager/utils.d.ts +31 -3
  46. package/dist/src/connection-manager/utils.d.ts.map +1 -1
  47. package/dist/src/connection-manager/utils.js +99 -18
  48. package/dist/src/connection-manager/utils.js.map +1 -1
  49. package/dist/src/connection-monitor.d.ts +1 -1
  50. package/dist/src/connection-monitor.d.ts.map +1 -1
  51. package/dist/src/connection-monitor.js +2 -3
  52. package/dist/src/connection-monitor.js.map +1 -1
  53. package/dist/src/connection.d.ts +62 -0
  54. package/dist/src/connection.d.ts.map +1 -0
  55. package/dist/src/connection.js +239 -0
  56. package/dist/src/connection.js.map +1 -0
  57. package/dist/src/get-peer.js +3 -3
  58. package/dist/src/get-peer.js.map +1 -1
  59. package/dist/src/index.d.ts +2 -2
  60. package/dist/src/index.js +2 -2
  61. package/dist/src/libp2p.d.ts.map +1 -1
  62. package/dist/src/libp2p.js +5 -5
  63. package/dist/src/libp2p.js.map +1 -1
  64. package/dist/src/peer-routing.js +1 -1
  65. package/dist/src/peer-routing.js.map +1 -1
  66. package/dist/src/random-walk.d.ts.map +1 -1
  67. package/dist/src/random-walk.js +13 -3
  68. package/dist/src/random-walk.js.map +1 -1
  69. package/dist/src/registrar.d.ts +3 -3
  70. package/dist/src/registrar.d.ts.map +1 -1
  71. package/dist/src/registrar.js +50 -41
  72. package/dist/src/registrar.js.map +1 -1
  73. package/dist/src/transport-manager.js +15 -2
  74. package/dist/src/transport-manager.js.map +1 -1
  75. package/dist/src/upgrader.d.ts +27 -25
  76. package/dist/src/upgrader.d.ts.map +1 -1
  77. package/dist/src/upgrader.js +97 -336
  78. package/dist/src/upgrader.js.map +1 -1
  79. package/dist/src/utils.d.ts +3 -0
  80. package/dist/src/utils.d.ts.map +1 -0
  81. package/dist/src/utils.js +25 -0
  82. package/dist/src/utils.js.map +1 -0
  83. package/dist/src/version.d.ts +1 -1
  84. package/dist/src/version.d.ts.map +1 -1
  85. package/dist/src/version.js +1 -1
  86. package/dist/src/version.js.map +1 -1
  87. package/package.json +26 -30
  88. package/src/address-manager/dns-mappings.ts +51 -51
  89. package/src/address-manager/index.ts +37 -17
  90. package/src/address-manager/ip-mappings.ts +64 -44
  91. package/src/address-manager/observed-addresses.ts +1 -3
  92. package/src/address-manager/transport-addresses.ts +7 -9
  93. package/src/config/connection-gater.browser.ts +3 -12
  94. package/src/config.ts +1 -1
  95. package/src/connection-manager/address-sorter.ts +1 -2
  96. package/src/connection-manager/connection-pruner.ts +8 -3
  97. package/src/connection-manager/constants.defaults.ts +5 -0
  98. package/src/connection-manager/dial-queue.ts +14 -29
  99. package/src/connection-manager/index.ts +62 -29
  100. package/src/connection-manager/reconnect-queue.ts +1 -1
  101. package/src/connection-manager/utils.ts +129 -21
  102. package/src/connection-monitor.ts +3 -4
  103. package/src/connection.ts +316 -0
  104. package/src/get-peer.ts +3 -3
  105. package/src/index.ts +2 -2
  106. package/src/libp2p.ts +5 -6
  107. package/src/peer-routing.ts +1 -1
  108. package/src/random-walk.ts +13 -3
  109. package/src/registrar.ts +67 -54
  110. package/src/transport-manager.ts +18 -2
  111. package/src/upgrader.ts +143 -421
  112. package/src/utils.ts +31 -0
  113. package/src/version.ts +1 -1
  114. package/dist/src/connection/index.d.ts +0 -84
  115. package/dist/src/connection/index.d.ts.map +0 -1
  116. package/dist/src/connection/index.js +0 -144
  117. package/dist/src/connection/index.js.map +0 -1
  118. package/dist/typedoc-urls.json +0 -24
  119. package/src/connection/index.ts +0 -199
package/dist/index.min.js CHANGED
@@ -1,23 +1,19 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2P=(()=>{var Up=Object.create;var zo=Object.defineProperty;var Kp=Object.getOwnPropertyDescriptor;var qp=Object.getOwnPropertyNames;var zp=Object.getPrototypeOf,Vp=Object.prototype.hasOwnProperty;var Dr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Ot=(r,t)=>{for(var e in t)zo(r,e,{get:t[e],enumerable:!0})},Nu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of qp(t))!Vp.call(r,o)&&o!==e&&zo(r,o,{get:()=>t[o],enumerable:!(n=Kp(t,o))||n.enumerable});return r};var Vo=(r,t,e)=>(e=r!=null?Up(zp(r)):{},Nu(t||!r||!r.__esModule?zo(e,"default",{value:r,enumerable:!0}):e,r)),Hp=r=>Nu(zo({},"__esModule",{value:!0}),r);var Zd=Dr((z2,sl)=>{"use strict";var R0=Object.prototype.hasOwnProperty,Rt="~";function co(){}Object.create&&(co.prototype=Object.create(null),new co().__proto__||(Rt=!1));function O0(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function jd(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new O0(e,n||r,o),i=Rt?Rt+t:t;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Ts(r,t){--r._eventsCount===0?r._events=new co:delete r._events[t]}function vt(){this._events=new co,this._eventsCount=0}vt.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)R0.call(e,n)&&t.push(Rt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};vt.prototype.listeners=function(t){var e=Rt?Rt+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};vt.prototype.listenerCount=function(t){var e=Rt?Rt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};vt.prototype.emit=function(t,e,n,o,s,i){var a=Rt?Rt+t:t;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,n,o,s,i),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(t,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c[f].fn.apply(c[f].context,l)}}return!0};vt.prototype.on=function(t,e,n){return jd(this,t,e,n,!1)};vt.prototype.once=function(t,e,n){return jd(this,t,e,n,!0)};vt.prototype.removeListener=function(t,e,n,o){var s=Rt?Rt+t:t;if(!this._events[s])return this;if(!e)return Ts(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&Ts(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Ts(this,s)}return this};vt.prototype.removeAllListeners=function(t){var e;return t?(e=Rt?Rt+t:t,this._events[e]&&Ts(this,e)):(this._events=new co,this._eventsCount=0),this};vt.prototype.off=vt.prototype.removeListener;vt.prototype.addListener=vt.prototype.on;vt.prefixed=Rt;vt.EventEmitter=vt;typeof sl<"u"&&(sl.exports=vt)});var th=Dr((f_,Jd)=>{Jd.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Qh=Dr(Io=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,l,f,d;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[u,l,f,d].join(".")},i=function(c){var u,l,f,d,h,p;for(u=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),h=p[0],l=p[1],c=c.substring(l),u.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var u,l,f,d,h;for(d=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=l)d=d*u+(e(c[f])-n)>>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")d=d*u+(10+e(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*u+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=function(){function c(u,l){var f,d,h,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(p=u.split("/",2),u=p[0],l=p[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=i(l)}catch(g){throw f=g,new Error("Invalid mask: "+l)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,d;for(d=i(this.first),f=i(this.last),l=0;d<=f;)u(a(d),d,l),l++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Io.ip2long=i,Io.long2ip=a,Io.Netmask=r}).call(Io)});var Sp=Dr((tP,_p)=>{function Wt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}_p.exports=Wt;Wt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Wt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Wt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Wt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Wt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Wt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Wt.prototype.start=Wt.prototype.try;Wt.prototype.errors=function(){return this._errors};Wt.prototype.attempts=function(){return this._attempts};Wt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var Ap=Dr(Ar=>{var Wb=Sp();Ar.operation=function(r){var t=Ar.timeouts(r);return new Wb(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Ar.timeouts=function(r){if(r instanceof Array)return[].concat(r);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var e in r)t[e]=r[e];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(s,i){return s-i}),n};Ar.createTimeout=function(r,t){var e=t.randomize?Math.random()+1:1,n=Math.round(e*Math.max(t.minTimeout,1)*Math.pow(t.factor,r));return n=Math.min(n,t.maxTimeout),n};Ar.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var u=Ar.operation(t),l=Array.prototype.slice.call(arguments,1),f=l.pop();l.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),f.apply(this,arguments))}),u.attempt(function(){c.apply(r,l)})}.bind(r,i),r[s].options=t}}});var Ip=Dr((rP,Cp)=>{Cp.exports=Ap()});var Cw={};Ot(Cw,{createLibp2p:()=>_w,dnsaddrResolver:()=>Se,isLibp2p:()=>Aw});var Bu=Symbol.for("@libp2p/connection");var Pa=Symbol.for("@libp2p/content-routing");var Da=Symbol.for("@libp2p/peer-discovery");var Ho=Symbol.for("@libp2p/peer-id");function Te(r){return!!r?.[Ho]}var La=Symbol.for("@libp2p/peer-routing");var Ra="keep-alive";var kw=Symbol.for("@libp2p/transport");var He;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(He||(He={}));var Gt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var k=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Lr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},An=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var $o=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Rr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var $e=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Or=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Pe=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Wo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Go=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},Cn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},jo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Zo=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},pe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var kr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Mr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},Xo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Qo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},De=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Bt=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Yo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Fu(...r){let t=[];for(let e of r)Yo(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Uu(...r){let t=[];for(let e of r)Yo(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var In=Symbol.for("@libp2p/service-capabilities"),Oa=Symbol.for("@libp2p/service-dependencies");var Fa={};Ot(Fa,{base58btc:()=>j,base58flickr:()=>Qp});var ix=new Uint8Array(0);function Ku(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function me(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function qu(r){return new TextEncoder().encode(r)}function zu(r){return new TextDecoder().decode(r)}function $p(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,m=0,w=0,E=p.length;w!==E&&p[w]===0;)w++,g++;for(var _=(E-w)*l+1>>>0,C=new Uint8Array(_);w!==E;){for(var b=p[w],L=0,R=_-1;(b!==0||L<m)&&R!==-1;R--,L++)b+=256*C[R]>>>0,C[R]=b%a>>>0,b=b/a>>>0;if(b!==0)throw new Error("Non-zero carry");m=L,w++}for(var I=_-m;I!==_&&C[I]===0;)I++;for(var y=c.repeat(g);I<_;++I)y+=r.charAt(C[I]);return y}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var m=0,w=0;p[g]===c;)m++,g++;for(var E=(p.length-g)*u+1>>>0,_=new Uint8Array(E);p[g];){var C=e[p.charCodeAt(g)];if(C===255)return;for(var b=0,L=E-1;(C!==0||b<w)&&L!==-1;L--,b++)C+=a*_[L]>>>0,_[L]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");w=b,g++}if(p[g]!==" "){for(var R=E-w;R!==E&&_[R]===0;)R++;for(var I=new Uint8Array(m+(E-R)),y=m;R!==E;)I[y++]=_[R++];return I}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Wp=$p,Gp=Wp,Hu=Gp;var ka=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ma=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return $u(this,t)}},Na=class{decoders;constructor(t){this.decoders=t}or(t){return $u(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function $u(r,t){return new Na({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Ba=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new ka(t,e,n),this.decoder=new Ma(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Nr({name:r,prefix:t,encode:e,decode:n}){return new Ba(r,t,e,n)}function Le({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Hu(e,r);return Nr({prefix:t,name:r,encode:n,decode:s=>me(o(s))})}function jp(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=t[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Zp(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function Xp(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function rt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Xp(n);return Nr({prefix:t,name:r,encode(s){return Zp(s,n,e)},decode(s){return jp(s,o,e,r)}})}var j=Le({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Qp=Le({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ua={};Ot(Ua,{base32:()=>zt,base32hex:()=>em,base32hexpad:()=>nm,base32hexpadupper:()=>om,base32hexupper:()=>rm,base32pad:()=>Jp,base32padupper:()=>tm,base32upper:()=>Yp,base32z:()=>sm});var zt=rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Yp=rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Jp=rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),tm=rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),em=rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),rm=rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),nm=rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),om=rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),sm=rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ka={};Ot(Ka,{base36:()=>Tn,base36upper:()=>im});var Tn=Le({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),im=Le({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var am=ju,Wu=128,cm=127,lm=~cm,um=Math.pow(2,31);function ju(r,t,e){t=t||[],e=e||0;for(var n=e;r>=um;)t[e++]=r&255|Wu,r/=128;for(;r&lm;)t[e++]=r&255|Wu,r>>>=7;return t[e]=r|0,ju.bytes=e-n+1,t}var fm=qa,dm=128,Gu=127;function qa(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw qa.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Gu)<<o:(i&Gu)*Math.pow(2,o),o+=7}while(i>=dm);return qa.bytes=s-n,e}var hm=Math.pow(2,7),pm=Math.pow(2,14),mm=Math.pow(2,21),gm=Math.pow(2,28),ym=Math.pow(2,35),bm=Math.pow(2,42),wm=Math.pow(2,49),xm=Math.pow(2,56),Em=Math.pow(2,63),vm=function(r){return r<hm?1:r<pm?2:r<mm?3:r<gm?4:r<ym?5:r<bm?6:r<wm?7:r<xm?8:r<Em?9:10},_m={encode:am,decode:fm,encodingLength:vm},Sm=_m,Pn=Sm;function Dn(r,t=0){return[Pn.decode(r,t),Pn.decode.bytes]}function Br(r,t,e=0){return Pn.encode(r,t,e),t}function Fr(r){return Pn.encodingLength(r)}function jt(r,t){let e=t.byteLength,n=Fr(r),o=n+Fr(e),s=new Uint8Array(o+e);return Br(r,s,0),Br(e,s,n),s.set(t,o),new Ur(r,e,t,s)}function ge(r){let t=me(r),[e,n]=Dn(t),[o,s]=Dn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ur(e,o,i,t)}function Zu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ku(r.bytes,e.bytes)}}var Ur=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Xu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Cm(e,za(r),t??j.encoder);default:return Im(e,za(r),t??zt.encoder)}}var Qu=new WeakMap;function za(r){let t=Qu.get(r);if(t==null){let e=new Map;return Qu.set(r,e),e}return t}var tt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Ln)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Tm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=jt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Zu(t.multihash,n.multihash)}toString(t){return Xu(this,t)}toJSON(){return{"/":Xu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Yu(n,o,s.bytes))}else if(e[Pm]===!0){let{version:n,multihash:o,code:s}=e,i=ge(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Ln)throw new Error(`Version 0 CID must use dag-pb (code: ${Ln}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Yu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Ln,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=me(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Ur(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=Dn(t.subarray(e));return e+=d,f},o=n(),s=Ln;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(t,e){let[n,o]=Am(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return za(s).set(n,t),s}};function Am(r,t){switch(r[0]){case"Q":{let e=t??j;return[j.prefix,e.decode(`${j.prefix}${r}`)]}case j.prefix:{let e=t??j;return[j.prefix,e.decode(r)]}case zt.prefix:{let e=t??zt;return[zt.prefix,e.decode(r)]}case Tn.prefix:{let e=t??Tn;return[Tn.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Cm(r,t,e){let{prefix:n}=e;if(n!==j.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Im(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Ln=112,Tm=18;function Yu(r,t,e){let n=Fr(r),o=n+Fr(t),s=new Uint8Array(o+e.byteLength);return Br(r,s,0),Br(t,s,n),s.set(e,o),s}var Pm=Symbol.for("@ipld/js-cid/CID");var Va={};Ot(Va,{identity:()=>Zt});var Ju=0,Dm="identity",tf=me;function Lm(r){return jt(Ju,tf(r))}var Zt={code:Ju,name:Dm,encode:tf,digest:Lm};function G(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function nt(r=0){return new Uint8Array(r)}function bt(r=0){return new Uint8Array(r)}function Xt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=bt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var rf=Symbol.for("@achingbrain/uint8arraylist");function ef(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function ts(r){return!!r?.[rf]}var z=class r{bufs;length;[rf]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(ts(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(ts(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=ef(this.bufs,t);return e.buf[e.index]}set(t,e){let n=ef(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(ts(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Xt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Xt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,l=e>a&&e<=c;if(u&&l){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!ts(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=e;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){l=Math.max(1,d-a[h]);break}}if(l===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=bt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=bt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!G(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var Ha={};Ot(Ha,{base10:()=>Rm});var Rm=Le({prefix:"9",name:"base10",alphabet:"0123456789"});var $a={};Ot($a,{base16:()=>Om,base16upper:()=>km});var Om=rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),km=rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Wa={};Ot(Wa,{base2:()=>Mm});var Mm=rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ga={};Ot(Ga,{base256emoji:()=>Km});var nf=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Nm=nf.reduce((r,t,e)=>(r[e]=t,r),[]),Bm=nf.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Fm(r){return r.reduce((t,e)=>(t+=Nm[e],t),"")}function Um(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Bm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Km=Nr({prefix:"\u{1F680}",name:"base256emoji",encode:Fm,decode:Um});var Xa={};Ot(Xa,{base64:()=>ja,base64pad:()=>qm,base64url:()=>Za,base64urlpad:()=>zm});var ja=rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qm=rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Za=rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zm=rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qa={};Ot(Qa,{base8:()=>Vm});var Vm=rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ya={};Ot(Ya,{identity:()=>Hm});var Hm=Nr({prefix:"\0",name:"identity",encode:r=>zu(r),decode:r=>qu(r)});var Vx=new TextEncoder,Hx=new TextDecoder;var ec={};Ot(ec,{sha256:()=>Kr,sha512:()=>Gm});function tc({name:r,code:t,encode:e}){return new Ja(r,t,e)}var Ja=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?jt(this.code,e):e.then(n=>jt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function sf(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Kr=tc({name:"sha2-256",code:18,encode:sf("SHA-256")}),Gm=tc({name:"sha2-512",code:19,encode:sf("SHA-512")});var Rn={...Ya,...Wa,...Qa,...Ha,...$a,...Ua,...Ka,...Fa,...Xa,...Ga},rE={...ec,...Va};function cf(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var af=cf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),rc=cf("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=bt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),jm={utf8:af,"utf-8":af,hex:Rn.base16,latin1:rc,ascii:rc,binary:rc,...Rn},es=jm;function D(r,t="utf8"){let e=es[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function N(r,t="utf8"){let e=es[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Zm=parseInt("11111",2),nc=parseInt("10000000",2),Xm=parseInt("01111111",2),lf={0:On,1:On,2:Qm,3:tg,4:eg,5:Jm,6:Ym,16:On,22:On,48:On};function ye(r,t={offset:0}){let e=r[t.offset]&Zm;if(t.offset++,lf[e]!=null)return lf[e](r,t);throw new Error("No decoder for tag "+e)}function kn(r,t){let e=0;if((r[t.offset]&nc)===nc){let n=r[t.offset]&Xm,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function On(r,t){kn(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ye(r,t);if(n===null)break;e.push(n)}return e}function Qm(r,t){let e=kn(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function Ym(r,t){let e=kn(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let u=r[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let l=0;for(let f=0;f<c.length;f++)l+=c[f]<<f*7;a+=`.${l}`,c=[]}}return a}function Jm(r,t){return t.offset++,null}function tg(r,t){let e=kn(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function eg(r,t){let e=kn(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function rg(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new z;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function rs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=rg(r.byteLength);return new z(Uint8Array.from([t.byteLength|nc]),t)}function Ct(r){let t=new z,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new z(Uint8Array.from([2]),rs(t),t)}function Mn(r){let t=Uint8Array.from([0]),e=new z(t,r);return new z(Uint8Array.from([3]),rs(e),e)}function uf(r){return new z(Uint8Array.from([4]),rs(r),r)}function Qt(r,t=48){let e=new z;for(let n of r)e.append(n);return new z(Uint8Array.from([t]),rs(e),e)}async function ff(r="P-256"){let t=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",t.publicKey),privateKey:await crypto.subtle.exportKey("jwk",t.privateKey)}}async function df(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);e?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function hf(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var ng=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),og=Uint8Array.from([6,5,43,129,4,0,34]),sg=Uint8Array.from([6,5,43,129,4,0,35]),ig={ext:!0,kty:"EC",crv:"P-256"},ag={ext:!0,kty:"EC",crv:"P-384"},cg={ext:!0,kty:"EC",crv:"P-521"},oc=32,sc=48,ic=66;function ac(r){let t=ye(r);return pf(t)}function pf(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===oc*2+1)return n=N(t.subarray(e,e+oc),"base64url"),o=N(t.subarray(e+oc),"base64url"),new We({...ig,key_ops:["verify"],x:n,y:o});if(t.byteLength===sc*2+1)return n=N(t.subarray(e,e+sc),"base64url"),o=N(t.subarray(e+sc),"base64url"),new We({...ag,key_ops:["verify"],x:n,y:o});if(t.byteLength===ic*2+1)return n=N(t.subarray(e,e+ic),"base64url"),o=N(t.subarray(e+ic),"base64url"),new We({...cg,key_ops:["verify"],x:n,y:o});throw new k(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function mf(r){return Qt([Ct(Uint8Array.from([1])),uf(D(r.d??"","base64url")),Qt([yf(r.crv)],160),Qt([Mn(new z(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function gf(r){return Qt([Ct(Uint8Array.from([1])),Qt([yf(r.crv)],160),Qt([Mn(new z(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function yf(r){if(r==="P-256")return ng;if(r==="P-384")return og;if(r==="P-521")return sg;throw new k(`Invalid curve ${r}`)}async function bf(r="P-256"){let t=await ff(r);return new ns(t.privateKey)}var We=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=gf(this.jwk)),this._raw}toMultihash(){return Zt.digest(Vt(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}async verify(t,e,n){return hf(this.jwk,e,t,n)}},ns=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new We({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=mf(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}async sign(t,e){return df(this.jwk,t,e)}};var Ge=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function zr(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Nn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function wt(r,...t){if(!zr(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function xf(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Nn(r.outputLen),Nn(r.blockLen)}function Vr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Ef(r,t){wt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function we(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function os(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Yt(r,t){return r<<32-t|r>>>t}var vf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",lg=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function ie(r){if(wt(r),vf)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=lg[r[e]];return t}var be={_0:48,_9:57,A:65,F:70,a:97,f:102};function wf(r){if(r>=be._0&&r<=be._9)return r-be._0;if(r>=be.A&&r<=be.F)return r-(be.A-10);if(r>=be.a&&r<=be.f)return r-(be.a-10)}function Hr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(vf)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=wf(r.charCodeAt(s)),a=wf(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function _f(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Bn(r){return typeof r=="string"&&(r=_f(r)),wt(r),r}function Ft(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];wt(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var qr=class{};function cc(r){let t=n=>r().update(Bn(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function je(r=32){if(Ge&&typeof Ge.getRandomValues=="function")return Ge.getRandomValues(new Uint8Array(r));if(Ge&&typeof Ge.randomBytes=="function")return Uint8Array.from(Ge.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function ug(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}function Sf(r,t,e){return r&t^~r&e}function Af(r,t,e){return r&t^r&e^t&e}var Fn=class extends qr{constructor(t,e,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=os(this.buffer)}update(t){Vr(this),t=Bn(t),wt(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=os(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Vr(this),Ef(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,we(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;ug(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=os(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},xe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ht=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var ss=BigInt(4294967295),Cf=BigInt(32);function fg(r,t=!1){return t?{h:Number(r&ss),l:Number(r>>Cf&ss)}:{h:Number(r>>Cf&ss)|0,l:Number(r&ss)|0}}function If(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=fg(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var lc=(r,t,e)=>r>>>e,uc=(r,t,e)=>r<<32-e|t>>>e,Ze=(r,t,e)=>r>>>e|t<<32-e,Xe=(r,t,e)=>r<<32-e|t>>>e,Un=(r,t,e)=>r<<64-e|t>>>e-32,Kn=(r,t,e)=>r>>>e-32|t<<64-e;function ae(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Tf=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Pf=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Df=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Lf=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Rf=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Of=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var hg=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Oe=new Uint32Array(64),is=class extends Fn{constructor(t=32){super(64,t,8,!1),this.A=xe[0]|0,this.B=xe[1]|0,this.C=xe[2]|0,this.D=xe[3]|0,this.E=xe[4]|0,this.F=xe[5]|0,this.G=xe[6]|0,this.H=xe[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)Oe[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Oe[f-15],h=Oe[f-2],p=Yt(d,7)^Yt(d,18)^d>>>3,g=Yt(h,17)^Yt(h,19)^h>>>10;Oe[f]=g+Oe[f-7]+p+Oe[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Yt(a,6)^Yt(a,11)^Yt(a,25),h=l+d+Sf(a,c,u)+hg[f]+Oe[f]|0,g=(Yt(n,2)^Yt(n,13)^Yt(n,22))+Af(n,o,s)|0;l=u,u=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){we(Oe)}destroy(){this.set(0,0,0,0,0,0,0,0),we(this.buffer)}};var kf=If(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),pg=kf[0],mg=kf[1],ke=new Uint32Array(80),Me=new Uint32Array(80),fc=class extends Fn{constructor(t=64){super(128,t,16,!1),this.Ah=ht[0]|0,this.Al=ht[1]|0,this.Bh=ht[2]|0,this.Bl=ht[3]|0,this.Ch=ht[4]|0,this.Cl=ht[5]|0,this.Dh=ht[6]|0,this.Dl=ht[7]|0,this.Eh=ht[8]|0,this.El=ht[9]|0,this.Fh=ht[10]|0,this.Fl=ht[11]|0,this.Gh=ht[12]|0,this.Gl=ht[13]|0,this.Hh=ht[14]|0,this.Hl=ht[15]|0}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[t,e,n,o,s,i,a,c,u,l,f,d,h,p,g,m]}set(t,e,n,o,s,i,a,c,u,l,f,d,h,p,g,m){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=m|0}process(t,e){for(let _=0;_<16;_++,e+=4)ke[_]=t.getUint32(e),Me[_]=t.getUint32(e+=4);for(let _=16;_<80;_++){let C=ke[_-15]|0,b=Me[_-15]|0,L=Ze(C,b,1)^Ze(C,b,8)^lc(C,b,7),R=Xe(C,b,1)^Xe(C,b,8)^uc(C,b,7),I=ke[_-2]|0,y=Me[_-2]|0,S=Ze(I,y,19)^Un(I,y,61)^lc(I,y,6),x=Xe(I,y,19)^Kn(I,y,61)^uc(I,y,6),v=Df(R,x,Me[_-7],Me[_-16]),A=Lf(v,L,S,ke[_-7],ke[_-16]);ke[_]=A|0,Me[_]=v|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:w,Hl:E}=this;for(let _=0;_<80;_++){let C=Ze(f,d,14)^Ze(f,d,18)^Un(f,d,41),b=Xe(f,d,14)^Xe(f,d,18)^Kn(f,d,41),L=f&h^~f&g,R=d&p^~d&m,I=Rf(E,b,R,mg[_],Me[_]),y=Of(I,w,C,L,pg[_],ke[_]),S=I|0,x=Ze(n,o,28)^Un(n,o,34)^Un(n,o,39),v=Xe(n,o,28)^Kn(n,o,34)^Kn(n,o,39),A=n&s^n&a^s&a,P=o&i^o&c^i&c;w=g|0,E=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=ae(u|0,l|0,y|0,S|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let T=Tf(S,v,P);n=Pf(T,y,x,A),o=T|0}({h:n,l:o}=ae(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ae(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ae(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ae(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=ae(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ae(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=ae(this.Gh|0,this.Gl|0,g|0,m|0),{h:w,l:E}=ae(this.Hh|0,this.Hl|0,w|0,E|0),this.set(n,o,s,i,a,c,u,l,f,d,h,p,g,m,w,E)}roundClean(){we(ke,Me)}destroy(){we(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var as=cc(()=>new is);var Mf=cc(()=>new fc);var pc=BigInt(0),hc=BigInt(1);function Ee(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function qn(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Nf(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?pc:BigInt("0x"+r)}function $r(r){return Nf(ie(r))}function Qe(r){return wt(r),Nf(ie(Uint8Array.from(r).reverse()))}function cs(r,t){return Hr(r.toString(16).padStart(t*2,"0"))}function Wr(r,t){return cs(r,t).reverse()}function Q(r,t,e){let n;if(typeof t=="string")try{n=Hr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(zr(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}var dc=r=>typeof r=="bigint"&&pc<=r;function Bf(r,t,e){return dc(r)&&dc(t)&&dc(e)&&t<=r&&r<e}function Ne(r,t,e,n){if(!Bf(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Ff(r){let t;for(t=0;r>pc;r>>=hc,t+=1);return t}var Ye=r=>(hc<<BigInt(r))-hc;function Uf(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},u=(...h)=>e(i,s,...h),l=(h=n(0))=>{i=u(o(0),h),s=u(),h.length!==0&&(i=u(o(1),h),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,p=[];for(;h<t;){s=u();let g=s.slice();p.push(g),h+=s.length}return Ft(...p)};return(h,p)=>{c(),l(h);let g;for(;!(g=p(f()));)l();return c(),g}}function Be(r,t,e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(e).forEach(([o,s])=>n(o,s,!0))}function Gr(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var It=BigInt(0),ut=BigInt(1),Je=BigInt(2),gg=BigInt(3),zf=BigInt(4),Vf=BigInt(5),Hf=BigInt(8);function et(r,t){let e=r%t;return e>=It?e:t+e}function Y(r,t,e){let n=r;for(;t-- >It;)n*=n,n%=e;return n}function Kf(r,t){if(r===It)throw new Error("invert: expected non-zero number");if(t<=It)throw new Error("invert: expected positive modulus, got "+t);let e=et(r,t),n=t,o=It,s=ut,i=ut,a=It;for(;e!==It;){let u=n/e,l=n%e,f=o-i*u,d=s-a*u;n=e,e=l,o=i,s=a,i=f,a=d}if(n!==ut)throw new Error("invert: does not exist");return et(o,t)}function $f(r,t){let e=(r.ORDER+ut)/zf,n=r.pow(t,e);if(!r.eql(r.sqr(n),t))throw new Error("Cannot find square root");return n}function yg(r,t){let e=(r.ORDER-Vf)/Hf,n=r.mul(t,Je),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,Je),o),a=r.mul(s,r.sub(i,r.ONE));if(!r.eql(r.sqr(a),t))throw new Error("Cannot find square root");return a}function bg(r){if(r<BigInt(3))throw new Error("sqrt is not defined for small field");let t=r-ut,e=0;for(;t%Je===It;)t/=Je,e++;let n=Je,o=Jt(r);for(;qf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return $f;let s=o.pow(n,t),i=(t+ut)/Je;return function(c,u){if(c.is0(u))return u;if(qf(c,u)!==1)throw new Error("Cannot find square root");let l=e,f=c.mul(c.ONE,s),d=c.pow(u,t),h=c.pow(u,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===l)throw new Error("Cannot find square root");let m=ut<<BigInt(l-p-1),w=c.pow(f,m);l=p,f=c.sqr(w),d=c.mul(d,f),h=c.mul(h,w)}return h}}function wg(r){return r%zf===gg?$f:r%Hf===Vf?yg:bg(r)}var Wf=(r,t)=>(et(r,t)&ut)===ut,xg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function mc(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=xg.reduce((n,o)=>(n[o]="function",n),t);return Be(r,e),r}function Eg(r,t,e){if(e<It)throw new Error("invalid exponent, negatives unsupported");if(e===It)return r.ONE;if(e===ut)return t;let n=r.ONE,o=t;for(;e>It;)e&ut&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ut;return n}function zn(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function qf(r,t){let e=(r.ORDER-ut)/Je,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Gf(r,t){t!==void 0&&Nn(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Jt(r,t,e=!1,n={}){if(r<=It)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s;if(typeof t=="object"&&t!=null){if(n.sqrt||e)throw new Error("cannot specify opts in two arguments");let l=t;l.BITS&&(o=l.BITS),l.sqrt&&(s=l.sqrt),typeof l.isLE=="boolean"&&(e=l.isLE)}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:i,nByteLength:a}=Gf(r,o);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c,u=Object.freeze({ORDER:r,isLE:e,BITS:i,BYTES:a,MASK:Ye(i),ZERO:It,ONE:ut,create:l=>et(l,r),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return It<=l&&l<r},is0:l=>l===It,isValidNot0:l=>!u.is0(l)&&u.isValid(l),isOdd:l=>(l&ut)===ut,neg:l=>et(-l,r),eql:(l,f)=>l===f,sqr:l=>et(l*l,r),add:(l,f)=>et(l+f,r),sub:(l,f)=>et(l-f,r),mul:(l,f)=>et(l*f,r),pow:(l,f)=>Eg(u,l,f),div:(l,f)=>et(l*Kf(f,r),r),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>Kf(l,r),sqrt:s||(l=>(c||(c=wg(r)),c(u,l))),toBytes:l=>e?Wr(l,a):cs(l,a),fromBytes:l=>{if(l.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);return e?Qe(l):$r(l)},invertBatch:l=>zn(u,l),cmov:(l,f,d)=>d?f:l});return Object.freeze(u)}function jf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function gc(r){let t=jf(r);return t+Math.ceil(t/2)}function Zf(r,t,e=!1){let n=r.length,o=jf(t),s=gc(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Qe(r):$r(r),a=et(i,t-ut)+ut;return e?Wr(a,o):cs(a,o)}var Zr=BigInt(0),tr=BigInt(1);function jr(r,t){let e=t.negate();return r?e:t}function ls(r,t,e){let n=t==="pz"?i=>i.pz:i=>i.ez,o=zn(r.Fp,e.map(n));return e.map((i,a)=>i.toAffine(o[a])).map(r.fromAffine)}function Jf(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function yc(r,t){Jf(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=Ye(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Xf(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=tr);let u=t*n,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=t%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function vg(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function _g(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var bc=new WeakMap,td=new WeakMap;function wc(r){return td.get(r)||1}function Qf(r){if(r!==Zr)throw new Error("invalid wNAF")}function us(r,t){return{constTimeNegate:jr,hasPrecomputes(e){return wc(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Zr;)n&tr&&(o=o.add(s)),s=s.double(),n>>=tr;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=yc(n,t),i=[],a=e,c=a;for(let u=0;u<o;u++){c=a,i.push(c);for(let l=1;l<s;l++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let s=r.ZERO,i=r.BASE,a=yc(e,t);for(let c=0;c<a.windows;c++){let{nextN:u,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:p}=Xf(o,c,a);o=u,f?i=i.add(jr(h,n[p])):s=s.add(jr(d,n[l]))}return Qf(o),{p:s,f:i}},wNAFUnsafe(e,n,o,s=r.ZERO){let i=yc(e,t);for(let a=0;a<i.windows&&o!==Zr;a++){let{nextN:c,offset:u,isZero:l,isNeg:f}=Xf(o,a,i);if(o=c,!l){let d=n[u];s=s.add(f?d.negate():d)}}return Qf(o),s},getPrecomputes(e,n,o){let s=bc.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&(typeof o=="function"&&(s=o(s)),bc.set(n,s))),s},wNAFCached(e,n,o){let s=wc(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=wc(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Jf(n,t),td.set(e,n),bc.delete(e)}}}function ed(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>Zr||n>Zr;)e&tr&&(s=s.add(o)),n&tr&&(i=i.add(o)),o=o.double(),e>>=tr,n>>=tr;return{p1:s,p2:i}}function fs(r,t,e,n){vg(e,r),_g(n,t);let o=e.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=Ff(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Ye(c),l=new Array(Number(u)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,d=i;for(let h=f;h>=0;h-=c){l.fill(i);for(let g=0;g<s;g++){let m=n[g],w=Number(m>>BigInt(h)&u);l[w]=l[w].add(e[g])}let p=i;for(let g=l.length-1,m=i;g>0;g--)m=m.add(l[g]),p=p.add(m);if(d=d.add(p),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function Yf(r,t){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return mc(t),t}else return Jt(r)}function ds(r,t,e={}){if(!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let a of["p","n","h"]){let c=t[a];if(!(typeof c=="bigint"&&c>Zr))throw new Error(`CURVE.${a} must be positive bigint`)}let n=Yf(t.p,e.Fp),o=Yf(t.n,e.Fn),i=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let a of i)if(!n.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:o}}var ce=BigInt(0),Tt=BigInt(1),xc=BigInt(2),Sg=BigInt(8),Ag={zip215:!0};function Cg(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function Ig(r,t={}){let{Fp:e,Fn:n}=ds("edwards",r,t),{h:o,n:s}=r;Be(t,{},{uvRatio:"function"});let i=xc<<BigInt(n.BYTES*8)-Tt,a=g=>e.create(g),c=t.uvRatio||((g,m)=>{try{return{isValid:!0,value:e.sqrt(e.div(g,m))}}catch{return{isValid:!1,value:ce}}});if(!Cg(e,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");function u(g,m,w=!1){let E=w?Tt:ce;return Ne("coordinate "+g,m,E,i),m}function l(g){if(!(g instanceof h))throw new Error("ExtendedPoint expected")}let f=Gr((g,m)=>{let{ex:w,ey:E,ez:_}=g,C=g.is0();m==null&&(m=C?Sg:e.inv(_));let b=a(w*m),L=a(E*m),R=a(_*m);if(C)return{x:ce,y:Tt};if(R!==Tt)throw new Error("invZ was invalid");return{x:b,y:L}}),d=Gr(g=>{let{a:m,d:w}=r;if(g.is0())throw new Error("bad point: ZERO");let{ex:E,ey:_,ez:C,et:b}=g,L=a(E*E),R=a(_*_),I=a(C*C),y=a(I*I),S=a(L*m),x=a(I*a(S+R)),v=a(y+a(w*a(L*R)));if(x!==v)throw new Error("bad point: equation left != right (1)");let A=a(E*_),P=a(C*b);if(A!==P)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(m,w,E,_){this.ex=u("x",m),this.ey=u("y",w),this.ez=u("z",E,!0),this.et=u("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:w,y:E}=m||{};return u("x",w),u("y",E),new h(w,E,Tt,a(w*E))}static normalizeZ(m){return ls(h,"ez",m)}static msm(m,w){return fs(h,n,m,w)}_setWindowSize(m){this.precompute(m)}precompute(m=8,w=!0){return p.setWindowSize(this,m),w||this.multiply(xc),this}assertValidity(){d(this)}equals(m){l(m);let{ex:w,ey:E,ez:_}=this,{ex:C,ey:b,ez:L}=m,R=a(w*L),I=a(C*_),y=a(E*L),S=a(b*_);return R===I&&y===S}is0(){return this.equals(h.ZERO)}negate(){return new h(a(-this.ex),this.ey,this.ez,a(-this.et))}double(){let{a:m}=r,{ex:w,ey:E,ez:_}=this,C=a(w*w),b=a(E*E),L=a(xc*a(_*_)),R=a(m*C),I=w+E,y=a(a(I*I)-C-b),S=R+b,x=S-L,v=R-b,A=a(y*x),P=a(S*v),T=a(y*v),O=a(x*S);return new h(A,P,O,T)}add(m){l(m);let{a:w,d:E}=r,{ex:_,ey:C,ez:b,et:L}=this,{ex:R,ey:I,ez:y,et:S}=m,x=a(_*R),v=a(C*I),A=a(L*E*S),P=a(b*y),T=a((_+C)*(R+I)-x-v),O=P-A,F=P+A,B=a(v-w*x),st=a(T*O),W=a(F*B),U=a(T*B),ct=a(O*F);return new h(st,W,ct,U)}subtract(m){return this.add(m.negate())}multiply(m){let w=m;Ne("scalar",w,Tt,s);let{p:E,f:_}=p.wNAFCached(this,w,h.normalizeZ);return h.normalizeZ([E,_])[0]}multiplyUnsafe(m,w=h.ZERO){let E=m;return Ne("scalar",E,ce,s),E===ce?h.ZERO:this.is0()||E===Tt?this:p.wNAFCachedUnsafe(this,E,h.normalizeZ,w)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return p.wNAFCachedUnsafe(this,s).is0()}toAffine(m){return f(this,m)}clearCofactor(){return o===Tt?this:this.multiplyUnsafe(o)}static fromBytes(m,w=!1){return wt(m),this.fromHex(m,w)}static fromHex(m,w=!1){let{d:E,a:_}=r,C=e.BYTES;m=Q("pointHex",m,C),Ee("zip215",w);let b=m.slice(),L=m[C-1];b[C-1]=L&-129;let R=Qe(b),I=w?i:e.ORDER;Ne("pointHex.y",R,ce,I);let y=a(R*R),S=a(y-Tt),x=a(E*y-_),{isValid:v,value:A}=c(S,x);if(!v)throw new Error("Point.fromHex: invalid y coordinate");let P=(A&Tt)===Tt,T=(L&128)!==0;if(!w&&A===ce&&T)throw new Error("Point.fromHex: x=0 and x_0=1");return T!==P&&(A=a(-A)),h.fromAffine({x:A,y:R})}static fromPrivateScalar(m){return h.BASE.multiply(m)}toBytes(){let{x:m,y:w}=this.toAffine(),E=Wr(w,e.BYTES);return E[E.length-1]|=m&Tt?128:0,E}toRawBytes(){return this.toBytes()}toHex(){return ie(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}h.BASE=new h(r.Gx,r.Gy,Tt,a(r.Gx*r.Gy)),h.ZERO=new h(ce,Tt,Tt,ce),h.Fp=e,h.Fn=n;let p=us(h,n.BYTES*8);return h}function Tg(r,t){Be(t,{hash:"function"},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:e,hash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=i.ORDER,c=t.randomBytes||je,u=t.adjustScalarBytes||(b=>b),l=t.domain||((b,L,R)=>{if(Ee("phflag",R),L.length||R)throw new Error("Contexts/pre-hash are not supported");return b});function f(b){return i.create(b)}function d(b){return f(Qe(b))}function h(b){let L=s.BYTES;b=Q("private key",b,L);let R=Q("hashed private key",n(b),2*L),I=u(R.slice(0,L)),y=R.slice(L,2*L),S=d(I);return{head:I,prefix:y,scalar:S}}function p(b){let{head:L,prefix:R,scalar:I}=h(b),y=o.multiply(I),S=y.toBytes();return{head:L,prefix:R,scalar:I,point:y,pointBytes:S}}function g(b){return p(b).pointBytes}function m(b=Uint8Array.of(),...L){let R=Ft(...L);return d(n(l(R,Q("context",b),!!e)))}function w(b,L,R={}){b=Q("message",b),e&&(b=e(b));let{prefix:I,scalar:y,pointBytes:S}=p(L),x=m(R.context,I,b),v=o.multiply(x).toBytes(),A=m(R.context,v,S,b),P=f(x+A*y);Ne("signature.s",P,ce,a);let T=s.BYTES,O=Ft(v,Wr(P,T));return Q("result",O,T*2)}let E=Ag;function _(b,L,R,I=E){let{context:y,zip215:S}=I,x=s.BYTES;b=Q("signature",b,2*x),L=Q("message",L),R=Q("publicKey",R,x),S!==void 0&&Ee("zip215",S),e&&(L=e(L));let v=Qe(b.slice(x,2*x)),A,P,T;try{A=r.fromHex(R,S),P=r.fromHex(b.slice(0,x),S),T=o.multiplyUnsafe(v)}catch{return!1}if(!S&&A.isSmallOrder())return!1;let O=m(y,P.toBytes(),A.toBytes(),L);return P.add(A.multiplyUnsafe(O)).subtract(T).clearCofactor().is0()}return o.precompute(8),{getPublicKey:g,sign:w,verify:_,utils:{getExtendedPublicKey:p,randomPrivateKey:()=>c(s.BYTES),precompute(b=8,L=r.BASE){return L.precompute(b,!1)}},Point:r}}function Pg(r){let t={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=Jt(t.n,r.nBitLength,!0),o={Fp:e,Fn:n,uvRatio:r.uvRatio},s={hash:r.hash,randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:t,curveOpts:o,eddsaOpts:s}}function Dg(r,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:r})}function rd(r){let{CURVE:t,curveOpts:e,eddsaOpts:n}=Pg(r),o=Ig(t,e),s=Tg(o,n);return Dg(r,s)}var o1=BigInt(0),Lg=BigInt(1),nd=BigInt(2),s1=BigInt(3),Rg=BigInt(5),Og=BigInt(8),hs={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Og,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function kg(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=hs.p,a=r*r%s*r%s,c=Y(a,nd,s)*a%s,u=Y(c,Lg,s)*r%s,l=Y(u,Rg,s)*u%s,f=Y(l,t,s)*l%s,d=Y(f,e,s)*f%s,h=Y(d,n,s)*d%s,p=Y(h,o,s)*h%s,g=Y(p,o,s)*h%s,m=Y(g,t,s)*l%s;return{pow_p_5_8:Y(m,nd,s)*r%s,b2:a}}function Mg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var od=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ng(r,t){let e=hs.p,n=et(t*t*t,e),o=et(n*n*t,e),s=kg(r*o).pow_p_5_8,i=et(r*n*s,e),a=et(t*i*i,e),c=i,u=et(i*od,e),l=a===r,f=a===et(-r,e),d=a===et(-r*od,e);return l&&(i=c),(f||d)&&(i=u),Wf(i,e)&&(i=et(-i,e)),{isValid:l||f,value:i}}var Bg=Jt(hs.p,void 0,!0),Fg={...hs,Fp:Bg,hash:Mf,adjustScalarBytes:Mg,uvRatio:Ng},Vn=rd(Fg);var Hn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},$n=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ps=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var sd={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new ps("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var kt=sd;var ms=32,Wn=64,Ec=32;var Xr,id=(async()=>{try{return await kt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function ad(){let r=Vn.utils.randomPrivateKey(),t=Vn.getPublicKey(r);return{privateKey:Vg(r,t),publicKey:t}}async function Ug(r,t){let e;r.length===Wn?e=r.subarray(0,32):e=r;let n={crv:"Ed25519",kty:"OKP",x:N(r.subarray(32),"base64url"),d:N(e,"base64url"),ext:!0,key_ops:["sign"]},o=await kt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await kt.get().subtle.sign({name:"Ed25519"},o,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(s,0,s.byteLength)}function Kg(r,t){let e=r.subarray(0,Ec);return Vn.sign(t instanceof Uint8Array?t:t.subarray(),e)}async function cd(r,t){return Xr==null&&(Xr=await id),Xr?Ug(r,t):Kg(r,t)}async function qg(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await kt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await kt.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function zg(r,t,e){return Vn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function ld(r,t,e){return Xr==null&&(Xr=await id),Xr?qg(r,t,e):zg(r,t,e)}function Vg(r,t){let e=new Uint8Array(Wn);for(let n=0;n<Ec;n++)e[n]=r[n],e[Ec+n]=t[n];return e}function Qr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Gn=class{type="Ed25519";raw;constructor(t){this.raw=ys(t,ms)}toMultihash(){return Zt.digest(Vt(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=ld(this.raw,e,t);return Qr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},gs=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=ys(t,Wn),this.publicKey=new Gn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}sign(t,e){e?.signal?.throwIfAborted();let n=cd(this.raw,t);return Qr(n)?n.then(o=>(e?.signal?.throwIfAborted(),o)):(e?.signal?.throwIfAborted(),n)}};function vc(r){return r=ys(r,ms),new Gn(r)}async function fd(){let{privateKey:r,publicKey:t}=ad();return new gs(r,t)}function ys(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new k(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Hg=Math.pow(2,7),$g=Math.pow(2,14),Wg=Math.pow(2,21),_c=Math.pow(2,28),Sc=Math.pow(2,35),Ac=Math.pow(2,42),Cc=Math.pow(2,49),H=128,xt=127;function ft(r){if(r<Hg)return 1;if(r<$g)return 2;if(r<Wg)return 3;if(r<_c)return 4;if(r<Sc)return 5;if(r<Ac)return 6;if(r<Cc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Yr(r,t,e=0){switch(ft(r)){case 8:t[e++]=r&255|H,r/=128;case 7:t[e++]=r&255|H,r/=128;case 6:t[e++]=r&255|H,r/=128;case 5:t[e++]=r&255|H,r/=128;case 4:t[e++]=r&255|H,r>>>=7;case 3:t[e++]=r&255|H,r>>>=7;case 2:t[e++]=r&255|H,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Gg(r,t,e=0){switch(ft(r)){case 8:t.set(e++,r&255|H),r/=128;case 7:t.set(e++,r&255|H),r/=128;case 6:t.set(e++,r&255|H),r/=128;case 5:t.set(e++,r&255|H),r/=128;case 4:t.set(e++,r&255|H),r>>>=7;case 3:t.set(e++,r&255|H),r>>>=7;case 2:t.set(e++,r&255|H),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ic(r,t){let e=r[t],n=0;if(n+=e&xt,e<H||(e=r[t+1],n+=(e&xt)<<7,e<H)||(e=r[t+2],n+=(e&xt)<<14,e<H)||(e=r[t+3],n+=(e&xt)<<21,e<H)||(e=r[t+4],n+=(e&xt)*_c,e<H)||(e=r[t+5],n+=(e&xt)*Sc,e<H)||(e=r[t+6],n+=(e&xt)*Ac,e<H)||(e=r[t+7],n+=(e&xt)*Cc,e<H))return n;throw new RangeError("Could not decode varint")}function jg(r,t){let e=r.get(t),n=0;if(n+=e&xt,e<H||(e=r.get(t+1),n+=(e&xt)<<7,e<H)||(e=r.get(t+2),n+=(e&xt)<<14,e<H)||(e=r.get(t+3),n+=(e&xt)<<21,e<H)||(e=r.get(t+4),n+=(e&xt)*_c,e<H)||(e=r.get(t+5),n+=(e&xt)*Sc,e<H)||(e=r.get(t+6),n+=(e&xt)*Ac,e<H)||(e=r.get(t+7),n+=(e&xt)*Cc,e<H))return n;throw new RangeError("Could not decode varint")}function le(r,t,e=0){return t==null&&(t=bt(ft(r))),t instanceof Uint8Array?Yr(r,t,e):Gg(r,t,e)}function er(r,t=0){return r instanceof Uint8Array?Ic(r,t):jg(r,t)}var Tc=new Float32Array([-0]),Fe=new Uint8Array(Tc.buffer);function dd(r,t,e){Tc[0]=r,t[e]=Fe[0],t[e+1]=Fe[1],t[e+2]=Fe[2],t[e+3]=Fe[3]}function hd(r,t){return Fe[0]=r[t],Fe[1]=r[t+1],Fe[2]=r[t+2],Fe[3]=r[t+3],Tc[0]}var Pc=new Float64Array([-0]),Et=new Uint8Array(Pc.buffer);function pd(r,t,e){Pc[0]=r,t[e]=Et[0],t[e+1]=Et[1],t[e+2]=Et[2],t[e+3]=Et[3],t[e+4]=Et[4],t[e+5]=Et[5],t[e+6]=Et[6],t[e+7]=Et[7]}function md(r,t){return Et[0]=r[t],Et[1]=r[t+1],Et[2]=r[t+2],Et[3]=r[t+3],Et[4]=r[t+4],Et[5]=r[t+5],Et[6]=r[t+6],Et[7]=r[t+7],Pc[0]}var Zg=BigInt(Number.MAX_SAFE_INTEGER),Xg=BigInt(Number.MIN_SAFE_INTEGER),Ut=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return rr;if(t<Zg&&t>Xg)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>gd&&(o=0n,++n>gd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return rr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):rr}},rr=new Ut(0,0);rr.toBigInt=function(){return 0n};rr.zzEncode=rr.zzDecode=function(){return this};rr.length=function(){return 1};var gd=4294967296n;function yd(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function bd(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Dc(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function te(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function bs(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Lc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,te(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw te(this,4);return bs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw te(this,4);return bs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw te(this,4);let t=hd(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw te(this,4);let t=md(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw te(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return bd(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw te(this,t);this.pos+=t}else do if(this.pos>=this.len)throw te(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Ut(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw te(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw te(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw te(this,8);let t=bs(this.buf,this.pos+=4),e=bs(this.buf,this.pos+=4);return new Ut(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ic(this.buf,this.pos);return this.pos+=ft(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Rc(r){return new Lc(r instanceof Uint8Array?r:r.subarray())}function Pt(r,t,e){let n=Rc(r);return t.decode(n,void 0,e)}function Oc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return bt(i);o+i>t&&(n=bt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var nr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function kc(){}var Nc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Qg=Oc();function Yg(r){return globalThis.Buffer!=null?bt(r):Qg(r)}var Zn=class{len;head;tail;states;constructor(){this.len=0,this.head=new nr(kc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new nr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Bc((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ws,10,Ut.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ut.fromBigInt(t);return this._push(ws,e.length(),e)}uint64Number(t){return this._push(Yr,ft(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Ut.fromBigInt(t).zzEncode();return this._push(ws,e.length(),e)}sint64Number(t){let e=Ut.fromNumber(t).zzEncode();return this._push(ws,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Mc,1,t?1:0)}fixed32(t){return this._push(jn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ut.fromBigInt(t);return this._push(jn,4,e.lo)._push(jn,4,e.hi)}fixed64Number(t){let e=Ut.fromNumber(t);return this._push(jn,4,e.lo)._push(jn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(dd,4,t)}double(t){return this._push(pd,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Mc,1,0):this.uint32(e)._push(t0,e,t)}string(t){let e=yd(t);return e!==0?this.uint32(e)._push(Dc,e,t):this._push(Mc,1,0)}fork(){return this.states=new Nc(this),this.head=this.tail=new nr(kc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new nr(kc,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Yg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Mc(r,t,e){t[e]=r&255}function Jg(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Bc=class extends nr{next;constructor(t,e){super(Jg,t,e),this.next=void 0}};function ws(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function jn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function t0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Zn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(e0,t,r),this},Zn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(r0,t,r),this});function e0(r,t,e){t.set(r,e)}function r0(r,t,e){r.length<40?Dc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(D(r),e)}function Fc(){return new Zn}function Dt(r,t){let e=Fc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var tn;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(tn||(tn={}));function xs(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Uc(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return xs("enum",tn.VARINT,e,n)}function Lt(r,t){return xs("message",tn.LENGTH_DELIMITED,r,t)}var or=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Xn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var it;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(it||(it={}));var Kc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Kc||(Kc={}));(function(r){r.codec=()=>Uc(Kc)})(it||(it={}));var ue;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),it.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=it.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Pt(e,r.codec(),n)})(ue||(ue={}));var qc;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),it.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=it.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Pt(e,r.codec(),n)})(qc||(qc={}));function en(r){if(isNaN(r)||r<=0)throw new k("random bytes length must be a Number bigger than 0");return je(r)}var Yn={};Ot(Yn,{MAX_RSA_KEY_SIZE:()=>zc,generateRSAKeyPair:()=>Qc,jwkToJWKKeyPair:()=>Sd,jwkToPkcs1:()=>i0,jwkToPkix:()=>Wc,jwkToRSAPrivateKey:()=>Xc,pkcs1MessageToJwk:()=>Hc,pkcs1MessageToRSAPrivateKey:()=>Gc,pkcs1ToJwk:()=>s0,pkcs1ToRSAPrivateKey:()=>_d,pkixMessageToJwk:()=>$c,pkixMessageToRSAPublicKey:()=>Zc,pkixToJwk:()=>a0,pkixToRSAPublicKey:()=>jc});var Es=as;var rn=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Yn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return tt.createV1(114,this._multihash)}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}verify(t,e,n){return vd(this.jwk,e,t,n)}},Qn=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Yn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}sign(t,e){return Ed(this.jwk,t,e)}};var zc=8192,Vc=18,n0=1062,o0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function s0(r){let t=ye(r);return Hc(t)}function Hc(r){return{n:N(r[1],"base64url"),e:N(r[2],"base64url"),d:N(r[3],"base64url"),p:N(r[4],"base64url"),q:N(r[5],"base64url"),dp:N(r[6],"base64url"),dq:N(r[7],"base64url"),qi:N(r[8],"base64url"),kty:"RSA"}}function i0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new k("JWK was missing components");return Qt([Ct(Uint8Array.from([0])),Ct(D(r.n,"base64url")),Ct(D(r.e,"base64url")),Ct(D(r.d,"base64url")),Ct(D(r.p,"base64url")),Ct(D(r.q,"base64url")),Ct(D(r.dp,"base64url")),Ct(D(r.dq,"base64url")),Ct(D(r.qi,"base64url"))]).subarray()}function a0(r){let t=ye(r,{offset:0});return $c(t)}function $c(r){let t=ye(r[1],{offset:0});return{kty:"RSA",n:N(t[0],"base64url"),e:N(t[1],"base64url")}}function Wc(r){if(r.n==null||r.e==null)throw new k("JWK was missing components");return Qt([o0,Mn(Qt([Ct(D(r.n,"base64url")),Ct(D(r.e,"base64url"))]))]).subarray()}function _d(r){let t=ye(r);return Gc(t)}function Gc(r){let t=Hc(r);return Xc(t)}function jc(r,t){if(r.byteLength>=n0)throw new Lr("Key size is too large");let e=ye(r,{offset:0});return Zc(e,r,t)}function Zc(r,t,e){let n=$c(r);if(e==null){let o=Es(ue.encode({Type:it.RSA,Data:t}));e=jt(Vc,o)}return new rn(n,e)}function Xc(r){if(Cd(r)>zc)throw new k("Key size is too large");let t=Sd(r),e=Es(ue.encode({Type:it.RSA,Data:Wc(t.publicKey)})),n=jt(Vc,e);return new Qn(t.privateKey,new rn(t.publicKey,n))}async function Qc(r){if(r>zc)throw new k("Key size is too large");let t=await Ad(r),e=Es(ue.encode({Type:it.RSA,Data:Wc(t.publicKey)})),n=jt(Vc,e);return new Qn(t.privateKey,new rn(t.publicKey,n))}function Sd(r){if(r==null)throw new k("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Ad(r,t){let e=await kt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await c0(e,t);return{privateKey:n[0],publicKey:n[1]}}async function Ed(r,t,e){let n=await kt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await kt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function vd(r,t,e,n){let o=await kt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await kt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),s}async function c0(r,t){if(r.privateKey==null||r.publicKey==null)throw new k("Private and public key are required");let e=await Promise.all([kt.get().subtle.exportKey("jwk",r.privateKey),kt.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function Cd(r){if(r.kty!=="RSA")throw new k("invalid key type");if(r.n==null)throw new k("invalid key modulus");return D(r.n,"base64url").length*8}var vs=class extends qr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,xf(t);let n=Bn(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),we(s)}update(t){return Vr(this),this.iHash.update(t),this}digestInto(t){Vr(this),wt(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Yc=(r,t,e)=>new vs(r,t).update(e).digest();Yc.create=(r,t)=>new vs(r,t);function Id(r){r.lowS!==void 0&&Ee("lowS",r.lowS),r.prehash!==void 0&&Ee("prehash",r.prehash)}var Jc=class extends Error{constructor(t=""){super(t)}},ve={Err:Jc,_tlv:{encode:(r,t)=>{let{Err:e}=ve;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=qn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?qn(o.length/2|128):"";return qn(r)+s+o+t},decode(r,t){let{Err:e}=ve,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=ve;if(r<Jn)throw new t("integer: negative integers are not allowed");let e=qn(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=ve;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return $r(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=ve,o=Q("signature",r),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=ve,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Jn=BigInt(0),to=BigInt(1),l0=BigInt(2),_s=BigInt(3),u0=BigInt(4);function f0(r,t,e){function n(o){let s=r.sqr(o),i=r.mul(s,o);return r.add(r.add(i,r.mul(o,t)),e)}return n}function Td(r,t,e){let{BYTES:n}=r;function o(s){let i;if(typeof s=="bigint")i=s;else{let a=Q("private key",s);if(t){if(!t.includes(a.length*2))throw new Error("invalid private key");let c=new Uint8Array(n);c.set(a,c.length-a.length),a=c}try{i=r.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof s}`)}}if(e&&(i=r.create(i)),!r.isValidNot0(i))throw new Error("invalid private key: out of range [1..N-1]");return i}return o}function d0(r,t={}){let{Fp:e,Fn:n}=ds("weierstrass",r,t),{h:o,n:s}=r;Be(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:i}=t;if(i&&(!e.is0(r.a)||typeof i.beta!="bigint"||typeof i.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!e.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(I,y,S){let{x,y:v}=y.toAffine(),A=e.toBytes(x);if(Ee("isCompressed",S),S){a();let P=!e.isOdd(v);return Ft(Pd(P),A)}else return Ft(Uint8Array.of(4),A,e.toBytes(v))}function u(I){wt(I);let y=e.BYTES,S=y+1,x=2*y+1,v=I.length,A=I[0],P=I.subarray(1);if(v===S&&(A===2||A===3)){let T=e.fromBytes(P);if(!e.isValid(T))throw new Error("bad point: is not on curve, wrong x");let O=d(T),F;try{F=e.sqrt(O)}catch(W){let U=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+U)}a();let B=e.isOdd(F);return(A&1)===1!==B&&(F=e.neg(F)),{x:T,y:F}}else if(v===x&&A===4){let T=e.fromBytes(P.subarray(y*0,y*1)),O=e.fromBytes(P.subarray(y*1,y*2));if(!h(T,O))throw new Error("bad point: is not on curve");return{x:T,y:O}}else throw new Error(`bad point: got length ${v}, expected compressed=${S} or uncompressed=${x}`)}let l=t.toBytes||c,f=t.fromBytes||u,d=f0(e,r.a,r.b);function h(I,y){let S=e.sqr(y),x=d(I);return e.eql(S,x)}if(!h(r.Gx,r.Gy))throw new Error("bad curve params: generator point");let p=e.mul(e.pow(r.a,_s),u0),g=e.mul(e.sqr(r.b),BigInt(27));if(e.is0(e.add(p,g)))throw new Error("bad curve params: a or b");function m(I,y,S=!1){if(!e.isValid(y)||S&&e.is0(y))throw new Error(`bad point coordinate ${I}`);return y}function w(I){if(!(I instanceof b))throw new Error("ProjectivePoint expected")}let E=Gr((I,y)=>{let{px:S,py:x,pz:v}=I;if(e.eql(v,e.ONE))return{x:S,y:x};let A=I.is0();y==null&&(y=A?e.ONE:e.inv(v));let P=e.mul(S,y),T=e.mul(x,y),O=e.mul(v,y);if(A)return{x:e.ZERO,y:e.ZERO};if(!e.eql(O,e.ONE))throw new Error("invZ was invalid");return{x:P,y:T}}),_=Gr(I=>{if(I.is0()){if(t.allowInfinityPoint&&!e.is0(I.py))return;throw new Error("bad point: ZERO")}let{x:y,y:S}=I.toAffine();if(!e.isValid(y)||!e.isValid(S))throw new Error("bad point: x or y not field elements");if(!h(y,S))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function C(I,y,S,x,v){return S=new b(e.mul(S.px,I),S.py,S.pz),y=jr(x,y),S=jr(v,S),y.add(S)}class b{constructor(y,S,x){this.px=m("x",y),this.py=m("y",S,!0),this.pz=m("z",x),Object.freeze(this)}static fromAffine(y){let{x:S,y:x}=y||{};if(!y||!e.isValid(S)||!e.isValid(x))throw new Error("invalid affine point");if(y instanceof b)throw new Error("projective point not allowed");return e.is0(S)&&e.is0(x)?b.ZERO:new b(S,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){return ls(b,"pz",y)}static fromBytes(y){return wt(y),b.fromHex(y)}static fromHex(y){let S=b.fromAffine(f(Q("pointHex",y)));return S.assertValidity(),S}static fromPrivateKey(y){let S=Td(n,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return b.BASE.multiply(S(y))}static msm(y,S){return fs(b,n,y,S)}precompute(y=8,S=!0){return R.setWindowSize(this,y),S||this.multiply(_s),this}_setWindowSize(y){this.precompute(y)}assertValidity(){_(this)}hasEvenY(){let{y}=this.toAffine();if(!e.isOdd)throw new Error("Field doesn't support isOdd");return!e.isOdd(y)}equals(y){w(y);let{px:S,py:x,pz:v}=this,{px:A,py:P,pz:T}=y,O=e.eql(e.mul(S,T),e.mul(A,v)),F=e.eql(e.mul(x,T),e.mul(P,v));return O&&F}negate(){return new b(this.px,e.neg(this.py),this.pz)}double(){let{a:y,b:S}=r,x=e.mul(S,_s),{px:v,py:A,pz:P}=this,T=e.ZERO,O=e.ZERO,F=e.ZERO,B=e.mul(v,v),st=e.mul(A,A),W=e.mul(P,P),U=e.mul(v,A);return U=e.add(U,U),F=e.mul(v,P),F=e.add(F,F),T=e.mul(y,F),O=e.mul(x,W),O=e.add(T,O),T=e.sub(st,O),O=e.add(st,O),O=e.mul(T,O),T=e.mul(U,T),F=e.mul(x,F),W=e.mul(y,W),U=e.sub(B,W),U=e.mul(y,U),U=e.add(U,F),F=e.add(B,B),B=e.add(F,B),B=e.add(B,W),B=e.mul(B,U),O=e.add(O,B),W=e.mul(A,P),W=e.add(W,W),B=e.mul(W,U),T=e.sub(T,B),F=e.mul(W,st),F=e.add(F,F),F=e.add(F,F),new b(T,O,F)}add(y){w(y);let{px:S,py:x,pz:v}=this,{px:A,py:P,pz:T}=y,O=e.ZERO,F=e.ZERO,B=e.ZERO,st=r.a,W=e.mul(r.b,_s),U=e.mul(S,A),ct=e.mul(x,P),lt=e.mul(v,T),yt=e.add(S,x),Z=e.add(A,P);yt=e.mul(yt,Z),Z=e.add(U,ct),yt=e.sub(yt,Z),Z=e.add(S,v);let At=e.add(A,T);return Z=e.mul(Z,At),At=e.add(U,lt),Z=e.sub(Z,At),At=e.add(x,v),O=e.add(P,T),At=e.mul(At,O),O=e.add(ct,lt),At=e.sub(At,O),B=e.mul(st,Z),O=e.mul(W,lt),B=e.add(O,B),O=e.sub(ct,B),B=e.add(ct,B),F=e.mul(O,B),ct=e.add(U,U),ct=e.add(ct,U),lt=e.mul(st,lt),Z=e.mul(W,Z),ct=e.add(ct,lt),lt=e.sub(U,lt),lt=e.mul(st,lt),Z=e.add(Z,lt),U=e.mul(ct,Z),F=e.add(F,U),U=e.mul(At,Z),O=e.mul(yt,O),O=e.sub(O,U),U=e.mul(yt,ct),B=e.mul(At,B),B=e.add(B,U),new b(O,F,B)}subtract(y){return this.add(y.negate())}is0(){return this.equals(b.ZERO)}multiply(y){let{endo:S}=t;if(!n.isValidNot0(y))throw new Error("invalid scalar: out of range");let x,v,A=P=>R.wNAFCached(this,P,b.normalizeZ);if(S){let{k1neg:P,k1:T,k2neg:O,k2:F}=S.splitScalar(y),{p:B,f:st}=A(T),{p:W,f:U}=A(F);v=st.add(U),x=C(S.beta,B,W,P,O)}else{let{p:P,f:T}=A(y);x=P,v=T}return b.normalizeZ([x,v])[0]}multiplyUnsafe(y){let{endo:S}=t,x=this;if(!n.isValid(y))throw new Error("invalid scalar: out of range");if(y===Jn||x.is0())return b.ZERO;if(y===to)return x;if(R.hasPrecomputes(this))return this.multiply(y);if(S){let{k1neg:v,k1:A,k2neg:P,k2:T}=S.splitScalar(y),{p1:O,p2:F}=ed(b,x,A,T);return C(S.beta,O,F,v,P)}else return R.wNAFCachedUnsafe(x,y)}multiplyAndAddUnsafe(y,S,x){let v=this.multiplyUnsafe(S).add(y.multiplyUnsafe(x));return v.is0()?void 0:v}toAffine(y){return E(this,y)}isTorsionFree(){let{isTorsionFree:y}=t;return o===to?!0:y?y(b,this):R.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){let{clearCofactor:y}=t;return o===to?this:y?y(b,this):this.multiplyUnsafe(o)}toBytes(y=!0){return Ee("isCompressed",y),this.assertValidity(),l(b,this,y)}toRawBytes(y=!0){return this.toBytes(y)}toHex(y=!0){return ie(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}b.BASE=new b(r.Gx,r.Gy,e.ONE),b.ZERO=new b(e.ZERO,e.ONE,e.ZERO),b.Fp=e,b.Fn=n;let L=n.BITS,R=us(b,t.endo?Math.ceil(L/2):L);return b}function Pd(r){return Uint8Array.of(r?2:3)}function h0(r,t,e={}){Be(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||je,o=t.hmac||((x,...v)=>Yc(t.hash,x,Ft(...v))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i;function u(x){let v=a>>to;return x>v}function l(x){return u(x)?i.neg(x):x}function f(x,v){if(!i.isValidNot0(v))throw new Error(`invalid signature ${x}: out of range 1..CURVE.n`)}class d{constructor(v,A,P){f("r",v),f("s",A),this.r=v,this.s=A,P!=null&&(this.recovery=P),Object.freeze(this)}static fromCompact(v){let A=i.BYTES,P=Q("compactSignature",v,A*2);return new d(i.fromBytes(P.subarray(0,A)),i.fromBytes(P.subarray(A,A*2)))}static fromDER(v){let{r:A,s:P}=ve.toSig(Q("DER",v));return new d(A,P)}assertValidity(){}addRecoveryBit(v){return new d(this.r,this.s,v)}recoverPublicKey(v){let A=s.ORDER,{r:P,s:T,recovery:O}=this;if(O==null||![0,1,2,3].includes(O))throw new Error("recovery id invalid");if(a*l0<A&&O>1)throw new Error("recovery id is ambiguous for h>1 curve");let B=O===2||O===3?P+a:P;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");let st=s.toBytes(B),W=r.fromHex(Ft(Pd((O&1)===0),st)),U=i.inv(B),ct=_(Q("msgHash",v)),lt=i.create(-ct*U),yt=i.create(T*U),Z=r.BASE.multiplyUnsafe(lt).add(W.multiplyUnsafe(yt));if(Z.is0())throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,i.neg(this.s),this.recovery):this}toBytes(v){if(v==="compact")return Ft(i.toBytes(this.r),i.toBytes(this.s));if(v==="der")return Hr(ve.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return ie(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ie(this.toBytes("compact"))}}let h=Td(i,e.allowedPrivateKeyLengths,e.wrapPrivateKey),p={isValidPrivateKey(x){try{return h(x),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{let x=a;return Zf(n(gc(x)),x)},precompute(x=8,v=r.BASE){return v.precompute(x,!1)}};function g(x,v=!0){return r.fromPrivateKey(x).toBytes(v)}function m(x){if(typeof x=="bigint")return!1;if(x instanceof r)return!0;let A=Q("key",x).length,P=s.BYTES,T=P+1,O=2*P+1;if(!(e.allowedPrivateKeyLengths||i.BYTES===T))return A===T||A===O}function w(x,v,A=!0){if(m(x)===!0)throw new Error("first arg must be private key");if(m(v)===!1)throw new Error("second arg must be public key");return r.fromHex(v).multiply(h(x)).toBytes(A)}let E=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let v=$r(x),A=x.length*8-c;return A>0?v>>BigInt(A):v},_=t.bits2int_modN||function(x){return i.create(E(x))},C=Ye(c);function b(x){return Ne("num < 2^"+c,x,Jn,C),i.toBytes(x)}function L(x,v,A=R){if(["recovered","canonical"].some(yt=>yt in A))throw new Error("sign() legacy options not supported");let{hash:P}=t,{lowS:T,prehash:O,extraEntropy:F}=A;T==null&&(T=!0),x=Q("msgHash",x),Id(A),O&&(x=Q("prehashed msgHash",P(x)));let B=_(x),st=h(v),W=[b(st),b(B)];if(F!=null&&F!==!1){let yt=F===!0?n(s.BYTES):F;W.push(Q("extraEntropy",yt))}let U=Ft(...W),ct=B;function lt(yt){let Z=E(yt);if(!i.isValidNot0(Z))return;let At=i.inv(Z),Sn=r.BASE.multiply(Z).toAffine(),Tr=i.create(Sn.x);if(Tr===Jn)return;let Ve=i.create(At*i.create(ct+Tr*st));if(Ve===Jn)return;let Ta=(Sn.x===Tr?0:2)|Number(Sn.y&to),Pr=Ve;return T&&u(Ve)&&(Pr=l(Ve),Ta^=1),new d(Tr,Pr,Ta)}return{seed:U,k2sig:lt}}let R={lowS:t.lowS,prehash:!1},I={lowS:t.lowS,prehash:!1};function y(x,v,A=R){let{seed:P,k2sig:T}=L(x,v,A);return Uf(t.hash.outputLen,i.BYTES,o)(P,T)}r.BASE.precompute(8);function S(x,v,A,P=I){let T=x;v=Q("msgHash",v),A=Q("publicKey",A),Id(P);let{lowS:O,prehash:F,format:B}=P;if("strict"in P)throw new Error("options.strict was renamed to lowS");if(B!==void 0&&!["compact","der","js"].includes(B))throw new Error('format must be "compact", "der" or "js"');let st=typeof T=="string"||zr(T),W=!st&&!B&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!st&&!W)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let U,ct;try{if(W)if(B===void 0||B==="js")U=new d(T.r,T.s);else throw new Error("invalid format");if(st){try{B!=="compact"&&(U=d.fromDER(T))}catch(Pr){if(!(Pr instanceof ve.Err))throw Pr}!U&&B!=="der"&&(U=d.fromCompact(T))}ct=r.fromHex(A)}catch{return!1}if(!U||O&&U.hasHighS())return!1;F&&(v=t.hash(v));let{r:lt,s:yt}=U,Z=_(v),At=i.inv(yt),Sn=i.create(Z*At),Tr=i.create(lt*At),Ve=r.BASE.multiplyUnsafe(Sn).add(ct.multiplyUnsafe(Tr));return Ve.is0()?!1:i.create(Ve.x)===lt}return Object.freeze({getPublicKey:g,getSharedSecret:w,sign:y,verify:S,utils:p,Point:r,Signature:d})}function p0(r){let t={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=Jt(t.n,r.nBitLength),o={Fp:e,Fn:n,allowedPrivateKeyLengths:r.allowedPrivateKeyLengths,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,wrapPrivateKey:r.wrapPrivateKey,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:t,curveOpts:o}}function m0(r){let{CURVE:t,curveOpts:e}=p0(r),n={hash:r.hash,hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:t,curveOpts:e,ecdsaOpts:n}}function g0(r,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:r})}function Dd(r){let{CURVE:t,curveOpts:e,ecdsaOpts:n}=m0(r),o=d0(t,e),s=h0(o,n,e);return g0(r,s)}function Ld(r,t){let e=n=>Dd({...r,hash:n});return{...e(t),create:e}}var Ss={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},$v=BigInt(0),y0=BigInt(1),tl=BigInt(2),Rd=(r,t)=>(r+t/tl)/t;function b0(r){let t=Ss.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,l=u*u*r%t,f=Y(l,e,t)*l%t,d=Y(f,e,t)*l%t,h=Y(d,tl,t)*u%t,p=Y(h,o,t)*h%t,g=Y(p,s,t)*p%t,m=Y(g,a,t)*g%t,w=Y(m,c,t)*m%t,E=Y(w,a,t)*g%t,_=Y(E,e,t)*l%t,C=Y(_,i,t)*p%t,b=Y(C,n,t)*u%t,L=Y(b,tl,t);if(!el.eql(el.sqr(L),r))throw new Error("Cannot find square root");return L}var el=Jt(Ss.p,void 0,void 0,{sqrt:b0}),ee=Ld({...Ss,Fp:el,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Ss.n,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-y0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Rd(s*r,t),c=Rd(-n*r,t),u=et(r-a*e-c*o,t),l=et(-a*n-c*s,t),f=u>i,d=l>i;if(f&&(u=t-u),d&&(l=t-l),u>i||l>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:d,k2:l}}}},as);function Od(r,t,e){let n=Kr.digest(t instanceof Uint8Array?t:t.subarray());if(Qr(n))return n.then(({digest:o})=>(e?.signal?.throwIfAborted(),ee.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Hn(String(o))});try{return ee.sign(n.digest,r).toDERRawBytes()}catch(o){throw new Hn(String(o))}}function kd(r,t,e,n){let o=Kr.digest(e instanceof Uint8Array?e:e.subarray());if(Qr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ee.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new $n(String(s))});try{return n?.signal?.throwIfAborted(),ee.verify(t,o.digest,r)}catch(s){throw new $n(String(s))}}var eo=class{type="secp256k1";raw;_key;constructor(t){this._key=Bd(t),this.raw=Md(this._key)}toMultihash(){return Zt.digest(Vt(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}verify(t,e,n){return kd(this._key,e,t,n)}},As=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=Nd(t),this.publicKey=new eo(e??Fd(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}sign(t,e){return Od(this.raw,t,e)}};function rl(r){return new eo(r)}async function Ud(){let r=w0();return new As(r)}function Md(r){return ee.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Nd(r){try{return ee.getPublicKey(r,!0),r}catch(t){throw new An(String(t))}}function Bd(r){try{return ee.ProjectivePoint.fromHex(r),r}catch(t){throw new Lr(String(t))}}function Fd(r){try{return ee.getPublicKey(r,!0)}catch(t){throw new An(String(t))}}function w0(){return ee.utils.randomPrivateKey()}async function Kd(r,t){if(r==="Ed25519")return fd();if(r==="secp256k1")return Ud();if(r==="RSA")return Qc(x0(t));if(r==="ECDSA")return bf(E0(t));throw new De}function nn(r,t){let{Type:e,Data:n}=ue.decode(r),o=n??new Uint8Array;switch(e){case it.RSA:return jc(o,t);case it.Ed25519:return vc(o);case it.secp256k1:return rl(o);case it.ECDSA:return ac(o);default:throw new De}}function qd(r){let{Type:t,Data:e}=ue.decode(r.digest),n=e??new Uint8Array;switch(t){case it.Ed25519:return vc(n);case it.secp256k1:return rl(n);case it.ECDSA:return ac(n);default:throw new De}}function Vt(r){return ue.encode({Type:it[r.type],Data:r.raw})}function x0(r){return r==null?2048:parseInt(r,10)}function E0(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new k("Unsupported curve, should be P-256, P-384 or P-521")}var zd=Symbol.for("nodejs.util.inspect.custom"),v0=114,ro=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ho]=!0;toString(){return this.string==null&&(this.string=j.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return tt.createV1(v0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return G(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return G(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[zd](){return`PeerId(${this.toString()})`}},no=class extends ro{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},oo=class extends ro{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},so=class extends ro{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},_0=2336,io=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Zt.digest(D(this.url))}[zd](){return`PeerId(${this.url})`}[Ho]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return tt.createV1(_0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=N(t)),t.toString()===this.toString())}};var S0=114,Vd=2336;function fe(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=ge(j.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return ao(tt.parse(r));if(t==null)throw new k('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=ge(t.decode(r))}return on(e)}function nl(r){if(r.type==="Ed25519")return new oo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new so({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new no({multihash:r.toCID().multihash,publicKey:r});throw new De}function Hd(r){return nl(r.publicKey)}function on(r){if(C0(r))return new no({multihash:r});if(A0(r))try{let t=qd(r);if(t.type==="Ed25519")return new oo({multihash:r,publicKey:t});if(t.type==="secp256k1")return new so({multihash:r,publicKey:t})}catch{let e=N(r.digest);return new io(new URL(e))}throw new Go("Supplied PeerID Multihash is invalid")}function ao(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==S0&&r.code!==Vd)throw new Wo("Supplied PeerID CID is invalid");if(r.code===Vd){let t=N(r.multihash.digest);return new io(new URL(t))}return on(r.multihash)}function A0(r){return r.code===Zt.code}function C0(r){return r.code===Kr.code}function sn(r){if(typeof r!="object"||r===null)return!1;let t=Object.getPrototypeOf(r);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:Wd}=Object.prototype,{propertyIsEnumerable:I0}=Object,an=(r,t,e)=>{Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0})},T0=void 0,$d={concatArrays:!1,ignoreUndefined:!1},Cs=r=>{let t=[];for(let e in r)Wd.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)I0.call(r,n)&&t.push(n)}return t};function cn(r){return Array.isArray(r)?P0(r):sn(r)?D0(r):r}function P0(r){let t=r.slice(0,0);return Cs(r).forEach(e=>{an(t,e,cn(r[e]))}),t}function D0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return Cs(r).forEach(e=>{an(t,e,cn(r[e]))}),t}var Gd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?an(r,o,ol(r[o],t[o],n)):an(r,o,cn(t[o])))}),r),L0=(r,t,e)=>{let n=r.slice(0,0),o=0;return[r,t].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Wd.call(s,a)&&(i.push(String(a)),s===r?an(n,o++,s[a]):an(n,o++,cn(s[a])));n=Gd(n,s,Cs(s).filter(a=>!i.includes(a)),e)}),n};function ol(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?L0(r,t,e):!sn(t)||!sn(r)?cn(t):Gd(r,t,Cs(t),e)}function Is(...r){let t=ol(cn($d),this!==T0&&this||{},$d),e={_:{}};for(let n of r)if(n!==void 0){if(!sn(n))throw new TypeError("`"+n+"` is not an Option Object");e=ol(e,{_:n},t)}return e._}var at=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var il=Vo(Zd(),1);var lo=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},al=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Xd=r=>globalThis.DOMException===void 0?new al(r):new DOMException(r),Qd=r=>{let t=r.reason===void 0?Xd("This operation was aborted."):r.reason;return t instanceof Error?t:Xd(t)};function cl(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,u=new Promise((l,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:h}=t;h.aborted&&f(Qd(h)),a=()=>{f(Qd(h))},h.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(l,f);return}let d=new lo;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{l(await r)}catch(h){f(h)}})()}).finally(()=>{u.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}function ll(r,t,e){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;e(r[i],t)<=0?(n=++i,o-=s+1):o=s}return n}var uo=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,id:e.id,run:t};if(this.size===0||this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=ll(this.#t,n,(s,i)=>i.priority-s.priority);this.#t.splice(o,0,n)}setPriority(t,e){let n=this.#t.findIndex(s=>s.id===t);if(n===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[o]=this.#t.splice(n,1);this.enqueue(o.run,{priority:e,id:t})}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var fo=class extends il.default{#t;#n;#e=0;#h;#a;#p=0;#o;#c;#r;#m;#s=0;#l;#i;#g;#w=1n;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:uo,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#n=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#h=t.intervalCap,this.#a=t.interval,this.#r=new t.queueClass,this.#m=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#g=t.throwOnTimeout===!0,this.#i=t.autoStart===!1}get#x(){return this.#n||this.#e<this.#h}get#E(){return this.#s<this.#l}#v(){this.#s--,this.#u(),this.emit("next")}#_(){this.#b(),this.#y(),this.#c=void 0}get#S(){let t=Date.now();if(this.#o===void 0){let e=this.#p-t;if(e<0)this.#e=this.#t?this.#s:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#_()},e)),!0}return!1}#u(){if(this.#r.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let t=!this.#S;if(this.#x&&this.#E){let e=this.#r.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#n||this.#o!==void 0||(this.#o=setInterval(()=>{this.#b()},this.#a),this.#p=Date.now()+this.#a)}#b(){this.#e===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#e=this.#t?this.#s:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#l=t,this.#f()}async#A(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}setPriority(t,e){this.#r.setPriority(t,e)}async add(t,e={}){return e.id??=(this.#w++).toString(),e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#s++,this.#e++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=cl(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#A(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof lo&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},e),this.emit("add"),this.#u()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(t){this.#r.size<t||await this.#d("next",()=>this.#r.size<t)}async onIdle(){this.#s===0&&this.#r.size===0||await this.#d("idle")}async#d(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#r.size}sizeBy(t){return this.#r.filter(t).length}get pending(){return this.#s}get isPaused(){return this.#i}};function Ps(r){let t=[Kt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var ul=60;function Ds(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(t=>({name:t.name,type:Kt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Kt[t.type],TTL:t.TTL??t.ttl??ul,data:t.data instanceof Uint8Array?N(t.data):t.data}))}}var k0=4;function fl(r,t={}){let e=new fo({concurrency:t.queryConcurrency??k0});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Ps(o.types).forEach(a=>{s.append("type",Kt[a])}),o.onProgress?.(new at("dns:query",{detail:n}));let i=await e.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Ds(await a.json());return o.onProgress?.(new at("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Yd(){return[fl("https://cloudflare-dns.com/dns-query"),fl("https://dns.google/resolve")]}var eh=Vo(th(),1);var dl=class{lru;constructor(t){this.lru=(0,eh.default)(t)}get(t,e){let n=!0,o=[];for(let s of e){let i=this.getAnswers(t,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return Ds({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Kt[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??ul)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function rh(r){return new dl(r)}var M0=1e3,Ls=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=rh(t.cacheSize??M0),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Yd())}async query(t,e={}){let n=Ps(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new at("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let u=await c(t,{...e,types:n});for(let l of u.Answer)this.cache.add(t,l);return u}catch(u){a.push(u),e.onProgress?.(new at("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Kt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Kt||(Kt={}));function nh(r={}){return new Ls(r)}var pt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},_e=class extends Error{static name="ValidationError";name="ValidationError"},ho=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Rs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Os=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=t,s+=l,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var oh=45,N0=15,ln=new Os;function ks(r){if(!(r.length>N0))return ln.new(r).parseWith(()=>ln.readIPv4Addr())}function Ms(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>oh))return ln.new(r).parseWith(()=>ln.readIPv6Addr())}function un(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>oh)return;let e=ln.new(r).parseWith(()=>ln.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function re(r){return!!ks(r)}function Ns(r){return!!Ms(r)}function pl(r){return t=>N(t,r)}function ml(r){return t=>D(t,r)}function fn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function sr(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function sh(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=D(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=sr(n);return Xt([e,o],e.length+o.length)}function ih(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=zt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=sr(n);return Xt([e,o],e.length+o.length)}function gl(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=N(t,"base32"),o=fn(e);return`${n}:${o}`}var yl=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new pt("Invalid byte value in IP address");t[n]=o}),t},ah=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=re(e[n]),i;s&&(i=yl(e[n]),e[n]=N(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,N(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new pt("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},ch=function(r){if(r.byteLength!==4)throw new pt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},lh=function(r){if(r.byteLength!==16)throw new pt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new pt(`Invalid IPv6 address "${e}"`)}};function uh(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new pt(`Invalid IPv6 address "${r}"`)}}var hl=Object.values(Rn).map(r=>r.decoder),B0=function(){let r=hl[0].or(hl[1]);return hl.slice(2).forEach(t=>r=r.or(t)),r}();function fh(r){return B0.decode(r)}function dh(r){return t=>r.encoder.encode(t)}function F0(r){if(parseInt(r).toString()!==r)throw new _e("Value must be an integer")}function U0(r){if(r<0)throw new _e("Value must be a positive integer, or zero")}function K0(r){return t=>{if(t>r)throw new _e(`Value must be smaller than or equal to ${r}`)}}function q0(...r){return t=>{for(let e of r)e(t)}}var po=q0(F0,U0,K0(65535));var dt=-1,bl=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new Rs(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Mt=new bl,ry=[{code:4,name:"ip4",size:32,valueToBytes:yl,bytesToValue:ch,validate:r=>{if(!re(r))throw new _e(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:sr,bytesToValue:fn,validate:po},{code:273,name:"udp",size:16,valueToBytes:sr,bytesToValue:fn,validate:po},{code:33,name:"dccp",size:16,valueToBytes:sr,bytesToValue:fn,validate:po},{code:41,name:"ip6",size:128,valueToBytes:ah,bytesToValue:lh,stringToValue:uh,validate:r=>{if(!Ns(r))throw new _e(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:dt},{code:43,name:"ipcidr",size:8,bytesToValue:pl("base10"),valueToBytes:ml("base10")},{code:53,name:"dns",size:dt,resolvable:!0},{code:54,name:"dns4",size:dt,resolvable:!0},{code:55,name:"dns6",size:dt,resolvable:!0},{code:56,name:"dnsaddr",size:dt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:sr,bytesToValue:fn,validate:po},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:dt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:dt,bytesToValue:pl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ml("base58btc")(r):tt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:gl,valueToBytes:sh},{code:445,name:"onion3",size:296,bytesToValue:gl,valueToBytes:ih},{code:446,name:"garlic64",size:dt},{code:447,name:"garlic32",size:dt},{code:448,name:"tls"},{code:449,name:"sni",size:dt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:dt,bytesToValue:dh(Za),valueToBytes:fh},{code:480,name:"http"},{code:481,name:"http-path",size:dt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:dt}];ry.forEach(r=>{Mt.addProtocol(r)});function hh(r){let t=[],e=0;for(;e<r.length;){let n=er(r,e),o=Mt.getProtocol(n),s=ft(n),i=ny(o,r,e+s),a=0;i>0&&o.size===dt&&(a=ft(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let l=e+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??N(f)}t.push(u),e+=c}return t}function ph(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Mt.getProtocol(n.code),s=ft(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,o.size===dt&&(c=ft(a)));let u=new Uint8Array(s+c+a),l=0;Yr(n.code,u,l),l+=s,i!=null&&(o.size===dt&&(Yr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return Xt(e,t)}function mh(r){if(r.charAt(0)!=="/")throw new pt('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Mt.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new pt(`Component ${o} was missing value`);e="value"}else if(e==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new pt(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new pt("Incomplete multiaddr");return t}function gh(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Mt.getProtocol(t.code);if(e==null)throw new pt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function ny(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:er(t,e)}var oy=Symbol.for("nodejs.util.inspect.custom"),Tl=Symbol.for("@multiformats/multiaddr"),sy=[53,54,55,56],Il=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function iy(r){if(r==null&&(r="/"),Ke(r))return r.getComponents();if(r instanceof Uint8Array)return hh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),mh(r);if(Array.isArray(r))return r;throw new pt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ks=class r{[Tl]=!0;#t;#n;#e;constructor(t="/",e={}){this.#t=iy(t),e.validate!==!1&&ay(this)}get bytes(){return this.#e==null&&(this.#e=ph(this.#t)),this.#e}toString(){return this.#n==null&&(this.#n=gh(this.#t)),this.#n}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="";for(let{code:a,name:c,value:u}of this.#t)a===42&&(s=`%${u??""}`),sy.includes(a)&&(e="tcp",o=443,n=`${u??""}${s}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",o=parseInt(u??"")),(a===4||a===41)&&(e="tcp",n=`${u??""}${s}`,t=a===41?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=Mt.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=Mt.getProtocol(t),o=[t];return e!=null&&o.push(n.valueToBytes?.(e)??D(e)),o})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new ho(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:o})=>{n===421&&t.push([n,o]),n===290&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?N(j.decode(`z${n}`),"base58btc"):N(tt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(Mt.getProtocol(t.code).path)return t.value??null;return null}equals(t){return G(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=yh.get(e.name);if(n==null)throw new Il(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>K(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[oy](){return`Multiaddr(${this.toString()})`}};function ay(r){r.getComponents().forEach(t=>{let e=Mt.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function bh(r,t,e){let n=0;for(let o of r)if(!(n<t)){if(n>e)break;if(o!==255)return!1;n++}return!0}function wh(r,t,e,n){let o=0;for(let s of r)if(!(o<e)){if(o>n)break;if(s!==t[o])return!1;o++}return!0}function Pl(r){switch(r.length){case ur:return r.join(".");case fr:{let t=[];for(let e=0;e<r.length;e++)e%2===0&&t.push(r[e].toString(16).padStart(2,"0")+r[e+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}function xh(r){let t=0;for(let[e,n]of r.entries()){if(n===255){t+=8;continue}for(;(n&128)!=0;)t++,n=n<<1;if((n&128)!=0)return-1;for(let o=e+1;o<r.length;o++)if(r[o]!=0)return-1;break}return t}function Eh(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var ur=4,fr=16,pS=parseInt("0xFFFF",16),cy=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function go(r,t){t.length===fr&&r.length===ur&&bh(t,0,11)&&(t=t.slice(12)),t.length===ur&&r.length===fr&&wh(r,cy,0,11)&&(r=r.slice(12));let e=r.length;if(e!=t.length)throw new Error("Failed to mask ip");let n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=r[o]&t[o];return n}function vh(r,t){if(typeof t=="string"&&(t=un(t)),t==null)throw new Error("Invalid ip");if(t.length!==r.network.length)return!1;for(let e=0;e<t.length;e++)if((r.network[e]&r.mask[e])!==(t[e]&r.mask[e]))return!1;return!0}function Dl(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=ur,o=ks(t);if(o==null&&(n=fr,o=Ms(t),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(e,10);if(Number.isNaN(s)||String(s).length!==e.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Ll(s,8*n);return{network:go(o,i),mask:i}}function Ll(r,t){if(t!==8*ur&&t!==8*fr)throw new Error("Invalid CIDR mask");if(r<0||r>t)throw new Error("Invalid CIDR mask");let e=t/8,n=new Uint8Array(e);for(let o=0;o<e;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var gn=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=Dl(t));else{let n=un(t);if(n==null)throw new Error("Failed to parse network");e=String(e);let o=parseInt(e,10);if(Number.isNaN(o)||String(o).length!==e.length||o<0||o>n.length*8){let s=un(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Ll(o,8*n.length);this.network=go(n,this.mask)}}contains(t){return vh({network:this.network,mask:this.mask},t)}toString(){let t=xh(this.mask),e=t!==-1?String(t):Eh(this.mask);return Pl(this.network)+"/"+e}};function Rl(r){let t,e;if(r.getComponents().forEach(n=>{(n.name==="ip4"||n.name==="ip6")&&(e=n.value),n.name==="ipcidr"&&(t=n.value)}),t==null||e==null)throw new Error("Invalid multiaddr");return new gn(e,t)}var yh=new Map;function Ke(r){return!!r?.[Tl]}function K(r){return new Ks(r)}function qs(r){let t=Mt.getProtocol(r);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}var Ol=class{dns;canResolve(t){return t.getComponents().some(({name:e})=>e==="dnsaddr")}async resolve(t,e){let n=t.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[t];let s=await this.getDNS(e).query(`_dnsaddr.${n}`,{signal:e?.signal,types:[Kt.TXT]}),i=t.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let u=c.data.replace(/["']/g,"").trim().split("=")[1];u!=null&&(i!=null&&!u.includes(i)||a.push(K(u)))}return a}getDNS(t){return t.dns!=null?t.dns:(this.dns==null&&(this.dns=nh()),this.dns)}},Se=new Ol;var ly={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Se}},transportManager:{faultTolerance:He.FATAL_ALL}};async function _h(r){let t=Is(ly,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new k("Private network is enforced, but no protector was provided");return t}function uy(r,t){try{if(typeof r=="string"&&r.length>0)return fy(r);if(typeof r=="number"&&isFinite(r))return t?.long?hy(r):dy(r);throw new Error("Value is not a string or number.")}catch(e){let n=py(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function fy(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Vs=uy;function dy(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function hy(r){let t=Math.abs(r);return t>=864e5?zs(r,t,864e5,"day"):t>=36e5?zs(r,t,36e5,"hour"):t>=6e4?zs(r,t,6e4,"minute"):t>=1e3?zs(r,t,1e3,"second"):`${r} ms`}function zs(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function py(r){return typeof r=="object"&&r!==null&&"message"in r}function kl(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=Vs,e.destroy=u,Object.keys(r).forEach(l=>{e[l]=r[l]}),e.names=[],e.skips=[],e.formatters={};function t(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(l){let f,d=null,h,p;function g(...m){if(!g.enabled)return;let w=g,E=Number(new Date),_=E-(f||E);w.diff=_,w.prev=f,w.curr=E,f=E,m[0]=e.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let C=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(L,R)=>{if(L==="%%")return"%";C++;let I=e.formatters[R];if(typeof I=="function"){let y=m[C];L=I.call(w,y),m.splice(C,1),C--}return L}),e.formatArgs.call(w,m),(w.log||e.log).apply(w,m)}return g.namespace=l,g.useColors=e.useColors(),g.color=e.selectColor(l),g.extend=n,g.destroy=e.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,p=e.enabled(l)),p),set:m=>{d=m}}),typeof e.init=="function"&&e.init(g),g}function n(l,f){let d=e(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){e.save(l),e.namespaces=l,e.names=[],e.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?e.skips.push(new RegExp("^"+l.substr(1)+"$")):e.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(l))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.setupFormatters(e.formatters),e.enable(e.load()),e}var Hs=Ey(),my=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function gy(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function yy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Vs(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var by=console.debug??console.log??(()=>{});function wy(r){try{r?Hs?.setItem("debug",r):Hs?.removeItem("debug")}catch{}}function xy(){let r;try{r=Hs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Ey(){try{return localStorage}catch{}}function vy(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Sh=kl({formatArgs:yy,save:wy,load:xy,useColors:gy,setupFormatters:vy,colors:my,storage:Hs,log:by});var Nt=Sh;Nt.formatters.b=r=>r==null?"undefined":j.baseEncode(r);Nt.formatters.t=r=>r==null?"undefined":zt.baseEncode(r);Nt.formatters.m=r=>r==null?"undefined":ja.baseEncode(r);Nt.formatters.p=r=>r==null?"undefined":r.toString();Nt.formatters.c=r=>r==null?"undefined":r.toString();Nt.formatters.k=r=>r==null?"undefined":r.toString();Nt.formatters.a=r=>r==null?"undefined":r.toString();Nt.formatters.e=r=>r==null?"undefined":Ah(r.stack)??Ah(r.message)??r.toString();function _y(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function $s(){return{forComponent(r){return Sy(r)}}}function Sy(r){let t=_y(`${r}:trace`);return Nt.enabled(`${r}:trace`)&&Nt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Nt(`${r}:trace`)),Object.assign(Nt(r),{error:Nt(`${r}:error`),trace:t})}function Ah(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function dr(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function Ws(r){let t=ge(j.decode(`z${r}`));return on(t)}var $t=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return dr(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return dr(this.map.values(),t=>t.key)}values(){return dr(this.map.values(),t=>t.value)}get size(){return this.map.size}};var hr=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return dr(this.set.entries(),t=>{let e=Ws(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=Ws(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return dr(this.set.values(),t=>Ws(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var Ml={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ch={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ih=new globalThis.TextEncoder;function Ay(r,t){let e=Ml[t],n=Ch[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Cy(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Ml[t],o=Ch[t],s=r;for(;s.length>0;){let i=Ih.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Nl(r,{size:t=32,utf8Buffer:e}={}){if(!Ml[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Cy(r,t,e);r=Ih.encode(r)}return Ay(r,t)}var yo={hash:r=>Number(Nl(r,{size:32})),hashV:(r,t)=>Iy(yo.hash(r,t))};function Iy(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),D(t,"base16")}var Bl=64,oe=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Bl)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=nt(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?G(this.fp,t.fp):!1}};function pr(r,t){return Math.floor(Math.random()*(t-r))+r}var mr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof oe))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof oe))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof oe))throw new TypeError("Invalid Fingerprint");let e=pr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof oe))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Ty=500,bo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??yo,this.seed=t.seed??pr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=D(t));let e=new oe(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new mr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new mr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[pr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new mr(this.bucketSize));for(let a=0;a<Ty;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new mr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=D(t));let e=new oe(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=D(t));let e=new oe(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Py={1:.5,2:.84,4:.95,8:.98};function Dy(r=.001){return r>.002?2:r>1e-5?4:8}function Th(r,t=.001){let e=Dy(t),n=Py[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Bl);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var Gs=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??yo,this.seed=t.seed??pr(0,Math.pow(2,10)),this.filterSeries=[new bo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=D(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new bo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=D(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=D(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function wo(r,t=.001,e){return new Gs({...Th(r,t),...e??{}})}var Fl=class extends $t{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ul(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Fl({name:t,metrics:e}):n=new $t,n}var xo;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:nt(0),payloadType:nt(0),payload:nt(0),signature:nt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Pt(e,r.codec(),n)})(xo||(xo={}));var js=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var yn=class r{static createFromProtobuf=t=>{let e=xo.decode(t),n=nn(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e,n)=>{if(e==null)throw new Error("Missing private key");let o=t.domain,s=t.codec,i=t.marshal(),a=Ph(o,s,i),c=await e.sign(a.subarray(),n);return new r({publicKey:e.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(t,e,n)=>{let o=r.createFromProtobuf(t);if(!await o.validate(e,n))throw new js("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=xo.encode({publicKey:Vt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:G(this.marshal(),t.marshal())}async validate(t,e){let n=Ph(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},Ph=(r,t,e)=>{let n=D(r),o=le(n.byteLength),s=le(t.length),i=le(e.length);return new z(o,n,s,t,i,e)};function Dh(r,t){let e=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==t.length?!1:(t.sort(e),r.sort(e).every((n,o)=>t[o].equals(n)))}var Lh="libp2p-peer-record",Rh=Uint8Array.from([3,1]);var Eo;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Lt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:nt(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(l&7);break}}}return c})),o),n.encode=s=>Dt(s,n.codec()),n.decode=(s,i)=>Pt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Lt((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:nt(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new or('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),e),r.encode=n=>Dt(n,r.codec()),r.decode=(n,o)=>Pt(n,r.codec(),o)})(Eo||(Eo={}));var gr=class r{static createFromProtobuf=t=>{let e=Eo.decode(t),n=on(ge(e.peerId)),o=(e.addresses??[]).map(i=>K(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Lh;static CODEC=Rh;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(t){let{peerId:e,multiaddrs:n,seqNumber:o}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Eo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof r)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!Dh(this.multiaddrs,t.multiaddrs))}};function Ly(r){return r[Symbol.asyncIterator]!=null}function Ry(r){if(Ly(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var vo=Ry;var se=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};function ot(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Zs=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},bn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Zs(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Zs(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Kl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Xs(r={}){return Oy(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Oy(r,t){t=t??{};let e=t.onEnd,n=new bn,o,s,i,a=ot(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,w)=>{s=E=>{s=null,n.push(E);try{m(r(n))}catch(_){w(_)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ot()})}},u=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new bn,s!=null?s({error:m}):(n.push({error:m}),o)),f=m=>{if(i)return o;if(t?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?l(m):u({done:!0})),h=()=>(n=new bn,d(),{done:!0}),p=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async m=>{let w=m?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let E,_;w!=null&&(E=new Promise((C,b)=>{_=()=>{b(new Kl)},w.addEventListener("abort",_)}));try{await Promise.race([a.promise,E])}finally{_!=null&&w!=null&&w?.removeEventListener("abort",_)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(m){return g.throw(m),e!=null&&(e(m),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(m){return g.end(m),e!=null&&(e(m),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:m=>g.onEmpty(m)},o}var ql=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function he(r,t,e,n){let o=new ql(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",l),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},u=f=>{a(),i(f.detail)},l=()=>{a(),i(o)};e?.addEventListener("abort",l),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var Qs=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Ys=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function mt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Ys(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Ys(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Js=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new se)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ky(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ti=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=ky(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new se),this.cleanup())}async join(t={}){let e=new Js(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await mt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};function zl(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var _o=class extends Bt{concurrency;maxSize;queue;pending;sort;autoStart;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=t.autoStart??!0,this.sort=t.sort,this.queue=[],this.emitEmpty=zl(this.emitEmpty.bind(this),1),this.emitIdle=zl(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Qs;let n=new ti(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new se)}),this.clear()}async onEmpty(t){this.size!==0&&await he(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await he(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await he(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Xs({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new se("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var ei="lock:worker:request-read",ri="lock:worker:abort-read-request",ni="lock:worker:release-read",oi="lock:master:grant-read",si="lock:master:error-read",ii="lock:worker:request-write",ai="lock:worker:abort-write-request",ci="lock:worker:release-write",li="lock:master:grant-write",ui="lock:master:error-write",fi="lock:worker:finalize",di="mortice",Oh={singleProcess:!1};var Vl=(r,t,e,n,o,s,i,a,c)=>u=>{if(u.data==null)return;let l={type:u.data.type,name:u.data.name,identifier:u.data.identifier};l.type===o&&r.safeDispatchEvent(e,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{t.postMessage({type:c,name:l.name,identifier:l.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===l.identifier&&(t.removeEventListener("message",d),f())};t.addEventListener("message",d)})},onError:f=>{t.postMessage({type:i,name:l.name,identifier:l.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),l.type===s&&r.safeDispatchEvent(n,{detail:{name:l.name,identifier:l.identifier}}),l.type===fi&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var kh=(r=10)=>Math.random().toString().substring(2,r+2);var hi=class{name;channel;constructor(t){this.name=t,this.channel=new BroadcastChannel(di)}readLock(t){return this.sendRequest(ei,ri,oi,si,ni,t)}writeLock(t){return this.sendRequest(ii,ai,li,ui,ci,t)}finalize(){this.channel.postMessage({type:fi,name:this.name}),this.channel.close()}async sendRequest(t,e,n,o,s,i){i?.signal?.throwIfAborted();let a=kh();return this.channel.postMessage({type:t,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:e,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",l,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",l);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),u(h)}};this.channel.addEventListener("message",f)})}};var Mh=r=>{if(r=Object.assign({},Oh,r),!!globalThis.document||r.singleProcess){let e=new BroadcastChannel(di),n=new Bt;return e.addEventListener("message",Vl(n,e,"requestReadLock","abortReadLockRequest",ei,ri,si,ni,oi)),e.addEventListener("message",Vl(n,e,"requestWriteLock","abortWriteLockRequest",ii,ai,ui,ci,li)),n}return new hi(r.name)};var yr=new Map,So;function Nh(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function My(r){if(So==null&&(So=Mh(r),!Nh(So))){let t=So;t.addEventListener("requestReadLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=yr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};t.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await e.detail.handler().finally(()=>{c()})}).catch(c=>{e.detail.onError(c)}).finally(()=>{t.removeEventListener("abortReadLockRequest",a)})}),t.addEventListener("requestWriteLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=yr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};t.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await e.detail.handler().finally(()=>{c()})}).catch(c=>{e.detail.onError(c)}).finally(()=>{t.removeEventListener("abortWriteLockRequest",a)})}),t.addEventListener("finalizeRequest",e=>{let n=e.detail.name,o=yr.get(n);o?.finalize()})}return So}async function Hl(r,t){let e,n,o=new Promise((i,a)=>{e=i,n=a}),s=()=>{n(new se)};return t?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{e(()=>{t?.signal?.removeEventListener("abort",s),i()})})},{signal:t?.signal}).catch(i=>{n(i)}),o}var Bh=(r,t)=>{let e=yr.get(r);if(e!=null)return e;let n=My(t);if(Nh(n))return e=n,yr.set(r,e),e;let o=new _o({concurrency:1}),s;return e={async readLock(i){if(s!=null)return Hl(s,i);s=new _o({concurrency:t.concurrency,autoStart:!1});let a=s,c=Hl(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Hl(o,i)},finalize:()=>{yr.delete(r)},queue:o},yr.set(r,e),t.autoFinalize===!0&&o.addEventListener("idle",()=>{e.finalize()},{once:!0}),e};var Ny={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function $l(r){let t=Object.assign({},Ny,r);return Bh(t.name,t)}var Ae;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Lt((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:"",value:nt(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Dt(i,o.codec()),o.decode=(i,a)=>Pt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Lt((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),mi.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.key=i.string();break}case 2:{u.value=mi.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Dt(i,o.codec()),o.decode=(i,a)=>Pt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Lt((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),pi.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new or('Decode error - map field "addresses" had too many elements');a.addresses.push(pi.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new or('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Xn('Decode error - map field "metadata" had too many elements');let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(l.key,l.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Xn('Decode error - map field "tags" had too many elements');let l=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(l.key,l.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Dt(o,r.codec()),r.decode=(o,s)=>Pt(o,r.codec(),s)})(Ae||(Ae={}));var pi;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),e.observed!=null&&(n.uint32(24),n.uint64Number(e.observed)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:nt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}case 3:{s.observed=e.uint64Number();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Pt(e,r.codec(),n)})(pi||(pi={}));var mi;(function(r){let t;r.codec=()=>(t==null&&(t=Lt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Pt(e,r.codec(),n)})(mi||(mi={}));function By(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;r.type==="RSA"&&(e=r.toMultihash());let n=nn(t.publicKey,e);return nl(n)}function Fh(r,t,e){let n=Ae.decode(t);return wn(r,n,e)}function wn(r,t,e){let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:By(r,t),addresses:t.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-e).map(({multiaddr:s,isCertified:i})=>({multiaddr:K(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function Uh(r,t){return Fy(r.addresses,t.addresses)&&Uy(r.protocols,t.protocols)&&Ky(r.publicKey,t.publicKey)&&qy(r.peerRecordEnvelope,t.peerRecordEnvelope)&&zy(r.metadata,t.metadata)&&Vy(r.tags,t.tags)}function Fy(r,t){return qh(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!G(e.multiaddr,n.multiaddr)))}function Uy(r,t){return qh(r,t,(e,n)=>e===n)}function Ky(r,t){return Kh(r,t)}function qy(r,t){return Kh(r,t)}function zy(r,t){return zh(r,t,(e,n)=>G(e,n))}function Vy(r,t){return zh(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function Kh(r,t){return r==null&&t==null?!0:r!=null&&t!=null?G(r,t):!1}function qh(r,t,e){if(r.length!==t.length)return!1;for(let n=0;n<r.length;n++)if(!e(r[n],t[n]))return!1;return!0}function zh(r,t,e){if(r.size!==t.size)return!1;for(let[n,o]of r.entries()){let s=t.get(n);if(s==null||!e(o,s))return!1}return!0}var Ce="/",Vh=new TextEncoder().encode(Ce),gi=Vh[0],br=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=D(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==gi)throw new Error("Invalid key")}toString(t="utf8"){return N(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Ce))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Vh),this._buf[0]!==gi){let t=new Uint8Array(this._buf.byteLength+1);t.fill(gi,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===gi;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Ce).slice(1)}type(){return Hy(this.baseNamespace())}name(){return $y(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Ce)||(t+=Ce),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Ce):new r(t.slice(0,-1).join(Ce))}child(t){return this.toString()===Ce?t:t.toString()===Ce?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...Wy(t.map(e=>e.namespaces()))])}};function Hy(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function $y(r){let t=r.split(":");return t[t.length-1]}function Wy(r){return[].concat(...r)}var Wl="/peers/";function Ao(r){if(!Te(r)||r.type==null)throw new k("Invalid PeerId");let t=r.toCID().toString();return new br(`${Wl}${t}`)}async function Hh(r,t,e,n,o){let s=new Map;for(let i of e){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=K(i.multiaddr)),!Ke(i.multiaddr))throw new k("Multiaddr was invalid");if(!await t(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),u=s.get(c);u!=null?i.isCertified=u.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getPeerId();return r.equals(c)&&(a=a.decapsulate(K(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function bi(r,t,e,n){if(t==null)throw new k("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new k("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new k("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=yi(d,{validate:$h})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=yi(d,{validate:Wh,map:Gh})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=yi([...a.entries()],{validate:$h})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),h=new Map(c);for(let[p,g]of d)g==null?h.delete(p):h.set(p,g);c=yi([...h.entries()],{validate:Wh,map:Gh})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=Vt(o.id.publicKey):t.publicKey!=null?l=Vt(t.publicKey):r.publicKey!=null&&(l=Vt(r.publicKey));let f={addresses:await Hh(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:l,peerRecordEnvelope:u};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>G(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function yi(r,t){let e=new Map;for(let[n,o]of r)o!=null&&t.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&e.set(n,t.map?.(n,o)??o);return e}function $h(r,t){if(typeof r!="string")throw new k("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new k("Metadata value must be a Uint8Array")}function Wh(r,t){if(typeof r!="string")throw new k("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new k("Tag value must be an integer");if(t.value<0||t.value>100)throw new k("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new k("Tag ttl must be an integer");if(t.ttl<0)throw new k("Tag ttl must be between greater than 0")}}function Gh(r,t){let e;t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl)));let n={value:t.value??0};return e!=null&&(n.expiry=e),n}function jh(r){let t=r.toString().split("/")[2],e=tt.parse(t,zt);return ao(e)}function Gl(r,t,e){let n=jh(r);return Fh(n,t,e)}function Gy(r,t){return{prefix:Wl,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(Gl(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(Gl(n.key,n.value,t),Gl(o.key,o.value,t)))}}var wi=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.locks=Ul({name:"libp2p_peer_store_locks",metrics:t.metrics}),this.maxAddressAge=e.maxAddressAge??36e5,this.maxPeerAge=e.maxPeerAge??216e5}getLock(t){let e=this.locks.get(t);return e==null&&(e={refs:0,lock:$l({name:t.toString(),singleProcess:!0})},this.locks.set(t,e)),e.refs++,e}maybeRemoveLock(t,e){e.refs--,e.refs===0&&(e.lock.finalize(),this.locks.delete(t))}async getReadLock(t,e){let n=this.getLock(t);try{let o=await n.lock.readLock(e);return()=>{o(),this.maybeRemoveLock(t,n)}}catch(o){throw this.maybeRemoveLock(t,n),o}}async getWriteLock(t,e){let n=this.getLock(t);try{let o=await n.lock.writeLock(e);return()=>{o(),this.maybeRemoveLock(t,n)}}catch(o){throw this.maybeRemoveLock(t,n),o}}async has(t,e){try{return await this.load(t,e),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(t,e){this.peerId.equals(t)||await this.datastore.delete(Ao(t),e)}async load(t,e){let n=Ao(t),o=await this.datastore.get(n,e),s=Ae.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new $e;return wn(t,s,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e,n){let o=await this.#t(t,n),s=await bi(t,e,"patch",{...n,addressFilter:this.addressFilter});return this.#n(t,s,o)}async patch(t,e,n){let o=await this.#t(t,n),s=await bi(t,e,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#n(t,s,o)}async merge(t,e,n){let o=await this.#t(t,n),s=await bi(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#n(t,s,o)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(Gy(t??{},this.maxAddressAge),t)){let o=jh(e);if(o.equals(this.peerId))continue;let s=Ae.decode(n);if(this.#e(o,s)){await this.datastore.delete(e,t);continue}yield wn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t,e){try{let n=Ao(t),o=await this.datastore.get(n,e),s=Ae.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new $e;return{peerPB:s,peer:wn(t,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#n(t,e,n,o){e.updated=Date.now();let s=Ae.encode(e);return await this.datastore.put(Ao(t),s,o),{peer:wn(t,e,this.maxAddressAge),previous:n?.peer,updated:n==null||!Uh(e,n.peerPB)}}#e(t,e){if(e.updated==null)return!0;if(this.peerId.equals(t))return!1;let n=e.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=e.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var jl=class{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new wi(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){for await(let n of this.store.all(e))t(n)}async all(t){return vo(this.store.all(t))}async delete(t,e){let n=await this.store.getReadLock(t,e);try{await this.store.delete(t,e)}finally{n()}}async has(t,e){let n=await this.store.getReadLock(t,e);try{return await this.store.has(t,e)}finally{this.log.trace("has release read lock"),n?.()}}async get(t,e){let n=await this.store.getReadLock(t,e);try{return await this.store.load(t,e)}finally{n?.()}}async getInfo(t,e){let n=await this.get(t,e);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.save(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async patch(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.patch(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async merge(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.merge(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async consumePeerRecord(t,e,n){let o=Te(e)?e:Te(e?.expectedPeer)?e.expectedPeer:void 0,s=Te(e)||e===void 0?n:e,i=await yn.openAndCertify(t,gr.DOMAIN,s),a=ao(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=gr.createFromProtobuf(i.payload),u;try{u=await this.get(a,s)}catch(l){if(l.name!=="NotFoundError")throw l}if(u?.peerRecordEnvelope!=null){let l=yn.createFromProtobuf(u.peerRecordEnvelope),f=gr.createFromProtobuf(l.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:t,addresses:c.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))},s),!0}#t(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}};function Zh(r,t={}){return new jl(r,t)}var xi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};function jy(r){return r[Symbol.asyncIterator]!=null}function Zy(r){if(jy(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Zl=Zy;function Xy(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Xh=Xy;function Qy(r){return r[Symbol.asyncIterator]!=null}function Yy(r,t){let e=0;if(Qy(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Xh(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=t(o,e++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){i===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var wr=Yy;function Jy(r){return r[Symbol.asyncIterator]!=null}function tb(r,t){return Jy(r)?async function*(){yield*(await vo(r)).sort(t)}():function*(){yield*vo(r).sort(t)}()}var Xl=tb;function eb(r){return r[Symbol.asyncIterator]!=null}function rb(r,t){return eb(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var Ql=rb;var Ei=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await Zl(this.putMany(t,n)),t=[],await Zl(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=wr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>Xl(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=wr(n,()=>o++>=s)}return t.limit!=null&&(n=Ql(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=wr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>wr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>Xl(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=wr(n,()=>s++>=o)}return t.limit!=null&&(n=Ql(n,t.limit)),n}};var vi=class extends Ei{data;constructor(){super(),this.data=new Map}put(t,e,n){return n?.signal?.throwIfAborted(),this.data.set(t.toString(),e),t}get(t,e){e?.signal?.throwIfAborted();let n=this.data.get(t.toString());if(n==null)throw new xi;return n}has(t,e){return e?.signal?.throwIfAborted(),this.data.has(t.toString())}delete(t,e){e?.signal?.throwIfAborted(),this.data.delete(t.toString())}*_all(t,e){e?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new br(n),value:o},e?.signal?.throwIfAborted()}*_allKeys(t,e){e?.signal?.throwIfAborted();for(let n of this.data.keys())yield new br(n),e?.signal?.throwIfAborted()}};function Co(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Yh=Vo(Qh(),1),nb=["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"],ob=nb.map(r=>new Yh.Netmask(r));function Yl(r){for(let t of ob)if(t.contains(r))return!0;return!1}function sb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function ib(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Yl(o)}function ab(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function cb(r){let t=r.split(":"),e=t[t.length-1];return Yl(e)}function lb(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function qe(r){if(re(r))return Yl(r);if(sb(r))return ib(r);if(ab(r))return cb(r);if(Ns(r))return lb(r)}var J=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),M=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),q=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),_t=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),$=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function X(...r){function t(o){let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var ub=M(421),Jh=X(ub),Si=M(54),Ai=M(55),Ci=M(56),tu=M(53),k6=X(Si,q(M(421))),M6=X(Ai,q(M(421))),N6=X(Ci,q(M(421))),B6=X(_t(tu,Ci,Si,Ai),q(M(421))),tp=$(M(4),q(M(43))),ep=$(q(M(42)),M(41),q(M(43))),eu=_t(tp,ep),xr=_t(eu,tu,Si,Ai,Ci),F6=X(_t(eu,$(_t(tu,Ci,Si,Ai),q(M(421))))),ru=X(tp),nu=X(ep),U6=X(eu),ou=$(xr,M(6)),To=$(xr,M(273)),Po=X($(ou,q(M(421)))),K6=X(To),su=$(To,J(460),q(M(421))),Ii=$(To,J(461),q(M(421))),fb=_t(su,Ii),q6=X(su),rp=X(Ii),Jl=_t(xr,ou,To,su,Ii),np=_t($(Jl,J(477),q(M(421)))),Er=X(np),op=_t($(Jl,J(478),q(M(421))),$(Jl,J(448),q(M(449)),J(477),q(M(421)))),Do=X(op),sp=$(To,J(280),q(M(466)),q(M(466)),q(M(421))),iu=X(sp),ip=$(Ii,J(465),q(M(466)),q(M(466)),q(M(421))),au=X(ip),_i=_t(np,op,$(ou,q(M(421))),$(fb,q(M(421))),$(xr,q(M(421))),sp,ip,M(421)),z6=X(_i),db=$(_i,J(290),M(421)),Lo=X(db),hb=_t($(_i,J(290),J(281),q(M(421))),$(_i,J(281),q(M(421))),$(J(281),q(M(421)))),cu=X(hb),pb=_t($(xr,M(6),J(480),q(M(421))),$(xr,J(480),q(M(421)))),V6=X(pb),mb=$(xr,_t($(M(6,"443"),J(480)),$(M(6),J(443)),$(M(6),J(448),J(480)),$(J(448),J(480)),J(448),J(443)),q(M(421))),H6=X(mb),gb=_t($(M(777),q(M(421)))),$6=X(gb),yb=_t($(M(400),q(M(421)))),W6=X(yb);var lu=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function St(r){let{name:t,metrics:e}=r,n;return e!=null?n=new lu({name:t,metrics:e}):n=new Map,n}var ap=864e13;var bb=448,uu=449,wb=53,xb=54,Eb=55,vb=56,Ti=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=St({name:"libp2p_address_manager_dns_mappings",metrics:t.metrics})}has(t){let e=this.findHost(t);for(let n of this.mappings.values())if(n.domain===e)return!0;return!1}add(t,e){e.forEach(n=>{this.log("add DNS mapping %s to %s",n,t);let o=qe(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?ap-Date.now():0,lastVerified:o?ap-Date.now():void 0})})}remove(t){let e=this.findHost(t),n=!1;for(let[o,s]of this.mappings.entries())s.domain===e&&(this.log("removing %s to %s DNS mapping %e",o,s.domain,new Error("where")),this.mappings.delete(o),n=n||s.verified);return n}getAll(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n].multiaddr.stringTuples(),i=s[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(s,c.domain)&&(t.splice(n,1),n--,e.push({multiaddr:K(`/${s.map(l=>[qs(l[0]).name,l[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return e}maybeAddSNITuple(t,e){for(let n=0;n<t.length;n++)if(t[n][0]===bb&&t[n+1]?.[0]!==uu)return t.splice(n+1,0,[uu,e]),!0;return!1}confirm(t,e){let n=this.findHost(t),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",s,i.domain),o=i.verified,i.verified=!0,i.expires=Date.now()+e,i.lastVerified=Date.now());return o}unconfirm(t,e){let n=this.findHost(t),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",s,i.domain),o=o||i.verified,i.verified=!1,i.expires=Date.now()+e);return o}findHost(t){for(let e of t.stringTuples())if(e[0]===uu||e[0]===wb||e[0]===xb||e[0]===Eb||e[0]===vb)return e[1]}};var fu=4,du=41,hu=6,_b=273,Pi=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=St({name:"libp2p_address_manager_ip_mappings",metrics:t.metrics})}has(t){let e=t.stringTuples();for(let n of this.mappings.values())for(let o of n)if(o.externalIp===e[0][1])return!0;return!1}add(t,e,n,o=e,s="tcp"){let i=`${t}-${e}-${s}`,a=this.mappings.get(i)??[],c={internalIp:t,internalPort:e,externalIp:n,externalPort:o,externalFamily:re(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(t){let e=t.stringTuples(),n=e[0][1]??"",o=e[1][0]===hu?"tcp":"udp",s=parseInt(e[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let u=0;u<c.length;u++){let l=c[u];l.externalIp===n&&l.externalPort===s&&l.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",l.externalIp,l.externalPort,n,s,o),i=i||l.verified,c.splice(u,1),u--)}c.length===0&&this.mappings.delete(a)}return i}getAll(t){let e=[];for(let{multiaddr:n}of t){let o=n.stringTuples(),s;if((o[0][0]===fu||o[0][0]===du)&&o[1][0]===hu?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===fu||o[0][0]===du)&&o[1][0]===_b&&(s=`${o[0][1]}-${o[1][1]}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)o[0][0]=a.externalFamily===4?fu:du,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:K(`/${o.map(c=>[qs(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return e}confirm(t,e){let o=t.stringTuples()[0][1],s=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===o&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),s=a.verified,a.verified=!0,a.expires=Date.now()+e,a.lastVerified=Date.now());return s}unconfirm(t,e){let n=t.stringTuples(),o=n[0][1]??"",s=n[1][0]===hu?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let u=0;u<c.length;u++){let l=c[u];l.externalIp===o&&l.externalPort===i&&l.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",l.externalIp,l.externalPort,o,i,s),a=a||l.verified,l.verified=!1,l.expires=Date.now()+e)}return a}};function cp(r){try{for(let{code:t,value:e}of r.getComponents())if(t!==42&&e!=null){if(t===4)return e.startsWith("169.254.");if(t===41)return e.toLowerCase().startsWith("fe80")}}catch{}return!1}function Di(r){try{for(let{code:t}of r.getComponents())if(t!==42)return t===4||t===41}catch{}return!1}function vr(r){try{if(!Di(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:qe(t)??!1}catch{}return!0}var Sb={maxObservedAddresses:10},Li=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=St({name:"libp2p_address_manager_observed_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??Sb.maxObservedAddresses}has(t){return this.addresses.has(t.toString())}removePrefixed(t){for(let e of this.addresses.keys())e.toString().startsWith(t)&&this.addresses.delete(e)}add(t){this.addresses.size!==this.maxObservedAddresses&&(vr(t)||cp(t)||(this.log("adding observed address %a",t),this.addresses.set(t.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([t,e])=>({multiaddr:K(t),verified:e.verified,type:"observed",expires:e.expires,lastVerified:e.lastVerified}))}remove(t){let e=this.addresses.get(t.toString())?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(t.toString()),e}confirm(t,e){let n=t.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+e,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var Ab=[4,41,53,54,55,56];function pu(r){try{for(let{code:t}of r.getComponents())if(t!==42)return Ab.includes(t)}catch{}return!1}var Cb={maxObservedAddresses:10},Ri=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=St({name:"libp2p_address_manager_transport_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??Cb.maxObservedAddresses}get(t,e){if(vr(t))return{multiaddr:t,verified:!0,type:"transport",expires:Date.now()+e,lastVerified:Date.now()};let n=this.toKey(t),o=this.addresses.get(n);return o==null&&(o={verified:!pu(t),expires:0},this.addresses.set(n,o)),{multiaddr:t,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(t){let e=this.toKey(t);return this.addresses.has(e)}remove(t){let e=this.toKey(t),n=this.addresses.get(e)?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(e),n}confirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+e,this.addresses.set(n,o),s}toKey(t){if(pu(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var lp=6e4,up={maxObservedAddresses:10,addressVerificationTTL:lp*10,addressVerificationRetry:lp*5},Ib=r=>r;function mu(r,t){let e=r.getPeerId();return e!=null&&fe(e).equals(t)&&(r=r.decapsulate(K(`/p2p/${t.toString()}`))),r}var Oi=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(t,e={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=e;this.components=t,this.log=t.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Li(t,e),this.dnsMappings=new Ti(t,e),this.ipMappings=new Pi(t,e),this.transportAddresses=new Ri(t,e),this.announceFilter=e.announceFilter??Ib,this.observedAddressFilter=wo(1024),this.addressVerificationTTL=e.addressVerificationTTL??up.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??up.addressVerificationRetry,this._updatePeerStoreAddresses=Co(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAddresses().map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>K(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>K(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>K(t))}getObservedAddrs(){return this.observed.getAll().map(t=>t.multiaddr)}addObservedAddr(t){let e=t.stringTuples(),n=`${e[0][1]}:${e[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),t=mu(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=mu(t,this.components.peerId);let n=!0;(e?.type==="transport"||this.transportAddresses.has(t))&&!this.transportAddresses.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="dns-mapping"||this.dnsMappings.has(t))&&!this.dnsMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="ip-mapping"||this.ipMappings.has(t))&&!this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="observed"||this.observed.has(t))&&(this.maybeUpgradeToIPMapping(t)?(this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(t,e){t=mu(t,this.components.peerId);let n=!1;this.observed.has(t)&&!this.observed.remove(t)&&n&&(n=!1),this.transportAddresses.has(t)&&!this.transportAddresses.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(t)&&!this.dnsMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(t)&&!this.ipMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let t=new Set,e=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return t.has(o)?!1:(t.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(e.map(n=>{let o=K(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let t=this.getAnnounceAddrs();if(t.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(t)}),t.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let e=[];e=e.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),e=e.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),e=e.concat(this.observed.getAll()),e=e.concat(this.ipMappings.getAll(e)),e=e.concat(this.dnsMappings.getAll(e)),e}addDNSMapping(t,e){this.dnsMappings.add(t,e)}removeDNSMapping(t){this.dnsMappings.remove(K(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${re(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(K(`/ip${re(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(t){if(this.ipMappings.has(t))return!1;let e=t.toOptions();if(e.family===6||e.host==="127.0.0.1"||qe(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Er.exactMatch(s)||Do.exactMatch(s),s=>Po.exactMatch(s),s=>rp.exactMatch(s)];for(let s of o){if(!s(t))continue;let i=n.filter(u=>u.getAddrs().filter(l=>l.toOptions().family===4&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>u.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(t),this.ipMappings.add(c.host,c.port,e.host,e.port,e.transport),!0}return!1}};var fp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(fp||(fp={}));var ki=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Mi=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},xn=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},Ro=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Ni=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Bi=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},Fi=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},Oo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Ui=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Ki=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},qi=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},zi=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Vi=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},_r=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},Sr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},Hi=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}},$i=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}};var gu=class{components={};_started=!1;constructor(t={}){this.components={};for(let[e,n]of Object.entries(t))this.components[e]=n;this.components.logger==null&&(this.components.logger=$s())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>Yo(e)).map(async e=>{await e[t]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Pb=["metrics","connectionProtector","dns"],Db=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function dp(r={}){let t=new gu(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!Db.includes(o)){let i=t.components[o];if(i==null&&!Pb.includes(o))throw new ki(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?t.components[o]=s:Reflect.set(n,o,s),!0}})}function hp(r){let t={};for(let e of Object.values(r.components))for(let n of Lb(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of Rb(e))if(t[n]!==!0)throw new Mi(`Service "${Ob(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Lb(r){return Array.isArray(r?.[In])?r[In]:[]}function Rb(r){return Array.isArray(r?.[Oa])?r[Oa]:[]}function Ob(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var kb=4,Mb=41;function pp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(Er.matches(t))return!1;let e=t.stringTuples();return e[0][0]===kb||e[0][0]===Mb?!!qe(`${e[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var mp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Nb=new WeakMap;function Bb({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(mp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(mp())},l=()=>{o&&o.removeEventListener("abort",u)},f=new Promise((d,h)=>{i=()=>{l(),d(n)},a=h,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",u,{once:!0}),Nb.set(f,()=>{c(s),s=null,i()}),f}}var Fb=Bb(),gp=Fb;var Wi=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}},Gi=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ji=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new yu}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Wi("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await gp(a)}return i}penalty(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},yu=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function Zi(r){if(Te(r))return{peerId:r,multiaddrs:[]};let t=Array.isArray(r)?r:[r],e;if(t.length>0){let n=t[0].getPeerId();e=n==null?void 0:fe(n),t.forEach(o=>{if(!Ke(o))throw new Pe("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(e!=null)throw new k("Multiaddrs must all have the same peer id or have no peer id")}else{let i=fe(s);if(e?.equals(i)!==!0)throw new k("Multiaddrs must all have the same peer id or have no peer id")}})}return t=t.filter(n=>!Jh.exactMatch(n)),{peerId:e,multiaddrs:t}}var Ub=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function yp(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Ub;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}function ko(r){try{let t;typeof r=="string"?t=K(r):t=r;let e=new Set([...t.getComponents().map(n=>n.name)]);if(!e.has("ipcidr")){let o=e.has("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(o)}return Rl(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Xi=class{connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.allow=(e.allow??[]).map(n=>ko(n)),this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(t=>{this.log.error("error while pruning connections %e",t)})}async _maybePruneConnections(){let t=this.connectionManager.getConnections(),e=t.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",e,n),e<=n)return;let o=new $t;for(let c of t){let u=c.remotePeer;if(!o.has(u)){o.set(u,0);try{let l=await this.peerStore.get(u);o.set(u,[...l.tags.values()].reduce((f,d)=>f+d.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let s=this.sortConnections(t,o),i=Math.max(e-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(l=>l.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await yp(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(t,e){return t.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=e.get(n.remotePeer)??0,i=e.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var bp="last-dial-failure",wp="last-dial-success";var xp=100,Qi=50;var Yi=class{deferred;signal;constructor(t){this.signal=t,this.deferred=ot(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Gt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Kb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ji=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Kb(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Gt),this.cleanup())}async join(t={}){let e=new Yi(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await mt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var En=class extends Bt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Co(this.emitEmpty.bind(this),1),this.emitIdle=Co(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Gi;let n=new Ji(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Gt)}),this.clear()}async onEmpty(t){this.size!==0&&await he(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await he(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await he(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Xs({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new Gt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var ta=class extends En{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Ie(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function Ep(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function bu(r){if(!Di(r))return!1;let{address:t}=r.nodeAddress();return Ep(t)}function qb(r,t){let e=Po.exactMatch(r.multiaddr),n=Po.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=Do.exactMatch(r.multiaddr),s=Do.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Er.exactMatch(r.multiaddr),a=Er.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=cu.exactMatch(r.multiaddr),u=cu.exactMatch(t.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let l=iu.exactMatch(r.multiaddr),f=iu.exactMatch(t.multiaddr);if(l&&!f)return-1;if(!l&&f)return 1;let d=au.exactMatch(r.multiaddr),h=au.exactMatch(t.multiaddr);return d&&!h?-1:!d&&h?1:0}function zb(r,t){let e=bu(r.multiaddr),n=bu(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Vb(r,t){let e=vr(r.multiaddr),n=vr(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Hb(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function $b(r,t){let e=Lo.exactMatch(r.multiaddr),n=Lo.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function vp(r){return r.sort(qb).sort(Hb).sort($b).sort(Vb).sort(zb)}async function wu(r,t,e){let n=e.depth??0;if(n>(e.maxRecursiveDepth??32))throw new $i("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(t))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,e);for(let c of a)s.push(...await wu(c,t,{...e,depth:n+1}))}return o===!1&&s.push(r),s}var Mo={maxParallelDials:Qi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Se}},ea=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??Mo.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??Mo.maxDialQueueLength,this.dialTimeout=e.dialTimeout??Mo.dialTimeout,this.connections=e.connections??new $t,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.resolvers=e.resolvers??Mo.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new ta({concurrency:e.maxParallelDials??Mo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail?.name!==Gt.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=Zi(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0||a.limits!=null?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new at("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new at("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new kr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new at("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new at("dial-queue:start-dial"));let c=Ie([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??_u,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async dialPeer(t,e){let n=t.peerId,o=t.multiaddrs,s=new Set,i=t.multiaddrs.size===0,a=0,c=0,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],f=new Set(t.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...t,signal:e});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}l.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(h=>h.multiaddr.toString())),t?.onProgress?.(new at("dial-queue:calculated-addresses",l));for(let h of l){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,t.peerId),new kr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...t,signal:e});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[wp]:D(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}return p}catch(p){if(this.log.error("dial failed to %a",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[bp]:D(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(e.aborted)throw new Zo(p.message);u.push(p)}}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(f=>({multiaddr:K(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new kr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new Oo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let f=await this.components.peerStore.get(t);o.push(...f.addresses),this.log("loaded multiaddrs for %p",t,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",t);try{let f=await this.components.peerRouting.findPeer(t,n);this.log("found multiaddrs for %p in the peer routing",t,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",t):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",t,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await wu(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(t!=null){let f=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new qi("The dial request has no valid addresses");let u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=this.addressSorter==null?vp(u):u.sort(this.addressSorter);if(l.length===0)throw new Oo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!Lo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ra=class extends En{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Pp=Vo(Ip(),1);var Gb=Object.prototype.toString,jb=r=>Gb.call(r)==="[object Error]",Zb=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function Su(r){return r&&jb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Zb.has(r.message):!1}var Au=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},Tp=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Cu(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=Pp.default.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Au)throw c.originalError;if(c instanceof TypeError&&!Su(c))throw c;if(Tp(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){Tp(u,a,t),i(),n(u)}}})})}var na=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new ra({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,this.events=t.events,t.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(t){if(!this.started)return;let e=await this.peerStore.get(t);Dp(e)&&(this.queue.has(t)||this.queue.add(async n=>{await Cu(async o=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",t,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",t,n);let o={};[...e.tags.keys()].forEach(s=>{s.startsWith(Ra)&&(o[s]=void 0)}),await this.peerStore.merge(t,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",t,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>Dp(e)]});await Promise.all(t.map(async e=>{await this.connectionManager.openConnection(e.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}};function Dp(r){for(let t of r.tags.keys())if(t.startsWith(Ra))return!0;return!1}var _u=50,Iu={maxConnections:xp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},oa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(t,e={}){if(this.maxConnections=e.maxConnections??Iu.maxConnections,this.maxConnections<1)throw new k("Connection Manager maxConnections must be greater than 0");this.connections=new $t,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(e.allow??[]).map(n=>ko(n)),this.deny=(e.deny??[]).map(n=>ko(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??Iu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ji({points:e.inboundConnectionThreshold??Iu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Xi({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{allow:e.allow?.map(n=>K(n))}),this.dialQueue=new ea(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??Qi,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:Se},connections:this.connections}),this.reconnectQueue=new na({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let e of this.connections.values())for(let n of e)t[n.direction]++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Fu(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Uu(this.reconnectQueue,this.dialQueue,this.connectionPruner);let t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(t){if(this.maxConnections<1)throw new k("Connection Manager maxConnections must be greater than 0");let e=!1;t<this.maxConnections&&(e=!0),this.maxConnections=t,e&&this.connectionPruner.maybePruneConnections()}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.id);this.connections.set(n,s),s.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new pe("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=Zi(t);if(this.peerId.equals(n))throw new Or("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new at("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??_u});if(o.status!=="open")throw new Rr("Remote closed connection during opening");let s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)if(a.id===o.id&&(i=!0),e.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new Pe("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>K(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var vn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(t){this.timeSpan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timeSpan)}push(t,e=Date.now()){if(this.previousTime!=null){let n=this.alpha(e,this.previousTime),o=t-this.movingAverage,s=n*o;this.movingAverage=n*t+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=t;this.previousTime=e}};var Yb=1.2,Jb=2,tw=5e3,ew=6e4,rw=5e3,sa=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(t={}){let e=t.interval??rw;this.success=new vn(e),this.failure=new vn(e),this.next=new vn(e),this.failureMultiplier=t.failureMultiplier??Jb,this.timeoutMultiplier=t.timeoutMultiplier??Yb,this.minTimeout=t.minTimeout??tw,this.maxTimeout=t.maxTimeout??ew,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier));e<this.minTimeout&&(e=this.minTimeout),e>this.maxTimeout&&(e=this.maxTimeout);let n=AbortSignal.timeout(e),o=Ie([t.signal,n]);return o.start=Date.now(),o.timeout=e,o}cleanUp(t){let e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}};var Tu=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ot(),this.haveNext=ot()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ot(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ot(),await mt(this.readNext.promise,e?.signal,e)}};function ia(){return new Tu}var aa=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ca(r,t){let e=ia();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new z;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:u}=await mt(n.next(),i?.signal);return c===!0?null:u}for(;o.byteLength<i.bytes;){let{value:c,done:u}=await mt(n.next(),i?.signal);if(u===!0)throw new aa("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var nw=1e4,ow="1.0.0",sw="ping",iw="ipfs",Lp=32,aw=!0,la=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??iw}/${sw}/${ow}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??nw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??aw,this.timeout=new sa({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[In]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=ca(o);e=Date.now(),await Promise.all([s.write(en(Lp),{signal:n}),s.read({bytes:Lp,signal:n})]),t.rtt=Date.now()-e,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function cw(r){return r[Symbol.asyncIterator]!=null}async function lw(r,t,e){try{await Promise.all(r.map(async n=>{for await(let o of n)await t.push(o,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*uw(r){let t=new AbortController,e=ia();lw(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*fw(r){for(let t of r)yield*t}function dw(...r){let t=[];for(let e of r)cw(e)||t.push(e);return t.length===r.length?fw(t):uw(r)}var No=dw;var ua=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t,this.findProviders=t.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=t.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=t.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=t.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:N(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:N(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(this.routers.length===0)throw new xn("No content routers available");let n=this,o=new hr;for await(let s of No(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(t,e))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},e),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new xn("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(this.routers.length===0)throw new xn("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new pe;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new pe;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(t,e)))}};var fa=globalThis.CustomEvent??Event;async function*Pu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=ot(),a=ot(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===e&&(i=ot(),await i.promise),l)break;let g={done:!1};s.push(g),p().then(m=>{g.done=!0,g.ok=!0,g.value=m,o.dispatchEvent(new fa("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new fa("task-complete"))})}c=!0,o.dispatchEvent(new fa("task-complete"))}catch(p){u=p,o.dispatchEvent(new fa("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw l=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let g=s[p];if(s.splice(p,1),p--,g.ok)yield g.value;else throw l=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=ot(),await a.promise),u!=null||(n?yield*d():yield*h(),u!=null))throw u;if(c&&s.length===0)break}}var da=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[],this.findPeer=t.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=t.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:N(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(this.routers.length===0)throw new Ro("No peer routers available");if(t.toString()===this.peerId.toString())throw new Ni("Should not try to find self");let n=this,o=No(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>async function*(){try{yield await s.findPeer(t,e)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},e),s;throw new $e}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new Ro("No peer routers available");let n=this,o=wo(1024);for await(let s of Pu(async function*(){let i=No(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(t,e)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...e,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},e),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var ha=class extends Bt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(t){this.walking||this.startWalk(),this.walkers++;let e=Ie([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ot(),yield(await he(this,"walk:peer",e,{errorEvent:"walk:error"})).detail}finally{e.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let t=Ie([this.walkController.signal,this.shutdownController.signal]);let e=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=en(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:t}))t.aborted&&this.log("aborting walk"),t.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await mt(this.needNext.promise,t)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-e),this.walking=!1})}};var Du=32,Lu=64,pa=class{log;topologies;handlers;components;constructor(t){this.components=t,this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,t.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let e={};for(let[n,o]of this.topologies)e[n]=o.size;return e}}),this.handlers=St({name:"libp2p_registrar_protocol_handlers",metrics:t.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){let e=this.handlers.get(t);if(e==null)throw new Bi(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t)&&n?.force!==!0)throw new Fi(`Handler already registered for protocol ${t}`);let o=Is.bind({ignoreUndefined:!0})({maxInboundStreams:Du,maxOutboundStreams:Lu},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]},n)}async unhandle(t,e){(Array.isArray(t)?t:[t]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},e)}async register(t,e){if(e==null)throw new k("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,e),n}unregister(t){for(let[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(e))}_onDisconnect(t){let e=t.detail,n={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(e,n).then(o=>{for(let s of o.protocols){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e)!==!1&&(a.filter?.remove(e),a.onDisconnect?.(e))}}).catch(o=>{o.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,o)})}_onPeerUpdate(t){let{peer:e,previous:n}=t.detail,o=(n?.protocols??[]).filter(s=>!e.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e.id)!==!1&&(a.filter?.remove(e.id),a.onDisconnect?.(e.id))}}_onPeerIdentify(t){let e=t.detail.protocols,n=t.detail.connection,o=t.detail.peerId;for(let s of e){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var ma=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=St({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=St({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??He.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new k("Transport must have a valid tag");if(this.transports.has(e))throw new k(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new Hi(`No transport available for address ${String(t)}`);return e?.onProgress?.(new at("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new pe("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach(s=>{e.errors.set(s.toString(),new Ui)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(t);for(let c of a){this.log("creating listener for %s on %a",s,c);let u=i.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(s)??[];l==null&&(l=[],this.listeners.set(s,l)),l.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let f=l.findIndex(d=>d===u);l.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),ru.matches(c)?e.ipv4.attempts++:nu.matches(c)&&e.ipv6.attempts++,n.push(u.listen(c).then(()=>{e.errors.delete(c.toString()),ru.matches(c)&&e.ipv4.success++,nu.matches(c)&&e.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),e.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(e)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===He.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Ki(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
3
- ${[...e.errors.entries()].map(([s,i])=>`
4
- ${s}: ${`${i.stack??i}`.split(`
2
+ "use strict";var Libp2P=(()=>{var nm=Object.create;var Wo=Object.defineProperty;var om=Object.getOwnPropertyDescriptor;var sm=Object.getOwnPropertyNames;var im=Object.getPrototypeOf,am=Object.prototype.hasOwnProperty;var La=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Fe=(r,e)=>{for(var t in e)Wo(r,t,{get:e[t],enumerable:!0})},rf=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sm(e))!am.call(r,o)&&o!==t&&Wo(r,o,{get:()=>e[o],enumerable:!(n=om(e,o))||n.enumerable});return r};var Da=(r,e,t)=>(t=r!=null?nm(im(r)):{},rf(e||!r||!r.__esModule?Wo(t,"default",{value:r,enumerable:!0}):t,r)),cm=r=>rf(Wo({},"__esModule",{value:!0}),r);var Sh=La(vo=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,f,u,d;return l=(c&255<<24)>>>24,f=(c&255<<16)>>>16,u=(c&65280)>>>8,d=c&255,[l,f,u,d].join(".")},i=function(c){var l,f,u,d,h,p;for(l=[],u=d=0;d<=3&&c.length!==0;u=++d){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],f=p[1],c=c.substring(f),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,f,u,d,h;for(d=0,l=10,f="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,f="7")),h=u;u<c.length;){if("0"<=c[u]&&c[u]<=f)d=d*l+(t(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")d=d*l+(10+t(c[u])-s)>>>0;else if("A"<=c[u]&&c[u]<="F")d=d*l+(10+t(c[u])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");u++}if(u===h)throw new Error("empty octet");return[d,u]},r=(function(){function c(l,f){var u,d,h,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(f||(p=l.split("/",2),l=p[0],f=p[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=i(f)}catch(m){throw u=m,new Error("Invalid mask: "+f)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw u=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var f,u,d;for(d=i(this.first),u=i(this.last),f=0;d<=u;)l(a(d),d,f),f++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),vo.ip2long=i,vo.long2ip=a,vo.Netmask=r}).call(vo)});var Xh=La(($C,iu)=>{"use strict";var Eb=Object.prototype.hasOwnProperty,Me="~";function To(){}Object.create&&(To.prototype=Object.create(null),new To().__proto__||(Me=!1));function vb(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function jh(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new vb(t,n||r,o),i=Me?Me+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function fi(r,e){--r._eventsCount===0?r._events=new To:delete r._events[e]}function Ie(){this._events=new To,this._eventsCount=0}Ie.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Eb.call(t,n)&&e.push(Me?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Ie.prototype.listeners=function(e){var t=Me?Me+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Ie.prototype.listenerCount=function(e){var t=Me?Me+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Ie.prototype.emit=function(e,t,n,o,s,i){var a=Me?Me+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,f,u;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(u=1,f=new Array(l-1);u<l;u++)f[u-1]=arguments[u];c.fn.apply(c.context,f)}else{var d=c.length,h;for(u=0;u<d;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(l-1);h<l;h++)f[h-1]=arguments[h];c[u].fn.apply(c[u].context,f)}}return!0};Ie.prototype.on=function(e,t,n){return jh(this,e,t,n,!1)};Ie.prototype.once=function(e,t,n){return jh(this,e,t,n,!0)};Ie.prototype.removeListener=function(e,t,n,o){var s=Me?Me+e:e;if(!this._events[s])return this;if(!t)return fi(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&fi(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:fi(this,s)}return this};Ie.prototype.removeAllListeners=function(e){var t;return e?(t=Me?Me+e:e,this._events[t]&&fi(this,t)):(this._events=new To,this._eventsCount=0),this};Ie.prototype.off=Ie.prototype.removeListener;Ie.prototype.addListener=Ie.prototype.on;Ie.prefixed=Me;Ie.EventEmitter=Ie;typeof iu<"u"&&(iu.exports=Ie)});var Qh=La((fI,Zh)=>{Zh.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Vw={};Fe(Vw,{createLibp2p:()=>Uw,dnsaddrResolver:()=>kt,isLibp2p:()=>qw});var nf=Symbol.for("@libp2p/connection");var Ra=Symbol.for("@libp2p/content-routing");var Qe=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var I=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Nr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Rn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var tr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var rr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Mr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Bt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},jo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Xo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Yo=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Zo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Qo=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},ht=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Br=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var On=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Jo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},es=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ft=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ts=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var Oa=Symbol.for("@libp2p/peer-discovery");var rs=Symbol.for("@libp2p/peer-id");function Ut(r){return!!r?.[rs]}var ka=Symbol.for("@libp2p/peer-routing");var Na="keep-alive";function ns(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function of(...r){let e=[];for(let t of r)ns(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function sf(...r){let e=[];for(let t of r)ns(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Jw=Symbol.for("@libp2p/transport");var nr;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(nr||(nr={}));var Pe=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var kn=Symbol.for("@libp2p/service-capabilities"),Ma=Symbol.for("@libp2p/service-dependencies");var qa={};Fe(qa,{base58btc:()=>ee,base58flickr:()=>mm});var Tx=new Uint8Array(0);function af(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function pt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function cf(r){return new TextEncoder().encode(r)}function lf(r){return new TextDecoder().decode(r)}function lm(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,w=0,g=0,_=p.length;g!==_&&p[g]===0;)g++,m++;for(var E=(_-g)*f+1>>>0,C=new Uint8Array(E);g!==_;){for(var k=p[g],V=0,$=E-1;(k!==0||V<w)&&$!==-1;$--,V++)k+=256*C[$]>>>0,C[$]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");w=V,g++}for(var N=E-w;N!==E&&C[N]===0;)N++;for(var v=c.repeat(m);N<E;++N)v+=r.charAt(C[N]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var w=0,g=0;p[m]===c;)w++,m++;for(var _=(p.length-m)*l+1>>>0,E=new Uint8Array(_);p[m];){var C=t[p.charCodeAt(m)];if(C===255)return;for(var k=0,V=_-1;(C!==0||k<g)&&V!==-1;V--,k++)C+=a*E[V]>>>0,E[V]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");g=k,m++}if(p[m]!==" "){for(var $=_-g;$!==_&&E[$]===0;)$++;for(var N=new Uint8Array(w+(_-$)),v=w;$!==_;)N[v++]=E[$++];return N}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:h}}var um=lm,fm=um,ff=fm;var Ba=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Fa=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return df(this,e)}},Ua=class{decoders;constructor(e){this.decoders=e}or(e){return df(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function df(r,e){return new Ua({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ka=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ba(e,t,n),this.decoder=new Fa(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Fr({name:r,prefix:e,encode:t,decode:n}){return new Ka(r,e,t,n)}function Kt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=ff(t,r);return Fr({prefix:e,name:r,encode:n,decode:s=>pt(o(s))})}function dm(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let f=e[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|f,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function hm(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function pm(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=pm(n);return Fr({prefix:e,name:r,encode(s){return hm(s,n,t)},decode(s){return dm(s,o,t,r)}})}var ee=Kt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mm=Kt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Va={};Fe(Va,{base32:()=>We,base32hex:()=>wm,base32hexpad:()=>Em,base32hexpadupper:()=>vm,base32hexupper:()=>xm,base32pad:()=>ym,base32padupper:()=>bm,base32upper:()=>gm,base32z:()=>Sm});var We=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),gm=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ym=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bm=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wm=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xm=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Em=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),vm=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Sm=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $a={};Fe($a,{base36:()=>Nn,base36upper:()=>_m});var Nn=Kt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_m=Kt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Am=mf,hf=128,Cm=127,Im=~Cm,Tm=Math.pow(2,31);function mf(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Tm;)e[t++]=r&255|hf,r/=128;for(;r&Im;)e[t++]=r&255|hf,r>>>=7;return e[t]=r|0,mf.bytes=t-n+1,e}var Pm=za,Lm=128,pf=127;function za(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw za.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&pf)<<o:(i&pf)*Math.pow(2,o),o+=7}while(i>=Lm);return za.bytes=s-n,t}var Dm=Math.pow(2,7),Rm=Math.pow(2,14),Om=Math.pow(2,21),km=Math.pow(2,28),Nm=Math.pow(2,35),Mm=Math.pow(2,42),Bm=Math.pow(2,49),Fm=Math.pow(2,56),Um=Math.pow(2,63),Km=function(r){return r<Dm?1:r<Rm?2:r<Om?3:r<km?4:r<Nm?5:r<Mm?6:r<Bm?7:r<Fm?8:r<Um?9:10},qm={encode:Am,decode:Pm,encodingLength:Km},Vm=qm,Mn=Vm;function Bn(r,e=0){return[Mn.decode(r,e),Mn.decode.bytes]}function Ur(r,e,t=0){return Mn.encode(r,e,t),e}function Kr(r){return Mn.encodingLength(r)}function ct(r,e){let t=e.byteLength,n=Kr(r),o=n+Kr(t),s=new Uint8Array(o+t);return Ur(r,s,0),Ur(t,s,n),s.set(e,o),new qr(r,t,e,s)}function mt(r){let e=pt(r),[t,n]=Bn(e),[o,s]=Bn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new qr(t,o,i,e)}function gf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&af(r.bytes,t.bytes)}}var qr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function yf(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return zm(t,Ha(r),e??ee.encoder);default:return Hm(t,Ha(r),e??We.encoder)}}var bf=new WeakMap;function Ha(r){let e=bf.get(r);if(e==null){let t=new Map;return bf.set(r,t),t}return e}var ue=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Fn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Gm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ct(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&gf(e.multihash,n.multihash)}toString(e){return yf(this,e)}toJSON(){return{"/":yf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??wf(n,o,s.bytes))}else if(t[Wm]===!0){let{version:n,multihash:o,code:s}=t,i=mt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Fn)throw new Error(`Version 0 CID must use dag-pb (code: ${Fn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=wf(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Fn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=pt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new qr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,d]=Bn(e.subarray(t));return t+=d,u},o=n(),s=Fn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,f=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=$m(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ha(s).set(n,e),s}};function $m(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case We.prefix:{let t=e??We;return[We.prefix,t.decode(r)]}case Nn.prefix:{let t=e??Nn;return[Nn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function zm(r,e,t){let{prefix:n}=t;if(n!==ee.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Hm(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Fn=112,Gm=18;function wf(r,e,t){let n=Kr(r),o=n+Kr(e),s=new Uint8Array(o+t.byteLength);return Ur(r,s,0),Ur(e,s,n),s.set(t,o),s}var Wm=Symbol.for("@ipld/js-cid/CID");var Ga={};Fe(Ga,{identity:()=>Je});var xf=0,jm="identity",Ef=pt;function Xm(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ct(xf,Ef(r))}var Je={code:xf,name:jm,encode:Ef,digest:Xm};function Y(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ce(r=0){return new Uint8Array(r)}function Se(r=0){return new Uint8Array(r)}function et(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Se(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Sf=Symbol.for("@achingbrain/uint8arraylist");function vf(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function ss(r){return!!r?.[Sf]}var Z=class r{bufs;length;[Sf]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ss(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ss(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=vf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=vf(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ss(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return et(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:et(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(i);break}let u=e-a;n.push(i.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ss(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let u=t;u<=c;u+=f){f=0;for(let d=l;d>=0;d--){let h=this.get(u+d);if(n[d]!==h){f=Math.max(1,d-a[h]);break}}if(f===0)return u}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ce(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Se(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ce(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ce(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ce(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Y(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Wa={};Fe(Wa,{base10:()=>Ym});var Ym=Kt({prefix:"9",name:"base10",alphabet:"0123456789"});var ja={};Fe(ja,{base16:()=>Zm,base16upper:()=>Qm});var Zm=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Qm=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xa={};Fe(Xa,{base2:()=>Jm});var Jm=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ya={};Fe(Ya,{base256emoji:()=>og});var _f=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),eg=_f.reduce((r,e,t)=>(r[t]=e,r),[]),tg=_f.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function rg(r){return r.reduce((e,t)=>(e+=eg[t],e),"")}function ng(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=tg[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var og=Fr({prefix:"\u{1F680}",name:"base256emoji",encode:rg,decode:ng});var Ja={};Fe(Ja,{base64:()=>Za,base64pad:()=>sg,base64url:()=>Qa,base64urlpad:()=>ig});var Za=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sg=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Qa=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ig=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ec={};Fe(ec,{base8:()=>ag});var ag=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var tc={};Fe(tc,{identity:()=>cg});var cg=Fr({prefix:"\0",name:"identity",encode:r=>lf(r),decode:r=>cf(r)});var fE=new TextEncoder,dE=new TextDecoder;var oc={};Fe(oc,{sha256:()=>Vr,sha512:()=>dg});var fg=20;function nc({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new rc(r,e,t,n,o)}var rc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??fg,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Af(n,this.code,t?.truncate):n.then(o=>Af(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Af(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ct(e,r)}function If(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Vr=nc({name:"sha2-256",code:18,encode:If("SHA-256")}),dg=nc({name:"sha2-512",code:19,encode:If("SHA-512")});var Un={...tc,...Xa,...ec,...Wa,...ja,...Va,...$a,...qa,...Ja,...Ya},_E={...oc,...Ga};function Pf(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Tf=Pf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),sc=Pf("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Se(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),hg={utf8:Tf,"utf-8":Tf,hex:Un.base16,latin1:sc,ascii:sc,binary:sc,...Un},is=hg;function T(r,e="utf8"){let t=is[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function K(r,e="utf8"){let t=is[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var pg=parseInt("11111",2),ic=parseInt("10000000",2),mg=parseInt("01111111",2),Lf={0:Kn,1:Kn,2:gg,3:wg,4:xg,5:bg,6:yg,16:Kn,22:Kn,48:Kn};function gt(r,e={offset:0}){let t=r[e.offset]&pg;if(e.offset++,Lf[t]!=null)return Lf[t](r,e);throw new Error("No decoder for tag "+t)}function qn(r,e){let t=0;if((r[e.offset]&ic)===ic){let n=r[e.offset]&mg,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Kn(r,e){qn(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=gt(r,e);if(n===null)break;t.push(n)}return t}function gg(r,e){let t=qn(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function yg(r,e){let t=qn(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let f=0;for(let u=0;u<c.length;u++)f+=c[u]<<u*7;a+=`.${f}`,c=[]}}return a}function bg(r,e){return e.offset++,null}function wg(r,e){let t=qn(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function xg(r,e){let t=qn(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Eg(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Z;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function as(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Eg(r.byteLength);return new Z(Uint8Array.from([e.byteLength|ic]),e)}function Le(r){let e=new Z,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Z(Uint8Array.from([2]),as(e),e)}function Vn(r){let e=Uint8Array.from([0]),t=new Z(e,r);return new Z(Uint8Array.from([3]),as(t),t)}function Df(r){return new Z(Uint8Array.from([4]),as(r),r)}function tt(r,e=48){let t=new Z;for(let n of r)t.append(n);return new Z(Uint8Array.from([e]),as(t),t)}async function Rf(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function Of(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function kf(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var vg=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Sg=Uint8Array.from([6,5,43,129,4,0,34]),_g=Uint8Array.from([6,5,43,129,4,0,35]),Ag={ext:!0,kty:"EC",crv:"P-256"},Cg={ext:!0,kty:"EC",crv:"P-384"},Ig={ext:!0,kty:"EC",crv:"P-521"},ac=32,cc=48,lc=66;function uc(r){let e=gt(r);return Nf(e)}function Nf(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===ac*2+1)return n=K(e.subarray(t,t+ac),"base64url"),o=K(e.subarray(t+ac),"base64url"),new or({...Ag,key_ops:["verify"],x:n,y:o});if(e.byteLength===cc*2+1)return n=K(e.subarray(t,t+cc),"base64url"),o=K(e.subarray(t+cc),"base64url"),new or({...Cg,key_ops:["verify"],x:n,y:o});if(e.byteLength===lc*2+1)return n=K(e.subarray(t,t+lc),"base64url"),o=K(e.subarray(t+lc),"base64url"),new or({...Ig,key_ops:["verify"],x:n,y:o});throw new I(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Mf(r){return tt([Le(Uint8Array.from([1])),Df(T(r.d??"","base64url")),tt([Ff(r.crv)],160),tt([Vn(new Z(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function Bf(r){return tt([Le(Uint8Array.from([1])),tt([Ff(r.crv)],160),tt([Vn(new Z(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function Ff(r){if(r==="P-256")return vg;if(r==="P-384")return Sg;if(r==="P-521")return _g;throw new I(`Invalid curve ${r}`)}async function Uf(r="P-256"){let e=await Rf(r);return new cs(e.privateKey)}var or=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Bf(this.jwk)),this._raw}toMultihash(){return Je.digest(je(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}async verify(e,t,n){return kf(this.jwk,t,e,n)}},cs=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new or({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Mf(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}async sign(e,t){return Of(this.jwk,e,t)}};var sr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function bt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function $n(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Ue(r,...e){if(!bt(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function ls(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");$n(r.outputLen),$n(r.blockLen)}function zr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function qf(r,e){Ue(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function wt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function us(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function rt(r,e){return r<<32-e|r>>>e}var Vf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Tg=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Xe(r){if(Ue(r),Vf)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Tg[r[t]];return e}var yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Kf(r){if(r>=yt._0&&r<=yt._9)return r-yt._0;if(r>=yt.A&&r<=yt.F)return r-(yt.A-10);if(r>=yt.a&&r<=yt.f)return r-(yt.a-10)}function ir(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Vf)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Kf(r.charCodeAt(s)),a=Kf(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function fc(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function zn(r){return typeof r=="string"&&(r=fc(r)),Ue(r),r}function De(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ue(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var $r=class{};function dc(r){let e=n=>r().update(zn(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Vt(r=32){if(sr&&typeof sr.getRandomValues=="function")return sr.getRandomValues(new Uint8Array(r));if(sr&&typeof sr.randomBytes=="function")return Uint8Array.from(sr.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function Pg(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}function $f(r,e,t){return r&e^~r&t}function zf(r,e,t){return r&e^r&t^e&t}var Hn=class extends $r{constructor(e,t,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=us(this.buffer)}update(e){zr(this),e=zn(e),Ue(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=us(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){zr(this),qf(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,wt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)t[u]=0;Pg(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=us(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var we=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var fs=BigInt(4294967295),Hf=BigInt(32);function Lg(r,e=!1){return e?{h:Number(r&fs),l:Number(r>>Hf&fs)}:{h:Number(r>>Hf&fs)|0,l:Number(r&fs)|0}}function Gf(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Lg(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var hc=(r,e,t)=>r>>>t,pc=(r,e,t)=>r<<32-t|e>>>t,ar=(r,e,t)=>r>>>t|e<<32-t,cr=(r,e,t)=>r<<32-t|e>>>t,Gn=(r,e,t)=>r<<64-t|e>>>t-32,Wn=(r,e,t)=>r>>>t-32|e<<64-t;function lt(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Wf=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),jf=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Xf=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Yf=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Zf=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Qf=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Rg=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$t=new Uint32Array(64),ds=class extends Hn{constructor(e=32){super(64,e,8,!1),this.A=xt[0]|0,this.B=xt[1]|0,this.C=xt[2]|0,this.D=xt[3]|0,this.E=xt[4]|0,this.F=xt[5]|0,this.G=xt[6]|0,this.H=xt[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)$t[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=$t[u-15],h=$t[u-2],p=rt(d,7)^rt(d,18)^d>>>3,m=rt(h,17)^rt(h,19)^h>>>10;$t[u]=m+$t[u-7]+p+$t[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){let d=rt(a,6)^rt(a,11)^rt(a,25),h=f+d+$f(a,c,l)+Rg[u]+$t[u]|0,m=(rt(n,2)^rt(n,13)^rt(n,22))+zf(n,o,s)|0;f=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,l,f)}roundClean(){wt($t)}destroy(){this.set(0,0,0,0,0,0,0,0),wt(this.buffer)}};var Jf=Gf(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Og=Jf[0],kg=Jf[1],zt=new Uint32Array(80),Ht=new Uint32Array(80),mc=class extends Hn{constructor(e=64){super(128,e,16,!1),this.Ah=we[0]|0,this.Al=we[1]|0,this.Bh=we[2]|0,this.Bl=we[3]|0,this.Ch=we[4]|0,this.Cl=we[5]|0,this.Dh=we[6]|0,this.Dl=we[7]|0,this.Eh=we[8]|0,this.El=we[9]|0,this.Fh=we[10]|0,this.Fl=we[11]|0,this.Gh=we[12]|0,this.Gl=we[13]|0,this.Hh=we[14]|0,this.Hl=we[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:f,Fh:u,Fl:d,Gh:h,Gl:p,Hh:m,Hl:w}=this;return[e,t,n,o,s,i,a,c,l,f,u,d,h,p,m,w]}set(e,t,n,o,s,i,a,c,l,f,u,d,h,p,m,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=f|0,this.Fh=u|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=w|0}process(e,t){for(let E=0;E<16;E++,t+=4)zt[E]=e.getUint32(t),Ht[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let C=zt[E-15]|0,k=Ht[E-15]|0,V=ar(C,k,1)^ar(C,k,8)^hc(C,k,7),$=cr(C,k,1)^cr(C,k,8)^pc(C,k,7),N=zt[E-2]|0,v=Ht[E-2]|0,D=ar(N,v,19)^Gn(N,v,61)^hc(N,v,6),F=cr(N,v,19)^Wn(N,v,61)^pc(N,v,6),R=Xf($,F,Ht[E-7],Ht[E-16]),x=Yf(R,V,D,zt[E-7],zt[E-16]);zt[E]=x|0,Ht[E]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:d,Fh:h,Fl:p,Gh:m,Gl:w,Hh:g,Hl:_}=this;for(let E=0;E<80;E++){let C=ar(u,d,14)^ar(u,d,18)^Gn(u,d,41),k=cr(u,d,14)^cr(u,d,18)^Wn(u,d,41),V=u&h^~u&m,$=d&p^~d&w,N=Zf(_,k,$,kg[E],Ht[E]),v=Qf(N,g,C,V,Og[E],zt[E]),D=N|0,F=ar(n,o,28)^Gn(n,o,34)^Gn(n,o,39),R=cr(n,o,28)^Wn(n,o,34)^Wn(n,o,39),x=n&s^n&a^s&a,y=o&i^o&c^i&c;g=m|0,_=w|0,m=h|0,w=p|0,h=u|0,p=d|0,{h:u,l:d}=lt(l|0,f|0,v|0,D|0),l=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let b=Wf(D,R,y);n=jf(b,v,F,x),o=b|0}({h:n,l:o}=lt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=lt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=lt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=lt(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:d}=lt(this.Eh|0,this.El|0,u|0,d|0),{h,l:p}=lt(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:w}=lt(this.Gh|0,this.Gl|0,m|0,w|0),{h:g,l:_}=lt(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,o,s,i,a,c,l,f,u,d,h,p,m,w,g,_)}roundClean(){wt(zt,Ht)}destroy(){wt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var hs=dc(()=>new ds);var ed=dc(()=>new mc);var bc=BigInt(0),yc=BigInt(1);function Et(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Ve(r,e,t=""){let n=bt(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function jn(r){let e=r.toString(16);return e.length&1?"0"+e:e}function td(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?bc:BigInt("0x"+r)}function Hr(r){return td(Xe(r))}function vt(r){return Ue(r),td(Xe(Uint8Array.from(r).reverse()))}function ps(r,e){return ir(r.toString(16).padStart(e*2,"0"))}function wc(r,e){return ps(r,e).reverse()}function Q(r,e,t){let n;if(typeof e=="string")try{n=ir(e)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(bt(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(r+" of length "+t+" expected, got "+o);return n}function rd(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function xc(r){return Uint8Array.from(r)}var gc=r=>typeof r=="bigint"&&bc<=r;function nd(r,e,t){return gc(r)&&gc(e)&&gc(t)&&e<=r&&r<t}function Xn(r,e,t,n){if(!nd(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function ms(r){let e;for(e=0;r>bc;r>>=yc,e+=1);return e}var Gt=r=>(yc<<BigInt(r))-yc;function od(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>t(i,s,...h),f=(h=n(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,p=[];for(;h<e;){s=l();let m=s.slice();p.push(m),h+=s.length}return De(...p)};return(h,p)=>{c(),f(h);let m;for(;!(m=p(u()));)f();return c(),m}}function Wt(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(t).forEach(([o,s])=>n(o,s,!0))}var Ec=()=>{throw new Error("not implemented")};function Gr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var Re=BigInt(0),pe=BigInt(1),lr=BigInt(2),ad=BigInt(3),cd=BigInt(4),ld=BigInt(5),Ng=BigInt(7),ud=BigInt(8),Mg=BigInt(9),fd=BigInt(16);function le(r,e){let t=r%e;return t>=Re?t:e+t}function ne(r,e,t){let n=r;for(;e-- >Re;)n*=n,n%=t;return n}function sd(r,e){if(r===Re)throw new Error("invert: expected non-zero number");if(e<=Re)throw new Error("invert: expected positive modulus, got "+e);let t=le(r,e),n=e,o=Re,s=pe,i=pe,a=Re;for(;t!==Re;){let l=n/t,f=n%t,u=o-i*l,d=s-a*l;n=t,t=f,o=i,s=a,i=u,a=d}if(n!==pe)throw new Error("invert: does not exist");return le(o,e)}function vc(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function dd(r,e){let t=(r.ORDER+pe)/cd,n=r.pow(e,t);return vc(r,n,e),n}function Bg(r,e){let t=(r.ORDER-ld)/ud,n=r.mul(e,lr),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,lr),o),a=r.mul(s,r.sub(i,r.ONE));return vc(r,a,e),a}function Fg(r){let e=$e(r),t=hd(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+Ng)/fd;return(a,c)=>{let l=a.pow(c,i),f=a.mul(l,n),u=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(f),c),p=a.eql(a.sqr(u),c);l=a.cmov(l,f,h),f=a.cmov(d,u,p);let m=a.eql(a.sqr(f),c),w=a.cmov(l,f,m);return vc(a,w,c),w}}function hd(r){if(r<ad)throw new Error("sqrt is not defined for small field");let e=r-pe,t=0;for(;e%lr===Re;)e/=lr,t++;let n=lr,o=$e(r);for(;id(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return dd;let s=o.pow(n,e),i=(e+pe)/lr;return function(c,l){if(c.is0(l))return l;if(id(c,l)!==1)throw new Error("Cannot find square root");let f=t,u=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===f)throw new Error("Cannot find square root");let w=pe<<BigInt(f-p-1),g=c.pow(u,w);f=p,u=c.sqr(g),d=c.mul(d,u),h=c.mul(h,g)}return h}}function Ug(r){return r%cd===ad?dd:r%ud===ld?Bg:r%fd===Mg?Fg(r):hd(r)}var St=(r,e)=>(le(r,e)&pe)===pe,Kg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Sc(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=Kg.reduce((n,o)=>(n[o]="function",n),e);return Wt(r,t),r}function qg(r,e,t){if(t<Re)throw new Error("invalid exponent, negatives unsupported");if(t===Re)return r.ONE;if(t===pe)return e;let n=r.ONE,o=e;for(;t>Re;)t&pe&&(n=r.mul(n,o)),o=r.sqr(o),t>>=pe;return n}function Yn(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function id(r,e){let t=(r.ORDER-pe)/lr,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function gs(r,e){e!==void 0&&$n(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function $e(r,e,t=!1,n={}){if(r<=Re)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(o=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:l}=gs(r,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let f,u=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:l,MASK:Gt(c),ZERO:Re,ONE:pe,allowedLengths:a,create:d=>le(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Re<=d&&d<r},is0:d=>d===Re,isValidNot0:d=>!u.is0(d)&&u.isValid(d),isOdd:d=>(d&pe)===pe,neg:d=>le(-d,r),eql:(d,h)=>d===h,sqr:d=>le(d*d,r),add:(d,h)=>le(d+h,r),sub:(d,h)=>le(d-h,r),mul:(d,h)=>le(d*h,r),pow:(d,h)=>qg(u,d,h),div:(d,h)=>le(d*sd(h,r),r),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>sd(d,r),sqrt:s||(d=>(f||(f=Ug(r)),f(u,d))),toBytes:d=>t?wc(d,l):ps(d,l),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let m=new Uint8Array(l);m.set(d,t?0:m.length-d.length),d=m}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let p=t?vt(d):Hr(d);if(i&&(p=le(p,r)),!h&&!u.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>Yn(u,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(u)}function pd(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function _c(r){let e=pd(r);return e+Math.ceil(e/2)}function Ac(r,e,t=!1){let n=r.length,o=pd(e),s=_c(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?vt(r):Hr(r),a=le(i,e-pe)+pe;return t?wc(a,o):ps(a,o)}var Wr=BigInt(0),ur=BigInt(1);function Zn(r,e){let t=e.negate();return r?t:e}function _t(r,e){let t=Yn(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function bd(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Cc(r,e){bd(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Gt(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function md(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=ur);let l=e*n,f=l+Math.abs(a)-1,u=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:f,isZero:u,isNeg:d,isNegF:h,offsetF:l}}function Vg(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function $g(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var Ic=new WeakMap,wd=new WeakMap;function Tc(r){return wd.get(r)||1}function gd(r){if(r!==Wr)throw new Error("invalid wNAF")}var jr=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Wr;)t&ur&&(n=n.add(o)),o=o.double(),t>>=ur;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=Cc(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Cc(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:f,isNeg:u,isNegF:d,offsetF:h}=md(n,a,i);n=c,f?s=s.add(Zn(d,t[h])):o=o.add(Zn(u,t[l]))}return gd(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=Cc(e,this.bits);for(let i=0;i<s.windows&&n!==Wr;i++){let{nextN:a,offset:c,isZero:l,isNeg:f}=md(n,i,s);if(n=a,!l){let u=t[c];o=o.add(f?u.negate():u)}}return gd(n),o}getPrecomputes(e,t,n){let o=Ic.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Ic.set(t,o))),o}cached(e,t,n){let o=Tc(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Tc(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){bd(t,this.bits),wd.set(e,t),Ic.delete(e)}hasCache(e){return Tc(e)!==1}};function xd(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Wr||n>Wr;)t&ur&&(s=s.add(o)),n&ur&&(i=i.add(o)),o=o.double(),t>>=ur,n>>=ur;return{p1:s,p2:i}}function Xr(r,e,t,n){Vg(t,r),$g(n,e);let o=t.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=ms(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Gt(c),f=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c,d=i;for(let h=u;h>=0;h-=c){f.fill(i);for(let m=0;m<s;m++){let w=n[m],g=Number(w>>BigInt(h)&l);f[g]=f[g].add(t[m])}let p=i;for(let m=f.length-1,w=i;m>0;m--)w=w.add(f[m]),p=p.add(w);if(d=d.add(p),h!==0)for(let m=0;m<c;m++)d=d.double()}return d}function yd(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Sc(e),e}else return $e(r,{isLE:t})}function ys(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Wr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=yd(e.p,t.Fp,n),s=yd(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}var jt=BigInt(0),me=BigInt(1),Pc=BigInt(2),zg=BigInt(8);function Hg(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function Gg(r,e={}){let t=ys("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;Wt(e,{},{uvRatio:"function"});let a=Pc<<BigInt(o.BYTES*8)-me,c=w=>n.create(w),l=e.uvRatio||((w,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,g))}}catch{return{isValid:!1,value:jt}}});if(!Hg(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(w,g,_=!1){let E=_?me:jt;return Xn("coordinate "+w,g,E,a),g}function u(w){if(!(w instanceof p))throw new Error("ExtendedPoint expected")}let d=Gr((w,g)=>{let{X:_,Y:E,Z:C}=w,k=w.is0();g==null&&(g=k?zg:n.inv(C));let V=c(_*g),$=c(E*g),N=n.mul(C,g);if(k)return{x:jt,y:me};if(N!==me)throw new Error("invZ was invalid");return{x:V,y:$}}),h=Gr(w=>{let{a:g,d:_}=s;if(w.is0())throw new Error("bad point: ZERO");let{X:E,Y:C,Z:k,T:V}=w,$=c(E*E),N=c(C*C),v=c(k*k),D=c(v*v),F=c($*g),R=c(v*c(F+N)),x=c(D+c(_*c($*N)));if(R!==x)throw new Error("bad point: equation left != right (1)");let y=c(E*C),b=c(k*V);if(y!==b)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(g,_,E,C){this.X=f("x",g),this.Y=f("y",_),this.Z=f("z",E,!0),this.T=f("t",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:_,y:E}=g||{};return f("x",_),f("y",E),new p(_,E,me,c(_*E))}static fromBytes(g,_=!1){let E=n.BYTES,{a:C,d:k}=s;g=xc(Ve(g,E,"point")),Et(_,"zip215");let V=xc(g),$=g[E-1];V[E-1]=$&-129;let N=vt(V),v=_?a:n.ORDER;Xn("point.y",N,jt,v);let D=c(N*N),F=c(D-me),R=c(k*D-C),{isValid:x,value:y}=l(F,R);if(!x)throw new Error("bad point: invalid y coordinate");let b=(y&me)===me,S=($&128)!==0;if(!_&&y===jt&&S)throw new Error("bad point: x=0 and x_0=1");return S!==b&&(y=c(-y)),p.fromAffine({x:y,y:N})}static fromHex(g,_=!1){return p.fromBytes(Q("point",g),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,_=!0){return m.createCache(this,g),_||this.multiply(Pc),this}assertValidity(){h(this)}equals(g){u(g);let{X:_,Y:E,Z:C}=this,{X:k,Y:V,Z:$}=g,N=c(_*$),v=c(k*C),D=c(E*$),F=c(V*C);return N===v&&D===F}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=s,{X:_,Y:E,Z:C}=this,k=c(_*_),V=c(E*E),$=c(Pc*c(C*C)),N=c(g*k),v=_+E,D=c(c(v*v)-k-V),F=N+V,R=F-$,x=N-V,y=c(D*R),b=c(F*x),S=c(D*x),A=c(R*F);return new p(y,b,A,S)}add(g){u(g);let{a:_,d:E}=s,{X:C,Y:k,Z:V,T:$}=this,{X:N,Y:v,Z:D,T:F}=g,R=c(C*N),x=c(k*v),y=c($*E*F),b=c(V*D),S=c((C+k)*(N+v)-R-x),A=b-y,O=b+y,P=c(x-_*R),L=c(S*A),B=c(O*P),q=c(S*P),oe=c(A*O);return new p(L,B,oe,q)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:E}=m.cached(this,g,C=>_t(p,C));return _t(p,[_,E])[0]}multiplyUnsafe(g,_=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===jt?p.ZERO:this.is0()||g===me?this:m.unsafe(this,g,E=>_t(p,E),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(g){return d(this,g)}clearCofactor(){return i===me?this:this.multiplyUnsafe(i)}toBytes(){let{x:g,y:_}=this.toAffine(),E=n.toBytes(_);return E[E.length-1]|=g&me?128:0,E}toHex(){return Xe(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(g){return _t(p,g)}static msm(g,_){return Xr(p,o,g,_)}_setWindowSize(g){this.precompute(g)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,me,c(s.Gx*s.Gy)),p.ZERO=new p(jt,me,me,jt),p.Fp=n,p.Fn=o;let m=new jr(p,o.BITS);return p.BASE.precompute(8),p}var bs=class{constructor(e){this.ep=e}static fromBytes(e){Ec()}static fromHex(e){Ec()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Xe(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function Wg(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Wt(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||Vt,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,D,F)=>{if(Et(F,"phflag"),D.length||F)throw new Error("Contexts/pre-hash are not supported");return v});function f(v){return i.create(vt(v))}function u(v){let D=E.secretKey;v=Q("private key",v,D);let F=Q("hashed private key",e(v),2*D),R=c(F.slice(0,D)),x=F.slice(D,2*D),y=f(R);return{head:R,prefix:x,scalar:y}}function d(v){let{head:D,prefix:F,scalar:R}=u(v),x=o.multiply(R),y=x.toBytes();return{head:D,prefix:F,scalar:R,point:x,pointBytes:y}}function h(v){return d(v).pointBytes}function p(v=Uint8Array.of(),...D){let F=De(...D);return f(e(l(F,Q("context",v),!!n)))}function m(v,D,F={}){v=Q("message",v),n&&(v=n(v));let{prefix:R,scalar:x,pointBytes:y}=d(D),b=p(F.context,R,v),S=o.multiply(b).toBytes(),A=p(F.context,S,y,v),O=i.create(b+A*x);if(!i.isValid(O))throw new Error("sign failed: invalid s");let P=De(S,i.toBytes(O));return Ve(P,E.signature,"result")}let w={zip215:!0};function g(v,D,F,R=w){let{context:x,zip215:y}=R,b=E.signature;v=Q("signature",v,b),D=Q("message",D),F=Q("publicKey",F,E.publicKey),y!==void 0&&Et(y,"zip215"),n&&(D=n(D));let S=b/2,A=v.subarray(0,S),O=vt(v.subarray(S,b)),P,L,B;try{P=r.fromBytes(F,y),L=r.fromBytes(A,y),B=o.multiplyUnsafe(O)}catch{return!1}if(!y&&P.isSmallOrder())return!1;let q=p(x,L.toBytes(),P.toBytes(),D);return L.add(P.multiplyUnsafe(q)).subtract(B).clearCofactor().is0()}let _=s.BYTES,E={secretKey:_,publicKey:_,signature:2*_,seed:_};function C(v=a(E.seed)){return Ve(v,E.seed,"seed")}function k(v){let D=N.randomSecretKey(v);return{secretKey:D,publicKey:h(D)}}function V(v){return bt(v)&&v.length===i.BYTES}function $(v,D){try{return!!r.fromBytes(v,D)}catch{return!1}}let N={getExtendedPublicKey:d,randomSecretKey:C,isValidSecretKey:V,isValidPublicKey:$,toMontgomery(v){let{y:D}=r.fromBytes(v),F=E.publicKey,R=F===32;if(!R&&F!==57)throw new Error("only defined for 25519 and 448");let x=R?s.div(me+D,me-D):s.div(D-me,D+me);return s.toBytes(x)},toMontgomerySecret(v){let D=E.secretKey;Ve(v,D);let F=e(v.subarray(0,D));return c(F).subarray(0,D)},randomPrivateKey:C,precompute(v=8,D=r.BASE){return D.precompute(v,!1)}};return Object.freeze({keygen:k,getPublicKey:h,sign:m,verify:g,utils:N,Point:r,lengths:E})}function jg(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=$e(e.n,r.nBitLength,!0),o={Fp:t,Fn:n,uvRatio:r.uvRatio},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:o,hash:r.hash,eddsaOpts:s}}function Xg(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function Ed(r){let{CURVE:e,curveOpts:t,hash:n,eddsaOpts:o}=jg(r),s=Gg(e,t),i=Wg(s,n,o);return Xg(r,i)}var Yg=BigInt(0),At=BigInt(1),vd=BigInt(2),Pv=BigInt(3),Zg=BigInt(5),Qg=BigInt(8),Yr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qn={p:Yr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Qg,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Jg(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=Yr,a=r*r%s*r%s,c=ne(a,vd,s)*a%s,l=ne(c,At,s)*r%s,f=ne(l,Zg,s)*l%s,u=ne(f,e,s)*f%s,d=ne(u,t,s)*u%s,h=ne(d,n,s)*d%s,p=ne(h,o,s)*h%s,m=ne(p,o,s)*h%s,w=ne(m,e,s)*f%s;return{pow_p_5_8:ne(w,vd,s)*r%s,b2:a}}function ey(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Lc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Oc(r,e){let t=Yr,n=le(e*e*e,t),o=le(n*n*e,t),s=Jg(r*o).pow_p_5_8,i=le(r*n*s,t),a=le(e*i*i,t),c=i,l=le(i*Lc,t),f=a===r,u=a===le(-r,t),d=a===le(-r*Lc,t);return f&&(i=c),(u||d)&&(i=l),St(i,t)&&(i=le(-i,t)),{isValid:f||u,value:i}}var Xt=$e(Qn.p,{isLE:!0}),ty=$e(Qn.n,{isLE:!0}),ry={...Qn,Fp:Xt,hash:ed,adjustScalarBytes:ey,uvRatio:Oc},Ye=Ed(ry);var Dc=Lc,ny=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),oy=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),sy=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),iy=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Sd=r=>Oc(At,r),ay=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Rc=r=>Ye.Point.Fp.create(vt(r)&ay);function _d(r){let{d:e}=Qn,t=Yr,n=g=>Xt.create(g),o=n(Dc*r*r),s=n((o+At)*sy),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:l}=Oc(s,a),f=n(l*r);St(f,t)||(f=n(-f)),c||(l=f),c||(i=o);let u=n(i*(o-At)*iy-a),d=l*l,h=n((l+l)*a),p=n(u*ny),m=n(At-d),w=n(At+d);return new Ye.Point(n(h*w),n(m*p),n(p*w),n(h*m))}function cy(r){Ue(r,64);let e=Rc(r.subarray(0,32)),t=_d(e),n=Rc(r.subarray(32,64)),o=_d(n);return new Ct(t.add(o))}var Ct=class r extends bs{constructor(e){super(e)}static fromAffine(e){return new r(Ye.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return cy(Q("ristrettoHash",e,64))}static fromBytes(e){Ue(e,32);let{a:t,d:n}=Qn,o=Yr,s=C=>Xt.create(C),i=Rc(e);if(!rd(Xt.toBytes(i),e)||St(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(At+t*a),l=s(At-t*a),f=s(c*c),u=s(l*l),d=s(t*n*f-u),{isValid:h,value:p}=Sd(s(d*u)),m=s(p*l),w=s(p*m*d),g=s((i+i)*m);St(g,o)&&(g=s(-g));let _=s(c*w),E=s(g*_);if(!h||St(E,o)||_===Yg)throw new Error("invalid ristretto255 encoding 2");return new r(new Ye.Point(g,_,At,E))}static fromHex(e){return r.fromBytes(Q("ristrettoHex",e,32))}static msm(e,t){return Xr(r,Ye.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=Yr,i=w=>Xt.create(w),a=i(i(n+t)*i(n-t)),c=i(e*t),l=i(c*c),{value:f}=Sd(i(a*l)),u=i(f*a),d=i(f*c),h=i(u*d*o),p;if(St(o*h,s)){let w=i(t*Dc),g=i(e*Dc);e=w,t=g,p=i(u*oy)}else p=d;St(e*h,s)&&(t=i(-t));let m=i((n-t)*p);return St(m,s)&&(m=i(-m)),Xt.toBytes(m)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=l=>Xt.create(l),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Ct.BASE=new Ct(Ye.Point.BASE);Ct.ZERO=new Ct(Ye.Point.ZERO);Ct.Fp=Xt;Ct.Fn=ty;var Jn=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},eo=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ws=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ad={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ws("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Ke=Ad;var xs=32,to=64,kc=32;var Zr,Cd=(async()=>{try{return await Ke.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Id(){let r=Ye.utils.randomPrivateKey(),e=Ye.getPublicKey(r);return{privateKey:hy(r,e),publicKey:e}}async function ly(r,e){let t;r.length===to?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:K(r.subarray(32),"base64url"),d:K(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Ke.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Ke.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function uy(r,e){let t=r.subarray(0,kc);return Ye.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function Td(r,e){return Zr==null&&(Zr=await Cd),Zr?ly(r,e):uy(r,e)}async function fy(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ke.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ke.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function dy(r,e,t){return Ye.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Pd(r,e,t){return Zr==null&&(Zr=await Cd),Zr?fy(r,e,t):dy(r,e,t)}function hy(r,e){let t=new Uint8Array(to);for(let n=0;n<kc;n++)t[n]=r[n],t[kc+n]=e[n];return t}function Qr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ro=class{type="Ed25519";raw;constructor(e){this.raw=vs(e,xs)}toMultihash(){return Je.digest(je(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Pd(this.raw,t,e);return Qr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},Es=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=vs(e,to),this.publicKey=new ro(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=Td(this.raw,e);return Qr(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function Nc(r){return r=vs(r,xs),new ro(r)}async function Dd(){let{privateKey:r,publicKey:e}=Id();return new Es(r,e)}function vs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new I(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var py=Math.pow(2,7),my=Math.pow(2,14),gy=Math.pow(2,21),Mc=Math.pow(2,28),Bc=Math.pow(2,35),Fc=Math.pow(2,42),Uc=Math.pow(2,49),W=128,_e=127;function ge(r){if(r<py)return 1;if(r<my)return 2;if(r<gy)return 3;if(r<Mc)return 4;if(r<Bc)return 5;if(r<Fc)return 6;if(r<Uc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Jr(r,e,t=0){switch(ge(r)){case 8:e[t++]=r&255|W,r/=128;case 7:e[t++]=r&255|W,r/=128;case 6:e[t++]=r&255|W,r/=128;case 5:e[t++]=r&255|W,r/=128;case 4:e[t++]=r&255|W,r>>>=7;case 3:e[t++]=r&255|W,r>>>=7;case 2:e[t++]=r&255|W,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function yy(r,e,t=0){switch(ge(r)){case 8:e.set(t++,r&255|W),r/=128;case 7:e.set(t++,r&255|W),r/=128;case 6:e.set(t++,r&255|W),r/=128;case 5:e.set(t++,r&255|W),r/=128;case 4:e.set(t++,r&255|W),r>>>=7;case 3:e.set(t++,r&255|W),r>>>=7;case 2:e.set(t++,r&255|W),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Kc(r,e){let t=r[e],n=0;if(n+=t&_e,t<W||(t=r[e+1],n+=(t&_e)<<7,t<W)||(t=r[e+2],n+=(t&_e)<<14,t<W)||(t=r[e+3],n+=(t&_e)<<21,t<W)||(t=r[e+4],n+=(t&_e)*Mc,t<W)||(t=r[e+5],n+=(t&_e)*Bc,t<W)||(t=r[e+6],n+=(t&_e)*Fc,t<W)||(t=r[e+7],n+=(t&_e)*Uc,t<W))return n;throw new RangeError("Could not decode varint")}function by(r,e){let t=r.get(e),n=0;if(n+=t&_e,t<W||(t=r.get(e+1),n+=(t&_e)<<7,t<W)||(t=r.get(e+2),n+=(t&_e)<<14,t<W)||(t=r.get(e+3),n+=(t&_e)<<21,t<W)||(t=r.get(e+4),n+=(t&_e)*Mc,t<W)||(t=r.get(e+5),n+=(t&_e)*Bc,t<W)||(t=r.get(e+6),n+=(t&_e)*Fc,t<W)||(t=r.get(e+7),n+=(t&_e)*Uc,t<W))return n;throw new RangeError("Could not decode varint")}function Yt(r,e,t=0){return e==null&&(e=Se(ge(r))),e instanceof Uint8Array?Jr(r,e,t):yy(r,e,t)}function fr(r,e=0){return r instanceof Uint8Array?Kc(r,e):by(r,e)}var qc=new Float32Array([-0]),Zt=new Uint8Array(qc.buffer);function Rd(r,e,t){qc[0]=r,e[t]=Zt[0],e[t+1]=Zt[1],e[t+2]=Zt[2],e[t+3]=Zt[3]}function Od(r,e){return Zt[0]=r[e],Zt[1]=r[e+1],Zt[2]=r[e+2],Zt[3]=r[e+3],qc[0]}var Vc=new Float64Array([-0]),Ae=new Uint8Array(Vc.buffer);function kd(r,e,t){Vc[0]=r,e[t]=Ae[0],e[t+1]=Ae[1],e[t+2]=Ae[2],e[t+3]=Ae[3],e[t+4]=Ae[4],e[t+5]=Ae[5],e[t+6]=Ae[6],e[t+7]=Ae[7]}function Nd(r,e){return Ae[0]=r[e],Ae[1]=r[e+1],Ae[2]=r[e+2],Ae[3]=r[e+3],Ae[4]=r[e+4],Ae[5]=r[e+5],Ae[6]=r[e+6],Ae[7]=r[e+7],Vc[0]}var wy=BigInt(Number.MAX_SAFE_INTEGER),xy=BigInt(Number.MIN_SAFE_INTEGER),ze=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return dr;if(e<wy&&e>xy)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Md&&(o=0n,++n>Md&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return dr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):dr}},dr=new ze(0,0);dr.toBigInt=function(){return 0n};dr.zzEncode=dr.zzDecode=function(){return this};dr.length=function(){return 1};var Md=4294967296n;function Bd(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Fd(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function $c(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function nt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ss(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var zc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,nt(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw nt(this,4);return Ss(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw nt(this,4);return Ss(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw nt(this,4);let e=Od(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw nt(this,4);let e=Nd(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw nt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Fd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw nt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw nt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ze(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw nt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw nt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw nt(this,8);let e=Ss(this.buf,this.pos+=4),t=Ss(this.buf,this.pos+=4);return new ze(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Kc(this.buf,this.pos);return this.pos+=ge(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Hc(r){return new zc(r instanceof Uint8Array?r:r.subarray())}function Oe(r,e,t){let n=Hc(r);return e.decode(n,void 0,t)}function Gc(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Se(i);o+i>e&&(n=Se(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var hr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Wc(){}var Xc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ey=Gc();function vy(r){return globalThis.Buffer!=null?Se(r):Ey(r)}var so=class{len;head;tail;states;constructor(){this.len=0,this.head=new hr(Wc,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new hr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Yc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(_s,10,ze.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ze.fromBigInt(e);return this._push(_s,t.length(),t)}uint64Number(e){return this._push(Jr,ge(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=ze.fromBigInt(e).zzEncode();return this._push(_s,t.length(),t)}sint64Number(e){let t=ze.fromNumber(e).zzEncode();return this._push(_s,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(jc,1,e?1:0)}fixed32(e){return this._push(oo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ze.fromBigInt(e);return this._push(oo,4,t.lo)._push(oo,4,t.hi)}fixed64Number(e){let t=ze.fromNumber(e);return this._push(oo,4,t.lo)._push(oo,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Rd,4,e)}double(e){return this._push(kd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(jc,1,0):this.uint32(t)._push(_y,t,e)}string(e){let t=Bd(e);return t!==0?this.uint32(t)._push($c,t,e):this._push(jc,1,0)}fork(){return this.states=new Xc(this),this.head=this.tail=new hr(Wc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new hr(Wc,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=vy(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function jc(r,e,t){e[t]=r&255}function Sy(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Yc=class extends hr{next;constructor(e,t){super(Sy,e,t),this.next=void 0}};function _s(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function oo(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function _y(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(so.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Ay,e,r),this},so.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Cy,e,r),this});function Ay(r,e,t){e.set(r,t)}function Cy(r,e,t){r.length<40?$c(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(T(r),t)}function Zc(){return new so}function ke(r,e){let t=Zc();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var en;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(en||(en={}));function As(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Qc(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return As("enum",en.VARINT,t,n)}function Ne(r,e){return As("message",en.LENGTH_DELIMITED,r,e)}var pr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},io=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var fe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(fe||(fe={}));var Jc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Jc||(Jc={}));(function(r){r.codec=()=>Qc(Jc)})(fe||(fe={}));var ut;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Oe(t,r.codec(),n)})(ut||(ut={}));var el;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Oe(t,r.codec(),n)})(el||(el={}));function tn(r){if(isNaN(r)||r<=0)throw new I("random bytes length must be a Number bigger than 0");return Vt(r)}var co={};Fe(co,{MAX_RSA_KEY_SIZE:()=>tl,generateRSAKeyPair:()=>ul,jwkToJWKKeyPair:()=>zd,jwkToPkcs1:()=>Ly,jwkToPkix:()=>sl,jwkToRSAPrivateKey:()=>ll,pkcs1MessageToJwk:()=>nl,pkcs1MessageToRSAPrivateKey:()=>il,pkcs1ToJwk:()=>Py,pkcs1ToRSAPrivateKey:()=>$d,pkixMessageToJwk:()=>ol,pkixMessageToRSAPublicKey:()=>cl,pkixToJwk:()=>Dy,pkixToRSAPublicKey:()=>al});var Cs=hs;var rn=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=co.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}verify(e,t,n){return Vd(this.jwk,t,e,n)}},ao=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=co.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}sign(e,t){return qd(this.jwk,e,t)}};var tl=8192,rl=18,Iy=1062,Ty=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Py(r){let e=gt(r);return nl(e)}function nl(r){return{n:K(r[1],"base64url"),e:K(r[2],"base64url"),d:K(r[3],"base64url"),p:K(r[4],"base64url"),q:K(r[5],"base64url"),dp:K(r[6],"base64url"),dq:K(r[7],"base64url"),qi:K(r[8],"base64url"),kty:"RSA"}}function Ly(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new I("JWK was missing components");return tt([Le(Uint8Array.from([0])),Le(T(r.n,"base64url")),Le(T(r.e,"base64url")),Le(T(r.d,"base64url")),Le(T(r.p,"base64url")),Le(T(r.q,"base64url")),Le(T(r.dp,"base64url")),Le(T(r.dq,"base64url")),Le(T(r.qi,"base64url"))]).subarray()}function Dy(r){let e=gt(r,{offset:0});return ol(e)}function ol(r){let e=gt(r[1],{offset:0});return{kty:"RSA",n:K(e[0],"base64url"),e:K(e[1],"base64url")}}function sl(r){if(r.n==null||r.e==null)throw new I("JWK was missing components");return tt([Ty,Vn(tt([Le(T(r.n,"base64url")),Le(T(r.e,"base64url"))]))]).subarray()}function $d(r){let e=gt(r);return il(e)}function il(r){let e=nl(r);return ll(e)}function al(r,e){if(r.byteLength>=Iy)throw new Nr("Key size is too large");let t=gt(r,{offset:0});return cl(t,r,e)}function cl(r,e,t){let n=ol(r);if(t==null){let o=Cs(ut.encode({Type:fe.RSA,Data:e}));t=ct(rl,o)}return new rn(n,t)}function ll(r){if(Gd(r)>tl)throw new I("Key size is too large");let e=zd(r),t=Cs(ut.encode({Type:fe.RSA,Data:sl(e.publicKey)})),n=ct(rl,t);return new ao(e.privateKey,new rn(e.publicKey,n))}async function ul(r){if(r>tl)throw new I("Key size is too large");let e=await Hd(r),t=Cs(ut.encode({Type:fe.RSA,Data:sl(e.publicKey)})),n=ct(rl,t);return new ao(e.privateKey,new rn(e.publicKey,n))}function zd(r){if(r==null)throw new I("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Hd(r,e){let t=await Ke.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Ry(t,e);return{privateKey:n[0],publicKey:n[1]}}async function qd(r,e,t){let n=await Ke.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ke.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Vd(r,e,t,n){let o=await Ke.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ke.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function Ry(r,e){if(r.privateKey==null||r.publicKey==null)throw new I("Private and public key are required");let t=await Promise.all([Ke.get().subtle.exportKey("jwk",r.privateKey),Ke.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Gd(r){if(r.kty!=="RSA")throw new I("invalid key type");if(r.n==null)throw new I("invalid key modulus");return T(r.n,"base64url").length*8}var Is=class extends $r{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ls(e);let n=zn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),wt(s)}update(e){return zr(this),this.iHash.update(e),this}digestInto(e){zr(this),Ue(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},fl=(r,e,t)=>new Is(r,e).update(t).digest();fl.create=(r,e)=>new Is(r,e);var Wd=(r,e)=>(r+(r>=0?e:-e)/jd)/e;function Oy(r,e,t){let[[n,o],[s,i]]=e,a=Wd(i*r,t),c=Wd(-o*r,t),l=r-a*n-c*s,f=-a*o-c*i,u=l<Tt,d=f<Tt;u&&(l=-l),d&&(f=-f);let h=Gt(Math.ceil(ms(t)/2))+on;if(l<Tt||l>=h||f<Tt||f>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:l,k2neg:d,k2:f}}function hl(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function dl(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Et(t.lowS,"lowS"),Et(t.prehash,"prehash"),t.format!==void 0&&hl(t.format),t}var pl=class extends Error{constructor(e=""){super(e)}},It={Err:pl,_tlv:{encode:(r,e)=>{let{Err:t}=It;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=jn(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?jn(o.length/2|128):"";return jn(r)+s+o+e},decode(r,e){let{Err:t}=It,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let f of l)i=i<<8|f;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=It;if(r<Tt)throw new e("integer: negative integers are not allowed");let t=jn(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=It;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Hr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=It,o=Q("signature",r),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:f}=n.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=It,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Tt=BigInt(0),on=BigInt(1),jd=BigInt(2),Ts=BigInt(3),ky=BigInt(4);function nn(r,e){let{BYTES:t}=r,n;if(typeof e=="bigint")n=e;else{let o=Q("private key",e);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Ny(r,e={}){let t=ys("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Wt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Yd(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(R,x,y){let{x:b,y:S}=x.toAffine(),A=n.toBytes(b);if(Et(y,"isCompressed"),y){f();let O=!n.isOdd(S);return De(Xd(O),A)}else return De(Uint8Array.of(4),A,n.toBytes(S))}function d(R){Ve(R,void 0,"Point");let{publicKey:x,publicKeyUncompressed:y}=l,b=R.length,S=R[0],A=R.subarray(1);if(b===x&&(S===2||S===3)){let O=n.fromBytes(A);if(!n.isValid(O))throw new Error("bad point: is not on curve, wrong x");let P=m(O),L;try{L=n.sqrt(P)}catch(oe){let J=oe instanceof Error?": "+oe.message:"";throw new Error("bad point: is not on curve, sqrt error"+J)}f();let B=n.isOdd(L);return(S&1)===1!==B&&(L=n.neg(L)),{x:O,y:L}}else if(b===y&&S===4){let O=n.BYTES,P=n.fromBytes(A.subarray(0,O)),L=n.fromBytes(A.subarray(O,O*2));if(!w(P,L))throw new Error("bad point: is not on curve");return{x:P,y:L}}else throw new Error(`bad point: got length ${b}, expected compressed=${x} or uncompressed=${y}`)}let h=e.toBytes||u,p=e.fromBytes||d;function m(R){let x=n.sqr(R),y=n.mul(x,R);return n.add(n.add(y,n.mul(R,s.a)),s.b)}function w(R,x){let y=n.sqr(x),b=m(R);return n.eql(y,b)}if(!w(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(s.a,Ts),ky),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,_)))throw new Error("bad curve params: a or b");function E(R,x,y=!1){if(!n.isValid(x)||y&&n.is0(x))throw new Error(`bad point coordinate ${R}`);return x}function C(R){if(!(R instanceof v))throw new Error("ProjectivePoint expected")}function k(R){if(!c||!c.basises)throw new Error("no endo");return Oy(R,c.basises,o.ORDER)}let V=Gr((R,x)=>{let{X:y,Y:b,Z:S}=R;if(n.eql(S,n.ONE))return{x:y,y:b};let A=R.is0();x==null&&(x=A?n.ONE:n.inv(S));let O=n.mul(y,x),P=n.mul(b,x),L=n.mul(S,x);if(A)return{x:n.ZERO,y:n.ZERO};if(!n.eql(L,n.ONE))throw new Error("invZ was invalid");return{x:O,y:P}}),$=Gr(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x,y}=R.toAffine();if(!n.isValid(x)||!n.isValid(y))throw new Error("bad point: x or y not field elements");if(!w(x,y))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(R,x,y,b,S){return y=new v(n.mul(y.X,R),y.Y,y.Z),x=Zn(b,x),y=Zn(S,y),x.add(y)}class v{constructor(x,y,b){this.X=E("x",x),this.Y=E("y",y,!0),this.Z=E("z",b),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){let{x:y,y:b}=x||{};if(!x||!n.isValid(y)||!n.isValid(b))throw new Error("invalid affine point");if(x instanceof v)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(b)?v.ZERO:new v(y,b,n.ONE)}static fromBytes(x){let y=v.fromAffine(p(Ve(x,void 0,"point")));return y.assertValidity(),y}static fromHex(x){return v.fromBytes(Q("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,y=!0){return F.createCache(this,x),y||this.multiply(Ts),this}assertValidity(){$(this)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){C(x);let{X:y,Y:b,Z:S}=this,{X:A,Y:O,Z:P}=x,L=n.eql(n.mul(y,P),n.mul(A,S)),B=n.eql(n.mul(b,P),n.mul(O,S));return L&&B}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:y}=s,b=n.mul(y,Ts),{X:S,Y:A,Z:O}=this,P=n.ZERO,L=n.ZERO,B=n.ZERO,q=n.mul(S,S),oe=n.mul(A,A),J=n.mul(O,O),G=n.mul(S,A);return G=n.add(G,G),B=n.mul(S,O),B=n.add(B,B),P=n.mul(x,B),L=n.mul(b,J),L=n.add(P,L),P=n.sub(oe,L),L=n.add(oe,L),L=n.mul(P,L),P=n.mul(G,P),B=n.mul(b,B),J=n.mul(x,J),G=n.sub(q,J),G=n.mul(x,G),G=n.add(G,B),B=n.add(q,q),q=n.add(B,q),q=n.add(q,J),q=n.mul(q,G),L=n.add(L,q),J=n.mul(A,O),J=n.add(J,J),q=n.mul(J,G),P=n.sub(P,q),B=n.mul(J,oe),B=n.add(B,B),B=n.add(B,B),new v(P,L,B)}add(x){C(x);let{X:y,Y:b,Z:S}=this,{X:A,Y:O,Z:P}=x,L=n.ZERO,B=n.ZERO,q=n.ZERO,oe=s.a,J=n.mul(s.b,Ts),G=n.mul(y,A),se=n.mul(b,O),he=n.mul(S,P),Be=n.add(y,b),ie=n.add(A,O);Be=n.mul(Be,ie),ie=n.add(G,se),Be=n.sub(Be,ie),ie=n.add(y,S);let ve=n.add(A,P);return ie=n.mul(ie,ve),ve=n.add(G,he),ie=n.sub(ie,ve),ve=n.add(b,S),L=n.add(O,P),ve=n.mul(ve,L),L=n.add(se,he),ve=n.sub(ve,L),q=n.mul(oe,ie),L=n.mul(J,he),q=n.add(L,q),L=n.sub(se,q),q=n.add(se,q),B=n.mul(L,q),se=n.add(G,G),se=n.add(se,G),he=n.mul(oe,he),ie=n.mul(J,ie),se=n.add(se,he),he=n.sub(G,he),he=n.mul(oe,he),ie=n.add(ie,he),G=n.mul(se,ie),B=n.add(B,G),G=n.mul(ve,ie),L=n.mul(Be,L),L=n.sub(L,G),G=n.mul(Be,se),q=n.mul(ve,q),q=n.add(q,G),new v(L,B,q)}subtract(x){return this.add(x.negate())}is0(){return this.equals(v.ZERO)}multiply(x){let{endo:y}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let b,S,A=O=>F.cached(this,O,P=>_t(v,P));if(y){let{k1neg:O,k1:P,k2neg:L,k2:B}=k(x),{p:q,f:oe}=A(P),{p:J,f:G}=A(B);S=oe.add(G),b=N(y.beta,q,J,O,L)}else{let{p:O,f:P}=A(x);b=O,S=P}return _t(v,[b,S])[0]}multiplyUnsafe(x){let{endo:y}=e,b=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===Tt||b.is0())return v.ZERO;if(x===on)return b;if(F.hasCache(this))return this.multiply(x);if(y){let{k1neg:S,k1:A,k2neg:O,k2:P}=k(x),{p1:L,p2:B}=xd(v,b,A,P);return N(y.beta,L,B,S,O)}else return F.unsafe(b,x)}multiplyAndAddUnsafe(x,y,b){let S=this.multiplyUnsafe(y).add(x.multiplyUnsafe(b));return S.is0()?void 0:S}toAffine(x){return V(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return i===on?!0:x?x(v,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return i===on?this:x?x(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return Et(x,"isCompressed"),this.assertValidity(),h(v,this,x)}toHex(x=!0){return Xe(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return _t(v,x)}static msm(x,y){return Xr(v,o,x,y)}static fromPrivateKey(x){return v.BASE.multiply(nn(o,x))}}v.BASE=new v(s.Gx,s.Gy,n.ONE),v.ZERO=new v(n.ZERO,n.ONE,n.ZERO),v.Fp=n,v.Fn=o;let D=o.BITS,F=new jr(v,e.endo?Math.ceil(D/2):D);return v.BASE.precompute(8),v}function Xd(r){return Uint8Array.of(r?2:3)}function Yd(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function My(r,e={}){let{Fn:t}=r,n=e.randomBytes||Vt,o=Object.assign(Yd(r.Fp,t),{seed:_c(t.ORDER)});function s(h){try{return!!nn(t,h)}catch{return!1}}function i(h,p){let{publicKey:m,publicKeyUncompressed:w}=o;try{let g=h.length;return p===!0&&g!==m||p===!1&&g!==w?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return Ac(Ve(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(nn(t,h)).toBytes(p)}function l(h){let p=a(h);return{secretKey:p,publicKey:c(p)}}function f(h){if(typeof h=="bigint")return!1;if(h instanceof r)return!0;let{secretKey:p,publicKey:m,publicKeyUncompressed:w}=o;if(t.allowedLengths||p===m)return;let g=Q("key",h).length;return g===m||g===w}function u(h,p,m=!0){if(f(h)===!0)throw new Error("first arg must be private key");if(f(p)===!1)throw new Error("second arg must be public key");let w=nn(t,h);return r.fromHex(p).multiply(w).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>nn(t,h),precompute(h=8,p=r.BASE){return p.precompute(h,!1)}},lengths:o})}function By(r,e,t={}){ls(e),Wt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||Vt,o=t.hmac||((y,...b)=>fl(e,y,De(...b))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h}=My(r,t),p={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function w(y){let b=a>>on;return y>b}function g(y,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return b}function _(y,b){hl(b);let S=h.signature,A=b==="compact"?S:b==="recovered"?S+1:void 0;return Ve(y,A,`${b} signature`)}class E{constructor(b,S,A){this.r=g("r",b),this.s=g("s",S),A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(b,S=m){_(b,S);let A;if(S==="der"){let{r:B,s:q}=It.toSig(Ve(b));return new E(B,q)}S==="recovered"&&(A=b[0],S="compact",b=b.subarray(1));let O=i.BYTES,P=b.subarray(0,O),L=b.subarray(O,O*2);return new E(i.fromBytes(P),i.fromBytes(L),A)}static fromHex(b,S){return this.fromBytes(ir(b),S)}addRecoveryBit(b){return new E(this.r,this.s,b)}recoverPublicKey(b){let S=s.ORDER,{r:A,s:O,recovery:P}=this;if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");if(a*jd<S&&P>1)throw new Error("recovery id is ambiguous for h>1 curve");let B=P===2||P===3?A+a:A;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");let q=s.toBytes(B),oe=r.fromBytes(De(Xd((P&1)===0),q)),J=i.inv(B),G=k(Q("msgHash",b)),se=i.create(-G*J),he=i.create(O*J),Be=r.BASE.multiplyUnsafe(se).add(oe.multiplyUnsafe(he));if(Be.is0())throw new Error("point at infinify");return Be.assertValidity(),Be}hasHighS(){return w(this.s)}toBytes(b=m){if(hl(b),b==="der")return ir(It.hexFromSig(this));let S=i.toBytes(this.r),A=i.toBytes(this.s);if(b==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return De(Uint8Array.of(this.recovery),S,A)}return De(S,A)}toHex(b){return Xe(this.toBytes(b))}assertValidity(){}static fromCompact(b){return E.fromBytes(Q("sig",b),"compact")}static fromDER(b){return E.fromBytes(Q("sig",b),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Xe(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Xe(this.toBytes("compact"))}}let C=t.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let S=Hr(b),A=b.length*8-c;return A>0?S>>BigInt(A):S},k=t.bits2int_modN||function(b){return i.create(C(b))},V=Gt(c);function $(y){return Xn("num < 2^"+c,y,Tt,V),i.toBytes(y)}function N(y,b){return Ve(y,void 0,"message"),b?Ve(e(y),void 0,"prehashed message"):y}function v(y,b,S){if(["recovered","canonical"].some(se=>se in S))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:O,extraEntropy:P}=dl(S,p);y=N(y,O);let L=k(y),B=nn(i,b),q=[$(B),$(L)];if(P!=null&&P!==!1){let se=P===!0?n(h.secretKey):P;q.push(Q("extraEntropy",se))}let oe=De(...q),J=L;function G(se){let he=C(se);if(!i.isValidNot0(he))return;let Be=i.inv(he),ie=r.BASE.multiply(he).toAffine(),ve=i.create(ie.x);if(ve===Tt)return;let Go=i.create(Be*i.create(J+ve*B));if(Go===Tt)return;let ef=(ie.x===ve?0:2)|Number(ie.y&on),tf=Go;return A&&w(Go)&&(tf=i.neg(Go),ef^=1),new E(ve,tf,ef)}return{seed:oe,k2sig:G}}function D(y,b,S={}){y=Q("message",y);let{seed:A,k2sig:O}=v(y,b,S);return od(e.outputLen,i.BYTES,o)(A,O)}function F(y){let b,S=typeof y=="string"||bt(y),A=!S&&y!==null&&typeof y=="object"&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!S&&!A)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(A)b=new E(y.r,y.s);else if(S){try{b=E.fromBytes(Q("sig",y),"der")}catch(O){if(!(O instanceof It.Err))throw O}if(!b)try{b=E.fromBytes(Q("sig",y),"compact")}catch{return!1}}return b||!1}function R(y,b,S,A={}){let{lowS:O,prehash:P,format:L}=dl(A,p);if(S=Q("publicKey",S),b=N(Q("message",b),P),"strict"in A)throw new Error("options.strict was renamed to lowS");let B=L===void 0?F(y):E.fromBytes(Q("sig",y),L);if(B===!1)return!1;try{let q=r.fromBytes(S);if(O&&B.hasHighS())return!1;let{r:oe,s:J}=B,G=k(b),se=i.inv(J),he=i.create(G*se),Be=i.create(oe*se),ie=r.BASE.multiplyUnsafe(he).add(q.multiplyUnsafe(Be));return ie.is0()?!1:i.create(ie.x)===oe}catch{return!1}}function x(y,b,S={}){let{prehash:A}=dl(S,p);return b=N(b,A),E.fromBytes(y,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:u,utils:d,lengths:h,Point:r,sign:D,verify:R,recoverPublicKey:x,Signature:E,hash:e})}function Fy(r){let e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=$e(e.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),s={Fp:t,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:s}}function Uy(r){let{CURVE:e,curveOpts:t}=Fy(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:t,hash:r.hash,ecdsaOpts:n}}function Ky(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,gs(t.Fn.ORDER,t.Fn.BITS))})}function Zd(r){let{CURVE:e,curveOpts:t,hash:n,ecdsaOpts:o}=Uy(r),s=Ny(e,t),i=By(s,n,o);return Ky(r,i)}function Qd(r,e){let t=n=>Zd({...r,hash:n});return{...t(e),create:t}}var gl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},qy={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Jd=BigInt(2);function Vy(r){let e=gl.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,f=l*l*r%e,u=ne(f,t,e)*f%e,d=ne(u,t,e)*f%e,h=ne(d,Jd,e)*l%e,p=ne(h,o,e)*h%e,m=ne(p,s,e)*p%e,w=ne(m,a,e)*m%e,g=ne(w,c,e)*w%e,_=ne(g,a,e)*m%e,E=ne(_,t,e)*f%e,C=ne(E,i,e)*p%e,k=ne(C,n,e)*l%e,V=ne(k,Jd,e);if(!ml.eql(ml.sqr(V),r))throw new Error("Cannot find square root");return V}var ml=$e(gl.p,{sqrt:Vy}),ot=Qd({...gl,Fp:ml,lowS:!0,endo:qy},hs);function eh(r,e,t){let n=Vr.digest(e instanceof Uint8Array?e:e.subarray());if(Qr(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),ot.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Jn(String(o))});try{return ot.sign(n.digest,r).toDERRawBytes()}catch(o){throw new Jn(String(o))}}function th(r,e,t,n){let o=Vr.digest(t instanceof Uint8Array?t:t.subarray());if(Qr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ot.verify(e,s,r))).catch(s=>{throw s.name==="AbortError"?s:new eo(String(s))});try{return n?.signal?.throwIfAborted(),ot.verify(e,o.digest,r)}catch(s){throw new eo(String(s))}}var lo=class{type="secp256k1";raw;_key;constructor(e){this._key=oh(e),this.raw=rh(this._key)}toMultihash(){return Je.digest(je(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}verify(e,t,n){return th(this._key,t,e,n)}},Ps=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=nh(e),this.publicKey=new lo(t??sh(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Y(this.raw,e.raw)}sign(e,t){return eh(this.raw,e,t)}};function yl(r){return new lo(r)}async function ih(){let r=$y();return new Ps(r)}function rh(r){return ot.ProjectivePoint.fromHex(r).toRawBytes(!0)}function nh(r){try{return ot.getPublicKey(r,!0),r}catch(e){throw new Rn(String(e))}}function oh(r){try{return ot.ProjectivePoint.fromHex(r),r}catch(e){throw new Nr(String(e))}}function sh(r){try{return ot.getPublicKey(r,!0)}catch(e){throw new Rn(String(e))}}function $y(){return ot.utils.randomPrivateKey()}async function ah(r,e){if(r==="Ed25519")return Dd();if(r==="secp256k1")return ih();if(r==="RSA")return ul(zy(e));if(r==="ECDSA")return Uf(Hy(e));throw new Ft}function sn(r,e){let{Type:t,Data:n}=ut.decode(r),o=n??new Uint8Array;switch(t){case fe.RSA:return al(o,e);case fe.Ed25519:return Nc(o);case fe.secp256k1:return yl(o);case fe.ECDSA:return uc(o);default:throw new Ft}}function ch(r){let{Type:e,Data:t}=ut.decode(r.digest),n=t??new Uint8Array;switch(e){case fe.Ed25519:return Nc(n);case fe.secp256k1:return yl(n);case fe.ECDSA:return uc(n);default:throw new Ft}}function je(r){return ut.encode({Type:fe[r.type],Data:r.raw})}function zy(r){return r==null?2048:parseInt(r,10)}function Hy(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new I("Unsupported curve, should be P-256, P-384 or P-521")}var lh=Symbol.for("nodejs.util.inspect.custom"),Gy=114,uo=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[rs]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(Gy,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Y(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Y(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[lh](){return`PeerId(${this.toString()})`}},fo=class extends uo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ho=class extends uo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},po=class extends uo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Wy=2336,mo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Je.digest(T(this.url))}[lh](){return`PeerId(${this.url})`}[rs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(Wy,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=K(e)),e.toString()===this.toString())}};var jy=114,uh=2336;function ft(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=mt(ee.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return go(ue.parse(r));if(e==null)throw new I('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=mt(e.decode(r))}return an(t)}function bl(r){if(r.type==="Ed25519")return new ho({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new po({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new fo({multihash:r.toCID().multihash,publicKey:r});throw new Ft}function fh(r){return bl(r.publicKey)}function an(r){if(Yy(r))return new fo({multihash:r});if(Xy(r))try{let e=ch(r);if(e.type==="Ed25519")return new ho({multihash:r,publicKey:e});if(e.type==="secp256k1")return new po({multihash:r,publicKey:e})}catch{let t=K(r.digest);return new mo(new URL(t))}throw new Xo("Supplied PeerID Multihash is invalid")}function go(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==jy&&r.code!==uh)throw new jo("Supplied PeerID CID is invalid");if(r.code===uh){let e=K(r.multihash.digest);return new mo(new URL(e))}return an(r.multihash)}function Xy(r){return r.code===Je.code}function Yy(r){return r.code===Vr.code}var wl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},dh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},hh=new globalThis.TextEncoder;function Zy(r,e){let t=wl[e],n=dh[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Qy(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=wl[e],o=dh[e],s=r;for(;s.length>0;){let i=hh.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function xl(r,{size:e=32,utf8Buffer:t}={}){if(!wl[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Qy(r,e,t);r=hh.encode(r)}return Zy(r,e)}var yo={hash:r=>Number(xl(r,{size:32})),hashV:(r,e)=>Jy(yo.hash(r,e))};function Jy(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),T(e,"base16")}var El=64,st=class{fp;h;seed;constructor(e,t,n,o=2){if(o>El)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ce(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Y(this.fp,e.fp):!1}};function mr(r,e){return Math.floor(Math.random()*(e-r))+r}var gr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof st))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof st))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof st))throw new TypeError("Invalid Fingerprint");let t=mr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof st))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var e0=500,bo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??yo,this.seed=e.seed??mr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=T(e));let t=new st(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new gr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new gr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[mr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new gr(this.bucketSize));for(let a=0;a<e0;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new gr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=T(e));let t=new st(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=T(e));let t=new st(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},t0={1:.5,2:.84,4:.95,8:.98};function r0(r=.001){return r>.002?2:r>1e-5?4:8}function ph(r,e=.001){let t=r0(e),n=t0[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),El);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Ls=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??yo,this.seed=e.seed??mr(0,Math.pow(2,10)),this.filterSeries=[new bo({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=T(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new bo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function wo(r,e=.001,t){return new Ls({...ph(r,e),...t??{}})}function z(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new I(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var Ds=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let d=Number.parseInt(u,e);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=e,s+=f,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var mh=45,n0=15,cn=new Ds;function Rs(r){if(!(r.length>n0))return cn.new(r).parseWith(()=>cn.readIPv4Addr())}function Os(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>mh))return cn.new(r).parseWith(()=>cn.readIPv6Addr())}function ln(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>mh)return;let t=cn.new(r).parseWith(()=>cn.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function gh(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function yh(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function vl(r){switch(r.length){case yr:return r.join(".");case br:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function bh(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function wh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var yr=4,br=16,$S=parseInt("0xFFFF",16),o0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function xo(r,e){e.length===br&&r.length===yr&&gh(e,0,11)&&(e=e.slice(12)),e.length===yr&&r.length===br&&yh(r,o0,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function xh(r,e){if(typeof e=="string"&&(e=ln(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Sl(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=yr,o=Rs(e);if(o==null&&(n=br,o=Os(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=_l(s,8*n);return{network:xo(o,i),mask:i}}function _l(r,e){if(e!==8*yr&&e!==8*br)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var un=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Sl(e));else{let n=ln(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=ln(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=_l(o,8*n.length);this.network=xo(n,this.mask)}}contains(e){return xh({network:this.network,mask:this.mask},e)}toString(){let e=bh(this.mask),t=e!==-1?String(e):wh(this.mask);return vl(this.network)+"/"+t}};function Eh(r){try{let e=z(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function vh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Eo(r){try{let e=z(r);switch(e.type){case"ip4":case"ip6":return vh(e.host);default:return!1}}catch{return!1}}function xe(r){try{return z(r),!0}catch{return!1}}function it(r){return!!Rs(r)}function ks(r){return!!Os(r)}var _h=Da(Sh(),1),s0=["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"],i0=s0.map(r=>new _h.Netmask(r));function Al(r){for(let e of i0)if(e.contains(r))return!0;return!1}function a0(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function c0(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Al(o)}function l0(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function u0(r){let e=r.split(":"),t=e[e.length-1];return Al(t)}function f0(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function fn(r){if(it(r))return Al(r);if(a0(r))return c0(r);if(l0(r))return u0(r);if(ks(r))return f0(r)}function Pt(r){try{let e=z(r);switch(e.type){case"ip4":case"ip6":return fn(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function ye(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ns=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},dn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ns(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 t=this.head;this.head=t.next=new Ns(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Cl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function hn(r={}){return d0(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function d0(r,e){e=e??{};let t=e.onEnd,n=new dn,o,s,i,a=ye(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,g)=>{s=_=>{s=null,n.push(_);try{w(r(n))}catch(E){g(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ye()})}},l=w=>s!=null?s(w):(n.push(w),o),f=w=>(n=new dn,s!=null?s({error:w}):(n.push({error:w}),o)),u=w=>{if(i)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},d=w=>i?o:(i=!0,w!=null?f(w):l({done:!0})),h=()=>(n=new dn,d(),{done:!0}),p=w=>(d(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:u,end:d,get readableLength(){return n.size},onEmpty:async w=>{let g=w?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let _,E;g!=null&&(_=new Promise((C,k)=>{E=()=>{k(new Cl)},g.addEventListener("abort",E)}));try{await Promise.race([a.promise,_])}finally{E!=null&&g!=null&&g?.removeEventListener("abort",E)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(w){return m.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(w){return m.end(w),t!=null&&(t(w),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:w=>m.onEmpty(w)},o}var So=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Il=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Ah=r=>globalThis.DOMException===void 0?new Il(r):new DOMException(r),Ch=r=>{let e=r.reason===void 0?Ah("This operation was aborted."):r.reason;return e instanceof Error?e:Ah(e)};function _o(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,l=new Promise((f,u)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&u(Ch(h)),a=()=>{u(Ch(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(f,u);return}let d=new So;i=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?u(o):(d.message=o??`Promise timed out after ${t} milliseconds`,u(d))},t),(async()=>{try{f(await r)}catch(h){u(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var h0=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function p0(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:f}=h0(r),u=(...h)=>{let p=t.multiArgs?h:h[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(n(),s(c)))},d=h=>{n(),i(h)};n=()=>{for(let h of a)f(h,u);for(let h of t.rejectionEvents)f(h,d)};for(let h of a)l(h,u);for(let h of t.rejectionEvents)l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=_o(o,{milliseconds:t.timeout});return s.cancel=n,s}return o}function at(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=p0(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Ao(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Ms=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Bs=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},wr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function m0(r){return r.reason}async function Lt(r,e,t){if(e==null)return r;let n=t?.translateError??m0;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Fs=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ye(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Qe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function g0(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Us=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=g0(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Qe),this.cleanup())}async join(e={}){let t=new Fs(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Lt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var pn=class extends Pe{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ao(this.emitEmpty.bind(this),1),this.emitIdle=Ao(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Bs;let n=new Us(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Qe)}),this.clear()}async onEmpty(e){this.size!==0&&await at(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await at(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await at(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=hn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Qe("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function Dt(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var mn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var y0=1.2,b0=2,w0=5e3,x0=6e4,E0=5e3,Ks=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??E0;this.success=new mn(t),this.failure=new mn(t),this.next=new mn(t),this.failureMultiplier=e.failureMultiplier??b0,this.timeoutMultiplier=e.timeoutMultiplier??y0,this.minTimeout=e.minTimeout??w0,this.maxTimeout=e.maxTimeout??x0,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=Dt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Ee=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Rt=class extends Error{static name="ValidationError";name="ValidationError"},qs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Vs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Pl(r){return e=>K(e,r)}function Ll(r){return e=>T(e,r)}function gn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function xr(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ih(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=T(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xr(n);return et([t,o],t.length+o.length)}function Th(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=We.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xr(n);return et([t,o],t.length+o.length)}function Dl(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=K(e,"base32"),o=gn(t);return`${n}:${o}`}var Rl=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Ee("Invalid byte value in IP address");e[n]=o}),e},Ph=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=it(t[n]),i;s&&(i=Rl(t[n]),t[n]=K(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Ee("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Lh=function(r){if(r.byteLength!==4)throw new Ee("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Dh=function(r){if(r.byteLength!==16)throw new Ee("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${t}"`)}};function Rh(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ee(`Invalid IPv6 address "${r}"`)}}var Tl=Object.values(Un).map(r=>r.decoder),v0=(function(){let r=Tl[0].or(Tl[1]);return Tl.slice(2).forEach(e=>r=r.or(e)),r})();function Oh(r){return v0.decode(r)}function kh(r){return e=>r.encoder.encode(e)}function S0(r){if(parseInt(r).toString()!==r)throw new Rt("Value must be an integer")}function _0(r){if(r<0)throw new Rt("Value must be a positive integer, or zero")}function A0(r){return e=>{if(e>r)throw new Rt(`Value must be smaller than or equal to ${r}`)}}function C0(...r){return e=>{for(let t of r)t(e)}}var Co=C0(S0,_0,A0(65535));var be=-1,Ol=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Vs(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Ot=new Ol,q0=[{code:4,name:"ip4",size:32,valueToBytes:Rl,bytesToValue:Lh,validate:r=>{if(!it(r))throw new Rt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xr,bytesToValue:gn,validate:Co},{code:273,name:"udp",size:16,valueToBytes:xr,bytesToValue:gn,validate:Co},{code:33,name:"dccp",size:16,valueToBytes:xr,bytesToValue:gn,validate:Co},{code:41,name:"ip6",size:128,valueToBytes:Ph,bytesToValue:Dh,stringToValue:Rh,validate:r=>{if(!ks(r))throw new Rt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:be},{code:43,name:"ipcidr",size:8,bytesToValue:Pl("base10"),valueToBytes:Ll("base10")},{code:53,name:"dns",size:be},{code:54,name:"dns4",size:be},{code:55,name:"dns6",size:be},{code:56,name:"dnsaddr",size:be},{code:132,name:"sctp",size:16,valueToBytes:xr,bytesToValue:gn,validate:Co},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:be,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:be,bytesToValue:Pl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ll("base58btc")(r):ue.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Dl,valueToBytes:Ih},{code:445,name:"onion3",size:296,bytesToValue:Dl,valueToBytes:Th},{code:446,name:"garlic64",size:be},{code:447,name:"garlic32",size:be},{code:448,name:"tls"},{code:449,name:"sni",size:be},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:be,bytesToValue:kh(Qa),valueToBytes:Oh},{code:480,name:"http"},{code:481,name:"http-path",size:be,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:be}];q0.forEach(r=>{Ot.addProtocol(r)});function Nh(r){let e=[],t=0;for(;t<r.length;){let n=fr(r,t),o=Ot.getProtocol(n),s=ge(n),i=V0(o,r,t+s),a=0;i>0&&o.size===be&&(a=ge(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let f=t+s+a,u=r.subarray(f,f+i);l.value=o.bytesToValue?.(u)??K(u)}e.push(l),t+=c}return e}function Mh(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ot.getProtocol(n.code),s=ge(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??T(n.value),a=i.byteLength,o.size===be&&(c=ge(a)));let l=new Uint8Array(s+c+a),f=0;Jr(n.code,l,f),f+=s,i!=null&&(o.size===be&&(Jr(a,l,f),f+=c),l.set(i,f)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return et(t,e)}function Bh(r){if(r.charAt(0)!=="/")throw new Ee('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Ot.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Ee(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ee(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ee("Incomplete multiaddr");return e}function Fh(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ot.getProtocol(e.code);if(t==null)throw new Ee(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function V0(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:fr(e,t)}var $0=Symbol.for("nodejs.util.inspect.custom"),Wl=Symbol.for("@multiformats/multiaddr");function z0(r){if(r==null&&(r="/"),Jt(r))return r.getComponents();if(r instanceof Uint8Array)return Nh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Bh(r);if(Array.isArray(r))return r;throw new Ee("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ws=class r{[Wl]=!0;#e;#n;#t;constructor(e="/",t={}){this.#e=z0(e),t.validate!==!1&&H0(this)}get bytes(){return this.#t==null&&(this.#t=Mh(this.#e)),this.#t}toString(){return this.#n==null&&(this.#n=Fh(this.#e)),this.#n}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new qs(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return Y(this.bytes,e.bytes)}[$0](){return`Multiaddr(${this.toString()})`}};function H0(r){r.getComponents().forEach(e=>{let t=Ot.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function Jt(r){return!!r?.[Wl]}function j(r){return new Ws(r)}var js=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Uh(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new js(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new js(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var jl=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ye(),this.haveNext=ye()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ye(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ye(),await Uh(this.readNext.promise,t?.signal,t)}};function Kh(){return new jl}function G0(r){return r[Symbol.asyncIterator]!=null}async function W0(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*j0(r){let e=new AbortController,t=Kh();W0(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*X0(r){for(let e of r)yield*e}function Y0(...r){let e=[];for(let t of r)G0(t)||e.push(t);return e.length===r.length?X0(e):j0(r)}var vn=Y0;var Z0=4194304,Xs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Yl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Zl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ql=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Q0(r){return typeof r?.closeRead=="function"}function J0(r){return typeof r?.close=="function"}function Xl(r){return Q0(r)?r.readStatus==="closing"||r.readStatus==="closed":J0(r)?r.status!=="open":!1}function eb(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Jl(r,e){let t=e?.maxBufferSize??Z0,n=new Z,o=Promise.withResolvers(),s=!1;if(!eb(r))throw new I("Argument should be a Stream or a Multiaddr");let i=f=>{if(e?.stopPropagation,n.append(f.data),n.byteLength>t){let u=n.byteLength;n.consume(n.byteLength),o.reject(new Error(`Read buffer overflow - ${u} > ${t}`))}o.resolve()};r.addEventListener("message",i);let a=f=>{f.error!=null?o.reject(f.error):o.resolve()};r.addEventListener("close",a);let c=()=>{o.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(f){if(s===!0)throw new Xs("Stream was unwrapped");if(Xl(r)){if(f?.bytes==null)return null;if(n.byteLength<f.bytes)throw new wr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let u=f?.bytes??1;for(;;){if(n.byteLength>=u){o.resolve();break}if(await Lt(o.promise,f?.signal),Xl(r)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(Xl(r))throw new wr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(f)}let h=n.sublist(0,d);return n.consume(d),h},async write(f,u){if(s===!0)throw new Xs("Stream was unwrapped");r.send(f)||await at(r,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function Ys(r,e={}){let t=Jl(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ge(e.maxDataLength));let n=e?.lengthDecoder??fr,o=e?.lengthEncoder??Yt;return{async read(i){let a=-1,c=new Z;for(;;){let f=await t.read({...i,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Yl("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ql(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Zl(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw new wr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw new wr(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Z(o(i.byteLength),i),a)},async writeV(i,a){let c=new Z(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Sn(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:Vh}=Object.prototype,{propertyIsEnumerable:tb}=Object,_n=(r,e,t)=>{Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})},rb=void 0,qh={concatArrays:!1,ignoreUndefined:!1},Zs=r=>{let e=[];for(let t in r)Vh.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)tb.call(r,n)&&e.push(n)}return e};function An(r){return Array.isArray(r)?nb(r):Sn(r)?ob(r):r}function nb(r){let e=r.slice(0,0);return Zs(r).forEach(t=>{_n(e,t,An(r[t]))}),e}function ob(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return Zs(r).forEach(t=>{_n(e,t,An(r[t]))}),e}var $h=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?_n(r,o,eu(r[o],e[o],n)):_n(r,o,An(e[o])))}),r),sb=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Vh.call(s,a)&&(i.push(String(a)),s===r?_n(n,o++,s[a]):_n(n,o++,An(s[a])));n=$h(n,s,Zs(s).filter(a=>!i.includes(a)),t)}),n};function eu(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?sb(r,e,t):!Sn(e)||!Sn(r)?An(e):$h(r,e,Zs(e),t)}function Qs(...r){let e=eu(An(qh),this!==rb&&this||{},qh),t={_:{}};for(let n of r)if(n!==void 0){if(!Sn(n))throw new TypeError("`"+n+"` is not an Option Object");t=eu(t,{_:n},e)}return t._}var Js=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Cn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ei=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Io=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ti(r){return r[Symbol.asyncIterator]!=null}function zh(r,e){if(r.byteLength>e)throw new Cn("Message length too long")}var ni=r=>{let e=ge(r),t=Se(e);return Yt(r,t),ni.bytes=e,t};ni.bytes=0;function oi(r,e){e=e??{};let t=e.lengthEncoder??ni,n=e?.maxDataLength??4194304;function*o(s){zh(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return ti(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}oi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ni,n=e?.maxDataLength??4194304;return zh(r,n),new Z(t(r.byteLength),r)};var Sr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Sr||(Sr={}));var ru=r=>{let e=fr(r);return ru.bytes=ge(e),e};ru.bytes=0;function tu(r,e){let t=new Z,n=Sr.LENGTH,o=-1,s=e?.lengthDecoder??ru,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Sr.LENGTH)try{if(o=s(t),o<0)throw new Js("Invalid message length");if(o>a)throw new Cn("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=Sr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new ei("Message length length too long");break}throw l}if(n===Sr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=Sr.LENGTH}}}return ti(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Io("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Io("Unexpected end of input")})()}tu.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return tu(n,{...e??{},onLength:s=>{t=s}})};function ab(r,e){if(typeof r=="string")return cb(r);if(typeof r=="number")return fb(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var si=ab;function cb(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function lb(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function ub(r){let e=Math.abs(r);return e>=315576e5?_r(r,e,315576e5,"year"):e>=26298e5?_r(r,e,26298e5,"month"):e>=6048e5?_r(r,e,6048e5,"week"):e>=864e5?_r(r,e,864e5,"day"):e>=36e5?_r(r,e,36e5,"hour"):e>=6e4?_r(r,e,6e4,"minute"):e>=1e3?_r(r,e,1e3,"second"):`${r} ms`}function fb(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?ub(r):lb(r)}function _r(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function nu(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=si,t.destroy=l,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let u=0;for(let d=0;d<f.length;d++)u=(u<<5)-u+f.charCodeAt(d),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(f){let u,d=null,h,p;function m(...w){if(!m.enabled)return;let g=m,_=Number(new Date),E=_-(u||_);g.diff=E,g.prev=u,g.curr=_,u=_,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let C=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(V,$)=>{if(V==="%%")return"%";C++;let N=t.formatters[$];if(typeof N=="function"){let v=w[C];V=N.call(g,v),w.splice(C,1),C--}return V}),t.formatArgs.call(g,w),(g.log||t.log).apply(g,w)}return m.namespace=f,m.useColors=t.useColors(),m.color=t.selectColor(f),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(f)),p),set:w=>{d=w}}),typeof t.init=="function"&&t.init(m),m}function n(f,u){let d=t(this.namespace+(typeof u>"u"?":":u)+f);return d.log=this.log,d}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let u,d=(typeof f=="string"?f:"").split(/[\s,]+/),h=d.length;for(u=0;u<h;u++)d[u]&&(f=d[u].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.substr(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function s(){let f=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),f}function i(f){if(f[f.length-1]==="*")return!0;let u,d;for(u=0,d=t.skips.length;u<d;u++)if(t.skips[u].test(f))return!1;for(u=0,d=t.names.length;u<d;u++)if(t.names[u].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack??f.message:f}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var ii=bb(),db=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function hb(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function pb(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+si(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var mb=console.debug??console.log??(()=>{});function gb(r){try{r?ii?.setItem("debug",r):ii?.removeItem("debug")}catch{}}function yb(){let r;try{r=ii?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function bb(){try{return localStorage}catch{}}function wb(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Hh=nu({formatArgs:pb,save:gb,load:yb,useColors:hb,setupFormatters:wb,colors:db,storage:ii,log:mb});var qe=Hh;qe.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);qe.formatters.t=r=>r==null?"undefined":We.baseEncode(r);qe.formatters.m=r=>r==null?"undefined":Za.baseEncode(r);qe.formatters.p=r=>r==null?"undefined":r.toString();qe.formatters.c=r=>r==null?"undefined":r.toString();qe.formatters.k=r=>r==null?"undefined":r.toString();qe.formatters.a=r=>r==null?"undefined":r.toString();qe.formatters.e=r=>r==null?"undefined":Gh(r.stack)??Gh(r.message)??r.toString();function xb(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function ai(){return{forComponent(r){return Wh(r)}}}function Wh(r){let e=xb(`${r}:trace`);return qe.enabled(`${r}:trace`)&&qe.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=qe(`${r}:trace`)),Object.assign(qe(r),{error:qe(`${r}:error`),trace:e,newScope:t=>Wh(`${r}:${t}`)})}function Gh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var ci=class extends pn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var li=class extends pn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var ui=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new ou}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Ms("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},ou=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var su=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Ce(r){let{name:e,metrics:t}=r,n;return t!=null?n=new su({name:e,metrics:t}):n=new Map,n}var de=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var au=Da(Xh(),1);function cu(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Po=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=cu(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Lo=class extends au.default{#e;#n;#t=0;#h;#a;#p=0;#o;#c;#r;#m;#s=0;#l;#i;#g;#w=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Po,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#n=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#a=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#x(){return this.#n||this.#t<this.#h}get#E(){return this.#s<this.#l}#v(){this.#s--,this.#u(),this.emit("next")}#S(){this.#b(),this.#y(),this.#c=void 0}get#_(){let e=Date.now();if(this.#o===void 0){let t=this.#p-e;if(t<0)this.#t=this.#e?this.#s:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#S()},t)),!0}return!1}#u(){if(this.#r.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#_;if(this.#x&&this.#E){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#n||this.#o!==void 0||(this.#o=setInterval(()=>{this.#b()},this.#a),this.#p=Date.now()+this.#a)}#b(){this.#t===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#t=this.#e?this.#s:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#l=e,this.#f()}async#A(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#r.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#w++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#s++;try{t.signal?.throwIfAborted(),this.#t++;let s=e({signal:t.signal});t.timeout&&(s=_o(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#A(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof So&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},t),this.emit("add"),this.#u()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#s===0&&this.#r.size===0||await this.#d("idle")}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#i}};function di(r){let e=[He.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var lu=60;function hi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:He[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:He[e.type],TTL:e.TTL??e.ttl??lu,data:e.data instanceof Uint8Array?K(e.data):e.data}))}}var Sb=4;function uu(r,e={}){let t=new Lo({concurrency:e.queryConcurrency??Sb});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),di(o.types).forEach(a=>{s.append("type",He[a])}),o.onProgress?.(new de("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=hi(await a.json());return o.onProgress?.(new de("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Yh(){return[uu("https://cloudflare-dns.com/dns-query"),uu("https://dns.google/resolve")]}var Jh=Da(Qh(),1);var fu=class{lru;constructor(e){this.lru=(0,Jh.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return hi({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:He[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??lu)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function ep(r){return new fu(r)}var _b=1e3,pi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=ep(e.cacheSize??_b),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Yh())}async query(e,t={}){let n=di(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new de("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new de("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var He;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(He||(He={}));function tp(r={}){return new pi(r)}var du=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[He.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(j(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=tp()),this.dns)}},kt=new du;var Ab={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:kt}},transportManager:{faultTolerance:nr.FATAL_ALL}};async function rp(r){let e=Qs(Ab,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new I("Private network is enforced, but no protector was provided");return e}function Ar(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function mi(r){let e=mt(ee.decode(`z${r}`));return an(e)}var Ze=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Ar(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Ar(this.map.values(),e=>e.key)}values(){return Ar(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Cr=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Ar(this.set.entries(),e=>{let t=mi(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=mi(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ar(this.set.values(),e=>mi(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var hu=class extends Ze{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function pu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new hu({name:e,metrics:t}):n=new Ze,n}var Do;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:ce(0),payloadType:ce(0),payload:ce(0),signature:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Oe(t,r.codec(),n)})(Do||(Do={}));var gi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var In=class r{static createFromProtobuf=e=>{let t=Do.decode(e),n=sn(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=np(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new gi("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=Do.encode({publicKey:je(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Y(this.marshal(),e.marshal())}async validate(e,t){let n=np(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},np=(r,e,t)=>{let n=T(r),o=Yt(n.byteLength),s=Yt(e.length),i=Yt(t.length);return new Z(o,n,s,e,i,t)};var op="libp2p-peer-record",sp=Uint8Array.from([3,1]);var Ro;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ce(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let f=s.uint32();switch(f>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(f&7);break}}}return c})),o),n.encode=s=>ke(s,n.codec()),n.decode=(s,i)=>Oe(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ne((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ce(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new pr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>ke(n,r.codec()),r.decode=(n,o)=>Oe(n,r.codec(),o)})(Ro||(Ro={}));function ip(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Ir=class r{static createFromProtobuf=e=>{let t=Ro.decode(e),n=an(mt(t.peerId)),o=(t.addresses??[]).map(i=>j(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=op;static CODEC=sp;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Ro.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!ip(this.multiaddrs,e.multiaddrs))}};function Cb(r){return r[Symbol.asyncIterator]!=null}function Ib(r){if(Cb(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Oo=Ib;var Ge=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function yi(r,e,t,n){let o=new Ge(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){gu(t,"abort",u),gu(r,e,l),gu(r,s,f)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},f=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},u=()=>{c(),a(o)};mu(t,"abort",u),mu(r,e,l),mu(r,s,f)})}function mu(r,e,t){r!=null&&(ap(r)?r.addEventListener(e,t):r.addListener(e,t))}function gu(r,e,t){r!=null&&(ap(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function ap(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var bi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var wi=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function cp(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new wi(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new wi(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var xi=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ge)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Tb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ei=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Tb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ge),this.cleanup())}async join(e={}){let t=new xi(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await cp(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function yu(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var ko=class extends Pe{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=yu(this.emitEmpty.bind(this),1),this.emitIdle=yu(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new bi;let n=new Ei(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Ge)}),this.clear()}async onEmpty(e){this.size!==0&&await yi(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await yi(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await yi(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=hn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Ge("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var vi="lock:worker:request-read",Si="lock:worker:abort-read-request",_i="lock:worker:release-read",Ai="lock:master:grant-read",Ci="lock:master:error-read",Ii="lock:worker:request-write",Ti="lock:worker:abort-write-request",Pi="lock:worker:release-write",Li="lock:master:grant-write",Di="lock:master:error-write",Ri="lock:worker:finalize",Oi="mortice",lp={singleProcess:!1};var bu=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===o&&r.safeDispatchEvent(t,{detail:{name:f.name,identifier:f.identifier,handler:async()=>{e.postMessage({type:c,name:f.name,identifier:f.identifier}),await new Promise(u=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===f.identifier&&(e.removeEventListener("message",d),u())};e.addEventListener("message",d)})},onError:u=>{e.postMessage({type:i,name:f.name,identifier:f.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),f.type===s&&r.safeDispatchEvent(n,{detail:{name:f.name,identifier:f.identifier}}),f.type===Ri&&r.safeDispatchEvent("finalizeRequest",{detail:{name:f.name}})};var up=(r=10)=>Math.random().toString().substring(2,r+2);var ki=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Oi)}readLock(e){return this.sendRequest(vi,Si,Ai,Ci,_i,e)}writeLock(e){return this.sendRequest(Ii,Ti,Li,Di,Pi,e)}finalize(){this.channel.postMessage({type:Ri,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=up();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let f=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",f,{once:!0});let u=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",u),i?.signal?.removeEventListener("abort",f);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",u)})}};var fp=r=>{if(r=Object.assign({},lp,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Oi),n=new Pe;return t.addEventListener("message",bu(n,t,"requestReadLock","abortReadLockRequest",vi,Si,Ci,_i,Ai)),t.addEventListener("message",bu(n,t,"requestWriteLock","abortWriteLockRequest",Ii,Ti,Di,Pi,Li)),n}return new ki(r.name)};var Tr=new Map,No;function dp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Pb(r){if(No==null&&(No=fp(r),!dp(No))){let e=No;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Tr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Tr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Tr.get(n);o?.finalize()})}return No}async function wu(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Ge)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var hp=(r,e)=>{let t=Tr.get(r);if(t!=null)return t;let n=Pb(e);if(dp(n))return t=n,Tr.set(r,t),t;let o=new ko({concurrency:1}),s;return t={async readLock(i){if(s!=null)return wu(s,i);s=new ko({concurrency:e.concurrency,autoStart:!1});let a=s,c=wu(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,wu(o,i)},finalize:()=>{Tr.delete(r)},queue:o},Tr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Lb={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function xu(r){let e=Object.assign({},Lb,r);return hp(e.name,e)}var Nt;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ce(0)},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(u&7);break}}}return l})),s),o.encode=i=>ke(i,o.codec()),o.decode=(i,a)=>Oe(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Mi.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Mi.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(u&7);break}}}return l})),s),o.encode=i=>ke(i,o.codec()),o.decode=(i,a)=>Oe(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ne((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Ni.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new pr('Decode error - map field "addresses" had too many elements');a.addresses.push(Ni.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new pr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new io('Decode error - map field "metadata" had too many elements');let f=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(f.key,f.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new io('Decode error - map field "tags" had too many elements');let f=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(f.key,f.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ke(o,r.codec()),r.decode=(o,s)=>Oe(o,r.codec(),s)})(Nt||(Nt={}));var Ni;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:ce(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}case 3:{s.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Oe(t,r.codec(),n)})(Ni||(Ni={}));var Mi;(function(r){let e;r.codec=()=>(e==null&&(e=Ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>ke(t,r.codec()),r.decode=(t,n)=>Oe(t,r.codec(),n)})(Mi||(Mi={}));function Db(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=sn(e.publicKey,t);return bl(n)}function pp(r,e,t){let n=Nt.decode(e);return Tn(r,n,t)}function Tn(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:Db(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function mp(r,e){return Rb(r.addresses,e.addresses)&&Ob(r.protocols,e.protocols)&&kb(r.publicKey,e.publicKey)&&Nb(r.peerRecordEnvelope,e.peerRecordEnvelope)&&Mb(r.metadata,e.metadata)&&Bb(r.tags,e.tags)}function Rb(r,e){return yp(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Y(t.multiaddr,n.multiaddr)))}function Ob(r,e){return yp(r,e,(t,n)=>t===n)}function kb(r,e){return gp(r,e)}function Nb(r,e){return gp(r,e)}function Mb(r,e){return bp(r,e,(t,n)=>Y(t,n))}function Bb(r,e){return bp(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function gp(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Y(r,e):!1}function yp(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function bp(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Mt="/",wp=new TextEncoder().encode(Mt),Bi=wp[0],Pr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=T(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Bi)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Mt))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=wp),this._buf[0]!==Bi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Bi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Bi;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Mt).slice(1)}type(){return Fb(this.baseNamespace())}name(){return Ub(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Mt)||(e+=Mt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Mt):new r(e.slice(0,-1).join(Mt))}child(e){return this.toString()===Mt?e:e.toString()===Mt?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Kb(e.map(t=>t.namespaces()))])}};function Fb(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Ub(r){let e=r.split(":");return e[e.length-1]}function Kb(r){return[].concat(...r)}var Eu="/peers/";function Mo(r){if(!Ut(r)||r.type==null)throw new I("Invalid PeerId");let e=r.toCID().toString();return new Pr(`${Eu}${e}`)}async function xp(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=j(i.multiaddr)),!Jt(i.multiaddr))throw new I("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(j(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Ui(r,e,t,n){if(e==null)throw new I("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new I("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new I("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Fi(d,{validate:Ep})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Fi(d,{validate:vp,map:Sp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Fi([...a.entries()],{validate:Ep})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Fi([...h.entries()],{validate:vp,map:Sp})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let f;o?.id.publicKey!=null?f=je(o.id.publicKey):e.publicKey!=null?f=je(e.publicKey):r.publicKey!=null&&(f=je(r.publicKey));let u={addresses:await xp(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:f,peerRecordEnvelope:l};return u.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>Y(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete u.publicKey,u}function Fi(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Ep(r,e){if(typeof r!="string")throw new I("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new I("Metadata value must be a Uint8Array")}function vp(r,e){if(typeof r!="string")throw new I("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new I("Tag value must be an integer");if(e.value<0||e.value>100)throw new I("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new I("Tag ttl must be an integer");if(e.ttl<0)throw new I("Tag ttl must be between greater than 0")}}function Sp(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function _p(r){let e=r.toString().split("/")[2],t=ue.parse(e,We);return go(t)}function vu(r,e,t){let n=_p(r);return pp(n,e,t)}function qb(r,e){return{prefix:Eu,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(vu(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(vu(n.key,n.value,e),vu(o.key,o.value,e)))}}var Ki=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=pu({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:xu({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Mo(e),t)}async load(e,t){let n=Mo(e),o=await this.datastore.get(n,t),s=Nt.decode(o);if(this.#t(e,s))throw await this.datastore.delete(n,t),new rr;return Tn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await Ui(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#n(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await Ui(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#n(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await Ui(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#n(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(qb(e??{},this.maxAddressAge),e)){let o=_p(t);if(o.equals(this.peerId))continue;let s=Nt.decode(n);if(this.#t(o,s)){await this.datastore.delete(t,e);continue}yield Tn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Mo(e),o=await this.datastore.get(n,t),s=Nt.decode(o);if(this.#t(e,s))throw await this.datastore.delete(n,t),new rr;return{peerPB:s,peer:Tn(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#n(e,t,n,o){t.updated=Date.now();let s=Nt.encode(t);return await this.datastore.put(Mo(e),s,o),{peer:Tn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!mp(t,n.peerPB)}}#t(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Su=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Ki(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Oo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Ut(t)?t:Ut(t?.expectedPeer)?t.expectedPeer:void 0,s=Ut(t)||t===void 0?n:t,i=await In.openAndCertify(e,Ir.DOMAIN,s),a=go(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=Ir.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(f){if(f.name!=="NotFoundError")throw f}if(l?.peerRecordEnvelope!=null){let f=In.createFromProtobuf(l.peerRecordEnvelope),u=Ir.createFromProtobuf(f.payload);if(u.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(f=>({isCertified:!0,multiaddr:f}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Ap(r,e={}){return new Su(r,e)}var qi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function Vb(r){return r[Symbol.asyncIterator]!=null}function $b(r){if(Vb(r))return(async()=>{for await(let e of r);})();for(let e of r);}var _u=$b;function zb(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Cp=zb;function Hb(r){return r[Symbol.asyncIterator]!=null}function Gb(r,e){let t=0;if(Hb(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Cp(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Lr=Gb;function Wb(r){return r[Symbol.asyncIterator]!=null}function jb(r,e){return Wb(r)?(async function*(){yield*(await Oo(r)).sort(e)})():(function*(){yield*Oo(r).sort(e)})()}var Au=jb;function Xb(r){return r[Symbol.asyncIterator]!=null}function Yb(r,e){return Xb(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Cu=Yb;var Vi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await _u(this.putMany(e,n)),e=[],await _u(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Lr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Au(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Lr(n,()=>o++>=s)}return e.limit!=null&&(n=Cu(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Lr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Au(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Lr(n,()=>s++>=o)}return e.limit!=null&&(n=Cu(n,e.limit)),n}};var $i=class extends Vi{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new qi;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new Pr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Pr(n),t?.signal?.throwIfAborted()}};var te=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),M=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Ip=r=>({match:e=>r.match(e)===!1?e:!1}),H=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Te=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),X=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function re(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Zb=M(421),Tp=re(Zb),Hi=M(54),Gi=M(55),Wi=M(56),Tu=M(53),m4=re(Hi,H(M(421))),g4=re(Gi,H(M(421))),y4=re(Wi,H(M(421))),b4=re(Te(Tu,Wi,Hi,Gi),H(M(421))),Pp=X(M(4),H(M(43))),Lp=X(H(M(42)),M(41),H(M(43))),Pu=Te(Pp,Lp),Dr=Te(Pu,Tu,Hi,Gi,Wi),w4=re(Te(Pu,X(Te(Tu,Wi,Hi,Gi),H(M(421))))),Lu=re(Pp),Du=re(Lp),x4=re(Pu),Ru=X(Dr,M(6)),Bo=X(Dr,M(273)),Fo=re(X(Ru,H(M(421)))),E4=re(Bo),Ou=X(Bo,te(460),H(M(421))),ji=X(Bo,te(461),H(M(421))),Qb=Te(Ou,ji),v4=re(Ou),Dp=re(ji),Iu=Te(Dr,Ru,Bo,Ou,ji),Rp=Te(X(Iu,te(477),H(M(421)))),Rr=re(Rp),Op=Te(X(Iu,te(478),H(M(421))),X(Iu,te(448),H(M(449)),te(477),H(M(421)))),Uo=re(Op),kp=X(Bo,te(280),H(M(466)),H(M(466)),H(M(421))),ku=re(kp),Np=X(ji,te(465),H(M(466)),H(M(466)),H(M(421))),Nu=re(Np),zi=Te(Rp,Op,X(Ru,H(M(421))),X(Qb,H(M(421))),X(Dr,H(M(421))),kp,Np,M(421)),S4=re(zi),Jb=X(H(zi),te(290),Ip(te(281)),H(M(421))),Or=re(Jb),ew=Te(X(zi,te(290),te(281),H(M(421))),X(zi,te(281),H(M(421))),X(te(281),H(M(421)))),Mu=re(ew),tw=Te(X(Dr,M(6),te(480),H(M(421))),X(Dr,te(480),H(M(421)))),_4=re(tw),rw=X(Dr,Te(X(M(6,"443"),te(480)),X(M(6),te(443)),X(M(6),te(448),te(480)),X(te(448),te(480)),te(448),te(443)),H(M(421))),A4=re(rw),nw=Te(X(M(777),H(M(421)))),C4=re(nw),ow=Te(X(M(400),H(M(421)))),I4=re(ow);var Mp=864e13;var Xi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Ce({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=z(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=fn(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?Mp-Date.now():0,lastVerified:o?Mp-Date.now():void 0})})}remove(e){let t=z(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!xe(o))continue;let s=z(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),j(n)}confirm(e,t){let n=z(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=z(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Yi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Ce({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=z(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:it(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=z(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!xe(n))continue;let o=z(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,j(i)):e}confirm(e,t){if(!xe(e))return!1;let n=z(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!xe(e))return!1;let n=z(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var sw={maxObservedAddresses:10},Zi=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??sw.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Pt(e)||Eh(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:j(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var iw={maxObservedAddresses:10},Qi=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Ce({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??iw.maxObservedAddresses}get(e,t){if(Pt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!xe(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!xe(e))return e.toString();let t=z(e);return`${t.host}-${t.port}-${t.protocol}`}};var Bp=6e4,Fp={maxObservedAddresses:10,addressVerificationTTL:Bp*10,addressVerificationRetry:Bp*5},aw=r=>r;function Bu(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&ft(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var Ji=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Zi(e,t),this.dnsMappings=new Xi(e,t),this.ipMappings=new Yi(e,t),this.transportAddresses=new Qi(e,t),this.announceFilter=t.announceFilter??aw,this.observedAddressFilter=wo(1024),this.addressVerificationTTL=t.addressVerificationTTL??Fp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Fp.addressVerificationRetry,this._updatePeerStoreAddresses=Ao(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>j(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=z(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Bu(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Bu(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Bu(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=j(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(j(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${it(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(j(`/ip${it(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!xe(e))return!1;let t=z(e);if(t.type!=="ip4"||fn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Rr.exactMatch(s)||Uo.exactMatch(s),s=>Fo.exactMatch(s),s=>Dp.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(f=>z(f).type==="ip4"&&s(f)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!Eo(l)).pop();if(a==null)continue;let c=z(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var Up;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Up||(Up={}));var ea=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},ta=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Pn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ko=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},ra=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},na=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},oa=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},qo=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},sa=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},ia=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},aa=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},ca=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},la=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},er=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},kr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ua=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},fa=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Fu=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=ai())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>ns(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},cw=["metrics","connectionProtector","dns"],lw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Kp(r={}){let e=new Fu(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!lw.includes(o)){let i=e.components[o];if(i==null&&!cw.includes(o))throw new ea(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function qp(r){let e={};for(let t of Object.values(r.components))for(let n of uw(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of fw(t))if(e[n]!==!0)throw new ta(`Service "${dw(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function uw(r){return Array.isArray(r?.[kn])?r[kn]:[]}function fw(r){return Array.isArray(r?.[Ma])?r[Ma]:[]}function dw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function Vp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>Rr.matches(e)?!0:Pt(e),denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function da(r){if(Ut(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:ft(n),e.forEach(o=>{if(!Jt(o))throw new Bt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new I("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ft(s);if(t?.equals(i)!==!0)throw new I("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Tp.exactMatch(n)),{peerId:t,multiaddrs:e}}var hw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function $p(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??hw;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Vo(r){let e=z(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new I(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new I(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new un(e.host,t)}function Uu(r){return!Or.exactMatch(r)}function ha(r,e,t){if(r==null||e==null)return;let n=e.sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>Uu(s)))return n}var pa=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Vo(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Ze;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let f=await this.peerStore.get(l);o.set(l,[...f.tags.values()].reduce((u,d)=>u+d.value,0))}catch(f){f.name!=="NotFoundError"&&this.log.error("error loading peer tags",f)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(f=>{if(xe(c.remoteAddr)){let u=z(c.remoteAddr);return f.contains(u.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await $p(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var zp="last-dial-failure",Hp="last-dial-success";var Gp=100,ma=50;function pw(r,e){let t=Fo.exactMatch(r.multiaddr),n=Fo.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=Uo.exactMatch(r.multiaddr),s=Uo.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Rr.exactMatch(r.multiaddr),a=Rr.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Mu.exactMatch(r.multiaddr),l=Mu.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let f=ku.exactMatch(r.multiaddr),u=ku.exactMatch(e.multiaddr);if(f&&!u)return-1;if(!f&&u)return 1;let d=Nu.exactMatch(r.multiaddr),h=Nu.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function mw(r,e){let t=Eo(r.multiaddr),n=Eo(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function gw(r,e){let t=Pt(r.multiaddr),n=Pt(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function yw(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function bw(r,e){let t=Or.exactMatch(r.multiaddr),n=Or.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function Wp(r){return r.sort(pw).sort(yw).sort(bw).sort(gw).sort(mw)}async function Ku(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new fa("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Ku(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var $o={maxParallelDials:ma,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:kt}},ga=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??$o.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??$o.maxDialQueueLength,this.dialTimeout=t.dialTimeout??$o.dialTimeout,this.connections=t.connections??new Ze,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??$o.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new li({concurrency:t.maxParallelDials??$o.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Qe.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=da(e);if(n!=null&&t.force!==!0){let i=ha(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new de("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Br("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new de("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new de("dial-queue:start-dial"));let a=Dt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??zu,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let f=[],u=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...u]);let d=await this.calculateMultiaddrs(n,u,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}f.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,f.map(h=>h.multiaddr.toString())),e?.onProgress?.(new de("dial-queue:calculated-addresses",f));for(let h of f){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Br("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[Hp]:T(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}return p}catch(p){if(this.log.error("dial failed to %a",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[zp]:T(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}if(t.aborted)throw new Qo(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:j(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Br("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new qo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(u){if(u.name!=="NotFoundError")throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...u.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(u){u.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,u)}}}let s=(await Promise.all(o.map(async u=>{let d=await Ku(u.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(u.multiaddr)?u:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(u),isCertified:d.isCertified}:d)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let d=u.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let u of i){let d=u.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||u.isCertified||!1;continue}a.set(d,u)}let c=[...a.values()];if(c.length===0)throw new aa("The dial request has no valid addresses");let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let f=this.addressSorter==null?Wp(l):l.sort(this.addressSorter);if(f.length===0)throw new qo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",f.map(({multiaddr:u})=>u.toString())),f}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!Or.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ww=Object.prototype.toString,xw=r=>ww.call(r)==="[object Error]",Ew=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function Hu(r){return r&&xw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Ew.has(r.message):!1}function vw(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function ya(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var Gu=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Sw=(r,e,t)=>{let n=t.retries-(e-1);return Object.freeze({error:r,attemptNumber:e,retriesLeft:n})};function _w(r,e){let t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*e.factor**(r-1));return n=Math.min(n,e.maxTimeout),n}async function Aw(r,e,t,n,o){let s=r;if(s instanceof Error||(s=new TypeError(`Non-error was thrown: "${s}". You should only throw errors.`)),s instanceof Gu)throw s.originalError;if(s instanceof TypeError&&!Hu(s))throw s;let i=Sw(s,e,t);await t.onFailedAttempt(i);let a=Date.now();if(a-n>=o||e>=t.retries+1||!await t.shouldRetry(i))throw s;let c=_w(e,t),l=o-(a-n);if(l<=0)throw s;let f=Math.min(c,l);f>0&&await new Promise((u,d)=>{let h=()=>{clearTimeout(p),t.signal?.removeEventListener("abort",h),d(t.signal.reason)},p=setTimeout(()=>{t.signal?.removeEventListener("abort",h),u()},f);t.unref&&p.unref?.(),t.signal?.addEventListener("abort",h,{once:!0})}),t.signal?.throwIfAborted()}async function Wu(r,e={}){if(e={...e},vw(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,ya("factor",e.factor,{min:0,allowInfinity:!1}),ya("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),ya("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0});let t=e.maxRetryTime??Number.POSITIVE_INFINITY;ya("maxRetryTime",t,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let n=0,o=Date.now(),s=t;for(;n<e.retries+1;){n++;try{e.signal?.throwIfAborted();let i=await r(n);return e.signal?.throwIfAborted(),i}catch(i){await Aw(i,n,e,o,s)}}throw new Error("Retry attempts exhausted without throwing an error.")}var ba=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new ci({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);jp(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Wu(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(Na)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>jp(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function jp(r){for(let e of r.tags.keys())if(e.startsWith(Na))return!0;return!1}var zu=50,ju={maxConnections:Gp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},wa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??ju.maxConnections,this.maxConnections<1)throw new I("Connection Manager maxConnections must be greater than 0");this.connections=new Ze,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Vo(j(n))),this.deny=(t.deny??[]).map(n=>Vo(j(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??ju.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ui({points:t.inboundConnectionThreshold??ju.inboundConnectionThreshold,duration:1}),this.connectionPruner=new pa({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>j(n))}),this.dialQueue=new ga(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??ma,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:kt},connections:this.connections}),this.reconnectQueue=new ba({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.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 o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await of(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await sf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([at(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new I("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new ht("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:o}=da(e);if(this.peerId.equals(n))throw new Mr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=ha(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new de("dial-queue:already-connected")),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??zu});if(s.status!=="open")throw new tr("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Bt("Duplicate multiaddr connection")),c;return a||i.push(s),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([at(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(xe(e.remoteAddr)){let s=z(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(xe(e.remoteAddr)){let s=z(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(xe(e.remoteAddr)){let o=z(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Tw=1e4,Pw="1.0.0",Lw="ping",Dw="ipfs",Xp=32,Rw=!0,xa=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Dw}/${Lw}/${Pw}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Tw,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Rw,this.timeout=new Ks({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[kn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Jl(o);t=Date.now(),await Promise.all([s.write(tn(Xp),{signal:n}),s.read({bytes:Xp,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var Ea=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:K(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:K(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Pn("No content routers available");let n=this,o=new Cr;for await(let s of vn(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new Pn("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Pn("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new ht;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new ht;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var va=globalThis.CustomEvent??Event;async function*Xu(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=ye(),a=ye(),c=!1,l,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ye(),await i.promise),f)break;let m={done:!1};s.push(m),p().then(w=>{m.done=!0,m.ok=!0,m.value=w,o.dispatchEvent(new va("task-complete"))},w=>{m.done=!0,m.err=w,o.dispatchEvent(new va("task-complete"))})}c=!0,o.dispatchEvent(new va("task-complete"))}catch(p){l=p,o.dispatchEvent(new va("task-complete"))}});function u(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw f=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;u();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw f=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(u()||(a=ye(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var Sa=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:K(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Ko("No peer routers available");if(e.toString()===this.peerId.toString())throw new ra("Should not try to find self");let n=this,o=vn(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new rr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ko("No peer routers available");let n=this,o=wo(1024);for await(let s of Xu((async function*(){let i=vn(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var _a=class extends Pe{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Dt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ye(),yield(await at(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Dt([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=tn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Lt(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Yu=32,Zu=64,Aa=class{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Ce({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new na(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new oa(`Handler already registered for protocol ${e}`);let o=Qs.bind({ignoreUndefined:!0})({maxInboundStreams:Yu,maxOutboundStreams:Zu},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new I("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t)!==!1&&(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var Ca=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Ce({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Ce({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??nr.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new I("Transport must have a valid tag");if(this.transports.has(t))throw new I(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}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[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new ua(`No transport available for address ${String(e)}`);return t?.onProgress?.(new de("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new ht("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new sa)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),f=this.listeners.get(s)??[];f==null&&(f=[],this.listeners.set(s,f)),f.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let u=f.findIndex(d=>d===l);f.splice(u,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),Lu.matches(c)?t.ipv4.attempts++:Du.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Lu.matches(c)&&t.ipv4.success++,Du.matches(c)&&t.ipv6.success++},u=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,u),t.errors.set(c.toString(),u),u}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===nr.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new ia(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
3
+ ${[...t.errors.entries()].map(([s,i])=>`
4
+ ${s}: ${`${Ow(i)}`.split(`
5
5
  `).join(`
6
6
  `)}
7
- `).join("")}`)}}ipv6Unsupported(t){if(t.ipv4.attempts===0||t.ipv6.attempts===0)return!1;let e=t.ipv4.attempts===t.ipv4.success,n=t.ipv6.success===0;return e&&n}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var gt="/multistream/1.0.0";var ga=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ya=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ba=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Bo(r,t={}){let e=ca(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ft(t.maxDataLength));let n=t?.lengthDecoder??er,o=t?.lengthEncoder??le;return{read:async i=>{let a=-1,c=new z;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new ga("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new ba("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new ya("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new z(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new z(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var pw=D(`
8
- `);async function Cr(r,t,e){await r.write(t,e)}async function Rp(r,t,e){await r.writeV(t,e)}async function mw(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==pw[0])throw t.log.error("Invalid mss message - missing newline",e),new jo("Missing newline");return e.sublist(0,-1)}async function ze(r,t){let e=await mw(r,t);return N(e.subarray())}async function Fo(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return gw(r,t[0],e);let n=Bo(r,{...e,maxDataLength:1024}),o=t.shift();if(o==null)throw new Error("At least one protocol must be specified");e.log.trace('select: write ["%s", "%s"]',gt,o);let s=D(`${gt}
9
- `),i=D(`${o}
10
- `);await Rp(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await ze(n,e);if(e.log.trace('select: read "%s"',a),a===gt&&(e.log.trace("select: reading protocol response"),a=await ze(n,e),e.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of t){e.log.trace('select: write "%s"',c),await Cr(n,D(`${c}
11
- `),e),e.log.trace("select: reading protocol response");let u=await ze(n,e);if(e.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new Cn("protocol selection failed")}function gw(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=ot(),c=!1,u=!1,l=ot(),f=!1,d=!1,h=ot(),p=Bo({sink:n,source:o},{...e,maxDataLength:1024});r.sink=async E=>{let{sink:_}=p.unwrap();await _(async function*(){let C=!1;for await(let b of E){if(u&&await l.promise,c)yield b;else{u=!0,e.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',gt,t,b.byteLength);let L=`${t}
12
- `;yield new z(Uint8Array.from([19]),D(`${gt}
13
- `),le(L.length),D(L),b).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',gt,t,b.byteLength),c=!0,u=!1,l.resolve(),g().catch(R=>{e.log.error("could not finish optimistic protocol negotiation of %s",t,R)})}C=!0}C||await g()}())};async function g(){if(i){e.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}i=!0;try{c||(e.log.trace("optimistic: doing send protocol for %s stream",t),await m()),f||(e.log.trace("optimistic: doing read protocol for %s stream",t),await w())}finally{i=!1,s=!0,a.resolve()}}async function m(){if(u){await l.promise;return}u=!0;try{e.log.trace('optimistic: write ["%s", "%s", data] in source',gt,t),await p.writeV([D(`${gt}
14
- `),D(`${t}
15
- `)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',gt,t)}finally{c=!0,u=!1,l.resolve()}}async function w(){if(d){await h.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let E=await ze(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',E),E===gt&&(E=await ze(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',E,t),E!==t)throw new Cn("protocol selection failed")}finally{f=!0,d=!1,h.resolve()}}if(r.source=async function*(){await g(),e.log.trace('optimistic: reading data from "%s" stream',t),yield*p.unwrap().source}(),r.closeRead!=null){let E=r.closeRead.bind(r);r.closeRead=async _=>{s||await g().catch(C=>{e.log.error("could not negotiate protocol before close read",C)}),await E(_)}}if(r.closeWrite!=null){let E=r.closeWrite.bind(r);r.closeWrite=async _=>{s||await g().catch(C=>{e.log.error("could not negotiate protocol before close write",C)}),await E(_)}}if(r.close!=null){let E=r.close.bind(r);r.close=async _=>{let C=[];u&&C.push(l.promise),d&&C.push(h.promise),C.length>0?await mt(Promise.all(C),_?.signal):(s=!0,i=!1,a.resolve()),await E(_)}}return{stream:r,protocol:t}}var wa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},_n=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},xa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Uo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ea(r){return r[Symbol.asyncIterator]!=null}function kp(r,t){if(r.byteLength>t)throw new _n("Message length too long")}var _a=r=>{let t=ft(r),e=bt(t);return le(r,e),_a.bytes=t,e};_a.bytes=0;function Sa(r,t){t=t??{};let e=t.lengthEncoder??_a,n=t?.maxDataLength??4194304;function*o(s){kp(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ea(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}Sa.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??_a,n=t?.maxDataLength??4194304;return kp(r,n),new z(e(r.byteLength),r)};var Ir;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ir||(Ir={}));var ku=r=>{let t=er(r);return ku.bytes=ft(t),t};ku.bytes=0;function Ou(r,t){let e=new z,n=Ir.LENGTH,o=-1,s=t?.lengthDecoder??ku,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Ir.LENGTH)try{if(o=s(e),o<0)throw new wa("Invalid message length");if(o>a)throw new _n("Message length too long");let u=s.bytes;e.consume(u),t?.onLength!=null&&t.onLength(o),n=Ir.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new xa("Message length length too long");break}throw u}if(n===Ir.DATA){if(e.byteLength<o)break;let u=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(u),yield u,n=Ir.LENGTH}}}return Ea(r)?async function*(){for await(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Uo("Unexpected end of input")}():function*(){for(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Uo("Unexpected end of input")}()}Ou.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return Ou(n,{...t??{},onLength:s=>{e=s}})};async function Ko(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=Bo(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await ze(n,e);if(e.log.trace('handle: read "%s"',o),o===gt){e.log.trace('handle: respond with "%s" for "%s"',gt,o),await Cr(n,D(`${gt}
16
- `),e),e.log.trace('handle: responded with "%s" for "%s"',gt,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await Cr(n,D(`${o}
17
- `),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new z(...t.map(i=>Sa.single(D(`${i}
18
- `))),D(`
19
- `));e.log.trace('handle: respond with "%s" for %s',t,o),await Cr(n,s,e),e.log.trace('handle: responded with "%s" for %s',t,o);continue}e.log.trace('handle: respond with "na" for "%s"',o),await Cr(n,D(`na
20
- `),e),e.log('handle: responded with "na" for "%s"',o)}}var ww=500,Mu=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Bu]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new $o("the connection is being closed");if(this.status==="closed")throw new Rr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(ww);t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this._close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this._abort(t),this.status="closed",this.timeline.close=Date.now())}};function Mp(r){return new Mu(r)}function Ew(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Du}function vw(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??Lu}function Np(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Aa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=St({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=St({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new zi(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Ie([AbortSignal.timeout(this.inboundUpgradeTimeout),t]);return e}async upgradeInbound(t,e){let n=!1,o=this.createInboundAbortSignal(e.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await mt(this.components.connectionManager.acceptIncomingConnection(t),o),!n)throw new Vi("Connection denied");await mt(this.shouldBlockConnection("denyInboundConnection",t),o),await this._performUpgrade(t,"inbound",{...e,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=fe(n),await mt(this.shouldBlockConnection("denyOutboundConnection",o,t),e.signal));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c;this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let u=t;if(n?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(t.log("protecting the %s connection",e),u=await l.protect(t,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new at(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(u,n):this._encryptOutbound(u,n));let l={...u,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,l)}else{let l=t.remoteAddr.getPeerId();if(l==null)throw new Pe(`${e} connection that skipped encryption must have a peer id`);let f=fe(l);c="native",s=f}if(s.equals(this.components.peerId)){let l=new Or("Can not dial self");throw t.abort(l),l}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new at(`upgrader:multiplex-${e}-connection`));let l=await(e==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=l.muxerFactory,i=l.stream}}catch(l){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,l),l}return await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",e),this._createConnection({cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{if(f==null)return;let g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:w,protocol:E}=await Ko(p,m,{signal:g,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",E);let _=Ew(E,this.components.registrar);if(Np(E,"inbound",f)===_){let b=new Xo(`Too many inbound protocol streams for protocol "${E}" - limit ${_}`);throw p.abort(b),b}p.source=w.source,p.sink=w.sink,p.protocol=E,w.closeWrite!=null&&(p.closeWrite=w.closeWrite),w.closeRead!=null&&(p.closeRead=w.closeRead),w.close!=null&&(p.close=w.close),await this.components.peerStore.merge(i,{protocols:[E]},{signal:g}),this.components.metrics?.trackProtocolStream(p,f),this._onStream({connection:f,stream:p,protocol:E})}).catch(async m=>{f.log.error("error handling incoming stream id %s - %e",p.id,m),p.timeline.close==null&&await p.close({signal:g}).catch(w=>p.abort(w))})}}),l=async(p,g={})=>{if(u==null)throw new _r("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",p);let m=await u.newStream();f.log.trace("started new stream %s for protocols %s",m.id,p);try{if(g.signal==null){m.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let b=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:b}}m.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:E}=await Fo(m,p,{...g,log:m.log,yieldBytes:!0});m.log.trace("selected protocol %s",E);let _=vw(E,this.components.registrar,g),C=Np(E,"outbound",f);if(C>=_){let b=new Qo(`Too many outbound protocol streams for protocol "${E}" - ${C}/${_}`);throw m.abort(b),b}return await this.components.peerStore.merge(i,{protocols:[E]}),m.source=w.source,m.sink=w.sink,m.protocol=E,w.closeWrite!=null&&(m.closeWrite=w.closeWrite),w.closeRead!=null&&(m.closeRead=w.closeRead),w.close!=null&&(m.close=w.close),this.components.metrics?.trackProtocolStream(m,f),m}catch(w){throw f.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",t.maConn.remoteAddr,p,w),m.timeline.close==null&&m.abort(w),w}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{f.log.error("error piping data through muxer - %e",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(g){f.log.error("error closing connection after timeline close %e",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(g=>{f.log.error("error thrown while dispatching connection:close event %e",g)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new _r("Connection is not multiplexed")};return f=Mp({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:l??h,getStreams:()=>u?.streams??[],close:async p=>{await u?.close(p),await o.close(p)},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f.__maConnTimeline=d,f}_onStream(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new Mr("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await Ko(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Sr(`no crypto module found for ${s}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,o),new Sr(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Fo(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Sr(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,s),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,o),new Sr(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await Fo(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new _r(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await Ko(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new _r(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var Ca="2.9.0",Ia="js-libp2p";function Fp(r,t){return`${r??Ia}/${t??Ca} browser/${globalThis.navigator.userAgent}`}var qo=class extends Bt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new Bt,n=e.dispatchEvent.bind(e);e.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||f},this.peerId=t.peerId,this.logger=t.logger??$s(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Ia,s=t.nodeInfo?.version??Ca,i=this.components=dp({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??Fp(o,s)},logger:this.logger,events:e,datastore:t.datastore??new vi,connectionGater:pp(t.connectionGater),dns:t.dns});t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Zh(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let l={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:l})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new Aa(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(t.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new ma(this.components,t.transportManager)),this.configureComponent("connectionManager",new oa(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new la(this.components,t.connectionMonitor)),this.configureComponent("registrar",new pa(this.components)),this.configureComponent("addressManager",new Oi(this.components,t.addresses));let a=(t.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new da(this.components,{routers:a}));let c=(t.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ua(this.components,{routers:c})),this.configureComponent("randomWalk",new ha(this.components)),(t.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),t.services!=null)for(let u of Object.keys(t.services)){let l=t.services[u],f=l(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=f,this.configureComponent(u,f),f[Pa]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Pa])),f[La]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[La])),f[Da]!=null&&(this.log("registering service %s for peer discovery",u),f[Da].addEventListener?.("peer",d=>{this.#t(d)}))}hp(i)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new hr;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new k("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new k("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){Ke(t)&&(t=fe(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t,e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Xt([D("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=nn(o);return await this.peerStore.patch(t,{publicKey:s},e),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t,e){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async n=>{await this.components.registrar.unhandle(n,e)}))}async register(t,e,n){return this.components.registrar.register(t,e,n)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function _w(r={}){r.privateKey??=await Kd("Ed25519");let t=new qo({...await _h(r),peerId:Hd(r.privateKey)});return r.start!==!1&&await t.start(),t}var Sw=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Aw(r){return r==null?!1:r instanceof qo?!0:Sw.every(t=>typeof r[t]=="function")}return Hp(Cw);})();
7
+ `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function Ow(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var dt="/multistream/1.0.0";var kw=T(`
8
+ `);async function zo(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==kw[0])throw new Zo("Missing newline");return K(n).trimEnd()}async function Ln(r,e,t={}){if(e=Array.isArray(e)?[...e]:[e],e.length===0)throw new Error("At least one protocol must be specified");let n=r.log.newScope("mss:select"),o=Ys(r,{...t,maxDataLength:1024,stopPropagation:!0});for(let s=0;s<e.length;s++){let i=e[s],a;if(s===0){n.trace('write ["%s", "%s"]',dt,i);let c=T(`${dt}
9
+ `),l=T(`${i}
10
+ `);if(await o.writeV([c,l],t),n.trace("reading multistream-select header"),a=await zo(o,t),n.trace('read "%s"',a),a!==dt){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(T(`${i}
11
+ `),t);if(n.trace("reading protocol response"),a=await zo(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new Yo(`Protocol selection failed - could not negotiate ${e}`)}async function Dn(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=Ys(r,{...t,maxDataLength:1024,maxLengthLength:2,stopPropagation:!0});for(;;){n.trace("reading incoming string");let s=await zo(o,t);if(n.trace('read "%s"',s),s===dt){n.trace('respond with "%s" for "%s"',dt,s),await o.write(T(`${dt}
12
+ `),t),n.trace('responded with "%s" for "%s"',dt,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(T(`${s}
13
+ `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new Z(...e.map(a=>oi.single(T(`${a}
14
+ `))),T(`
15
+ `));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(T(`na
16
+ `),t),n('responded with "na" for "%s"',s)}}var Ju=class extends Pe{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=Uu(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new ts(n.local,n.error))})}[Symbol.toStringTag]="Connection";[nf]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new er("Connection is not multiplexed");if(this.muxer.status!=="open")throw new tr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new tr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new On("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let i=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:i}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await Ln(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Bw(n.protocol,this.components.registrar,t),s=Jp(n.protocol,"outbound",this);if(s>o){let i=new es(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(i),i}return await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n),n}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let c=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",c),t.protocol=await Dn(t,c,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Mw(t.protocol,this.components.registrar);if(Jp(t.protocol,"inbound",this)>o)throw new Jo(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new On("Cannot open protocol stream on limited connection");await i(t,this)}catch(o){t.abort(o)}}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function em(r,e){return new Ju(r,e)}function Mw(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Yu}function Bw(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Zu}function Jp(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Ia=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Ce({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Ce({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new ca(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Dt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new la("Connection denied");await Lt(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=ft(n),await Lt(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),o=await u.protect(o,n))}try{if(Fw(n)){if(n.remotePeer==null)throw new Bt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let u=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;u!=null&&(d=ft(u)),n?.onProgress?.(new de(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let u=new Mr("Can not dial self");throw e.abort(u),u}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new de(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(u){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,u),u}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let f=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return f.log("successfully upgraded connection"),f}_createConnection(e){let t=em(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Dn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new kr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new kr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await Ln(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new kr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new kr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Ln(e,o,n),i=t.get(s);if(i==null)throw new er(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection",s),new er(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Dn(e,o,n),i=t.get(s);if(i==null)throw new er(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function Fw(r){return r.skipEncryption===!0}var Ta="2.10.0-8484de8a2",Pa="js-libp2p";function rm(r,e){return`${r??Pa}/${e??Ta} browser/${globalThis.navigator.userAgent}`}var Ho=class extends Pe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Pe,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let f=n(l),u=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return f||u},this.peerId=e.peerId,this.logger=e.logger??ai(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??Pa,s=e.nodeInfo?.version??Ta,i=this.components=Kp({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??rm(o,s)},logger:this.logger,events:t,datastore:e.datastore??new $i,connectionGater:Vp(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Ap(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let f={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(u=>u.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:f})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Ia(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,f)=>this.configureComponent(`connection-encryption-${f}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,f)=>this.configureComponent(`stream-muxers-${f}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Ca(this.components,e.transportManager)),this.configureComponent("connectionManager",new wa(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new xa(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Aa(this.components)),this.configureComponent("addressManager",new Ji(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,f)=>this.configureComponent(`peer-router-${f}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Sa(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,f)=>this.configureComponent(`content-router-${f}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ea(this.components,{routers:c})),this.configureComponent("randomWalk",new _a(this.components)),(e.peerDiscovery??[]).forEach((l,f)=>{this.configureComponent(`peer-discovery-${f}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,f)=>{this.components.transportManager.add(this.configureComponent(`transport-${f}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let f=e.services[l],u=f(this.components);if(u==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=u,this.configureComponent(l,u),u[Ra]!=null&&(this.log("registering service %s for content routing",l),c.push(u[Ra])),u[ka]!=null&&(this.log("registering service %s for peer routing",l),a.push(u[ka])),u[Oa]!=null&&(this.log("registering service %s for peer discovery",l),u[Oa].addEventListener?.("peer",d=>{this.#e(d)}))}qp(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Cr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new I("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new I("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Jt(e)&&(e=ft(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=et([T("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=sn(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Uw(r={}){r.privateKey??=await ah("Ed25519");let e=new Ho({...await rp(r),peerId:fh(r.privateKey)});return r.start!==!1&&await e.start(),e}var Kw=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function qw(r){return r==null?!1:r instanceof Ho?!0:Kw.every(e=>typeof r[e]=="function")}return cm(Vw);})();
21
17
  /*! Bundled license information:
22
18
 
23
19
  @noble/hashes/esm/utils.js: