libp2p 2.8.11 → 2.8.12

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 (50) hide show
  1. package/dist/index.min.js +7 -7
  2. package/dist/index.min.js.map +4 -4
  3. package/dist/src/config.js +1 -1
  4. package/dist/src/config.js.map +1 -1
  5. package/dist/src/connection-manager/constants.defaults.d.ts +4 -0
  6. package/dist/src/connection-manager/constants.defaults.d.ts.map +1 -1
  7. package/dist/src/connection-manager/constants.defaults.js +4 -0
  8. package/dist/src/connection-manager/constants.defaults.js.map +1 -1
  9. package/dist/src/connection-manager/dial-queue.d.ts +4 -3
  10. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  11. package/dist/src/connection-manager/dial-queue.js +7 -9
  12. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  13. package/dist/src/connection-manager/index.d.ts +3 -3
  14. package/dist/src/connection-manager/index.d.ts.map +1 -1
  15. package/dist/src/connection-manager/index.js +1 -1
  16. package/dist/src/connection-manager/index.js.map +1 -1
  17. package/dist/src/connection-manager/resolvers/dnsaddr.d.ts +11 -0
  18. package/dist/src/connection-manager/resolvers/dnsaddr.d.ts.map +1 -0
  19. package/dist/src/connection-manager/resolvers/dnsaddr.js +52 -0
  20. package/dist/src/connection-manager/resolvers/dnsaddr.js.map +1 -0
  21. package/dist/src/connection-manager/resolvers/index.d.ts +23 -0
  22. package/dist/src/connection-manager/resolvers/index.d.ts.map +1 -0
  23. package/dist/src/connection-manager/resolvers/index.js +31 -0
  24. package/dist/src/connection-manager/resolvers/index.js.map +1 -0
  25. package/dist/src/connection-manager/utils.d.ts +1 -6
  26. package/dist/src/connection-manager/utils.d.ts.map +1 -1
  27. package/dist/src/connection-manager/utils.js +4 -23
  28. package/dist/src/connection-manager/utils.js.map +1 -1
  29. package/dist/src/errors.d.ts +3 -0
  30. package/dist/src/errors.d.ts.map +1 -1
  31. package/dist/src/errors.js +6 -0
  32. package/dist/src/errors.js.map +1 -1
  33. package/dist/src/index.d.ts +1 -0
  34. package/dist/src/index.d.ts.map +1 -1
  35. package/dist/src/index.js +1 -0
  36. package/dist/src/index.js.map +1 -1
  37. package/dist/src/version.d.ts +1 -1
  38. package/dist/src/version.js +1 -1
  39. package/dist/typedoc-urls.json +1 -0
  40. package/package.json +10 -10
  41. package/src/config.ts +1 -1
  42. package/src/connection-manager/constants.defaults.ts +5 -0
  43. package/src/connection-manager/dial-queue.ts +10 -13
  44. package/src/connection-manager/index.ts +4 -4
  45. package/src/connection-manager/resolvers/dnsaddr.ts +69 -0
  46. package/src/connection-manager/resolvers/index.ts +59 -0
  47. package/src/connection-manager/utils.ts +6 -32
  48. package/src/errors.ts +7 -0
  49. package/src/index.ts +2 -0
  50. package/src/version.ts +1 -1
package/dist/index.min.js CHANGED
@@ -1,23 +1,23 @@
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 Dp=Object.create;var Uo=Object.defineProperty;var Lp=Object.getOwnPropertyDescriptor;var Rp=Object.getOwnPropertyNames;var kp=Object.getPrototypeOf,Op=Object.prototype.hasOwnProperty;var Sr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Rt=(r,t)=>{for(var e in t)Uo(r,e,{get:t[e],enumerable:!0})},Cu=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Rp(t))!Op.call(r,o)&&o!==e&&Uo(r,o,{get:()=>t[o],enumerable:!(n=Lp(t,o))||n.enumerable});return r};var Ko=(r,t,e)=>(e=r!=null?Dp(kp(r)):{},Cu(t||!r||!r.__esModule?Uo(e,"default",{value:r,enumerable:!0}):e,r)),Mp=r=>Cu(Uo({},"__esModule",{value:!0}),r);var Ud=Sr((X2,tl)=>{"use strict";var _0=Object.prototype.hasOwnProperty,Lt="~";function oo(){}Object.create&&(oo.prototype=Object.create(null),new oo().__proto__||(Lt=!1));function S0(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Fd(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new S0(e,n||r,o),i=Lt?Lt+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 As(r,t){--r._eventsCount===0?r._events=new oo:delete r._events[t]}function Et(){this._events=new oo,this._eventsCount=0}Et.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)_0.call(e,n)&&t.push(Lt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Et.prototype.listeners=function(t){var e=Lt?Lt+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};Et.prototype.listenerCount=function(t){var e=Lt?Lt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Et.prototype.emit=function(t,e,n,o,s,i){var a=Lt?Lt+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};Et.prototype.on=function(t,e,n){return Fd(this,t,e,n,!1)};Et.prototype.once=function(t,e,n){return Fd(this,t,e,n,!0)};Et.prototype.removeListener=function(t,e,n,o){var s=Lt?Lt+t:t;if(!this._events[s])return this;if(!e)return As(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&As(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:As(this,s)}return this};Et.prototype.removeAllListeners=function(t){var e;return t?(e=Lt?Lt+t:t,this._events[e]&&As(this,e)):(this._events=new oo,this._eventsCount=0),this};Et.prototype.off=Et.prototype.removeListener;Et.prototype.addListener=Et.prototype.on;Et.prefixed=Lt;Et.EventEmitter=Et;typeof tl<"u"&&(tl.exports=Et)});var Hd=Sr((w_,Vd)=>{Vd.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=Sr(Ao=>{(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}(),Ao.ip2long=i,Ao.long2ip=a,Ao.Netmask=r}).call(Ao)});var mp=Sr((u8,pp)=>{function Ht(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))}pp.exports=Ht;Ht.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ht.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ht.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};Ht.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)};Ht.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ht.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ht.prototype.start=Ht.prototype.try;Ht.prototype.errors=function(){return this._errors};Ht.prototype.attempts=function(){return this._attempts};Ht.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 gp=Sr(wr=>{var rw=mp();wr.operation=function(r){var t=wr.timeouts(r);return new rw(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};wr.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};wr.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};wr.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=wr.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 bp=Sr((d8,yp)=>{yp.exports=gp()});var Ow={};Rt(Ow,{createLibp2p:()=>kw});var Iu=Symbol.for("@libp2p/connection");var Aa=Symbol.for("@libp2p/content-routing");var Ca=Symbol.for("@libp2p/peer-discovery");var qo=Symbol.for("@libp2p/peer-id");function Ce(r){return!!r?.[qo]}var Ia=Symbol.for("@libp2p/peer-routing");var Ta="keep-alive";var zw=Symbol.for("@libp2p/transport");var qe;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(qe||(qe={}));var $t=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var O=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Ar=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},xn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var zo=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Cr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var ze=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Ir=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Ie=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Vo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Ho=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},En=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},$o=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Wo=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},fe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Tr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Pr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},Go=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},jo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Te=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Nt=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 Zo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Tu(...r){let t=[];for(let e of r)Zo(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 Pu(...r){let t=[];for(let e of r)Zo(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 vn=Symbol.for("@libp2p/service-capabilities"),Pa=Symbol.for("@libp2p/service-dependencies");var Oa={};Rt(Oa,{base58btc:()=>H,base58flickr:()=>zp});var px=new Uint8Array(0);function Du(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 de(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 Lu(r){return new TextEncoder().encode(r)}function Ru(r){return new TextDecoder().decode(r)}function Np(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 Bp=Np,Fp=Bp,Ou=Fp;var Da=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")}},La=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 Mu(this,t)}},Ra=class{decoders;constructor(t){this.decoders=t}or(t){return Mu(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 Mu(r,t){return new Ra({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ka=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 Da(t,e,n),this.decoder=new La(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Dr({name:r,prefix:t,encode:e,decode:n}){return new ka(r,t,e,n)}function Pe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Ou(e,r);return Dr({prefix:t,name:r,encode:n,decode:s=>de(o(s))})}function Up(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 Kp(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 qp(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function et({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=qp(n);return Dr({prefix:t,name:r,encode(s){return Kp(s,n,e)},decode(s){return Up(s,o,e,r)}})}var H=Pe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zp=Pe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ma={};Rt(Ma,{base32:()=>qt,base32hex:()=>Wp,base32hexpad:()=>jp,base32hexpadupper:()=>Zp,base32hexupper:()=>Gp,base32pad:()=>Hp,base32padupper:()=>$p,base32upper:()=>Vp,base32z:()=>Xp});var qt=et({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Vp=et({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Hp=et({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$p=et({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Wp=et({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gp=et({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jp=et({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zp=et({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xp=et({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Na={};Rt(Na,{base36:()=>_n,base36upper:()=>Qp});var _n=Pe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qp=Pe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Yp=Fu,Nu=128,Jp=127,tm=~Jp,em=Math.pow(2,31);function Fu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=em;)t[e++]=r&255|Nu,r/=128;for(;r&tm;)t[e++]=r&255|Nu,r>>>=7;return t[e]=r|0,Fu.bytes=e-n+1,t}var rm=Ba,nm=128,Bu=127;function Ba(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ba.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Bu)<<o:(i&Bu)*Math.pow(2,o),o+=7}while(i>=nm);return Ba.bytes=s-n,e}var om=Math.pow(2,7),sm=Math.pow(2,14),im=Math.pow(2,21),am=Math.pow(2,28),cm=Math.pow(2,35),lm=Math.pow(2,42),um=Math.pow(2,49),fm=Math.pow(2,56),dm=Math.pow(2,63),hm=function(r){return r<om?1:r<sm?2:r<im?3:r<am?4:r<cm?5:r<lm?6:r<um?7:r<fm?8:r<dm?9:10},pm={encode:Yp,decode:rm,encodingLength:hm},mm=pm,Sn=mm;function An(r,t=0){return[Sn.decode(r,t),Sn.decode.bytes]}function Lr(r,t,e=0){return Sn.encode(r,t,e),t}function Rr(r){return Sn.encodingLength(r)}function Wt(r,t){let e=t.byteLength,n=Rr(r),o=n+Rr(e),s=new Uint8Array(o+e);return Lr(r,s,0),Lr(e,s,n),s.set(t,o),new kr(r,e,t,s)}function he(r){let t=de(r),[e,n]=An(t),[o,s]=An(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new kr(e,o,i,t)}function Uu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Du(r.bytes,e.bytes)}}var kr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Ku(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return ym(e,Fa(r),t??H.encoder);default:return bm(e,Fa(r),t??qt.encoder)}}var qu=new WeakMap;function Fa(r){let t=qu.get(r);if(t==null){let e=new Map;return qu.set(r,e),e}return t}var J=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!==Cn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==wm)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=Wt(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&&Uu(t.multihash,n.multihash)}toString(t){return Ku(this,t)}toJSON(){return{"/":Ku(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??zu(n,o,s.bytes))}else if(e[xm]===!0){let{version:n,multihash:o,code:s}=e,i=he(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!==Cn)throw new Error(`Version 0 CID must use dag-pb (code: ${Cn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=zu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Cn,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=de(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 kr(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]=An(t.subarray(e));return e+=d,f},o=n(),s=Cn;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]=gm(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 Fa(s).set(n,t),s}};function gm(r,t){switch(r[0]){case"Q":{let e=t??H;return[H.prefix,e.decode(`${H.prefix}${r}`)]}case H.prefix:{let e=t??H;return[H.prefix,e.decode(r)]}case qt.prefix:{let e=t??qt;return[qt.prefix,e.decode(r)]}case _n.prefix:{let e=t??_n;return[_n.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 ym(r,t,e){let{prefix:n}=e;if(n!==H.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 bm(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 Cn=112,wm=18;function zu(r,t,e){let n=Rr(r),o=n+Rr(t),s=new Uint8Array(o+e.byteLength);return Lr(r,s,0),Lr(t,s,n),s.set(e,o),s}var xm=Symbol.for("@ipld/js-cid/CID");var Ua={};Rt(Ua,{identity:()=>Gt});var Vu=0,Em="identity",Hu=de;function vm(r){return Wt(Vu,Hu(r))}var Gt={code:Vu,name:Em,encode:Hu,digest:vm};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 rt(r=0){return new Uint8Array(r)}function yt(r=0){return new Uint8Array(r)}function jt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=yt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Wu=Symbol.for("@achingbrain/uint8arraylist");function $u(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 Qo(r){return!!r?.[Wu]}var z=class r{bufs;length;[Wu]=!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(Qo(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(Qo(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=$u(this.bufs,t);return e.buf[e.index]}set(t,e){let n=$u(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(Qo(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 jt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:jt(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(!Qo(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=yt(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=rt(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=rt(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=rt(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=yt(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=rt(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=rt(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=rt(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=rt(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=rt(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 Ka={};Rt(Ka,{base10:()=>_m});var _m=Pe({prefix:"9",name:"base10",alphabet:"0123456789"});var qa={};Rt(qa,{base16:()=>Sm,base16upper:()=>Am});var Sm=et({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Am=et({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var za={};Rt(za,{base2:()=>Cm});var Cm=et({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Va={};Rt(Va,{base256emoji:()=>Lm});var Gu=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}"),Im=Gu.reduce((r,t,e)=>(r[e]=t,r),[]),Tm=Gu.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Pm(r){return r.reduce((t,e)=>(t+=Im[e],t),"")}function Dm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Tm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Lm=Dr({prefix:"\u{1F680}",name:"base256emoji",encode:Pm,decode:Dm});var $a={};Rt($a,{base64:()=>Ha,base64pad:()=>Rm,base64url:()=>In,base64urlpad:()=>km});var Ha=et({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Rm=et({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),In=et({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),km=et({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wa={};Rt(Wa,{base8:()=>Om});var Om=et({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ga={};Rt(Ga,{identity:()=>Mm});var Mm=Dr({prefix:"\0",name:"identity",encode:r=>Ru(r),decode:r=>Lu(r)});var Qx=new TextEncoder,Yx=new TextDecoder;var Xa={};Rt(Xa,{sha256:()=>Or,sha512:()=>Fm});function Za({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?Wt(this.code,e):e.then(n=>Wt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Zu(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Or=Za({name:"sha2-256",code:18,encode:Zu("SHA-256")}),Fm=Za({name:"sha2-512",code:19,encode:Zu("SHA-512")});var Tn={...Ga,...za,...Wa,...Ka,...qa,...Ma,...Na,...Oa,...$a,...Va},uE={...Xa,...Ua};function Qu(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Xu=Qu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Qa=Qu("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=yt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Um={utf8:Xu,"utf-8":Xu,hex:Tn.base16,latin1:Qa,ascii:Qa,binary:Qa,...Tn},Yo=Um;function D(r,t="utf8"){let e=Yo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function M(r,t="utf8"){let e=Yo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Km=parseInt("11111",2),Ya=parseInt("10000000",2),qm=parseInt("01111111",2),Yu={0:Pn,1:Pn,2:zm,3:$m,4:Wm,5:Hm,6:Vm,16:Pn,22:Pn,48:Pn};function pe(r,t={offset:0}){let e=r[t.offset]&Km;if(t.offset++,Yu[e]!=null)return Yu[e](r,t);throw new Error("No decoder for tag "+e)}function Dn(r,t){let e=0;if((r[t.offset]&Ya)===Ya){let n=r[t.offset]&qm,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 Pn(r,t){Dn(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=pe(r,t);if(n===null)break;e.push(n)}return e}function zm(r,t){let e=Dn(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 Vm(r,t){let e=Dn(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 Hm(r,t){return t.offset++,null}function $m(r,t){let e=Dn(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 Wm(r,t){let e=Dn(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Gm(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 Jo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Gm(r.byteLength);return new z(Uint8Array.from([t.byteLength|Ya]),t)}function At(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]),Jo(t),t)}function Ln(r){let t=Uint8Array.from([0]),e=new z(t,r);return new z(Uint8Array.from([3]),Jo(e),e)}function Ju(r){return new z(Uint8Array.from([4]),Jo(r),r)}function Zt(r,t=48){let e=new z;for(let n of r)e.append(n);return new z(Uint8Array.from([t]),Jo(e),e)}async function tf(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 ef(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 rf(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 jm=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Zm=Uint8Array.from([6,5,43,129,4,0,34]),Xm=Uint8Array.from([6,5,43,129,4,0,35]),Qm={ext:!0,kty:"EC",crv:"P-256"},Ym={ext:!0,kty:"EC",crv:"P-384"},Jm={ext:!0,kty:"EC",crv:"P-521"},Ja=32,tc=48,ec=66;function rc(r){let t=pe(r);return nf(t)}function nf(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Ja*2+1)return n=M(t.subarray(e,e+Ja),"base64url"),o=M(t.subarray(e+Ja),"base64url"),new Ve({...Qm,key_ops:["verify"],x:n,y:o});if(t.byteLength===tc*2+1)return n=M(t.subarray(e,e+tc),"base64url"),o=M(t.subarray(e+tc),"base64url"),new Ve({...Ym,key_ops:["verify"],x:n,y:o});if(t.byteLength===ec*2+1)return n=M(t.subarray(e,e+ec),"base64url"),o=M(t.subarray(e+ec),"base64url"),new Ve({...Jm,key_ops:["verify"],x:n,y:o});throw new O(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function of(r){return Zt([At(Uint8Array.from([1])),Ju(D(r.d??"","base64url")),Zt([af(r.crv)],160),Zt([Ln(new z(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function sf(r){return Zt([At(Uint8Array.from([1])),Zt([af(r.crv)],160),Zt([Ln(new z(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function af(r){if(r==="P-256")return jm;if(r==="P-384")return Zm;if(r==="P-521")return Xm;throw new O(`Invalid curve ${r}`)}async function cf(r="P-256"){let t=await tf(r);return new ts(t.privateKey)}var Ve=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=sf(this.jwk)),this._raw}toMultihash(){return Gt.digest(zt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return H.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 rf(this.jwk,e,t,n)}},ts=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new Ve({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=of(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}async sign(t,e){return ef(this.jwk,t,e)}};var He=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Nr(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Rn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function bt(r,...t){if(!Nr(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 uf(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Rn(r.outputLen),Rn(r.blockLen)}function Br(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 ff(r,t){bt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function ge(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function es(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Xt(r,t){return r<<32-t|r>>>t}var df=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",tg=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function ne(r){if(bt(r),df)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=tg[r[e]];return t}var me={_0:48,_9:57,A:65,F:70,a:97,f:102};function lf(r){if(r>=me._0&&r<=me._9)return r-me._0;if(r>=me.A&&r<=me.F)return r-(me.A-10);if(r>=me.a&&r<=me.f)return r-(me.a-10)}function Fr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(df)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=lf(r.charCodeAt(s)),a=lf(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 hf(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function kn(r){return typeof r=="string"&&(r=hf(r)),bt(r),r}function Bt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];bt(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 Mr=class{};function nc(r){let t=n=>r().update(kn(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function $e(r=32){if(He&&typeof He.getRandomValues=="function")return He.getRandomValues(new Uint8Array(r));if(He&&typeof He.randomBytes=="function")return Uint8Array.from(He.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function eg(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 pf(r,t,e){return r&t^~r&e}function mf(r,t,e){return r&t^r&e^t&e}var On=class extends Mr{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=es(this.buffer)}update(t){Br(this),t=kn(t),bt(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=es(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){Br(this),ff(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,ge(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;eg(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=es(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()}},ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ft=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var rs=BigInt(4294967295),gf=BigInt(32);function rg(r,t=!1){return t?{h:Number(r&rs),l:Number(r>>gf&rs)}:{h:Number(r>>gf&rs)|0,l:Number(r&rs)|0}}function yf(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}=rg(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var oc=(r,t,e)=>r>>>e,sc=(r,t,e)=>r<<32-e|t>>>e,We=(r,t,e)=>r>>>e|t<<32-e,Ge=(r,t,e)=>r<<32-e|t>>>e,Mn=(r,t,e)=>r<<64-e|t>>>e-32,Nn=(r,t,e)=>r>>>e-32|t<<64-e;function oe(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var bf=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),wf=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,xf=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Ef=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,vf=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),_f=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var og=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]),Le=new Uint32Array(64),ns=class extends On{constructor(t=32){super(64,t,8,!1),this.A=ye[0]|0,this.B=ye[1]|0,this.C=ye[2]|0,this.D=ye[3]|0,this.E=ye[4]|0,this.F=ye[5]|0,this.G=ye[6]|0,this.H=ye[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)Le[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Le[f-15],h=Le[f-2],p=Xt(d,7)^Xt(d,18)^d>>>3,g=Xt(h,17)^Xt(h,19)^h>>>10;Le[f]=g+Le[f-7]+p+Le[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=Xt(a,6)^Xt(a,11)^Xt(a,25),h=l+d+pf(a,c,u)+og[f]+Le[f]|0,g=(Xt(n,2)^Xt(n,13)^Xt(n,22))+mf(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(){ge(Le)}destroy(){this.set(0,0,0,0,0,0,0,0),ge(this.buffer)}};var Sf=yf(["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))),sg=Sf[0],ig=Sf[1],Re=new Uint32Array(80),ke=new Uint32Array(80),ic=class extends On{constructor(t=64){super(128,t,16,!1),this.Ah=ft[0]|0,this.Al=ft[1]|0,this.Bh=ft[2]|0,this.Bl=ft[3]|0,this.Ch=ft[4]|0,this.Cl=ft[5]|0,this.Dh=ft[6]|0,this.Dl=ft[7]|0,this.Eh=ft[8]|0,this.El=ft[9]|0,this.Fh=ft[10]|0,this.Fl=ft[11]|0,this.Gh=ft[12]|0,this.Gl=ft[13]|0,this.Hh=ft[14]|0,this.Hl=ft[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)Re[_]=t.getUint32(e),ke[_]=t.getUint32(e+=4);for(let _=16;_<80;_++){let C=Re[_-15]|0,b=ke[_-15]|0,L=We(C,b,1)^We(C,b,8)^oc(C,b,7),R=Ge(C,b,1)^Ge(C,b,8)^sc(C,b,7),I=Re[_-2]|0,y=ke[_-2]|0,S=We(I,y,19)^Mn(I,y,61)^oc(I,y,6),x=Ge(I,y,19)^Nn(I,y,61)^sc(I,y,6),v=xf(R,x,ke[_-7],ke[_-16]),A=Ef(v,L,S,Re[_-7],Re[_-16]);Re[_]=A|0,ke[_]=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=We(f,d,14)^We(f,d,18)^Mn(f,d,41),b=Ge(f,d,14)^Ge(f,d,18)^Nn(f,d,41),L=f&h^~f&g,R=d&p^~d&m,I=vf(E,b,R,ig[_],ke[_]),y=_f(I,w,C,L,sg[_],Re[_]),S=I|0,x=We(n,o,28)^Mn(n,o,34)^Mn(n,o,39),v=Ge(n,o,28)^Nn(n,o,34)^Nn(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}=oe(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=bf(S,v,P);n=wf(T,y,x,A),o=T|0}({h:n,l:o}=oe(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=oe(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=oe(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=oe(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=oe(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=oe(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=oe(this.Gh|0,this.Gl|0,g|0,m|0),{h:w,l:E}=oe(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(){ge(Re,ke)}destroy(){ge(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var os=nc(()=>new ns);var Af=nc(()=>new ic);var lc=BigInt(0),cc=BigInt(1);function be(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Bn(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Cf(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?lc:BigInt("0x"+r)}function Ur(r){return Cf(ne(r))}function je(r){return bt(r),Cf(ne(Uint8Array.from(r).reverse()))}function ss(r,t){return Fr(r.toString(16).padStart(t*2,"0"))}function Kr(r,t){return ss(r,t).reverse()}function X(r,t,e){let n;if(typeof t=="string")try{n=Fr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Nr(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 ac=r=>typeof r=="bigint"&&lc<=r;function If(r,t,e){return ac(r)&&ac(t)&&ac(e)&&t<=r&&r<e}function Oe(r,t,e,n){if(!If(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Tf(r){let t;for(t=0;r>lc;r>>=cc,t+=1);return t}var Ze=r=>(cc<<BigInt(r))-cc;function Pf(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 Bt(...p)};return(h,p)=>{c(),l(h);let g;for(;!(g=p(f()));)l();return c(),g}}function Me(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 qr(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 Ct=BigInt(0),lt=BigInt(1),Xe=BigInt(2),ag=BigInt(3),Rf=BigInt(4),kf=BigInt(5),Of=BigInt(8);function tt(r,t){let e=r%t;return e>=Ct?e:t+e}function Q(r,t,e){let n=r;for(;t-- >Ct;)n*=n,n%=e;return n}function Df(r,t){if(r===Ct)throw new Error("invert: expected non-zero number");if(t<=Ct)throw new Error("invert: expected positive modulus, got "+t);let e=tt(r,t),n=t,o=Ct,s=lt,i=lt,a=Ct;for(;e!==Ct;){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!==lt)throw new Error("invert: does not exist");return tt(o,t)}function Mf(r,t){let e=(r.ORDER+lt)/Rf,n=r.pow(t,e);if(!r.eql(r.sqr(n),t))throw new Error("Cannot find square root");return n}function cg(r,t){let e=(r.ORDER-kf)/Of,n=r.mul(t,Xe),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,Xe),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 lg(r){if(r<BigInt(3))throw new Error("sqrt is not defined for small field");let t=r-lt,e=0;for(;t%Xe===Ct;)t/=Xe,e++;let n=Xe,o=Qt(r);for(;Lf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Mf;let s=o.pow(n,t),i=(t+lt)/Xe;return function(c,u){if(c.is0(u))return u;if(Lf(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=lt<<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 ug(r){return r%Rf===ag?Mf:r%Of===kf?cg:lg(r)}var Nf=(r,t)=>(tt(r,t)&lt)===lt,fg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function uc(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=fg.reduce((n,o)=>(n[o]="function",n),t);return Me(r,e),r}function dg(r,t,e){if(e<Ct)throw new Error("invalid exponent, negatives unsupported");if(e===Ct)return r.ONE;if(e===lt)return t;let n=r.ONE,o=t;for(;e>Ct;)e&lt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=lt;return n}function Fn(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 Lf(r,t){let e=(r.ORDER-lt)/Xe,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 Bf(r,t){t!==void 0&&Rn(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Qt(r,t,e=!1,n={}){if(r<=Ct)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}=Bf(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:Ze(i),ZERO:Ct,ONE:lt,create:l=>tt(l,r),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return Ct<=l&&l<r},is0:l=>l===Ct,isValidNot0:l=>!u.is0(l)&&u.isValid(l),isOdd:l=>(l&lt)===lt,neg:l=>tt(-l,r),eql:(l,f)=>l===f,sqr:l=>tt(l*l,r),add:(l,f)=>tt(l+f,r),sub:(l,f)=>tt(l-f,r),mul:(l,f)=>tt(l*f,r),pow:(l,f)=>dg(u,l,f),div:(l,f)=>tt(l*Df(f,r),r),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>Df(l,r),sqrt:s||(l=>(c||(c=ug(r)),c(u,l))),toBytes:l=>e?Kr(l,a):ss(l,a),fromBytes:l=>{if(l.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);return e?je(l):Ur(l)},invertBatch:l=>Fn(u,l),cmov:(l,f,d)=>d?f:l});return Object.freeze(u)}function Ff(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 fc(r){let t=Ff(r);return t+Math.ceil(t/2)}function Uf(r,t,e=!1){let n=r.length,o=Ff(t),s=fc(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?je(r):Ur(r),a=tt(i,t-lt)+lt;return e?Kr(a,o):ss(a,o)}var Vr=BigInt(0),Qe=BigInt(1);function zr(r,t){let e=t.negate();return r?e:t}function is(r,t,e){let n=t==="pz"?i=>i.pz:i=>i.ez,o=Fn(r.Fp,e.map(n));return e.map((i,a)=>i.toAffine(o[a])).map(r.fromAffine)}function Vf(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function dc(r,t){Vf(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=Ze(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Kf(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+=Qe);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 hg(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 pg(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 hc=new WeakMap,Hf=new WeakMap;function pc(r){return Hf.get(r)||1}function qf(r){if(r!==Vr)throw new Error("invalid wNAF")}function as(r,t){return{constTimeNegate:zr,hasPrecomputes(e){return pc(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Vr;)n&Qe&&(o=o.add(s)),s=s.double(),n>>=Qe;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=dc(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=dc(e,t);for(let c=0;c<a.windows;c++){let{nextN:u,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:p}=Kf(o,c,a);o=u,f?i=i.add(zr(h,n[p])):s=s.add(zr(d,n[l]))}return qf(o),{p:s,f:i}},wNAFUnsafe(e,n,o,s=r.ZERO){let i=dc(e,t);for(let a=0;a<i.windows&&o!==Vr;a++){let{nextN:c,offset:u,isZero:l,isNeg:f}=Kf(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=hc.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&(typeof o=="function"&&(s=o(s)),hc.set(n,s))),s},wNAFCached(e,n,o){let s=pc(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=pc(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Vf(n,t),Hf.set(e,n),hc.delete(e)}}}function $f(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>Vr||n>Vr;)e&Qe&&(s=s.add(o)),n&Qe&&(i=i.add(o)),o=o.double(),e>>=Qe,n>>=Qe;return{p1:s,p2:i}}function cs(r,t,e,n){hg(e,r),pg(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=Tf(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Ze(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 zf(r,t){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return uc(t),t}else return Qt(r)}function ls(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>Vr))throw new Error(`CURVE.${a} must be positive bigint`)}let n=zf(t.p,e.Fp),o=zf(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 se=BigInt(0),It=BigInt(1),mc=BigInt(2),mg=BigInt(8),gg={zip215:!0};function yg(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 bg(r,t={}){let{Fp:e,Fn:n}=ls("edwards",r,t),{h:o,n:s}=r;Me(t,{},{uvRatio:"function"});let i=mc<<BigInt(n.BYTES*8)-It,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:se}}});if(!yg(e,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");function u(g,m,w=!1){let E=w?It:se;return Oe("coordinate "+g,m,E,i),m}function l(g){if(!(g instanceof h))throw new Error("ExtendedPoint expected")}let f=qr((g,m)=>{let{ex:w,ey:E,ez:_}=g,C=g.is0();m==null&&(m=C?mg:e.inv(_));let b=a(w*m),L=a(E*m),R=a(_*m);if(C)return{x:se,y:It};if(R!==It)throw new Error("invZ was invalid");return{x:b,y:L}}),d=qr(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,It,a(w*E))}static normalizeZ(m){return is(h,"ez",m)}static msm(m,w){return cs(h,n,m,w)}_setWindowSize(m){this.precompute(m)}precompute(m=8,w=!0){return p.setWindowSize(this,m),w||this.multiply(mc),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(mc*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),k=a(x*S);return new h(A,P,k,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),k=P-A,B=P+A,N=a(v-w*x),ot=a(T*k),W=a(B*N),F=a(T*N),at=a(k*B);return new h(ot,W,at,F)}subtract(m){return this.add(m.negate())}multiply(m){let w=m;Oe("scalar",w,It,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 Oe("scalar",E,se,s),E===se?h.ZERO:this.is0()||E===It?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===It?this:this.multiplyUnsafe(o)}static fromBytes(m,w=!1){return bt(m),this.fromHex(m,w)}static fromHex(m,w=!1){let{d:E,a:_}=r,C=e.BYTES;m=X("pointHex",m,C),be("zip215",w);let b=m.slice(),L=m[C-1];b[C-1]=L&-129;let R=je(b),I=w?i:e.ORDER;Oe("pointHex.y",R,se,I);let y=a(R*R),S=a(y-It),x=a(E*y-_),{isValid:v,value:A}=c(S,x);if(!v)throw new Error("Point.fromHex: invalid y coordinate");let P=(A&It)===It,T=(L&128)!==0;if(!w&&A===se&&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=Kr(w,e.BYTES);return E[E.length-1]|=m&It?128:0,E}toRawBytes(){return this.toBytes()}toHex(){return ne(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}h.BASE=new h(r.Gx,r.Gy,It,a(r.Gx*r.Gy)),h.ZERO=new h(se,It,It,se),h.Fp=e,h.Fn=n;let p=as(h,n.BYTES*8);return h}function wg(r,t){Me(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||$e,u=t.adjustScalarBytes||(b=>b),l=t.domain||((b,L,R)=>{if(be("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(je(b))}function h(b){let L=s.BYTES;b=X("private key",b,L);let R=X("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=Bt(...L);return d(n(l(R,X("context",b),!!e)))}function w(b,L,R={}){b=X("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);Oe("signature.s",P,se,a);let T=s.BYTES,k=Bt(v,Kr(P,T));return X("result",k,T*2)}let E=gg;function _(b,L,R,I=E){let{context:y,zip215:S}=I,x=s.BYTES;b=X("signature",b,2*x),L=X("message",L),R=X("publicKey",R,x),S!==void 0&&be("zip215",S),e&&(L=e(L));let v=je(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 k=m(y,P.toBytes(),A.toBytes(),L);return P.add(A.multiplyUnsafe(k)).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 xg(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=Qt(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 Eg(r,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:r})}function Wf(r){let{CURVE:t,curveOpts:e,eddsaOpts:n}=xg(r),o=bg(t,e),s=wg(o,n);return Eg(r,s)}var d1=BigInt(0),vg=BigInt(1),Gf=BigInt(2),h1=BigInt(3),_g=BigInt(5),Sg=BigInt(8),us={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Sg,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ag(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=us.p,a=r*r%s*r%s,c=Q(a,Gf,s)*a%s,u=Q(c,vg,s)*r%s,l=Q(u,_g,s)*u%s,f=Q(l,t,s)*l%s,d=Q(f,e,s)*f%s,h=Q(d,n,s)*d%s,p=Q(h,o,s)*h%s,g=Q(p,o,s)*h%s,m=Q(g,t,s)*l%s;return{pow_p_5_8:Q(m,Gf,s)*r%s,b2:a}}function Cg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var jf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ig(r,t){let e=us.p,n=tt(t*t*t,e),o=tt(n*n*t,e),s=Ag(r*o).pow_p_5_8,i=tt(r*n*s,e),a=tt(t*i*i,e),c=i,u=tt(i*jf,e),l=a===r,f=a===tt(-r,e),d=a===tt(-r*jf,e);return l&&(i=c),(f||d)&&(i=u),Nf(i,e)&&(i=tt(-i,e)),{isValid:l||f,value:i}}var Tg=Qt(us.p,void 0,!0),Pg={...us,Fp:Tg,hash:Af,adjustScalarBytes:Cg,uvRatio:Ig},Un=Wf(Pg);var Kn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},qn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},fs=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Zf={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new fs("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=Zf;var ds=32,zn=64,gc=32;var Hr,Xf=(async()=>{try{return await kt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Qf(){let r=Un.utils.randomPrivateKey(),t=Un.getPublicKey(r);return{privateKey:Og(r,t),publicKey:t}}async function Dg(r,t){let e;r.length===zn?e=r.subarray(0,32):e=r;let n={crv:"Ed25519",kty:"OKP",x:M(r.subarray(32),"base64url"),d:M(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 Lg(r,t){let e=r.subarray(0,gc);return Un.sign(t instanceof Uint8Array?t:t.subarray(),e)}async function Yf(r,t){return Hr==null&&(Hr=await Xf),Hr?Dg(r,t):Lg(r,t)}async function Rg(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 kg(r,t,e){return Un.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Jf(r,t,e){return Hr==null&&(Hr=await Xf),Hr?Rg(r,t,e):kg(r,t,e)}function Og(r,t){let e=new Uint8Array(zn);for(let n=0;n<gc;n++)e[n]=r[n],e[gc+n]=t[n];return e}function $r(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Vn=class{type="Ed25519";raw;constructor(t){this.raw=ps(t,ds)}toMultihash(){return Gt.digest(zt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return H.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=Jf(this.raw,e,t);return $r(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},hs=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=ps(t,zn),this.publicKey=new Vn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}sign(t,e){e?.signal?.throwIfAborted();let n=Yf(this.raw,t);return $r(n)?n.then(o=>(e?.signal?.throwIfAborted(),o)):(e?.signal?.throwIfAborted(),n)}};function yc(r){return r=ps(r,ds),new Vn(r)}async function ed(){let{privateKey:r,publicKey:t}=Qf();return new hs(r,t)}function ps(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new O(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Mg=Math.pow(2,7),Ng=Math.pow(2,14),Bg=Math.pow(2,21),bc=Math.pow(2,28),wc=Math.pow(2,35),xc=Math.pow(2,42),Ec=Math.pow(2,49),$=128,wt=127;function ut(r){if(r<Mg)return 1;if(r<Ng)return 2;if(r<Bg)return 3;if(r<bc)return 4;if(r<wc)return 5;if(r<xc)return 6;if(r<Ec)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Wr(r,t,e=0){switch(ut(r)){case 8:t[e++]=r&255|$,r/=128;case 7:t[e++]=r&255|$,r/=128;case 6:t[e++]=r&255|$,r/=128;case 5:t[e++]=r&255|$,r/=128;case 4:t[e++]=r&255|$,r>>>=7;case 3:t[e++]=r&255|$,r>>>=7;case 2:t[e++]=r&255|$,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Fg(r,t,e=0){switch(ut(r)){case 8:t.set(e++,r&255|$),r/=128;case 7:t.set(e++,r&255|$),r/=128;case 6:t.set(e++,r&255|$),r/=128;case 5:t.set(e++,r&255|$),r/=128;case 4:t.set(e++,r&255|$),r>>>=7;case 3:t.set(e++,r&255|$),r>>>=7;case 2:t.set(e++,r&255|$),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function vc(r,t){let e=r[t],n=0;if(n+=e&wt,e<$||(e=r[t+1],n+=(e&wt)<<7,e<$)||(e=r[t+2],n+=(e&wt)<<14,e<$)||(e=r[t+3],n+=(e&wt)<<21,e<$)||(e=r[t+4],n+=(e&wt)*bc,e<$)||(e=r[t+5],n+=(e&wt)*wc,e<$)||(e=r[t+6],n+=(e&wt)*xc,e<$)||(e=r[t+7],n+=(e&wt)*Ec,e<$))return n;throw new RangeError("Could not decode varint")}function Ug(r,t){let e=r.get(t),n=0;if(n+=e&wt,e<$||(e=r.get(t+1),n+=(e&wt)<<7,e<$)||(e=r.get(t+2),n+=(e&wt)<<14,e<$)||(e=r.get(t+3),n+=(e&wt)<<21,e<$)||(e=r.get(t+4),n+=(e&wt)*bc,e<$)||(e=r.get(t+5),n+=(e&wt)*wc,e<$)||(e=r.get(t+6),n+=(e&wt)*xc,e<$)||(e=r.get(t+7),n+=(e&wt)*Ec,e<$))return n;throw new RangeError("Could not decode varint")}function ie(r,t,e=0){return t==null&&(t=yt(ut(r))),t instanceof Uint8Array?Wr(r,t,e):Fg(r,t,e)}function Ye(r,t=0){return r instanceof Uint8Array?vc(r,t):Ug(r,t)}var _c=new Float32Array([-0]),Ne=new Uint8Array(_c.buffer);function rd(r,t,e){_c[0]=r,t[e]=Ne[0],t[e+1]=Ne[1],t[e+2]=Ne[2],t[e+3]=Ne[3]}function nd(r,t){return Ne[0]=r[t],Ne[1]=r[t+1],Ne[2]=r[t+2],Ne[3]=r[t+3],_c[0]}var Sc=new Float64Array([-0]),xt=new Uint8Array(Sc.buffer);function od(r,t,e){Sc[0]=r,t[e]=xt[0],t[e+1]=xt[1],t[e+2]=xt[2],t[e+3]=xt[3],t[e+4]=xt[4],t[e+5]=xt[5],t[e+6]=xt[6],t[e+7]=xt[7]}function sd(r,t){return xt[0]=r[t],xt[1]=r[t+1],xt[2]=r[t+2],xt[3]=r[t+3],xt[4]=r[t+4],xt[5]=r[t+5],xt[6]=r[t+6],xt[7]=r[t+7],Sc[0]}var Kg=BigInt(Number.MAX_SAFE_INTEGER),qg=BigInt(Number.MIN_SAFE_INTEGER),Ft=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 Je;if(t<Kg&&t>qg)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>id&&(o=0n,++n>id&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Je;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):Je}},Je=new Ft(0,0);Je.toBigInt=function(){return 0n};Je.zzEncode=Je.zzDecode=function(){return this};Je.length=function(){return 1};var id=4294967296n;function ad(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 cd(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 Ac(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 Yt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ms(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Cc=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,Yt(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 Yt(this,4);return ms(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Yt(this,4);return ms(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Yt(this,4);let t=nd(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Yt(this,4);let t=sd(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 Yt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return cd(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Yt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Yt(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 Ft(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 Yt(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 Yt(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 Yt(this,8);let t=ms(this.buf,this.pos+=4),e=ms(this.buf,this.pos+=4);return new Ft(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=vc(this.buf,this.pos);return this.pos+=ut(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 Ic(r){return new Cc(r instanceof Uint8Array?r:r.subarray())}function Tt(r,t,e){let n=Ic(r);return t.decode(n,void 0,e)}function Tc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return yt(i);o+i>t&&(n=yt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var tr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Pc(){}var Lc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},zg=Tc();function Vg(r){return globalThis.Buffer!=null?yt(r):zg(r)}var $n=class{len;head;tail;states;constructor(){this.len=0,this.head=new tr(Pc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new tr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Rc((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(gs,10,Ft.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ft.fromBigInt(t);return this._push(gs,e.length(),e)}uint64Number(t){return this._push(Wr,ut(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=Ft.fromBigInt(t).zzEncode();return this._push(gs,e.length(),e)}sint64Number(t){let e=Ft.fromNumber(t).zzEncode();return this._push(gs,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Dc,1,t?1:0)}fixed32(t){return this._push(Hn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ft.fromBigInt(t);return this._push(Hn,4,e.lo)._push(Hn,4,e.hi)}fixed64Number(t){let e=Ft.fromNumber(t);return this._push(Hn,4,e.lo)._push(Hn,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(rd,4,t)}double(t){return this._push(od,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Dc,1,0):this.uint32(e)._push($g,e,t)}string(t){let e=ad(t);return e!==0?this.uint32(e)._push(Ac,e,t):this._push(Dc,1,0)}fork(){return this.states=new Lc(this),this.head=this.tail=new tr(Pc,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 tr(Pc,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=Vg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Dc(r,t,e){t[e]=r&255}function Hg(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Rc=class extends tr{next;constructor(t,e){super(Hg,t,e),this.next=void 0}};function gs(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 Hn(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 $g(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&($n.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Wg,t,r),this},$n.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Gg,t,r),this});function Wg(r,t,e){t.set(r,e)}function Gg(r,t,e){r.length<40?Ac(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(D(r),e)}function kc(){return new $n}function Pt(r,t){let e=kc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var jr;(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"})(jr||(jr={}));function ys(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Oc(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 ys("enum",jr.VARINT,e,n)}function Dt(r,t){return ys("message",jr.LENGTH_DELIMITED,r,t)}var er=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Wn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var st;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(st||(st={}));var Mc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Mc||(Mc={}));(function(r){r.codec=()=>Oc(Mc)})(st||(st={}));var ae;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),st.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=st.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(ae||(ae={}));var Nc;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),st.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=st.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(Nc||(Nc={}));function Zr(r){if(isNaN(r)||r<=0)throw new O("random bytes length must be a Number bigger than 0");return $e(r)}var jn={};Rt(jn,{MAX_RSA_KEY_SIZE:()=>Bc,generateRSAKeyPair:()=>Wc,jwkToJWKKeyPair:()=>pd,jwkToPkcs1:()=>Qg,jwkToPkix:()=>qc,jwkToRSAPrivateKey:()=>$c,pkcs1MessageToJwk:()=>Uc,pkcs1MessageToRSAPrivateKey:()=>zc,pkcs1ToJwk:()=>Xg,pkcs1ToRSAPrivateKey:()=>hd,pkixMessageToJwk:()=>Kc,pkixMessageToRSAPublicKey:()=>Hc,pkixToJwk:()=>Yg,pkixToRSAPublicKey:()=>Vc});var bs=os;var Xr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=jn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return J.createV1(114,this._multihash)}toString(){return H.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 dd(this.jwk,e,t,n)}},Gn=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=jn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}sign(t,e){return fd(this.jwk,t,e)}};var Bc=8192,Fc=18,jg=1062,Zg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Xg(r){let t=pe(r);return Uc(t)}function Uc(r){return{n:M(r[1],"base64url"),e:M(r[2],"base64url"),d:M(r[3],"base64url"),p:M(r[4],"base64url"),q:M(r[5],"base64url"),dp:M(r[6],"base64url"),dq:M(r[7],"base64url"),qi:M(r[8],"base64url"),kty:"RSA"}}function Qg(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 O("JWK was missing components");return Zt([At(Uint8Array.from([0])),At(D(r.n,"base64url")),At(D(r.e,"base64url")),At(D(r.d,"base64url")),At(D(r.p,"base64url")),At(D(r.q,"base64url")),At(D(r.dp,"base64url")),At(D(r.dq,"base64url")),At(D(r.qi,"base64url"))]).subarray()}function Yg(r){let t=pe(r,{offset:0});return Kc(t)}function Kc(r){let t=pe(r[1],{offset:0});return{kty:"RSA",n:M(t[0],"base64url"),e:M(t[1],"base64url")}}function qc(r){if(r.n==null||r.e==null)throw new O("JWK was missing components");return Zt([Zg,Ln(Zt([At(D(r.n,"base64url")),At(D(r.e,"base64url"))]))]).subarray()}function hd(r){let t=pe(r);return zc(t)}function zc(r){let t=Uc(r);return $c(t)}function Vc(r,t){if(r.byteLength>=jg)throw new Ar("Key size is too large");let e=pe(r,{offset:0});return Hc(e,r,t)}function Hc(r,t,e){let n=Kc(r);if(e==null){let o=bs(ae.encode({Type:st.RSA,Data:t}));e=Wt(Fc,o)}return new Xr(n,e)}function $c(r){if(gd(r)>Bc)throw new O("Key size is too large");let t=pd(r),e=bs(ae.encode({Type:st.RSA,Data:qc(t.publicKey)})),n=Wt(Fc,e);return new Gn(t.privateKey,new Xr(t.publicKey,n))}async function Wc(r){if(r>Bc)throw new O("Key size is too large");let t=await md(r),e=bs(ae.encode({Type:st.RSA,Data:qc(t.publicKey)})),n=Wt(Fc,e);return new Gn(t.privateKey,new Xr(t.publicKey,n))}function pd(r){if(r==null)throw new O("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function md(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 Jg(e,t);return{privateKey:n[0],publicKey:n[1]}}async function fd(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 dd(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 Jg(r,t){if(r.privateKey==null||r.publicKey==null)throw new O("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 gd(r){if(r.kty!=="RSA")throw new O("invalid key type");if(r.n==null)throw new O("invalid key modulus");return D(r.n,"base64url").length*8}var ws=class extends Mr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,uf(t);let n=kn(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),ge(s)}update(t){return Br(this),this.iHash.update(t),this}digestInto(t){Br(this),bt(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()}},Gc=(r,t,e)=>new ws(r,t).update(e).digest();Gc.create=(r,t)=>new ws(r,t);function yd(r){r.lowS!==void 0&&be("lowS",r.lowS),r.prehash!==void 0&&be("prehash",r.prehash)}var jc=class extends Error{constructor(t=""){super(t)}},we={Err:jc,_tlv:{encode:(r,t)=>{let{Err:e}=we;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=Bn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Bn(o.length/2|128):"";return Bn(r)+s+o+t},decode(r,t){let{Err:e}=we,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}=we;if(r<Zn)throw new t("integer: negative integers are not allowed");let e=Bn(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}=we;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 Ur(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=we,o=X("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}=we,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Zn=BigInt(0),Xn=BigInt(1),t0=BigInt(2),xs=BigInt(3),e0=BigInt(4);function r0(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 bd(r,t,e){let{BYTES:n}=r;function o(s){let i;if(typeof s=="bigint")i=s;else{let a=X("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 n0(r,t={}){let{Fp:e,Fn:n}=ls("weierstrass",r,t),{h:o,n:s}=r;Me(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(be("isCompressed",S),S){a();let P=!e.isOdd(v);return Bt(wd(P),A)}else return Bt(Uint8Array.of(4),A,e.toBytes(v))}function u(I){bt(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 k=d(T),B;try{B=e.sqrt(k)}catch(W){let F=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}a();let N=e.isOdd(B);return(A&1)===1!==N&&(B=e.neg(B)),{x:T,y:B}}else if(v===x&&A===4){let T=e.fromBytes(P.subarray(y*0,y*1)),k=e.fromBytes(P.subarray(y*1,y*2));if(!h(T,k))throw new Error("bad point: is not on curve");return{x:T,y:k}}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=r0(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,xs),e0),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=qr((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),k=e.mul(v,y);if(A)return{x:e.ZERO,y:e.ZERO};if(!e.eql(k,e.ONE))throw new Error("invZ was invalid");return{x:P,y:T}}),_=qr(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=zr(x,y),S=zr(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 is(b,"pz",y)}static fromBytes(y){return bt(y),b.fromHex(y)}static fromHex(y){let S=b.fromAffine(f(X("pointHex",y)));return S.assertValidity(),S}static fromPrivateKey(y){let S=bd(n,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return b.BASE.multiply(S(y))}static msm(y,S){return cs(b,n,y,S)}precompute(y=8,S=!0){return R.setWindowSize(this,y),S||this.multiply(xs),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,k=e.eql(e.mul(S,T),e.mul(A,v)),B=e.eql(e.mul(x,T),e.mul(P,v));return k&&B}negate(){return new b(this.px,e.neg(this.py),this.pz)}double(){let{a:y,b:S}=r,x=e.mul(S,xs),{px:v,py:A,pz:P}=this,T=e.ZERO,k=e.ZERO,B=e.ZERO,N=e.mul(v,v),ot=e.mul(A,A),W=e.mul(P,P),F=e.mul(v,A);return F=e.add(F,F),B=e.mul(v,P),B=e.add(B,B),T=e.mul(y,B),k=e.mul(x,W),k=e.add(T,k),T=e.sub(ot,k),k=e.add(ot,k),k=e.mul(T,k),T=e.mul(F,T),B=e.mul(x,B),W=e.mul(y,W),F=e.sub(N,W),F=e.mul(y,F),F=e.add(F,B),B=e.add(N,N),N=e.add(B,N),N=e.add(N,W),N=e.mul(N,F),k=e.add(k,N),W=e.mul(A,P),W=e.add(W,W),N=e.mul(W,F),T=e.sub(T,N),B=e.mul(W,ot),B=e.add(B,B),B=e.add(B,B),new b(T,k,B)}add(y){w(y);let{px:S,py:x,pz:v}=this,{px:A,py:P,pz:T}=y,k=e.ZERO,B=e.ZERO,N=e.ZERO,ot=r.a,W=e.mul(r.b,xs),F=e.mul(S,A),at=e.mul(x,P),ct=e.mul(v,T),gt=e.add(S,x),Z=e.add(A,P);gt=e.mul(gt,Z),Z=e.add(F,at),gt=e.sub(gt,Z),Z=e.add(S,v);let St=e.add(A,T);return Z=e.mul(Z,St),St=e.add(F,ct),Z=e.sub(Z,St),St=e.add(x,v),k=e.add(P,T),St=e.mul(St,k),k=e.add(at,ct),St=e.sub(St,k),N=e.mul(ot,Z),k=e.mul(W,ct),N=e.add(k,N),k=e.sub(at,N),N=e.add(at,N),B=e.mul(k,N),at=e.add(F,F),at=e.add(at,F),ct=e.mul(ot,ct),Z=e.mul(W,Z),at=e.add(at,ct),ct=e.sub(F,ct),ct=e.mul(ot,ct),Z=e.add(Z,ct),F=e.mul(at,Z),B=e.add(B,F),F=e.mul(St,Z),k=e.mul(gt,k),k=e.sub(k,F),F=e.mul(gt,at),N=e.mul(St,N),N=e.add(N,F),new b(k,B,N)}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:k,k2:B}=S.splitScalar(y),{p:N,f:ot}=A(T),{p:W,f:F}=A(B);v=ot.add(F),x=C(S.beta,N,W,P,k)}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===Zn||x.is0())return b.ZERO;if(y===Xn)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:k,p2:B}=$f(b,x,A,T);return C(S.beta,k,B,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===Xn?!0:y?y(b,this):R.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){let{clearCofactor:y}=t;return o===Xn?this:y?y(b,this):this.multiplyUnsafe(o)}toBytes(y=!0){return be("isCompressed",y),this.assertValidity(),l(b,this,y)}toRawBytes(y=!0){return this.toBytes(y)}toHex(y=!0){return ne(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=as(b,t.endo?Math.ceil(L/2):L);return b}function wd(r){return Uint8Array.of(r?2:3)}function o0(r,t,e={}){Me(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||$e,o=t.hmac||((x,...v)=>Gc(t.hash,x,Bt(...v))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i;function u(x){let v=a>>Xn;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=X("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}=we.toSig(X("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:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*t0<A&&k>1)throw new Error("recovery id is ambiguous for h>1 curve");let N=k===2||k===3?P+a:P;if(!s.isValid(N))throw new Error("recovery id 2 or 3 invalid");let ot=s.toBytes(N),W=r.fromHex(Bt(wd((k&1)===0),ot)),F=i.inv(N),at=_(X("msgHash",v)),ct=i.create(-at*F),gt=i.create(T*F),Z=r.BASE.multiplyUnsafe(ct).add(W.multiplyUnsafe(gt));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 Bt(i.toBytes(this.r),i.toBytes(this.s));if(v==="der")return Fr(we.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return ne(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ne(this.toBytes("compact"))}}let h=bd(i,e.allowedPrivateKeyLengths,e.wrapPrivateKey),p={isValidPrivateKey(x){try{return h(x),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{let x=a;return Uf(n(fc(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=X("key",x).length,P=s.BYTES,T=P+1,k=2*P+1;if(!(e.allowedPrivateKeyLengths||i.BYTES===T))return A===T||A===k}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=Ur(x),A=x.length*8-c;return A>0?v>>BigInt(A):v},_=t.bits2int_modN||function(x){return i.create(E(x))},C=Ze(c);function b(x){return Oe("num < 2^"+c,x,Zn,C),i.toBytes(x)}function L(x,v,A=R){if(["recovered","canonical"].some(gt=>gt in A))throw new Error("sign() legacy options not supported");let{hash:P}=t,{lowS:T,prehash:k,extraEntropy:B}=A;T==null&&(T=!0),x=X("msgHash",x),yd(A),k&&(x=X("prehashed msgHash",P(x)));let N=_(x),ot=h(v),W=[b(ot),b(N)];if(B!=null&&B!==!1){let gt=B===!0?n(s.BYTES):B;W.push(X("extraEntropy",gt))}let F=Bt(...W),at=N;function ct(gt){let Z=E(gt);if(!i.isValidNot0(Z))return;let St=i.inv(Z),wn=r.BASE.multiply(Z).toAffine(),vr=i.create(wn.x);if(vr===Zn)return;let Ke=i.create(St*i.create(at+vr*ot));if(Ke===Zn)return;let Sa=(wn.x===vr?0:2)|Number(wn.y&Xn),_r=Ke;return T&&u(Ke)&&(_r=l(Ke),Sa^=1),new d(vr,_r,Sa)}return{seed:F,k2sig:ct}}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 Pf(t.hash.outputLen,i.BYTES,o)(P,T)}r.BASE.precompute(8);function S(x,v,A,P=I){let T=x;v=X("msgHash",v),A=X("publicKey",A),yd(P);let{lowS:k,prehash:B,format:N}=P;if("strict"in P)throw new Error("options.strict was renamed to lowS");if(N!==void 0&&!["compact","der","js"].includes(N))throw new Error('format must be "compact", "der" or "js"');let ot=typeof T=="string"||Nr(T),W=!ot&&!N&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!ot&&!W)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,at;try{if(W)if(N===void 0||N==="js")F=new d(T.r,T.s);else throw new Error("invalid format");if(ot){try{N!=="compact"&&(F=d.fromDER(T))}catch(_r){if(!(_r instanceof we.Err))throw _r}!F&&N!=="der"&&(F=d.fromCompact(T))}at=r.fromHex(A)}catch{return!1}if(!F||k&&F.hasHighS())return!1;B&&(v=t.hash(v));let{r:ct,s:gt}=F,Z=_(v),St=i.inv(gt),wn=i.create(Z*St),vr=i.create(ct*St),Ke=r.BASE.multiplyUnsafe(wn).add(at.multiplyUnsafe(vr));return Ke.is0()?!1:i.create(Ke.x)===ct}return Object.freeze({getPublicKey:g,getSharedSecret:w,sign:y,verify:S,utils:p,Point:r,Signature:d})}function s0(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=Qt(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 i0(r){let{CURVE:t,curveOpts:e}=s0(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 a0(r,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:r})}function xd(r){let{CURVE:t,curveOpts:e,ecdsaOpts:n}=i0(r),o=n0(t,e),s=o0(o,n,e);return a0(r,s)}function Ed(r,t){let e=n=>xd({...r,hash:n});return{...e(t),create:e}}var Es={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Jv=BigInt(0),c0=BigInt(1),Zc=BigInt(2),vd=(r,t)=>(r+t/Zc)/t;function l0(r){let t=Es.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=Q(l,e,t)*l%t,d=Q(f,e,t)*l%t,h=Q(d,Zc,t)*u%t,p=Q(h,o,t)*h%t,g=Q(p,s,t)*p%t,m=Q(g,a,t)*g%t,w=Q(m,c,t)*m%t,E=Q(w,a,t)*g%t,_=Q(E,e,t)*l%t,C=Q(_,i,t)*p%t,b=Q(C,n,t)*u%t,L=Q(b,Zc,t);if(!Xc.eql(Xc.sqr(L),r))throw new Error("Cannot find square root");return L}var Xc=Qt(Es.p,void 0,void 0,{sqrt:l0}),Jt=Ed({...Es,Fp:Xc,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Es.n,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-c0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=vd(s*r,t),c=vd(-n*r,t),u=tt(r-a*e-c*o,t),l=tt(-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}}}},os);function _d(r,t,e){let n=Or.digest(t instanceof Uint8Array?t:t.subarray());if($r(n))return n.then(({digest:o})=>(e?.signal?.throwIfAborted(),Jt.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Kn(String(o))});try{return Jt.sign(n.digest,r).toDERRawBytes()}catch(o){throw new Kn(String(o))}}function Sd(r,t,e,n){let o=Or.digest(e instanceof Uint8Array?e:e.subarray());if($r(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Jt.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new qn(String(s))});try{return n?.signal?.throwIfAborted(),Jt.verify(t,o.digest,r)}catch(s){throw new qn(String(s))}}var Qn=class{type="secp256k1";raw;_key;constructor(t){this._key=Id(t),this.raw=Ad(this._key)}toMultihash(){return Gt.digest(zt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return H.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 Sd(this._key,e,t,n)}},vs=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=Cd(t),this.publicKey=new Qn(e??Td(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}sign(t,e){return _d(this.raw,t,e)}};function Qc(r){return new Qn(r)}async function Pd(){let r=u0();return new vs(r)}function Ad(r){return Jt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Cd(r){try{return Jt.getPublicKey(r,!0),r}catch(t){throw new xn(String(t))}}function Id(r){try{return Jt.ProjectivePoint.fromHex(r),r}catch(t){throw new Ar(String(t))}}function Td(r){try{return Jt.getPublicKey(r,!0)}catch(t){throw new xn(String(t))}}function u0(){return Jt.utils.randomPrivateKey()}async function Dd(r,t){if(r==="Ed25519")return ed();if(r==="secp256k1")return Pd();if(r==="RSA")return Wc(f0(t));if(r==="ECDSA")return cf(d0(t));throw new Te}function Qr(r,t){let{Type:e,Data:n}=ae.decode(r),o=n??new Uint8Array;switch(e){case st.RSA:return Vc(o,t);case st.Ed25519:return yc(o);case st.secp256k1:return Qc(o);case st.ECDSA:return rc(o);default:throw new Te}}function Ld(r){let{Type:t,Data:e}=ae.decode(r.digest),n=e??new Uint8Array;switch(t){case st.Ed25519:return yc(n);case st.secp256k1:return Qc(n);case st.ECDSA:return rc(n);default:throw new Te}}function zt(r){return ae.encode({Type:st[r.type],Data:r.raw})}function f0(r){return r==null?2048:parseInt(r,10)}function d0(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 O("Unsupported curve, should be P-256, P-384 or P-521")}var Rd=Symbol.for("nodejs.util.inspect.custom"),h0=114,Yn=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()})`}[qo]=!0;toString(){return this.string==null&&(this.string=H.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return J.createV1(h0,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")}[Rd](){return`PeerId(${this.toString()})`}},Jn=class extends Yn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},to=class extends Yn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},eo=class extends Yn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},p0=2336,ro=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Gt.digest(D(this.url))}[Rd](){return`PeerId(${this.url})`}[qo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return J.createV1(p0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=M(t)),t.toString()===this.toString())}};var m0=114,kd=2336;function ce(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=he(H.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return no(J.parse(r));if(t==null)throw new O('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=he(t.decode(r))}return Yr(e)}function Yc(r){if(r.type==="Ed25519")return new to({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new eo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Jn({multihash:r.toCID().multihash,publicKey:r});throw new Te}function Od(r){return Yc(r.publicKey)}function Yr(r){if(y0(r))return new Jn({multihash:r});if(g0(r))try{let t=Ld(r);if(t.type==="Ed25519")return new to({multihash:r,publicKey:t});if(t.type==="secp256k1")return new eo({multihash:r,publicKey:t})}catch{let e=M(r.digest);return new ro(new URL(e))}throw new Ho("Supplied PeerID Multihash is invalid")}function no(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==m0&&r.code!==kd)throw new Vo("Supplied PeerID CID is invalid");if(r.code===kd){let t=M(r.multihash.digest);return new ro(new URL(t))}return Yr(r.multihash)}function g0(r){return r.code===Gt.code}function y0(r){return r.code===Or.code}function Jr(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:Nd}=Object.prototype,{propertyIsEnumerable:b0}=Object,tn=(r,t,e)=>{Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0})},w0=void 0,Md={concatArrays:!1,ignoreUndefined:!1},_s=r=>{let t=[];for(let e in r)Nd.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)b0.call(r,n)&&t.push(n)}return t};function en(r){return Array.isArray(r)?x0(r):Jr(r)?E0(r):r}function x0(r){let t=r.slice(0,0);return _s(r).forEach(e=>{tn(t,e,en(r[e]))}),t}function E0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return _s(r).forEach(e=>{tn(t,e,en(r[e]))}),t}var Bd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?tn(r,o,Jc(r[o],t[o],n)):tn(r,o,en(t[o])))}),r),v0=(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++)Nd.call(s,a)&&(i.push(String(a)),s===r?tn(n,o++,s[a]):tn(n,o++,en(s[a])));n=Bd(n,s,_s(s).filter(a=>!i.includes(a)),e)}),n};function Jc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?v0(r,t,e):!Jr(t)||!Jr(r)?en(t):Bd(r,t,_s(t),e)}function Ss(...r){let t=Jc(en(Md),this!==w0&&this||{},Md),e={_:{}};for(let n of r)if(n!==void 0){if(!Jr(n))throw new TypeError("`"+n+"` is not an Option Object");e=Jc(e,{_:n},t)}return e._}var it=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var el=Ko(Ud(),1);var so=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},rl=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Kd=r=>globalThis.DOMException===void 0?new rl(r):new DOMException(r),qd=r=>{let t=r.reason===void 0?Kd("This operation was aborted."):r.reason;return t instanceof Error?t:Kd(t)};function nl(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 so;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 ol(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 io=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=ol(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 ao=class extends el.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:io,...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=nl(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 so&&!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 Cs(r){let t=[Ut.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var sl=60;function Is(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:Ut[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Ut[t.type],TTL:t.TTL??t.ttl??sl,data:t.data instanceof Uint8Array?M(t.data):t.data}))}}var A0=4;function il(r,t={}){let e=new ao({concurrency:t.queryConcurrency??A0});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Cs(o.types).forEach(a=>{s.append("type",Ut[a])}),o.onProgress?.(new it("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=Is(await a.json());return o.onProgress?.(new it("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function zd(){return[il("https://cloudflare-dns.com/dns-query"),il("https://dns.google/resolve")]}var $d=Ko(Hd(),1);var al=class{lru;constructor(t){this.lru=(0,$d.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 Is({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:Ut[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??sl)*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 Wd(r){return new al(r)}var C0=1e3,Ts=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Wd(t.cacheSize??C0),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["."]=zd())}async query(t,e={}){let n=Cs(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new it("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 it("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Ut;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ut||(Ut={}));function Gd(r={}){return new Ts(r)}var dt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},xe=class extends Error{static name="ValidationError";name="ValidationError"},co=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ps=class extends Error{static name="InvalidProtocolError";name="InvalidProtocolError"};var Ds=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 jd=45,I0=15,rn=new Ds;function Ls(r){if(!(r.length>I0))return rn.new(r).parseWith(()=>rn.readIPv4Addr())}function Rs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>jd))return rn.new(r).parseWith(()=>rn.readIPv6Addr())}function nn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>jd)return;let e=rn.new(r).parseWith(()=>rn.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 Kt(r){return!!Ls(r)}function on(r){return!!Rs(r)}function ll(r){return t=>M(t,r)}function ul(r){return t=>D(t,r)}function sn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function rr(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Zd(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=rr(n);return jt([e,o],e.length+o.length)}function Xd(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=qt.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=rr(n);return jt([e,o],e.length+o.length)}function fl(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=M(t,"base32"),o=sn(e);return`${n}:${o}`}var dl=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 dt("Invalid byte value in IP address");t[n]=o}),t},Qd=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Kt(e[n]),i;s&&(i=dl(e[n]),e[n]=M(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,M(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 dt("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Yd=function(r){if(r.byteLength!==4)throw new dt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Jd=function(r){if(r.byteLength!==16)throw new dt("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 dt(`Invalid IPv6 address "${e}"`)}};function th(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new dt(`Invalid IPv6 address "${r}"`)}}var cl=Object.values(Tn).map(r=>r.decoder),T0=function(){let r=cl[0].or(cl[1]);return cl.slice(2).forEach(t=>r=r.or(t)),r}();function eh(r){return T0.decode(r)}function rh(r){return t=>r.encoder.encode(t)}function P0(r){if(parseInt(r).toString()!==r)throw new xe("Value must be an integer")}function D0(r){if(r<0)throw new xe("Value must be a positive integer, or zero")}function L0(r){return t=>{if(t>r)throw new xe(`Value must be smaller than or equal to ${r}`)}}function R0(...r){return t=>{for(let e of r)e(t)}}var lo=R0(P0,D0,L0(65535));var ht=-1,hl=class{protocolsByCode=new Map;protocolsByName=new Map;getCodec(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new Ps(`Protocol ${t} was unknown`);return e}addCodec(t,e,n){this.protocolsByCode.set(t,e),this.protocolsByName.set(e.name,e),n?.forEach(o=>{this.protocolsByName.set(o,e)})}deleteCodec(t){let e=this.getCodec(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Ot=new hl,cy=[{code:4,name:"ip4",size:32,valueToBytes:dl,bytesToValue:Yd,validate:r=>{if(!Kt(r))throw new xe(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:rr,bytesToValue:sn,validate:lo},{code:273,name:"udp",size:16,valueToBytes:rr,bytesToValue:sn,validate:lo},{code:33,name:"dccp",size:16,valueToBytes:rr,bytesToValue:sn,validate:lo},{code:41,name:"ip6",size:128,valueToBytes:Qd,bytesToValue:Jd,stringToValue:th,validate:r=>{if(!on(r))throw new xe(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ht},{code:43,name:"ipcidr",size:8,bytesToValue:ll("base10"),valueToBytes:ul("base10")},{code:53,name:"dns",size:ht,resolvable:!0},{code:54,name:"dns4",size:ht,resolvable:!0},{code:55,name:"dns6",size:ht,resolvable:!0},{code:56,name:"dnsaddr",size:ht,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:rr,bytesToValue:sn,validate:lo},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ht,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ht,bytesToValue:ll("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ul("base58btc")(r):J.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:fl,valueToBytes:Zd},{code:445,name:"onion3",size:296,bytesToValue:fl,valueToBytes:Xd},{code:446,name:"garlic64",size:ht},{code:447,name:"garlic32",size:ht},{code:448,name:"tls"},{code:449,name:"sni",size:ht},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ht,bytesToValue:rh(In),valueToBytes:eh},{code:480,name:"http"},{code:481,name:"http-path",size:ht,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:ht}];cy.forEach(r=>{Ot.addCodec(r.code,r,r.aliases)});function nh(r){let t=[],e=0;for(;e<r.length;){let n=Ye(r,e),o=Ot.getCodec(n),s=ut(n),i=ly(o,r,e+s),a=0;i>0&&o.size===ht&&(a=ut(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)??M(f)}t.push(u),e+=c}return t}function oh(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Ot.getCodec(n.code),s=ut(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,o.size===ht&&(c=ut(a)));let u=new Uint8Array(s+c+a),l=0;Wr(n.code,u,l),l+=s,i!=null&&(o.size===ht&&(Wr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return jt(e,t)}function sh(r){if(r.charAt(0)!=="/")throw new dt('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=Ot.getCodec(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 dt(`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 dt(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new dt("Incomplete multiaddr");return t}function ih(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Ot.getCodec(t.code);if(e==null)throw new dt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function ly(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Ye(t,e)}var uy=Symbol.for("nodejs.util.inspect.custom"),yl=Symbol.for("@multiformats/multiaddr"),fy=[53,54,55,56],gl=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function dy(r){if(r==null&&(r="/"),Be(r))return r.getComponents();if(r instanceof Uint8Array)return nh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),sh(r);if(Array.isArray(r))return r;throw new dt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ms=class r{[yl]=!0;#t;#n;#e;constructor(t="/",e={}){this.#t=dy(t),e.validate!==!1&&hy(this)}get bytes(){return this.#e==null&&(this.#e=oh(this.#t)),this.#e}toString(){return this.#n==null&&(this.#n=ih(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??""}`),fy.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=Ot.getCodec(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=Ot.getCodec(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 co(`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"?M(H.decode(`z${n}`),"base58btc"):M(J.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(Ot.getCodec(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=cn.get(e.name);if(n==null)throw new gl(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>q(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)}[uy](){return`Multiaddr(${this.toString()})`}};function hy(r){r.getComponents().forEach(t=>{let e=Ot.getCodec(t.code);t.value!=null&&e.validate?.(t.value)})}function ah(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 ch(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 bl(r){switch(r.length){case nr:return r.join(".");case or:{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 lh(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 uh(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var nr=4,or=16,vS=parseInt("0xFFFF",16),py=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function po(r,t){t.length===or&&r.length===nr&&ah(t,0,11)&&(t=t.slice(12)),t.length===nr&&r.length===or&&ch(r,py,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 fh(r,t){if(typeof t=="string"&&(t=nn(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 wl(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=nr,o=Ls(t);if(o==null&&(n=or,o=Rs(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=xl(s,8*n);return{network:po(o,i),mask:i}}function xl(r,t){if(t!==8*nr&&t!==8*or)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 ln=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=wl(t));else{let n=nn(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=nn(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=xl(o,8*n.length);this.network=po(n,this.mask)}}contains(t){return fh({network:this.network,mask:this.mask},t)}toString(){let t=lh(this.mask),e=t!==-1?String(t):uh(this.mask);return bl(this.network)+"/"+e}};function El(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 ln(e,t)}var cn=new Map;function Be(r){return!!r?.[yl]}function q(r){return new Ms(r)}function Ns(r){let t=Ot.getCodec(r);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}var vl={},_l={},my=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];my.forEach(r=>{let t=gy(...r);_l[t.code]=t,vl[t.name]=t});function gy(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function dh(r){if(typeof r=="number"){if(_l[r]!=null)return _l[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(vl[r]!=null)return vl[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var yy=32,{code:by}=dh("dnsaddr"),Sl=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},sr=async function(t,e={}){let n=e.maxRecursiveDepth??yy;if(n===0)throw new Sl("Max recursive depth reached");let[,o]=t.stringTuples().find(([u])=>u===by)??[],i=await(e?.dns??Gd()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[Ut.TXT]}),a=t.getPeerId(),c=[];for(let u of i.Answer){let l=u.data.replace(/["']/g,"").trim().split("=")[1];if(l==null||a!=null&&!l.includes(a))continue;let f=q(l);if(l.startsWith("/dnsaddr")){let d=await f.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(h=>h.toString()))}else c.push(f.toString())}return c};var wy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:sr}},transportManager:{faultTolerance:qe.FATAL_ALL}};async function hh(r){let t=Ss(wy,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new O("Private network is enforced, but no protector was provided");return t}function xy(r,t){try{if(typeof r=="string"&&r.length>0)return Ey(r);if(typeof r=="number"&&isFinite(r))return t?.long?_y(r):vy(r);throw new Error("Value is not a string or number.")}catch(e){let n=Sy(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function Ey(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 Fs=xy;function vy(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 _y(r){let t=Math.abs(r);return t>=864e5?Bs(r,t,864e5,"day"):t>=36e5?Bs(r,t,36e5,"hour"):t>=6e4?Bs(r,t,6e4,"minute"):t>=1e3?Bs(r,t,1e3,"second"):`${r} ms`}function Bs(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function Sy(r){return typeof r=="object"&&r!==null&&"message"in r}function Al(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=Fs,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 Us=Ly(),Ay=["#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 Cy(){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 Iy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Fs(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 Ty=console.debug??console.log??(()=>{});function Py(r){try{r?Us?.setItem("debug",r):Us?.removeItem("debug")}catch{}}function Dy(){let r;try{r=Us?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Ly(){try{return localStorage}catch{}}function Ry(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var ph=Al({formatArgs:Iy,save:Py,load:Dy,useColors:Cy,setupFormatters:Ry,colors:Ay,storage:Us,log:Ty});var Mt=ph;Mt.formatters.b=r=>r==null?"undefined":H.baseEncode(r);Mt.formatters.t=r=>r==null?"undefined":qt.baseEncode(r);Mt.formatters.m=r=>r==null?"undefined":Ha.baseEncode(r);Mt.formatters.p=r=>r==null?"undefined":r.toString();Mt.formatters.c=r=>r==null?"undefined":r.toString();Mt.formatters.k=r=>r==null?"undefined":r.toString();Mt.formatters.a=r=>r==null?"undefined":r.toString();Mt.formatters.e=r=>r==null?"undefined":mh(r.stack)??mh(r.message)??r.toString();function ky(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 Ks(){return{forComponent(r){return Oy(r)}}}function Oy(r){let t=ky(`${r}:trace`);return Mt.enabled(`${r}:trace`)&&Mt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Mt(`${r}:trace`)),Object.assign(Mt(r),{error:Mt(`${r}:error`),trace:t})}function mh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function ir(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 qs(r){let t=he(H.decode(`z${r}`));return Yr(t)}var Vt=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 ir(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 ir(this.map.values(),t=>t.key)}values(){return ir(this.map.values(),t=>t.value)}get size(){return this.map.size}};var ar=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 ir(this.set.entries(),t=>{let e=qs(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=qs(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return ir(this.set.values(),t=>qs(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 Cl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},gh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},yh=new globalThis.TextEncoder;function My(r,t){let e=Cl[t],n=gh[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Ny(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Cl[t],o=gh[t],s=r;for(;s.length>0;){let i=yh.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 Il(r,{size:t=32,utf8Buffer:e}={}){if(!Cl[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 Ny(r,t,e);r=yh.encode(r)}return My(r,t)}var mo={hash:r=>Number(Il(r,{size:32})),hashV:(r,t)=>By(mo.hash(r,t))};function By(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),D(t,"base16")}var Tl=64,ee=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Tl)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=rt(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 cr(r,t){return Math.floor(Math.random()*(t-r))+r}var lr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof ee))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ee))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 ee))throw new TypeError("Invalid Fingerprint");let e=cr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof ee))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Fy=500,go=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??mo,this.seed=t.seed??cr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=D(t));let e=new ee(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 lr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new lr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[cr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new lr(this.bucketSize));for(let a=0;a<Fy;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 lr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=D(t));let e=new ee(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 ee(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}},Uy={1:.5,2:.84,4:.95,8:.98};function Ky(r=.001){return r>.002?2:r>1e-5?4:8}function bh(r,t=.001){let e=Ky(t),n=Uy[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Tl);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var zs=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??mo,this.seed=t.seed??cr(0,Math.pow(2,10)),this.filterSeries=[new go({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 go({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 yo(r,t=.001,e){return new zs({...bh(r,t),...e??{}})}var Pl=class extends Vt{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 Dl(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Pl({name:t,metrics:e}):n=new Vt,n}var bo;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((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:rt(0),payloadType:rt(0),payload:rt(0),signature:rt(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=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(bo||(bo={}));var Vs=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var un=class r{static createFromProtobuf=t=>{let e=bo.decode(t),n=Qr(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=wh(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 Vs("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=bo.encode({publicKey:zt(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=wh(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},wh=(r,t,e)=>{let n=D(r),o=ie(n.byteLength),s=ie(t.length),i=ie(e.length);return new z(o,n,s,t,i,e)};function xh(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 Eh="libp2p-peer-record",vh=Uint8Array.from([3,1]);var wo;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Dt((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:rt(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=>Pt(s,n.codec()),n.decode=(s,i)=>Tt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Dt((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:rt(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 er('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=>Pt(n,r.codec()),r.decode=(n,o)=>Tt(n,r.codec(),o)})(wo||(wo={}));var ur=class r{static createFromProtobuf=t=>{let e=wo.decode(t),n=Yr(he(e.peerId)),o=(e.addresses??[]).map(i=>q(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Eh;static CODEC=vh;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=wo.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||!xh(this.multiaddrs,t.multiaddrs))}};function qy(r){return r[Symbol.asyncIterator]!=null}function zy(r){if(qy(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 xo=zy;var re=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};function nt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Hs=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}},fn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Hs(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 Hs(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 Ll=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function $s(r={}){return Vy(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 Vy(r,t){t=t??{};let e=t.onEnd,n=new fn,o,s,i,a=nt(),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=nt()})}},u=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new fn,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 fn,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 Ll)},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 Rl=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 ue(r,t,e,n){let o=new Rl(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 Ws=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Gs=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 pt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Gs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Gs(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 re)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Hy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Zs=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Hy(),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 re),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 pt(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 kl(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 Eo=class extends Nt{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=kl(this.emitEmpty.bind(this),1),this.emitIdle=kl(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 Ws;let n=new Zs(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 re)}),this.clear()}async onEmpty(t){this.size!==0&&await ue(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await ue(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ue(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=$s({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 re("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 Xs="lock:worker:request-read",Qs="lock:worker:abort-read-request",Ys="lock:worker:release-read",Js="lock:master:grant-read",ti="lock:master:error-read",ei="lock:worker:request-write",ri="lock:worker:abort-write-request",ni="lock:worker:release-write",oi="lock:master:grant-write",si="lock:master:error-write",ii="lock:worker:finalize",ai="mortice",_h={singleProcess:!1};var Ol=(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===ii&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var Sh=(r=10)=>Math.random().toString().substring(2,r+2);var ci=class{name;channel;constructor(t){this.name=t,this.channel=new BroadcastChannel(ai)}readLock(t){return this.sendRequest(Xs,Qs,Js,ti,Ys,t)}writeLock(t){return this.sendRequest(ei,ri,oi,si,ni,t)}finalize(){this.channel.postMessage({type:ii,name:this.name}),this.channel.close()}async sendRequest(t,e,n,o,s,i){i?.signal?.throwIfAborted();let a=Sh();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 Ah=r=>{if(r=Object.assign({},_h,r),!!globalThis.document||r.singleProcess){let e=new BroadcastChannel(ai),n=new Nt;return e.addEventListener("message",Ol(n,e,"requestReadLock","abortReadLockRequest",Xs,Qs,ti,Ys,Js)),e.addEventListener("message",Ol(n,e,"requestWriteLock","abortWriteLockRequest",ei,ri,si,ni,oi)),n}return new ci(r.name)};var fr=new Map,vo;function Ch(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function $y(r){if(vo==null&&(vo=Ah(r),!Ch(vo))){let t=vo;t.addEventListener("requestReadLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=fr.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=fr.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=fr.get(n);o?.finalize()})}return vo}async function Ml(r,t){let e,n,o=new Promise((i,a)=>{e=i,n=a}),s=()=>{n(new re)};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 Ih=(r,t)=>{let e=fr.get(r);if(e!=null)return e;let n=$y(t);if(Ch(n))return e=n,fr.set(r,e),e;let o=new Eo({concurrency:1}),s;return e={async readLock(i){if(s!=null)return Ml(s,i);s=new Eo({concurrency:t.concurrency,autoStart:!1});let a=s,c=Ml(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Ml(o,i)},finalize:()=>{fr.delete(r)},queue:o},fr.set(r,e),t.autoFinalize===!0&&o.addEventListener("idle",()=>{e.finalize()},{once:!0}),e};var Wy={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Nl(r){let t=Object.assign({},Wy,r);return Ih(t.name,t)}var ve;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Dt((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:rt(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=>Pt(i,o.codec()),o.decode=(i,a)=>Tt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Dt((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),ui.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=ui.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Pt(i,o.codec()),o.decode=(i,a)=>Tt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Dt((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),li.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 er('Decode error - map field "addresses" had too many elements');a.addresses.push(li.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 er('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 Wn('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 Wn('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=>Pt(o,r.codec()),r.decode=(o,s)=>Tt(o,r.codec(),s)})(ve||(ve={}));var li;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((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:rt(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=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(li||(li={}));var ui;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((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=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(ui||(ui={}));function Gy(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;r.type==="RSA"&&(e=r.toMultihash());let n=Qr(t.publicKey,e);return Yc(n)}function Th(r,t,e){let n=ve.decode(t);return dn(r,n,e)}function dn(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:Gy(r,t),addresses:t.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-e).map(({multiaddr:s,isCertified:i})=>({multiaddr:q(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function Ph(r,t){return jy(r.addresses,t.addresses)&&Zy(r.protocols,t.protocols)&&Xy(r.publicKey,t.publicKey)&&Qy(r.peerRecordEnvelope,t.peerRecordEnvelope)&&Yy(r.metadata,t.metadata)&&Jy(r.tags,t.tags)}function jy(r,t){return Lh(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!G(e.multiaddr,n.multiaddr)))}function Zy(r,t){return Lh(r,t,(e,n)=>e===n)}function Xy(r,t){return Dh(r,t)}function Qy(r,t){return Dh(r,t)}function Yy(r,t){return Rh(r,t,(e,n)=>G(e,n))}function Jy(r,t){return Rh(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function Dh(r,t){return r==null&&t==null?!0:r!=null&&t!=null?G(r,t):!1}function Lh(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 Rh(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 _e="/",kh=new TextEncoder().encode(_e),fi=kh[0],dr=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]!==fi)throw new Error("Invalid key")}toString(t="utf8"){return M(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(_e))}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=kh),this._buf[0]!==fi){let t=new Uint8Array(this._buf.byteLength+1);t.fill(fi,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===fi;)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(_e).slice(1)}type(){return tb(this.baseNamespace())}name(){return eb(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(_e)||(t+=_e),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(_e):new r(t.slice(0,-1).join(_e))}child(t){return this.toString()===_e?t:t.toString()===_e?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(),...rb(t.map(e=>e.namespaces()))])}};function tb(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function eb(r){let t=r.split(":");return t[t.length-1]}function rb(r){return[].concat(...r)}var Bl="/peers/";function _o(r){if(!Ce(r)||r.type==null)throw new O("Invalid PeerId");let t=r.toCID().toString();return new dr(`${Bl}${t}`)}async function Oh(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=q(i.multiaddr)),!Be(i.multiaddr))throw new O("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(q(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function hi(r,t,e,n){if(t==null)throw new O("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new O("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new O("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=di(d,{validate:Mh})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=di(d,{validate:Nh,map:Bh})}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=di([...a.entries()],{validate:Mh})}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=di([...h.entries()],{validate:Nh,map:Bh})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=zt(o.id.publicKey):t.publicKey!=null?l=zt(t.publicKey):r.publicKey!=null&&(l=zt(r.publicKey));let f={addresses:await Oh(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 di(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 Mh(r,t){if(typeof r!="string")throw new O("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new O("Metadata value must be a Uint8Array")}function Nh(r,t){if(typeof r!="string")throw new O("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new O("Tag value must be an integer");if(t.value<0||t.value>100)throw new O("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new O("Tag ttl must be an integer");if(t.ttl<0)throw new O("Tag ttl must be between greater than 0")}}function Bh(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 Fh(r){let t=r.toString().split("/")[2],e=J.parse(t,qt);return no(e)}function Fl(r,t,e){let n=Fh(r);return Th(n,t,e)}function nb(r,t){return{prefix:Bl,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(Fl(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(Fl(n.key,n.value,t),Fl(o.key,o.value,t)))}}var pi=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=Dl({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:Nl({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(_o(t),e)}async load(t,e){let n=_o(t),o=await this.datastore.get(n,e),s=ve.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new ze;return dn(t,s,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e,n){let o=await this.#t(t,n),s=await hi(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 hi(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 hi(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(nb(t??{},this.maxAddressAge),t)){let o=Fh(e);if(o.equals(this.peerId))continue;let s=ve.decode(n);if(this.#e(o,s)){await this.datastore.delete(e,t);continue}yield dn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t,e){try{let n=_o(t),o=await this.datastore.get(n,e),s=ve.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new ze;return{peerPB:s,peer:dn(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=ve.encode(e);return await this.datastore.put(_o(t),s,o),{peer:dn(t,e,this.maxAddressAge),previous:n?.peer,updated:n==null||!Ph(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 Ul=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 pi(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 xo(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=Ce(e)?e:Ce(e?.expectedPeer)?e.expectedPeer:void 0,s=Ce(e)||e===void 0?n:e,i=await un.openAndCertify(t,ur.DOMAIN,s),a=no(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=ur.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=un.createFromProtobuf(u.peerRecordEnvelope),f=ur.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 Uh(r,t={}){return new Ul(r,t)}var mi=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 ob(r){return r[Symbol.asyncIterator]!=null}function sb(r){if(ob(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Kl=sb;function ib(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 Kh=ib;function ab(r){return r[Symbol.asyncIterator]!=null}function cb(r,t){let e=0;if(ab(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Kh(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 hr=cb;function lb(r){return r[Symbol.asyncIterator]!=null}function ub(r,t){return lb(r)?async function*(){yield*(await xo(r)).sort(t)}():function*(){yield*xo(r).sort(t)}()}var ql=ub;function fb(r){return r[Symbol.asyncIterator]!=null}function db(r,t){return fb(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 zl=db;var gi=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 Kl(this.putMany(t,n)),t=[],await Kl(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=hr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>hr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>ql(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=hr(n,()=>o++>=s)}return t.limit!=null&&(n=zl(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=hr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>hr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>ql(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=hr(n,()=>s++>=o)}return t.limit!=null&&(n=zl(n,t.limit)),n}};var yi=class extends gi{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 mi;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 dr(n),value:o},e?.signal?.throwIfAborted()}*_allKeys(t,e){e?.signal?.throwIfAborted();for(let n of this.data.keys())yield new dr(n),e?.signal?.throwIfAborted()}};function So(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 zh=Ko(qh(),1),hb=["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"],pb=hb.map(r=>new zh.Netmask(r));function Vl(r){for(let t of pb)if(t.contains(r))return!0;return!1}function mb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function gb(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 Vl(o)}function yb(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function bb(r){let t=r.split(":"),e=t[t.length-1];return Vl(e)}function wb(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 Fe(r){if(Kt(r))return Vl(r);if(mb(r))return gb(r);if(yb(r))return bb(r);if(on(r))return wb(r)}var xb=r=>r.toString().split("/").slice(1),hn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),U=r=>({match:t=>hn(e=>e===r).match(t),pattern:r}),pr=()=>({match:r=>hn(t=>typeof t=="string").match(r),pattern:"{string}"}),pn=()=>({match:r=>hn(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),j=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{H.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Co=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{In.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),V=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),vt=(...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},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),K=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function Y(...r){function t(o){let s=xb(o);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 Eb=j(),Vh=Y(Eb),wi=K(U("dns4"),pr()),xi=K(U("dns6"),pr()),Ei=K(U("dnsaddr"),pr()),$l=K(U("dns"),pr()),j6=Y(wi,V(j())),Z6=Y(xi,V(j())),X6=Y(Ei,V(j())),Q6=Y(vt($l,Ei,wi,xi),V(j())),Hh=K(U("ip4"),hn(Kt)),$h=K(U("ip6"),hn(on)),Wl=vt(Hh,$h),Se=vt(Wl,$l,wi,xi,Ei),Y6=Y(vt(Wl,K(vt($l,Ei,wi,xi),V(j())))),Gl=Y(Hh),jl=Y($h),J6=Y(Wl),Zl=K(Se,U("tcp"),pn()),Io=K(Se,U("udp"),pn()),To=Y(K(Zl,V(j()))),t4=Y(Io),Xl=K(Io,U("quic"),V(j())),vi=K(Io,U("quic-v1"),V(j())),vb=vt(Xl,vi),e4=Y(Xl),Wh=Y(vi),Hl=vt(Se,Zl,Io,Xl,vi),Gh=vt(K(Hl,U("ws"),V(j()))),mr=Y(Gh),jh=vt(K(Hl,U("wss"),V(j())),K(Hl,U("tls"),V(K(U("sni"),pr())),U("ws"),V(j()))),Po=Y(jh),Zh=K(Io,U("webrtc-direct"),V(Co()),V(Co()),V(j())),Ql=Y(Zh),Xh=K(vi,U("webtransport"),V(Co()),V(Co()),V(j())),Yl=Y(Xh),bi=vt(Gh,jh,K(Zl,V(j())),K(vb,V(j())),K(Se,V(j())),Zh,Xh,j()),r4=Y(bi),_b=K(bi,U("p2p-circuit"),j()),Do=Y(_b),Sb=vt(K(bi,U("p2p-circuit"),U("webrtc"),V(j())),K(bi,U("webrtc"),V(j())),K(U("webrtc"),V(j()))),Jl=Y(Sb),Ab=vt(K(Se,U("tcp"),pn(),U("http"),V(j())),K(Se,U("http"),V(j()))),n4=Y(Ab),Cb=vt(K(Se,U("tcp"),vt(K(U("443"),U("http")),K(pn(),U("https")),K(pn(),U("tls"),U("http"))),V(j())),K(Se,U("tls"),U("http"),V(j())),K(Se,U("https"),V(j()))),o4=Y(Cb),Ib=vt(K(U("memory"),pr(),V(j()))),s4=Y(Ib);var tu=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 _t(r){let{name:t,metrics:e}=r,n;return e!=null?n=new tu({name:t,metrics:e}):n=new Map,n}var Qh=864e13;var Tb=448,eu=449,Pb=53,Db=54,Lb=55,Rb=56,_i=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=_t({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=Fe(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?Qh-Date.now():0,lastVerified:o?Qh-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:q(`/${s.map(l=>[Ns(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]===Tb&&t[n+1]?.[0]!==eu)return t.splice(n+1,0,[eu,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]===eu||e[0]===Pb||e[0]===Db||e[0]===Lb||e[0]===Rb)return e[1]}};var ru=4,nu=41,ou=6,kb=273,Si=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=_t({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:Kt(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]===ou?"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]===ru||o[0][0]===nu)&&o[1][0]===ou?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===ru||o[0][0]===nu)&&o[1][0]===kb&&(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?ru:nu,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:q(`/${o.map(c=>[Ns(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]===ou?"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 Yh(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 Ai(r){try{for(let{code:t}of r.getComponents())if(t!==42)return t===4||t===41}catch{}return!1}function gr(r){try{if(!Ai(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:Fe(t)??!1}catch{}return!0}var Ob={maxObservedAddresses:10},Ci=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=_t({name:"libp2p_address_manager_observed_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??Ob.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&&(gr(t)||Yh(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:q(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 Mb=[4,41,53,54,55,56];function su(r){try{for(let{code:t}of r.getComponents())if(t!==42)return Mb.includes(t)}catch{}return!1}var Nb={maxObservedAddresses:10},Ii=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=_t({name:"libp2p_address_manager_transport_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??Nb.maxObservedAddresses}get(t,e){if(gr(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:!su(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(su(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var Jh=6e4,tp={maxObservedAddresses:10,addressVerificationTTL:Jh*10,addressVerificationRetry:Jh*5},Bb=r=>r;function iu(r,t){let e=r.getPeerId();return e!=null&&ce(e).equals(t)&&(r=r.decapsulate(q(`/p2p/${t.toString()}`))),r}var Ti=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 Ci(t,e),this.dnsMappings=new _i(t,e),this.ipMappings=new Si(t,e),this.transportAddresses=new Ii(t,e),this.announceFilter=e.announceFilter??Bb,this.observedAddressFilter=yo(1024),this.addressVerificationTTL=e.addressVerificationTTL??tp.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??tp.addressVerificationRetry,this._updatePeerStoreAddresses=So(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=>q(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>q(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>q(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=iu(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=iu(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=iu(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=q(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(q(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${Kt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(q(`/ip${Kt(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"||Fe(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>mr.exactMatch(s)||Po.exactMatch(s),s=>To.exactMatch(s),s=>Wh.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 ep;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(ep||(ep={}));var Pi=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Di=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},mn=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},Lo=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Li=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Ri=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},ki=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},Ro=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Oi=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Mi=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},Ni=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Bi=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Fi=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},yr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},br=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},Ui=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var au=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=Ks())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>Zo(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")}},Ub=["metrics","connectionProtector","dns"],Kb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function rp(r={}){let t=new au(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!Kb.includes(o)){let i=t.components[o];if(i==null&&!Ub.includes(o))throw new Pi(`${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 np(r){let t={};for(let e of Object.values(r.components))for(let n of qb(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of zb(e))if(t[n]!==!0)throw new Di(`Service "${Vb(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function qb(r){return Array.isArray(r?.[vn])?r[vn]:[]}function zb(r){return Array.isArray(r?.[Pa])?r[Pa]:[]}function Vb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Hb=4,$b=41;function op(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(mr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===Hb||e[0][0]===$b?!!Fe(`${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 sp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Wb=new WeakMap;function Gb({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(sp());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(sp())},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}),Wb.set(f,()=>{c(s),s=null,i()}),f}}var jb=Gb(),ip=jb;var Ki=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}},qi=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var zi=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 cu}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 Ki("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 ip(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)}},cu=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 Vi(r){if(Ce(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:ce(n),t.forEach(o=>{if(!Be(o))throw new Ie("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(e!=null)throw new O("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ce(s);if(e?.equals(i)!==!0)throw new O("Multiaddrs must all have the same peer id or have no peer id")}})}return t=t.filter(n=>!Vh.exactMatch(n)),{peerId:e,multiaddrs:t}}var Zb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function ap(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Zb;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}async function cp(r,t){let e=!1;for(let o of cn.keys())if(e=r.protoNames().includes(o),e)break;if(!e)return[r];let n=await r.resolve(t);return t.log("resolved %s to",r,n.map(o=>o.toString())),n}function ko(r){try{let t;if(typeof r=="string"?t=q(r):t=r,!t.protoNames().includes("ipcidr")){let n=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(n)}return El(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Hi=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 Vt;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 ap(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 lp="last-dial-failure",up="last-dial-success";var fp=100,$i=50;var Wi=class{deferred;signal;constructor(t){this.signal=t,this.deferred=nt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new $t)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Xb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Gi=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Xb(),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 $t),this.cleanup())}async join(t={}){let e=new Wi(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 pt(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 gn=class extends Nt{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=So(this.emitEmpty.bind(this),1),this.emitIdle=So(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 qi;let n=new Gi(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 $t)}),this.clear()}async onEmpty(t){this.size!==0&&await ue(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await ue(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ue(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=$s({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 $t("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 ji=class extends gn{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Ae(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 dp(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function lu(r){if(!Ai(r))return!1;let{address:t}=r.nodeAddress();return dp(t)}function Qb(r,t){let e=To.exactMatch(r.multiaddr),n=To.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=Po.exactMatch(r.multiaddr),s=Po.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=mr.exactMatch(r.multiaddr),a=mr.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Jl.exactMatch(r.multiaddr),u=Jl.exactMatch(t.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let l=Ql.exactMatch(r.multiaddr),f=Ql.exactMatch(t.multiaddr);if(l&&!f)return-1;if(!l&&f)return 1;let d=Yl.exactMatch(r.multiaddr),h=Yl.exactMatch(t.multiaddr);return d&&!h?-1:!d&&h?1:0}function Yb(r,t){let e=lu(r.multiaddr),n=lu(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Jb(r,t){let e=gr(r.multiaddr),n=gr(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function tw(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function ew(r,t){let e=Do.exactMatch(r.multiaddr),n=Do.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function hp(r){return r.sort(Qb).sort(tw).sort(ew).sort(Jb).sort(Yb)}var Zi={maxParallelDials:$i,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:sr}},Xi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??Zi.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??Zi.maxDialQueueLength,this.dialTimeout=e.dialTimeout??Zi.dialTimeout,this.connections=e.connections??new Vt,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,this.shutDownController.signal;for(let[n,o]of Object.entries(e.resolvers??{}))cn.set(n,o);this.queue=new ji({concurrency:e.maxParallelDials??Zi.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail?.name!==$t.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}=Vi(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!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 it("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 it("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Tr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new it("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new it("dial-queue:start-dial"));let c=Ae([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??hu,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 it("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 Tr("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:{[up]: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:{[lp]: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 Wo(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:q(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Tr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new Ro("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 cp(f.multiaddr,{dns:this.components.dns,...n,log:this.log});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 Ni("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?hp(u):u.sort(this.addressSorter);if(l.length===0)throw new Ro("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=>!Do.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Qi=class extends gn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var xp=Ko(bp(),1);var nw=Object.prototype.toString,ow=r=>nw.call(r)==="[object Error]",sw=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 pu(r){return r&&ow(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:sw.has(r.message):!1}var mu=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}},wp=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function gu(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=xp.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 mu)throw c.originalError;if(c instanceof TypeError&&!pu(c))throw c;if(wp(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){wp(u,a,t),i(),n(u)}}})})}var Yi=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 Qi({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);Ep(e)&&(this.queue.has(t)||this.queue.add(async n=>{await gu(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(Ta)&&(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=>Ep(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 Ep(r){for(let t of r.tags.keys())if(t.startsWith(Ta))return!0;return!1}var hu=50,yu={maxConnections:fp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ji=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??yu.maxConnections,this.maxConnections<1)throw new O("Connection Manager maxConnections must be greater than 0");this.connections=new Vt,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??yu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new zi({points:e.inboundConnectionThreshold??yu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Hi({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{allow:e.allow?.map(n=>q(n))}),this.dialQueue=new Xi(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??$i,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:sr},connections:this.connections}),this.reconnectQueue=new Yi({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 Tu(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 Pu(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 O("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 fe("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=Vi(t);if(this.peerId.equals(n))throw new Ir("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 it("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??hu});if(o.status!=="open")throw new Cr("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 Ie("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=>q(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var yn=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 cw=1.2,lw=2,uw=5e3,fw=6e4,dw=5e3,ta=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(t={}){let e=t.interval??dw;this.success=new yn(e),this.failure=new yn(e),this.next=new yn(e),this.failureMultiplier=t.failureMultiplier??lw,this.timeoutMultiplier=t.timeoutMultiplier??cw,this.minTimeout=t.minTimeout??uw,this.maxTimeout=t.maxTimeout??fw,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=Ae([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 bu=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=nt(),this.haveNext=nt()}[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=nt(),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=nt(),await pt(this.readNext.promise,e?.signal,e)}};function ea(){return new bu}var ra=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function na(r,t){let e=ea();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 pt(n.next(),i?.signal);return c===!0?null:u}for(;o.byteLength<i.bytes;){let{value:c,done:u}=await pt(n.next(),i?.signal);if(u===!0)throw new ra("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 hw=1e4,pw="1.0.0",mw="ping",gw="ipfs",vp=32,yw=!0,oa=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??gw}/${mw}/${pw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??hw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??yw,this.timeout=new ta({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[vn]=["@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=na(o);e=Date.now(),await Promise.all([s.write(Zr(vp),{signal:n}),s.read({bytes:vp,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 bw(r){return r[Symbol.asyncIterator]!=null}async function ww(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*xw(r){let t=new AbortController,e=ea();ww(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*Ew(r){for(let t of r)yield*t}function vw(...r){let t=[];for(let e of r)bw(e)||t.push(e);return t.length===r.length?Ew(t):xw(r)}var Oo=vw;var sa=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:M(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:M(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 mn("No content routers available");let n=this,o=new ar;for await(let s of Oo(...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 mn("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 mn("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 fe;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 fe;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(t,e)))}};var ia=globalThis.CustomEvent??Event;async function*wu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=nt(),a=nt(),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=nt(),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 ia("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new ia("task-complete"))})}c=!0,o.dispatchEvent(new ia("task-complete"))}catch(p){u=p,o.dispatchEvent(new ia("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=nt(),await a.promise),u!=null||(n?yield*d():yield*h(),u!=null))throw u;if(c&&s.length===0)break}}var aa=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:M(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 Lo("No peer routers available");if(t.toString()===this.peerId.toString())throw new Li("Should not try to find self");let n=this,o=Oo(...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 ze}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new Lo("No peer routers available");let n=this,o=yo(1024);for await(let s of wu(async function*(){let i=Oo(...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 ca=class extends Nt{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=Ae([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=nt(),yield(await ue(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=Ae([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=Zr(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 pt(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 xu=32,Eu=64,la=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=_t({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 Ri(`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 ki(`Handler already registered for protocol ${t}`);let o=Ss.bind({ignoreUndefined:!0})({maxInboundStreams:xu,maxOutboundStreams:Eu},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 O("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 ua=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=_t({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=_t({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??qe.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new O("Transport must have a valid tag");if(this.transports.has(e))throw new O(`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 Ui(`No transport available for address ${String(t)}`);return e?.onProgress?.(new it("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 fe("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 Oi)});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})}),Gl.matches(c)?e.ipv4.attempts++:jl.matches(c)&&e.ipv6.attempts++,n.push(u.listen(c).then(()=>{e.errors.delete(c.toString()),Gl.matches(c)&&e.ipv4.success++,jl.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===qe.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Mi(`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:
2
+ "use strict";var Libp2P=(()=>{var Tp=Object.create;var Uo=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var Dp=Object.getOwnPropertyNames;var Lp=Object.getPrototypeOf,Rp=Object.prototype.hasOwnProperty;var Sr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Rt=(r,t)=>{for(var e in t)Uo(r,e,{get:t[e],enumerable:!0})},Au=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Dp(t))!Rp.call(r,o)&&o!==e&&Uo(r,o,{get:()=>t[o],enumerable:!(n=Pp(t,o))||n.enumerable});return r};var Ko=(r,t,e)=>(e=r!=null?Tp(Lp(r)):{},Au(t||!r||!r.__esModule?Uo(e,"default",{value:r,enumerable:!0}):e,r)),kp=r=>Au(Uo({},"__esModule",{value:!0}),r);var Fd=Sr((H2,tl)=>{"use strict";var E0=Object.prototype.hasOwnProperty,Lt="~";function no(){}Object.create&&(no.prototype=Object.create(null),new no().__proto__||(Lt=!1));function v0(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Bd(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new v0(e,n||r,o),i=Lt?Lt+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 As(r,t){--r._eventsCount===0?r._events=new no:delete r._events[t]}function Et(){this._events=new no,this._eventsCount=0}Et.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)E0.call(e,n)&&t.push(Lt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Et.prototype.listeners=function(t){var e=Lt?Lt+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};Et.prototype.listenerCount=function(t){var e=Lt?Lt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Et.prototype.emit=function(t,e,n,o,s,i){var a=Lt?Lt+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};Et.prototype.on=function(t,e,n){return Bd(this,t,e,n,!1)};Et.prototype.once=function(t,e,n){return Bd(this,t,e,n,!0)};Et.prototype.removeListener=function(t,e,n,o){var s=Lt?Lt+t:t;if(!this._events[s])return this;if(!e)return As(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&As(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:As(this,s)}return this};Et.prototype.removeAllListeners=function(t){var e;return t?(e=Lt?Lt+t:t,this._events[e]&&As(this,e)):(this._events=new no,this._eventsCount=0),this};Et.prototype.off=Et.prototype.removeListener;Et.prototype.addListener=Et.prototype.on;Et.prefixed=Lt;Et.EventEmitter=Et;typeof tl<"u"&&(tl.exports=Et)});var Vd=Sr((h_,zd)=>{zd.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 Kh=Sr(So=>{(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}(),So.ip2long=i,So.long2ip=a,So.Netmask=r}).call(So)});var hp=Sr((nP,dp)=>{function Ht(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))}dp.exports=Ht;Ht.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ht.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ht.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};Ht.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)};Ht.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ht.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ht.prototype.start=Ht.prototype.try;Ht.prototype.errors=function(){return this._errors};Ht.prototype.attempts=function(){return this._attempts};Ht.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 pp=Sr(wr=>{var Xb=hp();wr.operation=function(r){var t=wr.timeouts(r);return new Xb(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};wr.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};wr.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};wr.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=wr.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 gp=Sr((sP,mp)=>{mp.exports=pp()});var Tw={};Rt(Tw,{createLibp2p:()=>Iw,dnsaddrResolver:()=>ve});var Cu=Symbol.for("@libp2p/connection");var Aa=Symbol.for("@libp2p/content-routing");var Ca=Symbol.for("@libp2p/peer-discovery");var qo=Symbol.for("@libp2p/peer-id");function Ie(r){return!!r?.[qo]}var Ia=Symbol.for("@libp2p/peer-routing");var Ta="keep-alive";var Nw=Symbol.for("@libp2p/transport");var ze;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(ze||(ze={}));var $t=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var O=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Ar=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},wn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var zo=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Cr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var Ve=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Ir=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Te=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},Vo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Ho=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},xn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},$o=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Wo=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},fe=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Tr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Pr=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},Go=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},jo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Pe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Nt=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 Zo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Iu(...r){let t=[];for(let e of r)Zo(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 Tu(...r){let t=[];for(let e of r)Zo(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 En=Symbol.for("@libp2p/service-capabilities"),Pa=Symbol.for("@libp2p/service-dependencies");var Oa={};Rt(Oa,{base58btc:()=>H,base58flickr:()=>Kp});var cx=new Uint8Array(0);function Pu(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 de(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 Du(r){return new TextEncoder().encode(r)}function Lu(r){return new TextDecoder().decode(r)}function Op(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 Mp=Op,Np=Mp,ku=Np;var Da=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")}},La=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 Ou(this,t)}},Ra=class{decoders;constructor(t){this.decoders=t}or(t){return Ou(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 Ou(r,t){return new Ra({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ka=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 Da(t,e,n),this.decoder=new La(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Dr({name:r,prefix:t,encode:e,decode:n}){return new ka(r,t,e,n)}function De({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ku(e,r);return Dr({prefix:t,name:r,encode:n,decode:s=>de(o(s))})}function Bp(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 Fp(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 Up(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function et({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Up(n);return Dr({prefix:t,name:r,encode(s){return Fp(s,n,e)},decode(s){return Bp(s,o,e,r)}})}var H=De({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Kp=De({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ma={};Rt(Ma,{base32:()=>qt,base32hex:()=>Hp,base32hexpad:()=>Wp,base32hexpadupper:()=>Gp,base32hexupper:()=>$p,base32pad:()=>zp,base32padupper:()=>Vp,base32upper:()=>qp,base32z:()=>jp});var qt=et({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),qp=et({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zp=et({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Vp=et({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Hp=et({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),$p=et({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wp=et({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Gp=et({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jp=et({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Na={};Rt(Na,{base36:()=>vn,base36upper:()=>Zp});var vn=De({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zp=De({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xp=Bu,Mu=128,Qp=127,Yp=~Qp,Jp=Math.pow(2,31);function Bu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Jp;)t[e++]=r&255|Mu,r/=128;for(;r&Yp;)t[e++]=r&255|Mu,r>>>=7;return t[e]=r|0,Bu.bytes=e-n+1,t}var tm=Ba,em=128,Nu=127;function Ba(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ba.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Nu)<<o:(i&Nu)*Math.pow(2,o),o+=7}while(i>=em);return Ba.bytes=s-n,e}var rm=Math.pow(2,7),nm=Math.pow(2,14),om=Math.pow(2,21),sm=Math.pow(2,28),im=Math.pow(2,35),am=Math.pow(2,42),cm=Math.pow(2,49),lm=Math.pow(2,56),um=Math.pow(2,63),fm=function(r){return r<rm?1:r<nm?2:r<om?3:r<sm?4:r<im?5:r<am?6:r<cm?7:r<lm?8:r<um?9:10},dm={encode:Xp,decode:tm,encodingLength:fm},hm=dm,_n=hm;function Sn(r,t=0){return[_n.decode(r,t),_n.decode.bytes]}function Lr(r,t,e=0){return _n.encode(r,t,e),t}function Rr(r){return _n.encodingLength(r)}function Wt(r,t){let e=t.byteLength,n=Rr(r),o=n+Rr(e),s=new Uint8Array(o+e);return Lr(r,s,0),Lr(e,s,n),s.set(t,o),new kr(r,e,t,s)}function he(r){let t=de(r),[e,n]=Sn(t),[o,s]=Sn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new kr(e,o,i,t)}function Fu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Pu(r.bytes,e.bytes)}}var kr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Uu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return mm(e,Fa(r),t??H.encoder);default:return gm(e,Fa(r),t??qt.encoder)}}var Ku=new WeakMap;function Fa(r){let t=Ku.get(r);if(t==null){let e=new Map;return Ku.set(r,e),e}return t}var J=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!==An)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==ym)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=Wt(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&&Fu(t.multihash,n.multihash)}toString(t){return Uu(this,t)}toJSON(){return{"/":Uu(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??qu(n,o,s.bytes))}else if(e[bm]===!0){let{version:n,multihash:o,code:s}=e,i=he(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!==An)throw new Error(`Version 0 CID must use dag-pb (code: ${An}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=qu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,An,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=de(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 kr(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]=Sn(t.subarray(e));return e+=d,f},o=n(),s=An;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]=pm(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 Fa(s).set(n,t),s}};function pm(r,t){switch(r[0]){case"Q":{let e=t??H;return[H.prefix,e.decode(`${H.prefix}${r}`)]}case H.prefix:{let e=t??H;return[H.prefix,e.decode(r)]}case qt.prefix:{let e=t??qt;return[qt.prefix,e.decode(r)]}case vn.prefix:{let e=t??vn;return[vn.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 mm(r,t,e){let{prefix:n}=e;if(n!==H.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 gm(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 An=112,ym=18;function qu(r,t,e){let n=Rr(r),o=n+Rr(t),s=new Uint8Array(o+e.byteLength);return Lr(r,s,0),Lr(t,s,n),s.set(e,o),s}var bm=Symbol.for("@ipld/js-cid/CID");var Ua={};Rt(Ua,{identity:()=>Gt});var zu=0,wm="identity",Vu=de;function xm(r){return Wt(zu,Vu(r))}var Gt={code:zu,name:wm,encode:Vu,digest:xm};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 rt(r=0){return new Uint8Array(r)}function yt(r=0){return new Uint8Array(r)}function jt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=yt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var $u=Symbol.for("@achingbrain/uint8arraylist");function Hu(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 Qo(r){return!!r?.[$u]}var z=class r{bufs;length;[$u]=!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(Qo(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(Qo(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=Hu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Hu(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(Qo(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 jt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:jt(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(!Qo(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=yt(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=rt(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=rt(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=rt(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=yt(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=rt(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=rt(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=rt(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=rt(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=rt(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 Ka={};Rt(Ka,{base10:()=>Em});var Em=De({prefix:"9",name:"base10",alphabet:"0123456789"});var qa={};Rt(qa,{base16:()=>vm,base16upper:()=>_m});var vm=et({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_m=et({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var za={};Rt(za,{base2:()=>Sm});var Sm=et({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Va={};Rt(Va,{base256emoji:()=>Pm});var Wu=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}"),Am=Wu.reduce((r,t,e)=>(r[e]=t,r),[]),Cm=Wu.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Im(r){return r.reduce((t,e)=>(t+=Am[e],t),"")}function Tm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Cm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Pm=Dr({prefix:"\u{1F680}",name:"base256emoji",encode:Im,decode:Tm});var $a={};Rt($a,{base64:()=>Ha,base64pad:()=>Dm,base64url:()=>Cn,base64urlpad:()=>Lm});var Ha=et({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Dm=et({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Cn=et({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Lm=et({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wa={};Rt(Wa,{base8:()=>Rm});var Rm=et({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ga={};Rt(Ga,{identity:()=>km});var km=Dr({prefix:"\0",name:"identity",encode:r=>Lu(r),decode:r=>Du(r)});var $x=new TextEncoder,Wx=new TextDecoder;var Xa={};Rt(Xa,{sha256:()=>Or,sha512:()=>Nm});function Za({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?Wt(this.code,e):e.then(n=>Wt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ju(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Or=Za({name:"sha2-256",code:18,encode:ju("SHA-256")}),Nm=Za({name:"sha2-512",code:19,encode:ju("SHA-512")});var In={...Ga,...za,...Wa,...Ka,...qa,...Ma,...Na,...Oa,...$a,...Va},oE={...Xa,...Ua};function Xu(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Zu=Xu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Qa=Xu("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=yt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Bm={utf8:Zu,"utf-8":Zu,hex:In.base16,latin1:Qa,ascii:Qa,binary:Qa,...In},Yo=Bm;function D(r,t="utf8"){let e=Yo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function M(r,t="utf8"){let e=Yo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Fm=parseInt("11111",2),Ya=parseInt("10000000",2),Um=parseInt("01111111",2),Qu={0:Tn,1:Tn,2:Km,3:Vm,4:Hm,5:zm,6:qm,16:Tn,22:Tn,48:Tn};function pe(r,t={offset:0}){let e=r[t.offset]&Fm;if(t.offset++,Qu[e]!=null)return Qu[e](r,t);throw new Error("No decoder for tag "+e)}function Pn(r,t){let e=0;if((r[t.offset]&Ya)===Ya){let n=r[t.offset]&Um,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 Tn(r,t){Pn(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=pe(r,t);if(n===null)break;e.push(n)}return e}function Km(r,t){let e=Pn(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 qm(r,t){let e=Pn(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 zm(r,t){return t.offset++,null}function Vm(r,t){let e=Pn(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 Hm(r,t){let e=Pn(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function $m(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 Jo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=$m(r.byteLength);return new z(Uint8Array.from([t.byteLength|Ya]),t)}function At(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]),Jo(t),t)}function Dn(r){let t=Uint8Array.from([0]),e=new z(t,r);return new z(Uint8Array.from([3]),Jo(e),e)}function Yu(r){return new z(Uint8Array.from([4]),Jo(r),r)}function Zt(r,t=48){let e=new z;for(let n of r)e.append(n);return new z(Uint8Array.from([t]),Jo(e),e)}async function Ju(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 tf(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 ef(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 Wm=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Gm=Uint8Array.from([6,5,43,129,4,0,34]),jm=Uint8Array.from([6,5,43,129,4,0,35]),Zm={ext:!0,kty:"EC",crv:"P-256"},Xm={ext:!0,kty:"EC",crv:"P-384"},Qm={ext:!0,kty:"EC",crv:"P-521"},Ja=32,tc=48,ec=66;function rc(r){let t=pe(r);return rf(t)}function rf(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Ja*2+1)return n=M(t.subarray(e,e+Ja),"base64url"),o=M(t.subarray(e+Ja),"base64url"),new He({...Zm,key_ops:["verify"],x:n,y:o});if(t.byteLength===tc*2+1)return n=M(t.subarray(e,e+tc),"base64url"),o=M(t.subarray(e+tc),"base64url"),new He({...Xm,key_ops:["verify"],x:n,y:o});if(t.byteLength===ec*2+1)return n=M(t.subarray(e,e+ec),"base64url"),o=M(t.subarray(e+ec),"base64url"),new He({...Qm,key_ops:["verify"],x:n,y:o});throw new O(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function nf(r){return Zt([At(Uint8Array.from([1])),Yu(D(r.d??"","base64url")),Zt([sf(r.crv)],160),Zt([Dn(new z(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function of(r){return Zt([At(Uint8Array.from([1])),Zt([sf(r.crv)],160),Zt([Dn(new z(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function sf(r){if(r==="P-256")return Wm;if(r==="P-384")return Gm;if(r==="P-521")return jm;throw new O(`Invalid curve ${r}`)}async function af(r="P-256"){let t=await Ju(r);return new ts(t.privateKey)}var He=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=of(this.jwk)),this._raw}toMultihash(){return Gt.digest(zt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return H.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 ef(this.jwk,e,t,n)}},ts=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new He({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=nf(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}async sign(t,e){return tf(this.jwk,t,e)}};var $e=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Nr(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ln(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function bt(r,...t){if(!Nr(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 lf(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ln(r.outputLen),Ln(r.blockLen)}function Br(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 uf(r,t){bt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function ge(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function es(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Xt(r,t){return r<<32-t|r>>>t}var ff=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ym=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function ne(r){if(bt(r),ff)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Ym[r[e]];return t}var me={_0:48,_9:57,A:65,F:70,a:97,f:102};function cf(r){if(r>=me._0&&r<=me._9)return r-me._0;if(r>=me.A&&r<=me.F)return r-(me.A-10);if(r>=me.a&&r<=me.f)return r-(me.a-10)}function Fr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(ff)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=cf(r.charCodeAt(s)),a=cf(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 df(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Rn(r){return typeof r=="string"&&(r=df(r)),bt(r),r}function Bt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];bt(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 Mr=class{};function nc(r){let t=n=>r().update(Rn(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function We(r=32){if($e&&typeof $e.getRandomValues=="function")return $e.getRandomValues(new Uint8Array(r));if($e&&typeof $e.randomBytes=="function")return Uint8Array.from($e.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function Jm(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 hf(r,t,e){return r&t^~r&e}function pf(r,t,e){return r&t^r&e^t&e}var kn=class extends Mr{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=es(this.buffer)}update(t){Br(this),t=Rn(t),bt(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=es(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){Br(this),uf(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,ge(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;Jm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=es(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()}},ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var dt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var rs=BigInt(4294967295),mf=BigInt(32);function tg(r,t=!1){return t?{h:Number(r&rs),l:Number(r>>mf&rs)}:{h:Number(r>>mf&rs)|0,l:Number(r&rs)|0}}function gf(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}=tg(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var oc=(r,t,e)=>r>>>e,sc=(r,t,e)=>r<<32-e|t>>>e,Ge=(r,t,e)=>r>>>e|t<<32-e,je=(r,t,e)=>r<<32-e|t>>>e,On=(r,t,e)=>r<<64-e|t>>>e-32,Mn=(r,t,e)=>r>>>e-32|t<<64-e;function oe(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var yf=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),bf=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,wf=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),xf=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Ef=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),vf=(r,t,e,n,o,s)=>t+e+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]),Re=new Uint32Array(64),ns=class extends kn{constructor(t=32){super(64,t,8,!1),this.A=ye[0]|0,this.B=ye[1]|0,this.C=ye[2]|0,this.D=ye[3]|0,this.E=ye[4]|0,this.F=ye[5]|0,this.G=ye[6]|0,this.H=ye[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)Re[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Re[f-15],h=Re[f-2],p=Xt(d,7)^Xt(d,18)^d>>>3,g=Xt(h,17)^Xt(h,19)^h>>>10;Re[f]=g+Re[f-7]+p+Re[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=Xt(a,6)^Xt(a,11)^Xt(a,25),h=l+d+hf(a,c,u)+rg[f]+Re[f]|0,g=(Xt(n,2)^Xt(n,13)^Xt(n,22))+pf(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(){ge(Re)}destroy(){this.set(0,0,0,0,0,0,0,0),ge(this.buffer)}};var _f=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))),ng=_f[0],og=_f[1],ke=new Uint32Array(80),Oe=new Uint32Array(80),ic=class extends kn{constructor(t=64){super(128,t,16,!1),this.Ah=dt[0]|0,this.Al=dt[1]|0,this.Bh=dt[2]|0,this.Bl=dt[3]|0,this.Ch=dt[4]|0,this.Cl=dt[5]|0,this.Dh=dt[6]|0,this.Dl=dt[7]|0,this.Eh=dt[8]|0,this.El=dt[9]|0,this.Fh=dt[10]|0,this.Fl=dt[11]|0,this.Gh=dt[12]|0,this.Gl=dt[13]|0,this.Hh=dt[14]|0,this.Hl=dt[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),Oe[_]=t.getUint32(e+=4);for(let _=16;_<80;_++){let C=ke[_-15]|0,b=Oe[_-15]|0,L=Ge(C,b,1)^Ge(C,b,8)^oc(C,b,7),R=je(C,b,1)^je(C,b,8)^sc(C,b,7),I=ke[_-2]|0,y=Oe[_-2]|0,S=Ge(I,y,19)^On(I,y,61)^oc(I,y,6),x=je(I,y,19)^Mn(I,y,61)^sc(I,y,6),v=wf(R,x,Oe[_-7],Oe[_-16]),A=xf(v,L,S,ke[_-7],ke[_-16]);ke[_]=A|0,Oe[_]=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=Ge(f,d,14)^Ge(f,d,18)^On(f,d,41),b=je(f,d,14)^je(f,d,18)^Mn(f,d,41),L=f&h^~f&g,R=d&p^~d&m,I=Ef(E,b,R,og[_],Oe[_]),y=vf(I,w,C,L,ng[_],ke[_]),S=I|0,x=Ge(n,o,28)^On(n,o,34)^On(n,o,39),v=je(n,o,28)^Mn(n,o,34)^Mn(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}=oe(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=yf(S,v,P);n=bf(T,y,x,A),o=T|0}({h:n,l:o}=oe(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=oe(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=oe(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=oe(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=oe(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=oe(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=oe(this.Gh|0,this.Gl|0,g|0,m|0),{h:w,l:E}=oe(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(){ge(ke,Oe)}destroy(){ge(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var os=nc(()=>new ns);var Sf=nc(()=>new ic);var lc=BigInt(0),cc=BigInt(1);function be(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function Nn(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Af(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?lc:BigInt("0x"+r)}function Ur(r){return Af(ne(r))}function Ze(r){return bt(r),Af(ne(Uint8Array.from(r).reverse()))}function ss(r,t){return Fr(r.toString(16).padStart(t*2,"0"))}function Kr(r,t){return ss(r,t).reverse()}function X(r,t,e){let n;if(typeof t=="string")try{n=Fr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Nr(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 ac=r=>typeof r=="bigint"&&lc<=r;function Cf(r,t,e){return ac(r)&&ac(t)&&ac(e)&&t<=r&&r<e}function Me(r,t,e,n){if(!Cf(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function If(r){let t;for(t=0;r>lc;r>>=cc,t+=1);return t}var Xe=r=>(cc<<BigInt(r))-cc;function Tf(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 Bt(...p)};return(h,p)=>{c(),l(h);let g;for(;!(g=p(f()));)l();return c(),g}}function Ne(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 qr(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 Ct=BigInt(0),lt=BigInt(1),Qe=BigInt(2),sg=BigInt(3),Lf=BigInt(4),Rf=BigInt(5),kf=BigInt(8);function tt(r,t){let e=r%t;return e>=Ct?e:t+e}function Q(r,t,e){let n=r;for(;t-- >Ct;)n*=n,n%=e;return n}function Pf(r,t){if(r===Ct)throw new Error("invert: expected non-zero number");if(t<=Ct)throw new Error("invert: expected positive modulus, got "+t);let e=tt(r,t),n=t,o=Ct,s=lt,i=lt,a=Ct;for(;e!==Ct;){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!==lt)throw new Error("invert: does not exist");return tt(o,t)}function Of(r,t){let e=(r.ORDER+lt)/Lf,n=r.pow(t,e);if(!r.eql(r.sqr(n),t))throw new Error("Cannot find square root");return n}function ig(r,t){let e=(r.ORDER-Rf)/kf,n=r.mul(t,Qe),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,Qe),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 ag(r){if(r<BigInt(3))throw new Error("sqrt is not defined for small field");let t=r-lt,e=0;for(;t%Qe===Ct;)t/=Qe,e++;let n=Qe,o=Qt(r);for(;Df(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Of;let s=o.pow(n,t),i=(t+lt)/Qe;return function(c,u){if(c.is0(u))return u;if(Df(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=lt<<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 cg(r){return r%Lf===sg?Of:r%kf===Rf?ig:ag(r)}var Mf=(r,t)=>(tt(r,t)&lt)===lt,lg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function uc(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=lg.reduce((n,o)=>(n[o]="function",n),t);return Ne(r,e),r}function ug(r,t,e){if(e<Ct)throw new Error("invalid exponent, negatives unsupported");if(e===Ct)return r.ONE;if(e===lt)return t;let n=r.ONE,o=t;for(;e>Ct;)e&lt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=lt;return n}function Bn(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 Df(r,t){let e=(r.ORDER-lt)/Qe,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 Nf(r,t){t!==void 0&&Ln(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Qt(r,t,e=!1,n={}){if(r<=Ct)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}=Nf(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:Xe(i),ZERO:Ct,ONE:lt,create:l=>tt(l,r),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return Ct<=l&&l<r},is0:l=>l===Ct,isValidNot0:l=>!u.is0(l)&&u.isValid(l),isOdd:l=>(l&lt)===lt,neg:l=>tt(-l,r),eql:(l,f)=>l===f,sqr:l=>tt(l*l,r),add:(l,f)=>tt(l+f,r),sub:(l,f)=>tt(l-f,r),mul:(l,f)=>tt(l*f,r),pow:(l,f)=>ug(u,l,f),div:(l,f)=>tt(l*Pf(f,r),r),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>Pf(l,r),sqrt:s||(l=>(c||(c=cg(r)),c(u,l))),toBytes:l=>e?Kr(l,a):ss(l,a),fromBytes:l=>{if(l.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);return e?Ze(l):Ur(l)},invertBatch:l=>Bn(u,l),cmov:(l,f,d)=>d?f:l});return Object.freeze(u)}function Bf(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 fc(r){let t=Bf(r);return t+Math.ceil(t/2)}function Ff(r,t,e=!1){let n=r.length,o=Bf(t),s=fc(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Ze(r):Ur(r),a=tt(i,t-lt)+lt;return e?Kr(a,o):ss(a,o)}var Vr=BigInt(0),Ye=BigInt(1);function zr(r,t){let e=t.negate();return r?e:t}function is(r,t,e){let n=t==="pz"?i=>i.pz:i=>i.ez,o=Bn(r.Fp,e.map(n));return e.map((i,a)=>i.toAffine(o[a])).map(r.fromAffine)}function zf(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function dc(r,t){zf(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=Xe(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Uf(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+=Ye);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 fg(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 dg(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 hc=new WeakMap,Vf=new WeakMap;function pc(r){return Vf.get(r)||1}function Kf(r){if(r!==Vr)throw new Error("invalid wNAF")}function as(r,t){return{constTimeNegate:zr,hasPrecomputes(e){return pc(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Vr;)n&Ye&&(o=o.add(s)),s=s.double(),n>>=Ye;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=dc(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=dc(e,t);for(let c=0;c<a.windows;c++){let{nextN:u,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:p}=Uf(o,c,a);o=u,f?i=i.add(zr(h,n[p])):s=s.add(zr(d,n[l]))}return Kf(o),{p:s,f:i}},wNAFUnsafe(e,n,o,s=r.ZERO){let i=dc(e,t);for(let a=0;a<i.windows&&o!==Vr;a++){let{nextN:c,offset:u,isZero:l,isNeg:f}=Uf(o,a,i);if(o=c,!l){let d=n[u];s=s.add(f?d.negate():d)}}return Kf(o),s},getPrecomputes(e,n,o){let s=hc.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&(typeof o=="function"&&(s=o(s)),hc.set(n,s))),s},wNAFCached(e,n,o){let s=pc(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=pc(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){zf(n,t),Vf.set(e,n),hc.delete(e)}}}function Hf(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>Vr||n>Vr;)e&Ye&&(s=s.add(o)),n&Ye&&(i=i.add(o)),o=o.double(),e>>=Ye,n>>=Ye;return{p1:s,p2:i}}function cs(r,t,e,n){fg(e,r),dg(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=If(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Xe(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 qf(r,t){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return uc(t),t}else return Qt(r)}function ls(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>Vr))throw new Error(`CURVE.${a} must be positive bigint`)}let n=qf(t.p,e.Fp),o=qf(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 se=BigInt(0),It=BigInt(1),mc=BigInt(2),hg=BigInt(8),pg={zip215:!0};function mg(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 gg(r,t={}){let{Fp:e,Fn:n}=ls("edwards",r,t),{h:o,n:s}=r;Ne(t,{},{uvRatio:"function"});let i=mc<<BigInt(n.BYTES*8)-It,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:se}}});if(!mg(e,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");function u(g,m,w=!1){let E=w?It:se;return Me("coordinate "+g,m,E,i),m}function l(g){if(!(g instanceof h))throw new Error("ExtendedPoint expected")}let f=qr((g,m)=>{let{ex:w,ey:E,ez:_}=g,C=g.is0();m==null&&(m=C?hg:e.inv(_));let b=a(w*m),L=a(E*m),R=a(_*m);if(C)return{x:se,y:It};if(R!==It)throw new Error("invZ was invalid");return{x:b,y:L}}),d=qr(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,It,a(w*E))}static normalizeZ(m){return is(h,"ez",m)}static msm(m,w){return cs(h,n,m,w)}_setWindowSize(m){this.precompute(m)}precompute(m=8,w=!0){return p.setWindowSize(this,m),w||this.multiply(mc),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(mc*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),k=a(x*S);return new h(A,P,k,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),k=P-A,B=P+A,N=a(v-w*x),ot=a(T*k),W=a(B*N),F=a(T*N),at=a(k*B);return new h(ot,W,at,F)}subtract(m){return this.add(m.negate())}multiply(m){let w=m;Me("scalar",w,It,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 Me("scalar",E,se,s),E===se?h.ZERO:this.is0()||E===It?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===It?this:this.multiplyUnsafe(o)}static fromBytes(m,w=!1){return bt(m),this.fromHex(m,w)}static fromHex(m,w=!1){let{d:E,a:_}=r,C=e.BYTES;m=X("pointHex",m,C),be("zip215",w);let b=m.slice(),L=m[C-1];b[C-1]=L&-129;let R=Ze(b),I=w?i:e.ORDER;Me("pointHex.y",R,se,I);let y=a(R*R),S=a(y-It),x=a(E*y-_),{isValid:v,value:A}=c(S,x);if(!v)throw new Error("Point.fromHex: invalid y coordinate");let P=(A&It)===It,T=(L&128)!==0;if(!w&&A===se&&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=Kr(w,e.BYTES);return E[E.length-1]|=m&It?128:0,E}toRawBytes(){return this.toBytes()}toHex(){return ne(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}h.BASE=new h(r.Gx,r.Gy,It,a(r.Gx*r.Gy)),h.ZERO=new h(se,It,It,se),h.Fp=e,h.Fn=n;let p=as(h,n.BYTES*8);return h}function yg(r,t){Ne(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||We,u=t.adjustScalarBytes||(b=>b),l=t.domain||((b,L,R)=>{if(be("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(Ze(b))}function h(b){let L=s.BYTES;b=X("private key",b,L);let R=X("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=Bt(...L);return d(n(l(R,X("context",b),!!e)))}function w(b,L,R={}){b=X("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);Me("signature.s",P,se,a);let T=s.BYTES,k=Bt(v,Kr(P,T));return X("result",k,T*2)}let E=pg;function _(b,L,R,I=E){let{context:y,zip215:S}=I,x=s.BYTES;b=X("signature",b,2*x),L=X("message",L),R=X("publicKey",R,x),S!==void 0&&be("zip215",S),e&&(L=e(L));let v=Ze(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 k=m(y,P.toBytes(),A.toBytes(),L);return P.add(A.multiplyUnsafe(k)).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 bg(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=Qt(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 wg(r,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:r})}function $f(r){let{CURVE:t,curveOpts:e,eddsaOpts:n}=bg(r),o=gg(t,e),s=yg(o,n);return wg(r,s)}var i1=BigInt(0),xg=BigInt(1),Wf=BigInt(2),a1=BigInt(3),Eg=BigInt(5),vg=BigInt(8),us={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:vg,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _g(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=us.p,a=r*r%s*r%s,c=Q(a,Wf,s)*a%s,u=Q(c,xg,s)*r%s,l=Q(u,Eg,s)*u%s,f=Q(l,t,s)*l%s,d=Q(f,e,s)*f%s,h=Q(d,n,s)*d%s,p=Q(h,o,s)*h%s,g=Q(p,o,s)*h%s,m=Q(g,t,s)*l%s;return{pow_p_5_8:Q(m,Wf,s)*r%s,b2:a}}function Sg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Gf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ag(r,t){let e=us.p,n=tt(t*t*t,e),o=tt(n*n*t,e),s=_g(r*o).pow_p_5_8,i=tt(r*n*s,e),a=tt(t*i*i,e),c=i,u=tt(i*Gf,e),l=a===r,f=a===tt(-r,e),d=a===tt(-r*Gf,e);return l&&(i=c),(f||d)&&(i=u),Mf(i,e)&&(i=tt(-i,e)),{isValid:l||f,value:i}}var Cg=Qt(us.p,void 0,!0),Ig={...us,Fp:Cg,hash:Sf,adjustScalarBytes:Sg,uvRatio:Ag},Fn=$f(Ig);var Un=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},Kn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},fs=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var jf={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new fs("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=jf;var ds=32,qn=64,gc=32;var Hr,Zf=(async()=>{try{return await kt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Xf(){let r=Fn.utils.randomPrivateKey(),t=Fn.getPublicKey(r);return{privateKey:Rg(r,t),publicKey:t}}async function Tg(r,t){let e;r.length===qn?e=r.subarray(0,32):e=r;let n={crv:"Ed25519",kty:"OKP",x:M(r.subarray(32),"base64url"),d:M(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 Pg(r,t){let e=r.subarray(0,gc);return Fn.sign(t instanceof Uint8Array?t:t.subarray(),e)}async function Qf(r,t){return Hr==null&&(Hr=await Zf),Hr?Tg(r,t):Pg(r,t)}async function Dg(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 Lg(r,t,e){return Fn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Yf(r,t,e){return Hr==null&&(Hr=await Zf),Hr?Dg(r,t,e):Lg(r,t,e)}function Rg(r,t){let e=new Uint8Array(qn);for(let n=0;n<gc;n++)e[n]=r[n],e[gc+n]=t[n];return e}function $r(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var zn=class{type="Ed25519";raw;constructor(t){this.raw=ps(t,ds)}toMultihash(){return Gt.digest(zt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return H.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=Yf(this.raw,e,t);return $r(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},hs=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=ps(t,qn),this.publicKey=new zn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}sign(t,e){e?.signal?.throwIfAborted();let n=Qf(this.raw,t);return $r(n)?n.then(o=>(e?.signal?.throwIfAborted(),o)):(e?.signal?.throwIfAborted(),n)}};function yc(r){return r=ps(r,ds),new zn(r)}async function td(){let{privateKey:r,publicKey:t}=Xf();return new hs(r,t)}function ps(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new O(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var kg=Math.pow(2,7),Og=Math.pow(2,14),Mg=Math.pow(2,21),bc=Math.pow(2,28),wc=Math.pow(2,35),xc=Math.pow(2,42),Ec=Math.pow(2,49),$=128,wt=127;function ut(r){if(r<kg)return 1;if(r<Og)return 2;if(r<Mg)return 3;if(r<bc)return 4;if(r<wc)return 5;if(r<xc)return 6;if(r<Ec)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Wr(r,t,e=0){switch(ut(r)){case 8:t[e++]=r&255|$,r/=128;case 7:t[e++]=r&255|$,r/=128;case 6:t[e++]=r&255|$,r/=128;case 5:t[e++]=r&255|$,r/=128;case 4:t[e++]=r&255|$,r>>>=7;case 3:t[e++]=r&255|$,r>>>=7;case 2:t[e++]=r&255|$,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Ng(r,t,e=0){switch(ut(r)){case 8:t.set(e++,r&255|$),r/=128;case 7:t.set(e++,r&255|$),r/=128;case 6:t.set(e++,r&255|$),r/=128;case 5:t.set(e++,r&255|$),r/=128;case 4:t.set(e++,r&255|$),r>>>=7;case 3:t.set(e++,r&255|$),r>>>=7;case 2:t.set(e++,r&255|$),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function vc(r,t){let e=r[t],n=0;if(n+=e&wt,e<$||(e=r[t+1],n+=(e&wt)<<7,e<$)||(e=r[t+2],n+=(e&wt)<<14,e<$)||(e=r[t+3],n+=(e&wt)<<21,e<$)||(e=r[t+4],n+=(e&wt)*bc,e<$)||(e=r[t+5],n+=(e&wt)*wc,e<$)||(e=r[t+6],n+=(e&wt)*xc,e<$)||(e=r[t+7],n+=(e&wt)*Ec,e<$))return n;throw new RangeError("Could not decode varint")}function Bg(r,t){let e=r.get(t),n=0;if(n+=e&wt,e<$||(e=r.get(t+1),n+=(e&wt)<<7,e<$)||(e=r.get(t+2),n+=(e&wt)<<14,e<$)||(e=r.get(t+3),n+=(e&wt)<<21,e<$)||(e=r.get(t+4),n+=(e&wt)*bc,e<$)||(e=r.get(t+5),n+=(e&wt)*wc,e<$)||(e=r.get(t+6),n+=(e&wt)*xc,e<$)||(e=r.get(t+7),n+=(e&wt)*Ec,e<$))return n;throw new RangeError("Could not decode varint")}function ie(r,t,e=0){return t==null&&(t=yt(ut(r))),t instanceof Uint8Array?Wr(r,t,e):Ng(r,t,e)}function Je(r,t=0){return r instanceof Uint8Array?vc(r,t):Bg(r,t)}var _c=new Float32Array([-0]),Be=new Uint8Array(_c.buffer);function ed(r,t,e){_c[0]=r,t[e]=Be[0],t[e+1]=Be[1],t[e+2]=Be[2],t[e+3]=Be[3]}function rd(r,t){return Be[0]=r[t],Be[1]=r[t+1],Be[2]=r[t+2],Be[3]=r[t+3],_c[0]}var Sc=new Float64Array([-0]),xt=new Uint8Array(Sc.buffer);function nd(r,t,e){Sc[0]=r,t[e]=xt[0],t[e+1]=xt[1],t[e+2]=xt[2],t[e+3]=xt[3],t[e+4]=xt[4],t[e+5]=xt[5],t[e+6]=xt[6],t[e+7]=xt[7]}function od(r,t){return xt[0]=r[t],xt[1]=r[t+1],xt[2]=r[t+2],xt[3]=r[t+3],xt[4]=r[t+4],xt[5]=r[t+5],xt[6]=r[t+6],xt[7]=r[t+7],Sc[0]}var Fg=BigInt(Number.MAX_SAFE_INTEGER),Ug=BigInt(Number.MIN_SAFE_INTEGER),Ft=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 tr;if(t<Fg&&t>Ug)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>sd&&(o=0n,++n>sd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return tr;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):tr}},tr=new Ft(0,0);tr.toBigInt=function(){return 0n};tr.zzEncode=tr.zzDecode=function(){return this};tr.length=function(){return 1};var sd=4294967296n;function id(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 ad(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 Ac(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 Yt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ms(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Cc=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,Yt(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 Yt(this,4);return ms(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Yt(this,4);return ms(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Yt(this,4);let t=rd(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Yt(this,4);let t=od(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 Yt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return ad(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Yt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Yt(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 Ft(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 Yt(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 Yt(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 Yt(this,8);let t=ms(this.buf,this.pos+=4),e=ms(this.buf,this.pos+=4);return new Ft(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=vc(this.buf,this.pos);return this.pos+=ut(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 Ic(r){return new Cc(r instanceof Uint8Array?r:r.subarray())}function Tt(r,t,e){let n=Ic(r);return t.decode(n,void 0,e)}function Tc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return yt(i);o+i>t&&(n=yt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var er=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Pc(){}var Lc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Kg=Tc();function qg(r){return globalThis.Buffer!=null?yt(r):Kg(r)}var Hn=class{len;head;tail;states;constructor(){this.len=0,this.head=new er(Pc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new er(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Rc((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(gs,10,Ft.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ft.fromBigInt(t);return this._push(gs,e.length(),e)}uint64Number(t){return this._push(Wr,ut(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=Ft.fromBigInt(t).zzEncode();return this._push(gs,e.length(),e)}sint64Number(t){let e=Ft.fromNumber(t).zzEncode();return this._push(gs,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Dc,1,t?1:0)}fixed32(t){return this._push(Vn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ft.fromBigInt(t);return this._push(Vn,4,e.lo)._push(Vn,4,e.hi)}fixed64Number(t){let e=Ft.fromNumber(t);return this._push(Vn,4,e.lo)._push(Vn,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(ed,4,t)}double(t){return this._push(nd,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Dc,1,0):this.uint32(e)._push(Vg,e,t)}string(t){let e=id(t);return e!==0?this.uint32(e)._push(Ac,e,t):this._push(Dc,1,0)}fork(){return this.states=new Lc(this),this.head=this.tail=new er(Pc,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 er(Pc,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=qg(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Dc(r,t,e){t[e]=r&255}function zg(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Rc=class extends er{next;constructor(t,e){super(zg,t,e),this.next=void 0}};function gs(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 Vn(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 Vg(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Hn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Hg,t,r),this},Hn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push($g,t,r),this});function Hg(r,t,e){t.set(r,e)}function $g(r,t,e){r.length<40?Ac(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(D(r),e)}function kc(){return new Hn}function Pt(r,t){let e=kc();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var jr;(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"})(jr||(jr={}));function ys(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Oc(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 ys("enum",jr.VARINT,e,n)}function Dt(r,t){return ys("message",jr.LENGTH_DELIMITED,r,t)}var rr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},$n=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var st;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(st||(st={}));var Mc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Mc||(Mc={}));(function(r){r.codec=()=>Oc(Mc)})(st||(st={}));var ae;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),st.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=st.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(ae||(ae={}));var Nc;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),st.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=st.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(Nc||(Nc={}));function Zr(r){if(isNaN(r)||r<=0)throw new O("random bytes length must be a Number bigger than 0");return We(r)}var Gn={};Rt(Gn,{MAX_RSA_KEY_SIZE:()=>Bc,generateRSAKeyPair:()=>Wc,jwkToJWKKeyPair:()=>hd,jwkToPkcs1:()=>Zg,jwkToPkix:()=>qc,jwkToRSAPrivateKey:()=>$c,pkcs1MessageToJwk:()=>Uc,pkcs1MessageToRSAPrivateKey:()=>zc,pkcs1ToJwk:()=>jg,pkcs1ToRSAPrivateKey:()=>dd,pkixMessageToJwk:()=>Kc,pkixMessageToRSAPublicKey:()=>Hc,pkixToJwk:()=>Xg,pkixToRSAPublicKey:()=>Vc});var bs=os;var Xr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Gn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return J.createV1(114,this._multihash)}toString(){return H.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 fd(this.jwk,e,t,n)}},Wn=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Gn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}sign(t,e){return ud(this.jwk,t,e)}};var Bc=8192,Fc=18,Wg=1062,Gg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function jg(r){let t=pe(r);return Uc(t)}function Uc(r){return{n:M(r[1],"base64url"),e:M(r[2],"base64url"),d:M(r[3],"base64url"),p:M(r[4],"base64url"),q:M(r[5],"base64url"),dp:M(r[6],"base64url"),dq:M(r[7],"base64url"),qi:M(r[8],"base64url"),kty:"RSA"}}function Zg(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 O("JWK was missing components");return Zt([At(Uint8Array.from([0])),At(D(r.n,"base64url")),At(D(r.e,"base64url")),At(D(r.d,"base64url")),At(D(r.p,"base64url")),At(D(r.q,"base64url")),At(D(r.dp,"base64url")),At(D(r.dq,"base64url")),At(D(r.qi,"base64url"))]).subarray()}function Xg(r){let t=pe(r,{offset:0});return Kc(t)}function Kc(r){let t=pe(r[1],{offset:0});return{kty:"RSA",n:M(t[0],"base64url"),e:M(t[1],"base64url")}}function qc(r){if(r.n==null||r.e==null)throw new O("JWK was missing components");return Zt([Gg,Dn(Zt([At(D(r.n,"base64url")),At(D(r.e,"base64url"))]))]).subarray()}function dd(r){let t=pe(r);return zc(t)}function zc(r){let t=Uc(r);return $c(t)}function Vc(r,t){if(r.byteLength>=Wg)throw new Ar("Key size is too large");let e=pe(r,{offset:0});return Hc(e,r,t)}function Hc(r,t,e){let n=Kc(r);if(e==null){let o=bs(ae.encode({Type:st.RSA,Data:t}));e=Wt(Fc,o)}return new Xr(n,e)}function $c(r){if(md(r)>Bc)throw new O("Key size is too large");let t=hd(r),e=bs(ae.encode({Type:st.RSA,Data:qc(t.publicKey)})),n=Wt(Fc,e);return new Wn(t.privateKey,new Xr(t.publicKey,n))}async function Wc(r){if(r>Bc)throw new O("Key size is too large");let t=await pd(r),e=bs(ae.encode({Type:st.RSA,Data:qc(t.publicKey)})),n=Wt(Fc,e);return new Wn(t.privateKey,new Xr(t.publicKey,n))}function hd(r){if(r==null)throw new O("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function pd(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 Qg(e,t);return{privateKey:n[0],publicKey:n[1]}}async function ud(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 fd(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 Qg(r,t){if(r.privateKey==null||r.publicKey==null)throw new O("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 md(r){if(r.kty!=="RSA")throw new O("invalid key type");if(r.n==null)throw new O("invalid key modulus");return D(r.n,"base64url").length*8}var ws=class extends Mr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,lf(t);let n=Rn(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),ge(s)}update(t){return Br(this),this.iHash.update(t),this}digestInto(t){Br(this),bt(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()}},Gc=(r,t,e)=>new ws(r,t).update(e).digest();Gc.create=(r,t)=>new ws(r,t);function gd(r){r.lowS!==void 0&&be("lowS",r.lowS),r.prehash!==void 0&&be("prehash",r.prehash)}var jc=class extends Error{constructor(t=""){super(t)}},we={Err:jc,_tlv:{encode:(r,t)=>{let{Err:e}=we;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=Nn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Nn(o.length/2|128):"";return Nn(r)+s+o+t},decode(r,t){let{Err:e}=we,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}=we;if(r<jn)throw new t("integer: negative integers are not allowed");let e=Nn(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}=we;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 Ur(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=we,o=X("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}=we,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),Zn=BigInt(1),Yg=BigInt(2),xs=BigInt(3),Jg=BigInt(4);function t0(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 yd(r,t,e){let{BYTES:n}=r;function o(s){let i;if(typeof s=="bigint")i=s;else{let a=X("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 e0(r,t={}){let{Fp:e,Fn:n}=ls("weierstrass",r,t),{h:o,n:s}=r;Ne(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(be("isCompressed",S),S){a();let P=!e.isOdd(v);return Bt(bd(P),A)}else return Bt(Uint8Array.of(4),A,e.toBytes(v))}function u(I){bt(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 k=d(T),B;try{B=e.sqrt(k)}catch(W){let F=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}a();let N=e.isOdd(B);return(A&1)===1!==N&&(B=e.neg(B)),{x:T,y:B}}else if(v===x&&A===4){let T=e.fromBytes(P.subarray(y*0,y*1)),k=e.fromBytes(P.subarray(y*1,y*2));if(!h(T,k))throw new Error("bad point: is not on curve");return{x:T,y:k}}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=t0(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,xs),Jg),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=qr((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),k=e.mul(v,y);if(A)return{x:e.ZERO,y:e.ZERO};if(!e.eql(k,e.ONE))throw new Error("invZ was invalid");return{x:P,y:T}}),_=qr(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=zr(x,y),S=zr(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 is(b,"pz",y)}static fromBytes(y){return bt(y),b.fromHex(y)}static fromHex(y){let S=b.fromAffine(f(X("pointHex",y)));return S.assertValidity(),S}static fromPrivateKey(y){let S=yd(n,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return b.BASE.multiply(S(y))}static msm(y,S){return cs(b,n,y,S)}precompute(y=8,S=!0){return R.setWindowSize(this,y),S||this.multiply(xs),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,k=e.eql(e.mul(S,T),e.mul(A,v)),B=e.eql(e.mul(x,T),e.mul(P,v));return k&&B}negate(){return new b(this.px,e.neg(this.py),this.pz)}double(){let{a:y,b:S}=r,x=e.mul(S,xs),{px:v,py:A,pz:P}=this,T=e.ZERO,k=e.ZERO,B=e.ZERO,N=e.mul(v,v),ot=e.mul(A,A),W=e.mul(P,P),F=e.mul(v,A);return F=e.add(F,F),B=e.mul(v,P),B=e.add(B,B),T=e.mul(y,B),k=e.mul(x,W),k=e.add(T,k),T=e.sub(ot,k),k=e.add(ot,k),k=e.mul(T,k),T=e.mul(F,T),B=e.mul(x,B),W=e.mul(y,W),F=e.sub(N,W),F=e.mul(y,F),F=e.add(F,B),B=e.add(N,N),N=e.add(B,N),N=e.add(N,W),N=e.mul(N,F),k=e.add(k,N),W=e.mul(A,P),W=e.add(W,W),N=e.mul(W,F),T=e.sub(T,N),B=e.mul(W,ot),B=e.add(B,B),B=e.add(B,B),new b(T,k,B)}add(y){w(y);let{px:S,py:x,pz:v}=this,{px:A,py:P,pz:T}=y,k=e.ZERO,B=e.ZERO,N=e.ZERO,ot=r.a,W=e.mul(r.b,xs),F=e.mul(S,A),at=e.mul(x,P),ct=e.mul(v,T),gt=e.add(S,x),Z=e.add(A,P);gt=e.mul(gt,Z),Z=e.add(F,at),gt=e.sub(gt,Z),Z=e.add(S,v);let St=e.add(A,T);return Z=e.mul(Z,St),St=e.add(F,ct),Z=e.sub(Z,St),St=e.add(x,v),k=e.add(P,T),St=e.mul(St,k),k=e.add(at,ct),St=e.sub(St,k),N=e.mul(ot,Z),k=e.mul(W,ct),N=e.add(k,N),k=e.sub(at,N),N=e.add(at,N),B=e.mul(k,N),at=e.add(F,F),at=e.add(at,F),ct=e.mul(ot,ct),Z=e.mul(W,Z),at=e.add(at,ct),ct=e.sub(F,ct),ct=e.mul(ot,ct),Z=e.add(Z,ct),F=e.mul(at,Z),B=e.add(B,F),F=e.mul(St,Z),k=e.mul(gt,k),k=e.sub(k,F),F=e.mul(gt,at),N=e.mul(St,N),N=e.add(N,F),new b(k,B,N)}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:k,k2:B}=S.splitScalar(y),{p:N,f:ot}=A(T),{p:W,f:F}=A(B);v=ot.add(F),x=C(S.beta,N,W,P,k)}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===Zn)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:k,p2:B}=Hf(b,x,A,T);return C(S.beta,k,B,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===Zn?!0:y?y(b,this):R.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){let{clearCofactor:y}=t;return o===Zn?this:y?y(b,this):this.multiplyUnsafe(o)}toBytes(y=!0){return be("isCompressed",y),this.assertValidity(),l(b,this,y)}toRawBytes(y=!0){return this.toBytes(y)}toHex(y=!0){return ne(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=as(b,t.endo?Math.ceil(L/2):L);return b}function bd(r){return Uint8Array.of(r?2:3)}function r0(r,t,e={}){Ne(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||We,o=t.hmac||((x,...v)=>Gc(t.hash,x,Bt(...v))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i;function u(x){let v=a>>Zn;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=X("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}=we.toSig(X("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:k}=this;if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");if(a*Yg<A&&k>1)throw new Error("recovery id is ambiguous for h>1 curve");let N=k===2||k===3?P+a:P;if(!s.isValid(N))throw new Error("recovery id 2 or 3 invalid");let ot=s.toBytes(N),W=r.fromHex(Bt(bd((k&1)===0),ot)),F=i.inv(N),at=_(X("msgHash",v)),ct=i.create(-at*F),gt=i.create(T*F),Z=r.BASE.multiplyUnsafe(ct).add(W.multiplyUnsafe(gt));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 Bt(i.toBytes(this.r),i.toBytes(this.s));if(v==="der")return Fr(we.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return ne(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ne(this.toBytes("compact"))}}let h=yd(i,e.allowedPrivateKeyLengths,e.wrapPrivateKey),p={isValidPrivateKey(x){try{return h(x),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{let x=a;return Ff(n(fc(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=X("key",x).length,P=s.BYTES,T=P+1,k=2*P+1;if(!(e.allowedPrivateKeyLengths||i.BYTES===T))return A===T||A===k}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=Ur(x),A=x.length*8-c;return A>0?v>>BigInt(A):v},_=t.bits2int_modN||function(x){return i.create(E(x))},C=Xe(c);function b(x){return Me("num < 2^"+c,x,jn,C),i.toBytes(x)}function L(x,v,A=R){if(["recovered","canonical"].some(gt=>gt in A))throw new Error("sign() legacy options not supported");let{hash:P}=t,{lowS:T,prehash:k,extraEntropy:B}=A;T==null&&(T=!0),x=X("msgHash",x),gd(A),k&&(x=X("prehashed msgHash",P(x)));let N=_(x),ot=h(v),W=[b(ot),b(N)];if(B!=null&&B!==!1){let gt=B===!0?n(s.BYTES):B;W.push(X("extraEntropy",gt))}let F=Bt(...W),at=N;function ct(gt){let Z=E(gt);if(!i.isValidNot0(Z))return;let St=i.inv(Z),bn=r.BASE.multiply(Z).toAffine(),vr=i.create(bn.x);if(vr===jn)return;let qe=i.create(St*i.create(at+vr*ot));if(qe===jn)return;let Sa=(bn.x===vr?0:2)|Number(bn.y&Zn),_r=qe;return T&&u(qe)&&(_r=l(qe),Sa^=1),new d(vr,_r,Sa)}return{seed:F,k2sig:ct}}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 Tf(t.hash.outputLen,i.BYTES,o)(P,T)}r.BASE.precompute(8);function S(x,v,A,P=I){let T=x;v=X("msgHash",v),A=X("publicKey",A),gd(P);let{lowS:k,prehash:B,format:N}=P;if("strict"in P)throw new Error("options.strict was renamed to lowS");if(N!==void 0&&!["compact","der","js"].includes(N))throw new Error('format must be "compact", "der" or "js"');let ot=typeof T=="string"||Nr(T),W=!ot&&!N&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!ot&&!W)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,at;try{if(W)if(N===void 0||N==="js")F=new d(T.r,T.s);else throw new Error("invalid format");if(ot){try{N!=="compact"&&(F=d.fromDER(T))}catch(_r){if(!(_r instanceof we.Err))throw _r}!F&&N!=="der"&&(F=d.fromCompact(T))}at=r.fromHex(A)}catch{return!1}if(!F||k&&F.hasHighS())return!1;B&&(v=t.hash(v));let{r:ct,s:gt}=F,Z=_(v),St=i.inv(gt),bn=i.create(Z*St),vr=i.create(ct*St),qe=r.BASE.multiplyUnsafe(bn).add(at.multiplyUnsafe(vr));return qe.is0()?!1:i.create(qe.x)===ct}return Object.freeze({getPublicKey:g,getSharedSecret:w,sign:y,verify:S,utils:p,Point:r,Signature:d})}function n0(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=Qt(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 o0(r){let{CURVE:t,curveOpts:e}=n0(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 s0(r,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:r})}function wd(r){let{CURVE:t,curveOpts:e,ecdsaOpts:n}=o0(r),o=e0(t,e),s=r0(o,n,e);return s0(r,s)}function xd(r,t){let e=n=>wd({...r,hash:n});return{...e(t),create:e}}var Es={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Gv=BigInt(0),i0=BigInt(1),Zc=BigInt(2),Ed=(r,t)=>(r+t/Zc)/t;function a0(r){let t=Es.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=Q(l,e,t)*l%t,d=Q(f,e,t)*l%t,h=Q(d,Zc,t)*u%t,p=Q(h,o,t)*h%t,g=Q(p,s,t)*p%t,m=Q(g,a,t)*g%t,w=Q(m,c,t)*m%t,E=Q(w,a,t)*g%t,_=Q(E,e,t)*l%t,C=Q(_,i,t)*p%t,b=Q(C,n,t)*u%t,L=Q(b,Zc,t);if(!Xc.eql(Xc.sqr(L),r))throw new Error("Cannot find square root");return L}var Xc=Qt(Es.p,void 0,void 0,{sqrt:a0}),Jt=xd({...Es,Fp:Xc,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Es.n,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-i0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Ed(s*r,t),c=Ed(-n*r,t),u=tt(r-a*e-c*o,t),l=tt(-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}}}},os);function vd(r,t,e){let n=Or.digest(t instanceof Uint8Array?t:t.subarray());if($r(n))return n.then(({digest:o})=>(e?.signal?.throwIfAborted(),Jt.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Un(String(o))});try{return Jt.sign(n.digest,r).toDERRawBytes()}catch(o){throw new Un(String(o))}}function _d(r,t,e,n){let o=Or.digest(e instanceof Uint8Array?e:e.subarray());if($r(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Jt.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new Kn(String(s))});try{return n?.signal?.throwIfAborted(),Jt.verify(t,o.digest,r)}catch(s){throw new Kn(String(s))}}var Xn=class{type="secp256k1";raw;_key;constructor(t){this._key=Cd(t),this.raw=Sd(this._key)}toMultihash(){return Gt.digest(zt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return H.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 _d(this._key,e,t,n)}},vs=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=Ad(t),this.publicKey=new Xn(e??Id(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:G(this.raw,t.raw)}sign(t,e){return vd(this.raw,t,e)}};function Qc(r){return new Xn(r)}async function Td(){let r=c0();return new vs(r)}function Sd(r){return Jt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ad(r){try{return Jt.getPublicKey(r,!0),r}catch(t){throw new wn(String(t))}}function Cd(r){try{return Jt.ProjectivePoint.fromHex(r),r}catch(t){throw new Ar(String(t))}}function Id(r){try{return Jt.getPublicKey(r,!0)}catch(t){throw new wn(String(t))}}function c0(){return Jt.utils.randomPrivateKey()}async function Pd(r,t){if(r==="Ed25519")return td();if(r==="secp256k1")return Td();if(r==="RSA")return Wc(l0(t));if(r==="ECDSA")return af(u0(t));throw new Pe}function Qr(r,t){let{Type:e,Data:n}=ae.decode(r),o=n??new Uint8Array;switch(e){case st.RSA:return Vc(o,t);case st.Ed25519:return yc(o);case st.secp256k1:return Qc(o);case st.ECDSA:return rc(o);default:throw new Pe}}function Dd(r){let{Type:t,Data:e}=ae.decode(r.digest),n=e??new Uint8Array;switch(t){case st.Ed25519:return yc(n);case st.secp256k1:return Qc(n);case st.ECDSA:return rc(n);default:throw new Pe}}function zt(r){return ae.encode({Type:st[r.type],Data:r.raw})}function l0(r){return r==null?2048:parseInt(r,10)}function u0(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 O("Unsupported curve, should be P-256, P-384 or P-521")}var Ld=Symbol.for("nodejs.util.inspect.custom"),f0=114,Qn=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()})`}[qo]=!0;toString(){return this.string==null&&(this.string=H.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return J.createV1(f0,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")}[Ld](){return`PeerId(${this.toString()})`}},Yn=class extends Qn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Jn=class extends Qn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},to=class extends Qn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},d0=2336,eo=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Gt.digest(D(this.url))}[Ld](){return`PeerId(${this.url})`}[qo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return J.createV1(d0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=M(t)),t.toString()===this.toString())}};var h0=114,Rd=2336;function ce(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=he(H.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return ro(J.parse(r));if(t==null)throw new O('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=he(t.decode(r))}return Yr(e)}function Yc(r){if(r.type==="Ed25519")return new Jn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new to({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Yn({multihash:r.toCID().multihash,publicKey:r});throw new Pe}function kd(r){return Yc(r.publicKey)}function Yr(r){if(m0(r))return new Yn({multihash:r});if(p0(r))try{let t=Dd(r);if(t.type==="Ed25519")return new Jn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new to({multihash:r,publicKey:t})}catch{let e=M(r.digest);return new eo(new URL(e))}throw new Ho("Supplied PeerID Multihash is invalid")}function ro(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==h0&&r.code!==Rd)throw new Vo("Supplied PeerID CID is invalid");if(r.code===Rd){let t=M(r.multihash.digest);return new eo(new URL(t))}return Yr(r.multihash)}function p0(r){return r.code===Gt.code}function m0(r){return r.code===Or.code}function Jr(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:Md}=Object.prototype,{propertyIsEnumerable:g0}=Object,tn=(r,t,e)=>{Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0})},y0=void 0,Od={concatArrays:!1,ignoreUndefined:!1},_s=r=>{let t=[];for(let e in r)Md.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)g0.call(r,n)&&t.push(n)}return t};function en(r){return Array.isArray(r)?b0(r):Jr(r)?w0(r):r}function b0(r){let t=r.slice(0,0);return _s(r).forEach(e=>{tn(t,e,en(r[e]))}),t}function w0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return _s(r).forEach(e=>{tn(t,e,en(r[e]))}),t}var Nd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?tn(r,o,Jc(r[o],t[o],n)):tn(r,o,en(t[o])))}),r),x0=(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++)Md.call(s,a)&&(i.push(String(a)),s===r?tn(n,o++,s[a]):tn(n,o++,en(s[a])));n=Nd(n,s,_s(s).filter(a=>!i.includes(a)),e)}),n};function Jc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?x0(r,t,e):!Jr(t)||!Jr(r)?en(t):Nd(r,t,_s(t),e)}function Ss(...r){let t=Jc(en(Od),this!==y0&&this||{},Od),e={_:{}};for(let n of r)if(n!==void 0){if(!Jr(n))throw new TypeError("`"+n+"` is not an Option Object");e=Jc(e,{_:n},t)}return e._}var it=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var el=Ko(Fd(),1);var oo=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},rl=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Ud=r=>globalThis.DOMException===void 0?new rl(r):new DOMException(r),Kd=r=>{let t=r.reason===void 0?Ud("This operation was aborted."):r.reason;return t instanceof Error?t:Ud(t)};function nl(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(Kd(h)),a=()=>{f(Kd(h))},h.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(l,f);return}let d=new oo;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 ol(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 so=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=ol(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 io=class extends el.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:so,...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=nl(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 oo&&!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 Cs(r){let t=[Ut.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var sl=60;function Is(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:Ut[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Ut[t.type],TTL:t.TTL??t.ttl??sl,data:t.data instanceof Uint8Array?M(t.data):t.data}))}}var _0=4;function il(r,t={}){let e=new io({concurrency:t.queryConcurrency??_0});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Cs(o.types).forEach(a=>{s.append("type",Ut[a])}),o.onProgress?.(new it("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=Is(await a.json());return o.onProgress?.(new it("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function qd(){return[il("https://cloudflare-dns.com/dns-query"),il("https://dns.google/resolve")]}var Hd=Ko(Vd(),1);var al=class{lru;constructor(t){this.lru=(0,Hd.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 Is({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:Ut[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??sl)*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 $d(r){return new al(r)}var S0=1e3,Ts=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=$d(t.cacheSize??S0),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["."]=qd())}async query(t,e={}){let n=Cs(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new it("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 it("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Ut;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ut||(Ut={}));function Wd(r={}){return new Ts(r)}var ht=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},xe=class extends Error{static name="ValidationError";name="ValidationError"},ao=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ps=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Ds=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 Gd=45,A0=15,rn=new Ds;function Ls(r){if(!(r.length>A0))return rn.new(r).parseWith(()=>rn.readIPv4Addr())}function Rs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Gd))return rn.new(r).parseWith(()=>rn.readIPv6Addr())}function nn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Gd)return;let e=rn.new(r).parseWith(()=>rn.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 Kt(r){return!!Ls(r)}function on(r){return!!Rs(r)}function ll(r){return t=>M(t,r)}function ul(r){return t=>D(t,r)}function sn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function nr(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function jd(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=nr(n);return jt([e,o],e.length+o.length)}function Zd(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=qt.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=nr(n);return jt([e,o],e.length+o.length)}function fl(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=M(t,"base32"),o=sn(e);return`${n}:${o}`}var dl=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 ht("Invalid byte value in IP address");t[n]=o}),t},Xd=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Kt(e[n]),i;s&&(i=dl(e[n]),e[n]=M(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,M(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 ht("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Qd=function(r){if(r.byteLength!==4)throw new ht("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Yd=function(r){if(r.byteLength!==16)throw new ht("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 ht(`Invalid IPv6 address "${e}"`)}};function Jd(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new ht(`Invalid IPv6 address "${r}"`)}}var cl=Object.values(In).map(r=>r.decoder),C0=function(){let r=cl[0].or(cl[1]);return cl.slice(2).forEach(t=>r=r.or(t)),r}();function th(r){return C0.decode(r)}function eh(r){return t=>r.encoder.encode(t)}function I0(r){if(parseInt(r).toString()!==r)throw new xe("Value must be an integer")}function T0(r){if(r<0)throw new xe("Value must be a positive integer, or zero")}function P0(r){return t=>{if(t>r)throw new xe(`Value must be smaller than or equal to ${r}`)}}function D0(...r){return t=>{for(let e of r)e(t)}}var co=D0(I0,T0,P0(65535));var ft=-1,hl=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 Ps(`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)}))}},Ot=new hl,iy=[{code:4,name:"ip4",size:32,valueToBytes:dl,bytesToValue:Qd,validate:r=>{if(!Kt(r))throw new xe(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:nr,bytesToValue:sn,validate:co},{code:273,name:"udp",size:16,valueToBytes:nr,bytesToValue:sn,validate:co},{code:33,name:"dccp",size:16,valueToBytes:nr,bytesToValue:sn,validate:co},{code:41,name:"ip6",size:128,valueToBytes:Xd,bytesToValue:Yd,stringToValue:Jd,validate:r=>{if(!on(r))throw new xe(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ft},{code:43,name:"ipcidr",size:8,bytesToValue:ll("base10"),valueToBytes:ul("base10")},{code:53,name:"dns",size:ft,resolvable:!0},{code:54,name:"dns4",size:ft,resolvable:!0},{code:55,name:"dns6",size:ft,resolvable:!0},{code:56,name:"dnsaddr",size:ft,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:nr,bytesToValue:sn,validate:co},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ft,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ft,bytesToValue:ll("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ul("base58btc")(r):J.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:fl,valueToBytes:jd},{code:445,name:"onion3",size:296,bytesToValue:fl,valueToBytes:Zd},{code:446,name:"garlic64",size:ft},{code:447,name:"garlic32",size:ft},{code:448,name:"tls"},{code:449,name:"sni",size:ft},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ft,bytesToValue:eh(Cn),valueToBytes:th},{code:480,name:"http"},{code:481,name:"http-path",size:ft,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:ft}];iy.forEach(r=>{Ot.addProtocol(r)});function rh(r){let t=[],e=0;for(;e<r.length;){let n=Je(r,e),o=Ot.getProtocol(n),s=ut(n),i=ay(o,r,e+s),a=0;i>0&&o.size===ft&&(a=ut(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)??M(f)}t.push(u),e+=c}return t}function nh(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Ot.getProtocol(n.code),s=ut(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??D(n.value),a=i.byteLength,o.size===ft&&(c=ut(a)));let u=new Uint8Array(s+c+a),l=0;Wr(n.code,u,l),l+=s,i!=null&&(o.size===ft&&(Wr(a,u,l),l+=c),u.set(i,l)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return jt(e,t)}function oh(r){if(r.charAt(0)!=="/")throw new ht('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=Ot.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 ht(`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 ht(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new ht("Incomplete multiaddr");return t}function sh(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Ot.getProtocol(t.code);if(e==null)throw new ht(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function ay(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Je(t,e)}var cy=Symbol.for("nodejs.util.inspect.custom"),yl=Symbol.for("@multiformats/multiaddr"),ly=[53,54,55,56],gl=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function uy(r){if(r==null&&(r="/"),Fe(r))return r.getComponents();if(r instanceof Uint8Array)return rh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),oh(r);if(Array.isArray(r))return r;throw new ht("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ms=class r{[yl]=!0;#t;#n;#e;constructor(t="/",e={}){this.#t=uy(t),e.validate!==!1&&fy(this)}get bytes(){return this.#e==null&&(this.#e=nh(this.#t)),this.#e}toString(){return this.#n==null&&(this.#n=sh(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??""}`),ly.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=Ot.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=Ot.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 ao(`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"?M(H.decode(`z${n}`),"base58btc"):M(J.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(Ot.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=ih.get(e.name);if(n==null)throw new gl(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>q(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)}[cy](){return`Multiaddr(${this.toString()})`}};function fy(r){r.getComponents().forEach(t=>{let e=Ot.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function ah(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 ch(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 bl(r){switch(r.length){case or:return r.join(".");case sr:{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 lh(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 uh(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var or=4,sr=16,gS=parseInt("0xFFFF",16),dy=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ho(r,t){t.length===sr&&r.length===or&&ah(t,0,11)&&(t=t.slice(12)),t.length===or&&r.length===sr&&ch(r,dy,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 fh(r,t){if(typeof t=="string"&&(t=nn(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 wl(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=or,o=Ls(t);if(o==null&&(n=sr,o=Rs(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=xl(s,8*n);return{network:ho(o,i),mask:i}}function xl(r,t){if(t!==8*or&&t!==8*sr)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 cn=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=wl(t));else{let n=nn(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=nn(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=xl(o,8*n.length);this.network=ho(n,this.mask)}}contains(t){return fh({network:this.network,mask:this.mask},t)}toString(){let t=lh(this.mask),e=t!==-1?String(t):uh(this.mask);return bl(this.network)+"/"+e}};function El(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 cn(e,t)}var ih=new Map;function Fe(r){return!!r?.[yl]}function q(r){return new Ms(r)}function Ns(r){let t=Ot.getProtocol(r);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}var vl=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:[Ut.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(q(u)))}return a}getDNS(t){return t.dns!=null?t.dns:(this.dns==null&&(this.dns=Wd()),this.dns)}},ve=new vl;var hy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:ve}},transportManager:{faultTolerance:ze.FATAL_ALL}};async function dh(r){let t=Ss(hy,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new O("Private network is enforced, but no protector was provided");return t}function py(r,t){try{if(typeof r=="string"&&r.length>0)return my(r);if(typeof r=="number"&&isFinite(r))return t?.long?yy(r):gy(r);throw new Error("Value is not a string or number.")}catch(e){let n=by(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function my(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 Fs=py;function gy(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 yy(r){let t=Math.abs(r);return t>=864e5?Bs(r,t,864e5,"day"):t>=36e5?Bs(r,t,36e5,"hour"):t>=6e4?Bs(r,t,6e4,"minute"):t>=1e3?Bs(r,t,1e3,"second"):`${r} ms`}function Bs(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function by(r){return typeof r=="object"&&r!==null&&"message"in r}function _l(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=Fs,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 Us=Ay(),wy=["#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 xy(){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 Ey(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Fs(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 vy=console.debug??console.log??(()=>{});function _y(r){try{r?Us?.setItem("debug",r):Us?.removeItem("debug")}catch{}}function Sy(){let r;try{r=Us?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Ay(){try{return localStorage}catch{}}function Cy(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var hh=_l({formatArgs:Ey,save:_y,load:Sy,useColors:xy,setupFormatters:Cy,colors:wy,storage:Us,log:vy});var Mt=hh;Mt.formatters.b=r=>r==null?"undefined":H.baseEncode(r);Mt.formatters.t=r=>r==null?"undefined":qt.baseEncode(r);Mt.formatters.m=r=>r==null?"undefined":Ha.baseEncode(r);Mt.formatters.p=r=>r==null?"undefined":r.toString();Mt.formatters.c=r=>r==null?"undefined":r.toString();Mt.formatters.k=r=>r==null?"undefined":r.toString();Mt.formatters.a=r=>r==null?"undefined":r.toString();Mt.formatters.e=r=>r==null?"undefined":ph(r.stack)??ph(r.message)??r.toString();function Iy(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 Ks(){return{forComponent(r){return Ty(r)}}}function Ty(r){let t=Iy(`${r}:trace`);return Mt.enabled(`${r}:trace`)&&Mt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Mt(`${r}:trace`)),Object.assign(Mt(r),{error:Mt(`${r}:error`),trace:t})}function ph(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function ir(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 qs(r){let t=he(H.decode(`z${r}`));return Yr(t)}var Vt=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 ir(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 ir(this.map.values(),t=>t.key)}values(){return ir(this.map.values(),t=>t.value)}get size(){return this.map.size}};var ar=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 ir(this.set.entries(),t=>{let e=qs(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=qs(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return ir(this.set.values(),t=>qs(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 Sl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},mh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},gh=new globalThis.TextEncoder;function Py(r,t){let e=Sl[t],n=mh[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Dy(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Sl[t],o=mh[t],s=r;for(;s.length>0;){let i=gh.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 Al(r,{size:t=32,utf8Buffer:e}={}){if(!Sl[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 Dy(r,t,e);r=gh.encode(r)}return Py(r,t)}var po={hash:r=>Number(Al(r,{size:32})),hashV:(r,t)=>Ly(po.hash(r,t))};function Ly(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),D(t,"base16")}var Cl=64,ee=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Cl)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=rt(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 cr(r,t){return Math.floor(Math.random()*(t-r))+r}var lr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof ee))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof ee))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 ee))throw new TypeError("Invalid Fingerprint");let e=cr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof ee))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Ry=500,mo=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??po,this.seed=t.seed??cr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=D(t));let e=new ee(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 lr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new lr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[cr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new lr(this.bucketSize));for(let a=0;a<Ry;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 lr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=D(t));let e=new ee(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 ee(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}},ky={1:.5,2:.84,4:.95,8:.98};function Oy(r=.001){return r>.002?2:r>1e-5?4:8}function yh(r,t=.001){let e=Oy(t),n=ky[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Cl);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var zs=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??po,this.seed=t.seed??cr(0,Math.pow(2,10)),this.filterSeries=[new mo({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 mo({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 go(r,t=.001,e){return new zs({...yh(r,t),...e??{}})}var Il=class extends Vt{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 Tl(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Il({name:t,metrics:e}):n=new Vt,n}var yo;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((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:rt(0),payloadType:rt(0),payload:rt(0),signature:rt(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=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(yo||(yo={}));var Vs=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var ln=class r{static createFromProtobuf=t=>{let e=yo.decode(t),n=Qr(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=bh(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 Vs("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=yo.encode({publicKey:zt(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=bh(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},bh=(r,t,e)=>{let n=D(r),o=ie(n.byteLength),s=ie(t.length),i=ie(e.length);return new z(o,n,s,t,i,e)};function wh(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 xh="libp2p-peer-record",Eh=Uint8Array.from([3,1]);var bo;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Dt((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:rt(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=>Pt(s,n.codec()),n.decode=(s,i)=>Tt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Dt((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:rt(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 rr('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=>Pt(n,r.codec()),r.decode=(n,o)=>Tt(n,r.codec(),o)})(bo||(bo={}));var ur=class r{static createFromProtobuf=t=>{let e=bo.decode(t),n=Yr(he(e.peerId)),o=(e.addresses??[]).map(i=>q(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=xh;static CODEC=Eh;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=bo.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||!wh(this.multiaddrs,t.multiaddrs))}};function My(r){return r[Symbol.asyncIterator]!=null}function Ny(r){if(My(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 wo=Ny;var re=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};function nt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Hs=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}},un=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Hs(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 Hs(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 Pl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function $s(r={}){return By(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 By(r,t){t=t??{};let e=t.onEnd,n=new un,o,s,i,a=nt(),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=nt()})}},u=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new un,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 un,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 Pl)},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 Dl=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 ue(r,t,e,n){let o=new Dl(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 Ws=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Gs=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 pt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new Gs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Gs(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 re)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Fy(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Zs=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Fy(),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 re),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 pt(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 Ll(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 xo=class extends Nt{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=Ll(this.emitEmpty.bind(this),1),this.emitIdle=Ll(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 Ws;let n=new Zs(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 re)}),this.clear()}async onEmpty(t){this.size!==0&&await ue(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await ue(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ue(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=$s({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 re("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 Xs="lock:worker:request-read",Qs="lock:worker:abort-read-request",Ys="lock:worker:release-read",Js="lock:master:grant-read",ti="lock:master:error-read",ei="lock:worker:request-write",ri="lock:worker:abort-write-request",ni="lock:worker:release-write",oi="lock:master:grant-write",si="lock:master:error-write",ii="lock:worker:finalize",ai="mortice",vh={singleProcess:!1};var Rl=(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===ii&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var _h=(r=10)=>Math.random().toString().substring(2,r+2);var ci=class{name;channel;constructor(t){this.name=t,this.channel=new BroadcastChannel(ai)}readLock(t){return this.sendRequest(Xs,Qs,Js,ti,Ys,t)}writeLock(t){return this.sendRequest(ei,ri,oi,si,ni,t)}finalize(){this.channel.postMessage({type:ii,name:this.name}),this.channel.close()}async sendRequest(t,e,n,o,s,i){i?.signal?.throwIfAborted();let a=_h();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 Sh=r=>{if(r=Object.assign({},vh,r),!!globalThis.document||r.singleProcess){let e=new BroadcastChannel(ai),n=new Nt;return e.addEventListener("message",Rl(n,e,"requestReadLock","abortReadLockRequest",Xs,Qs,ti,Ys,Js)),e.addEventListener("message",Rl(n,e,"requestWriteLock","abortWriteLockRequest",ei,ri,si,ni,oi)),n}return new ci(r.name)};var fr=new Map,Eo;function Ah(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Uy(r){if(Eo==null&&(Eo=Sh(r),!Ah(Eo))){let t=Eo;t.addEventListener("requestReadLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=fr.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=fr.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=fr.get(n);o?.finalize()})}return Eo}async function kl(r,t){let e,n,o=new Promise((i,a)=>{e=i,n=a}),s=()=>{n(new re)};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 Ch=(r,t)=>{let e=fr.get(r);if(e!=null)return e;let n=Uy(t);if(Ah(n))return e=n,fr.set(r,e),e;let o=new xo({concurrency:1}),s;return e={async readLock(i){if(s!=null)return kl(s,i);s=new xo({concurrency:t.concurrency,autoStart:!1});let a=s,c=kl(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,kl(o,i)},finalize:()=>{fr.delete(r)},queue:o},fr.set(r,e),t.autoFinalize===!0&&o.addEventListener("idle",()=>{e.finalize()},{once:!0}),e};var Ky={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Ol(r){let t=Object.assign({},Ky,r);return Ch(t.name,t)}var _e;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Dt((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:rt(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=>Pt(i,o.codec()),o.decode=(i,a)=>Tt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Dt((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),ui.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=ui.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Pt(i,o.codec()),o.decode=(i,a)=>Tt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Dt((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),li.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 rr('Decode error - map field "addresses" had too many elements');a.addresses.push(li.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 rr('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 $n('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 $n('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=>Pt(o,r.codec()),r.decode=(o,s)=>Tt(o,r.codec(),s)})(_e||(_e={}));var li;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((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:rt(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=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(li||(li={}));var ui;(function(r){let t;r.codec=()=>(t==null&&(t=Dt((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=>Pt(e,r.codec()),r.decode=(e,n)=>Tt(e,r.codec(),n)})(ui||(ui={}));function qy(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;r.type==="RSA"&&(e=r.toMultihash());let n=Qr(t.publicKey,e);return Yc(n)}function Ih(r,t,e){let n=_e.decode(t);return fn(r,n,e)}function fn(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:qy(r,t),addresses:t.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-e).map(({multiaddr:s,isCertified:i})=>({multiaddr:q(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function Th(r,t){return zy(r.addresses,t.addresses)&&Vy(r.protocols,t.protocols)&&Hy(r.publicKey,t.publicKey)&&$y(r.peerRecordEnvelope,t.peerRecordEnvelope)&&Wy(r.metadata,t.metadata)&&Gy(r.tags,t.tags)}function zy(r,t){return Dh(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!G(e.multiaddr,n.multiaddr)))}function Vy(r,t){return Dh(r,t,(e,n)=>e===n)}function Hy(r,t){return Ph(r,t)}function $y(r,t){return Ph(r,t)}function Wy(r,t){return Lh(r,t,(e,n)=>G(e,n))}function Gy(r,t){return Lh(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function Ph(r,t){return r==null&&t==null?!0:r!=null&&t!=null?G(r,t):!1}function Dh(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 Lh(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 Se="/",Rh=new TextEncoder().encode(Se),fi=Rh[0],dr=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]!==fi)throw new Error("Invalid key")}toString(t="utf8"){return M(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Se))}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=Rh),this._buf[0]!==fi){let t=new Uint8Array(this._buf.byteLength+1);t.fill(fi,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===fi;)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(Se).slice(1)}type(){return jy(this.baseNamespace())}name(){return Zy(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Se)||(t+=Se),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Se):new r(t.slice(0,-1).join(Se))}child(t){return this.toString()===Se?t:t.toString()===Se?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(),...Xy(t.map(e=>e.namespaces()))])}};function jy(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function Zy(r){let t=r.split(":");return t[t.length-1]}function Xy(r){return[].concat(...r)}var Ml="/peers/";function vo(r){if(!Ie(r)||r.type==null)throw new O("Invalid PeerId");let t=r.toCID().toString();return new dr(`${Ml}${t}`)}async function kh(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=q(i.multiaddr)),!Fe(i.multiaddr))throw new O("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(q(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function hi(r,t,e,n){if(t==null)throw new O("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new O("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new O("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=di(d,{validate:Oh})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=di(d,{validate:Mh,map:Nh})}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=di([...a.entries()],{validate:Oh})}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=di([...h.entries()],{validate:Mh,map:Nh})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=zt(o.id.publicKey):t.publicKey!=null?l=zt(t.publicKey):r.publicKey!=null&&(l=zt(r.publicKey));let f={addresses:await kh(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 di(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 Oh(r,t){if(typeof r!="string")throw new O("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new O("Metadata value must be a Uint8Array")}function Mh(r,t){if(typeof r!="string")throw new O("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new O("Tag value must be an integer");if(t.value<0||t.value>100)throw new O("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new O("Tag ttl must be an integer");if(t.ttl<0)throw new O("Tag ttl must be between greater than 0")}}function Nh(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 Bh(r){let t=r.toString().split("/")[2],e=J.parse(t,qt);return ro(e)}function Nl(r,t,e){let n=Bh(r);return Ih(n,t,e)}function Qy(r,t){return{prefix:Ml,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(Nl(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(Nl(n.key,n.value,t),Nl(o.key,o.value,t)))}}var pi=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=Tl({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:Ol({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(vo(t),e)}async load(t,e){let n=vo(t),o=await this.datastore.get(n,e),s=_e.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new Ve;return fn(t,s,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e,n){let o=await this.#t(t,n),s=await hi(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 hi(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 hi(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(Qy(t??{},this.maxAddressAge),t)){let o=Bh(e);if(o.equals(this.peerId))continue;let s=_e.decode(n);if(this.#e(o,s)){await this.datastore.delete(e,t);continue}yield fn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t,e){try{let n=vo(t),o=await this.datastore.get(n,e),s=_e.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new Ve;return{peerPB:s,peer:fn(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=_e.encode(e);return await this.datastore.put(vo(t),s,o),{peer:fn(t,e,this.maxAddressAge),previous:n?.peer,updated:n==null||!Th(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 Bl=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 pi(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 wo(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=Ie(e)?e:Ie(e?.expectedPeer)?e.expectedPeer:void 0,s=Ie(e)||e===void 0?n:e,i=await ln.openAndCertify(t,ur.DOMAIN,s),a=ro(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=ur.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=ln.createFromProtobuf(u.peerRecordEnvelope),f=ur.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 Fh(r,t={}){return new Bl(r,t)}var mi=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 Yy(r){return r[Symbol.asyncIterator]!=null}function Jy(r){if(Yy(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Fl=Jy;function tb(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 Uh=tb;function eb(r){return r[Symbol.asyncIterator]!=null}function rb(r,t){let e=0;if(eb(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Uh(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 hr=rb;function nb(r){return r[Symbol.asyncIterator]!=null}function ob(r,t){return nb(r)?async function*(){yield*(await wo(r)).sort(t)}():function*(){yield*wo(r).sort(t)}()}var Ul=ob;function sb(r){return r[Symbol.asyncIterator]!=null}function ib(r,t){return sb(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 Kl=ib;var gi=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 Fl(this.putMany(t,n)),t=[],await Fl(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=hr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>hr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>Ul(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=hr(n,()=>o++>=s)}return t.limit!=null&&(n=Kl(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=hr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>hr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>Ul(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=hr(n,()=>s++>=o)}return t.limit!=null&&(n=Kl(n,t.limit)),n}};var yi=class extends gi{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 mi;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 dr(n),value:o},e?.signal?.throwIfAborted()}*_allKeys(t,e){e?.signal?.throwIfAborted();for(let n of this.data.keys())yield new dr(n),e?.signal?.throwIfAborted()}};function _o(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 qh=Ko(Kh(),1),ab=["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"],cb=ab.map(r=>new qh.Netmask(r));function ql(r){for(let t of cb)if(t.contains(r))return!0;return!1}function lb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function ub(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 ql(o)}function fb(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function db(r){let t=r.split(":"),e=t[t.length-1];return ql(e)}function hb(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 Ue(r){if(Kt(r))return ql(r);if(lb(r))return ub(r);if(fb(r))return db(r);if(on(r))return hb(r)}var pb=r=>r.toString().split("/").slice(1),dn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),U=r=>({match:t=>dn(e=>e===r).match(t),pattern:r}),pr=()=>({match:r=>dn(t=>typeof t=="string").match(r),pattern:"{string}"}),hn=()=>({match:r=>dn(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),j=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{H.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ao=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Cn.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),V=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),vt=(...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},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),K=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function Y(...r){function t(o){let s=pb(o);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 mb=j(),zh=Y(mb),wi=K(U("dns4"),pr()),xi=K(U("dns6"),pr()),Ei=K(U("dnsaddr"),pr()),Vl=K(U("dns"),pr()),F6=Y(wi,V(j())),U6=Y(xi,V(j())),K6=Y(Ei,V(j())),q6=Y(vt(Vl,Ei,wi,xi),V(j())),Vh=K(U("ip4"),dn(Kt)),Hh=K(U("ip6"),dn(on)),Hl=vt(Vh,Hh),Ae=vt(Hl,Vl,wi,xi,Ei),z6=Y(vt(Hl,K(vt(Vl,Ei,wi,xi),V(j())))),$l=Y(Vh),Wl=Y(Hh),V6=Y(Hl),Gl=K(Ae,U("tcp"),hn()),Co=K(Ae,U("udp"),hn()),Io=Y(K(Gl,V(j()))),H6=Y(Co),jl=K(Co,U("quic"),V(j())),vi=K(Co,U("quic-v1"),V(j())),gb=vt(jl,vi),$6=Y(jl),$h=Y(vi),zl=vt(Ae,Gl,Co,jl,vi),Wh=vt(K(zl,U("ws"),V(j()))),mr=Y(Wh),Gh=vt(K(zl,U("wss"),V(j())),K(zl,U("tls"),V(K(U("sni"),pr())),U("ws"),V(j()))),To=Y(Gh),jh=K(Co,U("webrtc-direct"),V(Ao()),V(Ao()),V(j())),Zl=Y(jh),Zh=K(vi,U("webtransport"),V(Ao()),V(Ao()),V(j())),Xl=Y(Zh),bi=vt(Wh,Gh,K(Gl,V(j())),K(gb,V(j())),K(Ae,V(j())),jh,Zh,j()),W6=Y(bi),yb=K(bi,U("p2p-circuit"),j()),Po=Y(yb),bb=vt(K(bi,U("p2p-circuit"),U("webrtc"),V(j())),K(bi,U("webrtc"),V(j())),K(U("webrtc"),V(j()))),Ql=Y(bb),wb=vt(K(Ae,U("tcp"),hn(),U("http"),V(j())),K(Ae,U("http"),V(j()))),G6=Y(wb),xb=vt(K(Ae,U("tcp"),vt(K(U("443"),U("http")),K(hn(),U("https")),K(hn(),U("tls"),U("http"))),V(j())),K(Ae,U("tls"),U("http"),V(j())),K(Ae,U("https"),V(j()))),j6=Y(xb),Eb=vt(K(U("memory"),pr(),V(j()))),Z6=Y(Eb);var Yl=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 _t(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Yl({name:t,metrics:e}):n=new Map,n}var Xh=864e13;var vb=448,Jl=449,_b=53,Sb=54,Ab=55,Cb=56,_i=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=_t({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=Ue(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?Xh-Date.now():0,lastVerified:o?Xh-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:q(`/${s.map(l=>[Ns(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]===vb&&t[n+1]?.[0]!==Jl)return t.splice(n+1,0,[Jl,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]===Jl||e[0]===_b||e[0]===Sb||e[0]===Ab||e[0]===Cb)return e[1]}};var tu=4,eu=41,ru=6,Ib=273,Si=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=_t({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:Kt(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]===ru?"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]===tu||o[0][0]===eu)&&o[1][0]===ru?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===tu||o[0][0]===eu)&&o[1][0]===Ib&&(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?tu:eu,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:q(`/${o.map(c=>[Ns(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]===ru?"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 Qh(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 Ai(r){try{for(let{code:t}of r.getComponents())if(t!==42)return t===4||t===41}catch{}return!1}function gr(r){try{if(!Ai(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:Ue(t)??!1}catch{}return!0}var Tb={maxObservedAddresses:10},Ci=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=_t({name:"libp2p_address_manager_observed_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??Tb.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&&(gr(t)||Qh(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:q(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 Pb=[4,41,53,54,55,56];function nu(r){try{for(let{code:t}of r.getComponents())if(t!==42)return Pb.includes(t)}catch{}return!1}var Db={maxObservedAddresses:10},Ii=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=_t({name:"libp2p_address_manager_transport_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??Db.maxObservedAddresses}get(t,e){if(gr(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:!nu(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(nu(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var Yh=6e4,Jh={maxObservedAddresses:10,addressVerificationTTL:Yh*10,addressVerificationRetry:Yh*5},Lb=r=>r;function ou(r,t){let e=r.getPeerId();return e!=null&&ce(e).equals(t)&&(r=r.decapsulate(q(`/p2p/${t.toString()}`))),r}var Ti=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 Ci(t,e),this.dnsMappings=new _i(t,e),this.ipMappings=new Si(t,e),this.transportAddresses=new Ii(t,e),this.announceFilter=e.announceFilter??Lb,this.observedAddressFilter=go(1024),this.addressVerificationTTL=e.addressVerificationTTL??Jh.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??Jh.addressVerificationRetry,this._updatePeerStoreAddresses=_o(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=>q(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>q(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>q(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=ou(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=ou(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=ou(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=q(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(q(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${Kt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(q(`/ip${Kt(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"||Ue(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>mr.exactMatch(s)||To.exactMatch(s),s=>Io.exactMatch(s),s=>$h.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 tp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(tp||(tp={}));var Pi=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Di=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},pn=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},Do=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Li=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Ri=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},ki=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},Lo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Oi=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Mi=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},Ni=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Bi=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Fi=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},yr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},br=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},Ui=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}},Ki=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}};var su=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=Ks())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>Zo(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")}},kb=["metrics","connectionProtector","dns"],Ob=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function ep(r={}){let t=new su(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!Ob.includes(o)){let i=t.components[o];if(i==null&&!kb.includes(o))throw new Pi(`${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 rp(r){let t={};for(let e of Object.values(r.components))for(let n of Mb(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of Nb(e))if(t[n]!==!0)throw new Di(`Service "${Bb(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Mb(r){return Array.isArray(r?.[En])?r[En]:[]}function Nb(r){return Array.isArray(r?.[Pa])?r[Pa]:[]}function Bb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Fb=4,Ub=41;function np(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(mr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===Fb||e[0][0]===Ub?!!Ue(`${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 op=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Kb=new WeakMap;function qb({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(op());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(op())},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}),Kb.set(f,()=>{c(s),s=null,i()}),f}}var zb=qb(),sp=zb;var qi=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}},zi=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Vi=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 iu}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 qi("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 sp(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)}},iu=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 Hi(r){if(Ie(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:ce(n),t.forEach(o=>{if(!Fe(o))throw new Te("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(e!=null)throw new O("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ce(s);if(e?.equals(i)!==!0)throw new O("Multiaddrs must all have the same peer id or have no peer id")}})}return t=t.filter(n=>!zh.exactMatch(n)),{peerId:e,multiaddrs:t}}var Vb=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function ip(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Vb;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}function Ro(r){try{let t;typeof r=="string"?t=q(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 El(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var $i=class{connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.allow=(e.allow??[]).map(n=>Ro(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 Vt;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 ip(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 ap="last-dial-failure",cp="last-dial-success";var lp=100,Wi=50;var Gi=class{deferred;signal;constructor(t){this.signal=t,this.deferred=nt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new $t)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Hb(){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=Hb(),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 $t),this.cleanup())}async join(t={}){let e=new Gi(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 pt(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 mn=class extends Nt{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=_o(this.emitEmpty.bind(this),1),this.emitIdle=_o(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 zi;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 $t)}),this.clear()}async onEmpty(t){this.size!==0&&await ue(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await ue(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ue(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=$s({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 $t("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 Zi=class extends mn{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Ce(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 up(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function au(r){if(!Ai(r))return!1;let{address:t}=r.nodeAddress();return up(t)}function $b(r,t){let e=Io.exactMatch(r.multiaddr),n=Io.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=To.exactMatch(r.multiaddr),s=To.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=mr.exactMatch(r.multiaddr),a=mr.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Ql.exactMatch(r.multiaddr),u=Ql.exactMatch(t.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let l=Zl.exactMatch(r.multiaddr),f=Zl.exactMatch(t.multiaddr);if(l&&!f)return-1;if(!l&&f)return 1;let d=Xl.exactMatch(r.multiaddr),h=Xl.exactMatch(t.multiaddr);return d&&!h?-1:!d&&h?1:0}function Wb(r,t){let e=au(r.multiaddr),n=au(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Gb(r,t){let e=gr(r.multiaddr),n=gr(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function jb(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function Zb(r,t){let e=Po.exactMatch(r.multiaddr),n=Po.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function fp(r){return r.sort($b).sort(jb).sort(Zb).sort(Gb).sort(Wb)}async function cu(r,t,e){let n=e.depth??0;if(n>(e.maxRecursiveDepth??32))throw new Ki("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 cu(c,t,{...e,depth:n+1}))}return o===!1&&s.push(r),s}var ko={maxParallelDials:Wi,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:ve}},Xi=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??ko.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??ko.maxDialQueueLength,this.dialTimeout=e.dialTimeout??ko.dialTimeout,this.connections=e.connections??new Vt,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.resolvers=e.resolvers??ko.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Zi({concurrency:e.maxParallelDials??ko.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail?.name!==$t.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}=Hi(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!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 it("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 it("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Tr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new it("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new it("dial-queue:start-dial"));let c=Ce([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??du,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 it("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 Tr("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:{[cp]: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:{[ap]: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 Wo(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:q(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Tr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new Lo("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 cu(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 Ni("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?fp(u):u.sort(this.addressSorter);if(l.length===0)throw new Lo("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=>!Po.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Qi=class extends mn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var bp=Ko(gp(),1);var Qb=Object.prototype.toString,Yb=r=>Qb.call(r)==="[object Error]",Jb=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&&Yb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Jb.has(r.message):!1}var pu=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}},yp=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function mu(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=bp.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 pu)throw c.originalError;if(c instanceof TypeError&&!hu(c))throw c;if(yp(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){yp(u,a,t),i(),n(u)}}})})}var Yi=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 Qi({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);wp(e)&&(this.queue.has(t)||this.queue.add(async n=>{await mu(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(Ta)&&(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=>wp(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 wp(r){for(let t of r.tags.keys())if(t.startsWith(Ta))return!0;return!1}var du=50,gu={maxConnections:lp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ji=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??gu.maxConnections,this.maxConnections<1)throw new O("Connection Manager maxConnections must be greater than 0");this.connections=new Vt,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=>Ro(n)),this.deny=(e.deny??[]).map(n=>Ro(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??gu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Vi({points:e.inboundConnectionThreshold??gu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new $i({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{allow:e.allow?.map(n=>q(n))}),this.dialQueue=new Xi(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??Wi,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:ve},connections:this.connections}),this.reconnectQueue=new Yi({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 Iu(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 Tu(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 O("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 fe("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=Hi(t);if(this.peerId.equals(n))throw new Ir("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 it("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??du});if(o.status!=="open")throw new Cr("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 Te("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=>q(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var gn=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 rw=1.2,nw=2,ow=5e3,sw=6e4,iw=5e3,ta=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(t={}){let e=t.interval??iw;this.success=new gn(e),this.failure=new gn(e),this.next=new gn(e),this.failureMultiplier=t.failureMultiplier??nw,this.timeoutMultiplier=t.timeoutMultiplier??rw,this.minTimeout=t.minTimeout??ow,this.maxTimeout=t.maxTimeout??sw,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=Ce([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 yu=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=nt(),this.haveNext=nt()}[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=nt(),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=nt(),await pt(this.readNext.promise,e?.signal,e)}};function ea(){return new yu}var ra=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function na(r,t){let e=ea();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 pt(n.next(),i?.signal);return c===!0?null:u}for(;o.byteLength<i.bytes;){let{value:c,done:u}=await pt(n.next(),i?.signal);if(u===!0)throw new ra("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 aw=1e4,cw="1.0.0",lw="ping",uw="ipfs",xp=32,fw=!0,oa=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??uw}/${lw}/${cw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??aw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??fw,this.timeout=new ta({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[En]=["@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=na(o);e=Date.now(),await Promise.all([s.write(Zr(xp),{signal:n}),s.read({bytes:xp,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 dw(r){return r[Symbol.asyncIterator]!=null}async function hw(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*pw(r){let t=new AbortController,e=ea();hw(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*mw(r){for(let t of r)yield*t}function gw(...r){let t=[];for(let e of r)dw(e)||t.push(e);return t.length===r.length?mw(t):pw(r)}var Oo=gw;var sa=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:M(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:M(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 pn("No content routers available");let n=this,o=new ar;for await(let s of Oo(...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 pn("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 pn("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 fe;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 fe;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(t,e)))}};var ia=globalThis.CustomEvent??Event;async function*bu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=nt(),a=nt(),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=nt(),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 ia("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new ia("task-complete"))})}c=!0,o.dispatchEvent(new ia("task-complete"))}catch(p){u=p,o.dispatchEvent(new ia("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=nt(),await a.promise),u!=null||(n?yield*d():yield*h(),u!=null))throw u;if(c&&s.length===0)break}}var aa=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:M(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 Do("No peer routers available");if(t.toString()===this.peerId.toString())throw new Li("Should not try to find self");let n=this,o=Oo(...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 Ve}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new Do("No peer routers available");let n=this,o=go(1024);for await(let s of bu(async function*(){let i=Oo(...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 ca=class extends Nt{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=Ce([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=nt(),yield(await ue(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=Ce([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=Zr(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 pt(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 wu=32,xu=64,la=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=_t({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 Ri(`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 ki(`Handler already registered for protocol ${t}`);let o=Ss.bind({ignoreUndefined:!0})({maxInboundStreams:wu,maxOutboundStreams:xu},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 O("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 ua=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=_t({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=_t({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??ze.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new O("Transport must have a valid tag");if(this.transports.has(e))throw new O(`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 Ui(`No transport available for address ${String(t)}`);return e?.onProgress?.(new it("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 fe("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 Oi)});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})}),$l.matches(c)?e.ipv4.attempts++:Wl.matches(c)&&e.ipv6.attempts++,n.push(u.listen(c).then(()=>{e.errors.delete(c.toString()),$l.matches(c)&&e.ipv4.success++,Wl.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===ze.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Mi(`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
3
  ${[...e.errors.entries()].map(([s,i])=>`
4
4
  ${s}: ${`${i.stack??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 mt="/multistream/1.0.0";var fa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},da=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ha=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Mo(r,t={}){let e=na(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ut(t.maxDataLength));let n=t?.lengthDecoder??Ye,o=t?.lengthEncoder??ie;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 fa("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new ha("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new da("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 Sw=D(`
8
- `);async function xr(r,t,e){await r.write(t,e)}async function _p(r,t,e){await r.writeV(t,e)}async function Aw(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==Sw[0])throw t.log.error("Invalid mss message - missing newline",e),new $o("Missing newline");return e.sublist(0,-1)}async function Ue(r,t){let e=await Aw(r,t);return M(e.subarray())}async function No(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return Cw(r,t[0],e);let n=Mo(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"]',mt,o);let s=D(`${mt}
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 mt="/multistream/1.0.0";var fa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},da=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ha=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Mo(r,t={}){let e=na(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ut(t.maxDataLength));let n=t?.lengthDecoder??Je,o=t?.lengthEncoder??ie;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 fa("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new ha("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new da("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 bw=D(`
8
+ `);async function xr(r,t,e){await r.write(t,e)}async function Ep(r,t,e){await r.writeV(t,e)}async function ww(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==bw[0])throw t.log.error("Invalid mss message - missing newline",e),new $o("Missing newline");return e.sublist(0,-1)}async function Ke(r,t){let e=await ww(r,t);return M(e.subarray())}async function No(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return xw(r,t[0],e);let n=Mo(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"]',mt,o);let s=D(`${mt}
9
9
  `),i=D(`${o}
10
- `);await _p(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await Ue(n,e);if(e.log.trace('select: read "%s"',a),a===mt&&(e.log.trace("select: reading protocol response"),a=await Ue(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 xr(n,D(`${c}
11
- `),e),e.log.trace("select: reading protocol response");let u=await Ue(n,e);if(e.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new En("protocol selection failed")}function Cw(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=nt(),c=!1,u=!1,l=nt(),f=!1,d=!1,h=nt(),p=Mo({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',mt,t,b.byteLength);let L=`${t}
10
+ `);await Ep(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await Ke(n,e);if(e.log.trace('select: read "%s"',a),a===mt&&(e.log.trace("select: reading protocol response"),a=await Ke(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 xr(n,D(`${c}
11
+ `),e),e.log.trace("select: reading protocol response");let u=await Ke(n,e);if(e.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new xn("protocol selection failed")}function xw(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=nt(),c=!1,u=!1,l=nt(),f=!1,d=!1,h=nt(),p=Mo({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',mt,t,b.byteLength);let L=`${t}
12
12
  `;yield new z(Uint8Array.from([19]),D(`${mt}
13
13
  `),ie(L.length),D(L),b).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',mt,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',mt,t),await p.writeV([D(`${mt}
14
14
  `),D(`${t}
15
- `)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',mt,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 Ue(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',E),E===mt&&(E=await Ue(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',E,t),E!==t)throw new En("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 pt(Promise.all(C),_?.signal):(s=!0,i=!1,a.resolve()),await E(_)}}return{stream:r,protocol:t}}var pa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ma=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Bo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ga(r){return r[Symbol.asyncIterator]!=null}function Ap(r,t){if(r.byteLength>t)throw new bn("Message length too long")}var ba=r=>{let t=ut(r),e=yt(t);return ie(r,e),ba.bytes=t,e};ba.bytes=0;function wa(r,t){t=t??{};let e=t.lengthEncoder??ba,n=t?.maxDataLength??4194304;function*o(s){Ap(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return ga(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}wa.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??ba,n=t?.maxDataLength??4194304;return Ap(r,n),new z(e(r.byteLength),r)};var Er;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Er||(Er={}));var Su=r=>{let t=Ye(r);return Su.bytes=ut(t),t};Su.bytes=0;function _u(r,t){let e=new z,n=Er.LENGTH,o=-1,s=t?.lengthDecoder??Su,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Er.LENGTH)try{if(o=s(e),o<0)throw new pa("Invalid message length");if(o>a)throw new bn("Message length too long");let u=s.bytes;e.consume(u),t?.onLength!=null&&t.onLength(o),n=Er.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new ma("Message length length too long");break}throw u}if(n===Er.DATA){if(e.byteLength<o)break;let u=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(u),yield u,n=Er.LENGTH}}}return ga(r)?async function*(){for await(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Bo("Unexpected end of input")}():function*(){for(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Bo("Unexpected end of input")}()}_u.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 _u(n,{...t??{},onLength:s=>{e=s}})};async function Fo(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=Mo(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await Ue(n,e);if(e.log.trace('handle: read "%s"',o),o===mt){e.log.trace('handle: respond with "%s" for "%s"',mt,o),await xr(n,D(`${mt}
15
+ `)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',mt,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 Ke(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',E),E===mt&&(E=await Ke(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',E,t),E!==t)throw new xn("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 pt(Promise.all(C),_?.signal):(s=!0,i=!1,a.resolve()),await E(_)}}return{stream:r,protocol:t}}var pa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},yn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ma=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Bo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ga(r){return r[Symbol.asyncIterator]!=null}function _p(r,t){if(r.byteLength>t)throw new yn("Message length too long")}var ba=r=>{let t=ut(r),e=yt(t);return ie(r,e),ba.bytes=t,e};ba.bytes=0;function wa(r,t){t=t??{};let e=t.lengthEncoder??ba,n=t?.maxDataLength??4194304;function*o(s){_p(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return ga(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}wa.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??ba,n=t?.maxDataLength??4194304;return _p(r,n),new z(e(r.byteLength),r)};var Er;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Er||(Er={}));var _u=r=>{let t=Je(r);return _u.bytes=ut(t),t};_u.bytes=0;function vu(r,t){let e=new z,n=Er.LENGTH,o=-1,s=t?.lengthDecoder??_u,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Er.LENGTH)try{if(o=s(e),o<0)throw new pa("Invalid message length");if(o>a)throw new yn("Message length too long");let u=s.bytes;e.consume(u),t?.onLength!=null&&t.onLength(o),n=Er.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new ma("Message length length too long");break}throw u}if(n===Er.DATA){if(e.byteLength<o)break;let u=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(u),yield u,n=Er.LENGTH}}}return ga(r)?async function*(){for await(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Bo("Unexpected end of input")}():function*(){for(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new Bo("Unexpected end of input")}()}vu.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 vu(n,{...t??{},onLength:s=>{e=s}})};async function Fo(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=Mo(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await Ke(n,e);if(e.log.trace('handle: read "%s"',o),o===mt){e.log.trace('handle: respond with "%s" for "%s"',mt,o),await xr(n,D(`${mt}
16
16
  `),e),e.log.trace('handle: responded with "%s" for "%s"',mt,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await xr(n,D(`${o}
17
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=>wa.single(D(`${i}
18
18
  `))),D(`
19
19
  `));e.log.trace('handle: respond with "%s" for %s',t,o),await xr(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 xr(n,D(`na
20
- `),e),e.log('handle: responded with "na" for "%s"',o)}}var Pw=500,Au=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";[Iu]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new zo("the connection is being closed");if(this.status==="closed")throw new Cr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Pr("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(Pw);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 Cp(r){return new Au(r)}function Lw(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return xu}function Rw(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??Eu}function Ip(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var xa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=_t({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=_t({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 Bi(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Ae([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 pt(this.components.connectionManager.acceptIncomingConnection(t),o),!n)throw new Fi("Connection denied");await pt(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=ce(n),await pt(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 it(`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 Ie(`${e} connection that skipped encryption must have a peer id`);let f=ce(l);c="native",s=f}if(s.equals(this.components.peerId)){let l=new Ir("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 it(`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 Fo(p,m,{signal:g,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",E);let _=Lw(E,this.components.registrar);if(Ip(E,"inbound",f)===_){let b=new Go(`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 yr("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 No(m,p,{...g,log:m.log,yieldBytes:!0});m.log.trace("selected protocol %s",E);let _=Rw(E,this.components.registrar,g),C=Ip(E,"outbound",f);if(C>=_){let b=new jo(`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 yr("Connection is not multiplexed")};return f=Cp({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 Pr("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 Fo(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new br(`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 br(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 No(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new br(`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 br(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 No(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 yr(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 Fo(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 yr(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var Ea="2.8.11",va="js-libp2p";function Pp(r,t){return`${r??va}/${t??Ea} browser/${globalThis.navigator.userAgent}`}var _a=class extends Nt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new Nt,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??Ks(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??va,s=t.nodeInfo?.version??Ea,i=this.components=rp({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??Pp(o,s)},logger:this.logger,events:e,datastore:t.datastore??new yi,connectionGater:op(t.connectionGater),dns:t.dns});t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Uh(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 xa(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 ua(this.components,t.transportManager)),this.configureComponent("connectionManager",new Ji(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new oa(this.components,t.connectionMonitor)),this.configureComponent("registrar",new la(this.components)),this.configureComponent("addressManager",new Ti(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 aa(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 sa(this.components,{routers:c})),this.configureComponent("randomWalk",new ca(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[Aa]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Aa])),f[Ia]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[Ia])),f[Ca]!=null&&(this.log("registering service %s for peer discovery",u),f[Ca].addEventListener?.("peer",d=>{this.#t(d)}))}np(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 ar;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 O("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new O("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={}){Be(t)&&(t=ce(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=jt([D("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=Qr(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 kw(r={}){r.privateKey??=await Dd("Ed25519");let t=new _a({...await hh(r),peerId:Od(r.privateKey)});return r.start!==!1&&await t.start(),t}return Mp(Ow);})();
20
+ `),e),e.log('handle: responded with "na" for "%s"',o)}}var _w=500,Su=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";[Cu]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new zo("the connection is being closed");if(this.status==="closed")throw new Cr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Pr("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(_w);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 Sp(r){return new Su(r)}function Aw(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return wu}function Cw(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??xu}function Ap(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var xa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=_t({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=_t({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 Bi(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Ce([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 pt(this.components.connectionManager.acceptIncomingConnection(t),o),!n)throw new Fi("Connection denied");await pt(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=ce(n),await pt(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 it(`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 Te(`${e} connection that skipped encryption must have a peer id`);let f=ce(l);c="native",s=f}if(s.equals(this.components.peerId)){let l=new Ir("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 it(`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 Fo(p,m,{signal:g,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",E);let _=Aw(E,this.components.registrar);if(Ap(E,"inbound",f)===_){let b=new Go(`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 yr("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 No(m,p,{...g,log:m.log,yieldBytes:!0});m.log.trace("selected protocol %s",E);let _=Cw(E,this.components.registrar,g),C=Ap(E,"outbound",f);if(C>=_){let b=new jo(`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 yr("Connection is not multiplexed")};return f=Sp({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 Pr("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 Fo(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new br(`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 br(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 No(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new br(`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 br(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 No(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 yr(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 Fo(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 yr(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var Ea="2.8.12",va="js-libp2p";function Ip(r,t){return`${r??va}/${t??Ea} browser/${globalThis.navigator.userAgent}`}var _a=class extends Nt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new Nt,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??Ks(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??va,s=t.nodeInfo?.version??Ea,i=this.components=ep({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??Ip(o,s)},logger:this.logger,events:e,datastore:t.datastore??new yi,connectionGater:np(t.connectionGater),dns:t.dns});t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Fh(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 xa(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 ua(this.components,t.transportManager)),this.configureComponent("connectionManager",new Ji(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new oa(this.components,t.connectionMonitor)),this.configureComponent("registrar",new la(this.components)),this.configureComponent("addressManager",new Ti(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 aa(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 sa(this.components,{routers:c})),this.configureComponent("randomWalk",new ca(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[Aa]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Aa])),f[Ia]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[Ia])),f[Ca]!=null&&(this.log("registering service %s for peer discovery",u),f[Ca].addEventListener?.("peer",d=>{this.#t(d)}))}rp(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 ar;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 O("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new O("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={}){Fe(t)&&(t=ce(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=jt([D("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=Qr(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 Iw(r={}){r.privateKey??=await Pd("Ed25519");let t=new _a({...await dh(r),peerId:kd(r.privateKey)});return r.start!==!1&&await t.start(),t}return kp(Tw);})();
21
21
  /*! Bundled license information:
22
22
 
23
23
  @noble/hashes/esm/utils.js: