libp2p 3.3.3-a34745c01 → 3.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,29 +1,29 @@
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 xb=Object.create;var Ws=Object.defineProperty;var Eb=Object.getOwnPropertyDescriptor;var vb=Object.getOwnPropertyNames;var Sb=Object.getPrototypeOf,Ab=Object.prototype.hasOwnProperty;var go=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),U=(r,e)=>{for(var t in e)Ws(r,t,{get:e[t],enumerable:!0})},Wh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vb(e))!Ab.call(r,o)&&o!==t&&Ws(r,o,{get:()=>e[o],enumerable:!(n=Eb(e,o))||n.enumerable});return r};var Vc=(r,e,t)=>(t=r!=null?xb(Sb(r)):{},Wh(e||!r||!r.__esModule?Ws(t,"default",{value:r,enumerable:!0}):t,r)),_b=r=>Wh(Ws({},"__esModule",{value:!0}),r);var gf=go(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.Netmask4Impl=void 0;kn.ip2long=Pn;kn.long2ip=Et;function Et(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var qv=48,$v=97,Vv=65;function Hv(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-qv)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-$v)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-Vv)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function Pn(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=Hv(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var mf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=Pn(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(Pn(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Et(this.netLong),this.mask=Et(this.maskLong),this.hostmask=Et(~this.maskLong),this.first=this.bitmask<=30?Et(this.netLong+1):this.base,this.last=this.bitmask<=30?Et(this.netLong+this.size-2):Et(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Et(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(Pn(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(Et(this.netLong+this.size*e),this.mask)}forEach(e){let t=Pn(this.first),n=Pn(this.last),o=0;for(;t<=n;)e(Et(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};kn.Netmask4Impl=mf});var Wg=go(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.Netmask6Impl=void 0;Rn.ip6bigint=bf;Rn.bigint2ip6=Fr;var jv=gf(),yf=(1n<<128n)-1n;function bf(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,jv.ip2long)(n),s=r.substring(0,t+1)+"0:0";return Gg(s)&~0xffffffffn|BigInt(o)}return Gg(r)}function Gg(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function Fr(r){if(r<0n||r>yf)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var wf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=yf>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=bf(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Fr(this.netBigint),this.mask=Fr(this.maskBigint),this.hostmask=Fr(~this.maskBigint&yf),this.first=this.base,this.last=Fr(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(bf(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(Fr(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(Fr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};Rn.Netmask6Impl=wf});var Xg=go(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.long2ip=ur.ip2long=ur.Netmask=void 0;var Yi=gf();Object.defineProperty(ur,"ip2long",{enumerable:!0,get:function(){return Yi.ip2long}});Object.defineProperty(ur,"long2ip",{enumerable:!0,get:function(){return Yi.long2ip}});var Gv=Wg(),xf=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new Gv.Netmask6Impl(e,t):this._impl=new Yi.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof Yi.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};ur.Netmask=xf});var Ry=go((qN,th)=>{"use strict";var WS=Object.prototype.hasOwnProperty,Ke="~";function Bs(){}Object.create&&(Bs.prototype=Object.create(null),new Bs().__proto__||(Ke=!1));function XS(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function ky(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new XS(t,n||r,o),i=Ke?Ke+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Sc(r,e){--r._eventsCount===0?r._events=new Bs:delete r._events[e]}function ke(){this._events=new Bs,this._eventsCount=0}ke.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)WS.call(t,n)&&e.push(Ke?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};ke.prototype.listeners=function(e){var t=Ke?Ke+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};ke.prototype.listenerCount=function(e){var t=Ke?Ke+e:e,n=this._events[t];return n?n.fn?1:n.length:0};ke.prototype.emit=function(e,t,n,o,s,i){var a=Ke?Ke+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(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(e,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,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,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};ke.prototype.on=function(e,t,n){return ky(this,e,t,n,!1)};ke.prototype.once=function(e,t,n){return ky(this,e,t,n,!0)};ke.prototype.removeListener=function(e,t,n,o){var s=Ke?Ke+e:e;if(!this._events[s])return this;if(!t)return Sc(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Sc(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Sc(this,s)}return this};ke.prototype.removeAllListeners=function(e){var t;return e?(t=Ke?Ke+e:e,this._events[t]&&Sc(this,t)):(this._events=new Bs,this._eventsCount=0),this};ke.prototype.off=ke.prototype.removeListener;ke.prototype.addListener=ke.prototype.on;ke.prefixed=Ke;ke.EventEmitter=ke;typeof th<"u"&&(th.exports=ke)});var ab=go((nF,ib)=>{ib.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var P_={};U(P_,{createLibp2p:()=>T_,dnsaddrResolver:()=>Xr,isLibp2p:()=>D_});var Xh=Symbol.for("@libp2p/connection");var Hc=Symbol.for("@libp2p/content-routing");var tt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var R=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Zr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},yo=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var mr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var gr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Qr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},jt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Xs=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Ys=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Zs=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Qs=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Js=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Ct=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Jr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var bo=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},ei=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},ti=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Gt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var ri=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var jc=Symbol.for("@libp2p/peer-discovery");var ni=Symbol.for("@libp2p/peer-id");function Wt(r){return!!r?.[ni]}var Gc=Symbol.for("@libp2p/peer-routing");var Wc="keep-alive";function oi(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Yh(...r){let e=[];for(let t of r)oi(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Zh(...r){let e=[];for(let t of r)oi(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var wo;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(wo||(wo={}));function Cb(r){return typeof r?.handleEvent=="function"}function Ib(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Re=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Ib(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}Cb(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var xo=Symbol.for("@libp2p/service-capabilities"),Xc=Symbol.for("@libp2p/service-dependencies");var eu={};U(eu,{base58btc:()=>re,base58flickr:()=>Nb});var mC=new Uint8Array(0);function Qh(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function It(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return yr(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return yr(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Jh(r){return new TextEncoder().encode(r)}function ep(r){return new TextDecoder().decode(r)}function Tb(r){return r?.buffer instanceof ArrayBuffer}function yr(r){return Tb(r)?r:r.slice()}function Lb(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),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,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var x=(w-y)*l+1>>>0,_=new Uint8Array(x);y!==w;){for(var A=p[y],D=0,I=x-1;(A!==0||D<m)&&I!==-1;I--,D++)A+=256*_[I]>>>0,_[I]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=D,y++}for(var v=x-m;v!==x&&_[v]===0;)v++;for(var O=c.repeat(g);v<x;++v)O+=r.charAt(_[v]);return O}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,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,x=new Uint8Array(w);p[g];){var _=t[p.charCodeAt(g)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<y)&&D!==-1;D--,A++)_+=a*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}if(p[g]!==" "){for(var I=w-y;I!==w&&x[I]===0;)I++;for(var v=new Uint8Array(m+(w-I)),O=m;I!==w;)v[O++]=x[I++];return v}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Db=Lb,Pb=Db,rp=Pb;var Yc=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Zc=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return np(this,e)}},Qc=class{decoders;constructor(e){this.decoders=e}or(e){return np(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function np(r,e){return new Qc({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Jc=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Yc(e,t,n),this.decoder=new Zc(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function en({name:r,prefix:e,encode:t,decode:n}){return new Jc(r,e,t,n)}function Xt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=rp(t,r);return en({prefix:e,name:r,encode:n,decode:s=>It(o(s))})}function kb(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Rb(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Ob(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Ob(n);return en({prefix:e,name:r,encode(s){return Rb(s,n,t)},decode(s){return kb(s,o,t,r)}})}var re=Xt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nb=Xt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var tu={};U(tu,{base32:()=>Ze,base32hex:()=>Ub,base32hexpad:()=>zb,base32hexpadupper:()=>qb,base32hexupper:()=>Kb,base32pad:()=>Fb,base32padupper:()=>Bb,base32upper:()=>Mb,base32z:()=>$b});var Ze=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Mb=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Fb=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Bb=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ub=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kb=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zb=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),qb=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$b=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ru={};U(ru,{base36:()=>Eo,base36upper:()=>Vb});var Eo=Xt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Vb=Xt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Hb=ip,op=128,jb=127,Gb=~jb,Wb=Math.pow(2,31);function ip(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Wb;)e[t++]=r&255|op,r/=128;for(;r&Gb;)e[t++]=r&255|op,r>>>=7;return e[t]=r|0,ip.bytes=t-n+1,e}var Xb=nu,Yb=128,sp=127;function nu(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw nu.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&sp)<<o:(i&sp)*Math.pow(2,o),o+=7}while(i>=Yb);return nu.bytes=s-n,t}var Zb=Math.pow(2,7),Qb=Math.pow(2,14),Jb=Math.pow(2,21),ew=Math.pow(2,28),tw=Math.pow(2,35),rw=Math.pow(2,42),nw=Math.pow(2,49),ow=Math.pow(2,56),sw=Math.pow(2,63),iw=function(r){return r<Zb?1:r<Qb?2:r<Jb?3:r<ew?4:r<tw?5:r<rw?6:r<nw?7:r<ow?8:r<sw?9:10},aw={encode:Hb,decode:Xb,encodingLength:iw},cw=aw,vo=cw;function So(r,e=0){return[vo.decode(r,e),vo.decode.bytes]}function tn(r,e,t=0){return vo.encode(r,e,t),e}function rn(r){return vo.encodingLength(r)}function pt(r,e){let t=e.byteLength,n=rn(r),o=n+rn(t),s=new Uint8Array(o+t);return tn(r,s,0),tn(t,s,n),s.set(e,o),new nn(r,t,e,s)}function Tt(r){let e=It(r),[t,n]=So(e),[o,s]=So(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new nn(t,o,i,e)}function ap(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Qh(r.bytes,t.bytes)}}var nn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=yr(n),this.bytes=yr(o)}};function cp(r,e){let{bytes:t,version:n}=r;return n===0?lw(t,ou(r),e??re.encoder):fw(t,ou(r),e??Ze.encoder)}var up=new WeakMap;function ou(r){let e=up.get(r);if(e==null){let t=new Map;return up.set(r,t),t}return e}var pe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=yr(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ao)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==dw)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=pt(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&ap(e.multihash,n.multihash)}toString(e){return cp(this,e)}toJSON(){return{"/":cp(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??lp(n,o,s.bytes))}else if(t[hw]===!0){let{version:n,multihash:o,code:s}=t,i=Tt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ao)throw new Error(`Version 0 CID must use dag-pb (code: ${Ao}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=lp(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ao,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=It(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new nn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=So(e.subarray(t));return t+=d,f},o=n(),s=Ao;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=uw(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ou(s).set(n,e),s}};function uw(r,e){switch(r[0]){case"Q":{let t=e??re;return[re.prefix,t.decode(`${re.prefix}${r}`)]}case re.prefix:{let t=e??re;return[re.prefix,t.decode(r)]}case Ze.prefix:{let t=e??Ze;return[Ze.prefix,t.decode(r)]}case Eo.prefix:{let t=e??Eo;return[Eo.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function lw(r,e,t){let{prefix:n}=t;if(n!==re.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function fw(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Ao=112,dw=18;function lp(r,e,t){let n=rn(r),o=n+rn(e),s=new Uint8Array(o+t.byteLength);return tn(r,s,0),tn(e,s,n),s.set(t,o),s}var hw=Symbol.for("@ipld/js-cid/CID");var su={};U(su,{identity:()=>rt});var fp=0,pw="identity",dp=It;function mw(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return pt(fp,dp(r))}var rt={code:fp,name:pw,encode:dp,digest:mw};function J(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function gw(r){return r.buffer instanceof ArrayBuffer}function Oe(r){return gw(r)?r:r.slice()}async function hp(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function pp(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,Oe(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function mp(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Oe(e),Oe(t.subarray()));return n?.signal?.throwIfAborted(),s}function Lt(r=0){return new Uint8Array(r)}function _o(r=0){return new Uint8Array(r)}function iu(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=_o(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function gp(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var bp=Symbol.for("@achingbrain/uint8arraylist");function yp(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function ii(r){return!!r?.[bp]}var ee=class r{bufs;length;[bp]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ii(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ii(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=yp(this.bufs,e);return t.buf[t.index]}set(e,t){let n=yp(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ii(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return iu(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:iu(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ii(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let 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=t;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(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=_o(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=Lt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=Lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=Lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=_o(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=Lt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=Lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=Lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=Lt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=Lt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!gp(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var au={};U(au,{base10:()=>yw});var yw=Xt({prefix:"9",name:"base10",alphabet:"0123456789"});var cu={};U(cu,{base16:()=>bw,base16upper:()=>ww});var bw=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ww=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var uu={};U(uu,{base2:()=>xw});var xw=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var lu={};U(lu,{base256emoji:()=>_w});var wp=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}"),Ew=wp.reduce((r,e,t)=>(r[t]=e,r),[]),vw=wp.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Sw(r){return r.reduce((e,t)=>(e+=Ew[t],e),"")}function Aw(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=vw[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var _w=en({prefix:"\u{1F680}",name:"base256emoji",encode:Sw,decode:Aw});var hu={};U(hu,{base64:()=>fu,base64pad:()=>Cw,base64url:()=>du,base64urlpad:()=>Iw});var fu=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Cw=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),du=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Iw=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var pu={};U(pu,{base8:()=>Tw});var Tw=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var mu={};U(mu,{identity:()=>Lw});var Lw=en({prefix:"\0",name:"identity",encode:r=>ep(r),decode:r=>Jh(r)});var r6=new TextEncoder,n6=new TextDecoder;var bu={};U(bu,{sha256:()=>on,sha512:()=>Rw});var kw=20;function yu({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new gu(r,e,t,n,o)}var gu=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??kw,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?xp(n,this.code,t?.truncate):n.then(o=>xp(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function xp(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return pt(e,r)}function vp(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var on=yu({name:"sha2-256",code:18,encode:vp("SHA-256")}),Rw=yu({name:"sha2-512",code:19,encode:vp("SHA-512")});var Co={...mu,...uu,...pu,...au,...cu,...tu,...ru,...eu,...hu,...lu},m6={...bu,...su};function qe(r=0){return new Uint8Array(r)}function br(r=0){return new Uint8Array(r)}function Ap(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Sp=Ap("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),wu=Ap("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=br(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Ow={utf8:Sp,"utf-8":Sp,hex:Co.base16,latin1:wu,ascii:wu,binary:wu,...Co},ai=Ow;function M(r,e="utf8"){let t=ai[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function z(r,e="utf8"){let t=ai[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Nw=parseInt("11111",2),xu=parseInt("10000000",2),Mw=parseInt("01111111",2),_p={0:Io,1:Io,2:Fw,3:Kw,4:zw,5:Uw,6:Bw,16:Io,22:Io,48:Io};function Dt(r,e={offset:0}){let t=r[e.offset]&Nw;if(e.offset++,_p[t]!=null)return _p[t](r,e);throw new Error("No decoder for tag "+t)}function To(r,e){let t=0;if((r[e.offset]&xu)===xu){let n=r[e.offset]&Mw,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Io(r,e){To(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Dt(r,e);if(n===null)break;t.push(n)}return t}function Fw(r,e){let t=To(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function Bw(r,e){let t=To(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let u=r[e.offset];if(e.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 Uw(r,e){return e.offset++,null}function Kw(r,e){let t=To(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function zw(r,e){let t=To(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function qw(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ee;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function ci(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=qw(r.byteLength);return new ee(Uint8Array.from([e.byteLength|xu]),e)}function Ne(r){let e=new ee,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ee(Uint8Array.from([2]),ci(e),e)}function Lo(r){let e=Uint8Array.from([0]),t=new ee(e,r);return new ee(Uint8Array.from([3]),ci(t),t)}function Cp(r){return new ee(Uint8Array.from([4]),ci(r),r)}function nt(r,e=48){let t=new ee;for(let n of r)t.append(n);return new ee(Uint8Array.from([e]),ci(t),t)}var $w=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Vw=Uint8Array.from([6,5,43,129,4,0,34]),Hw=Uint8Array.from([6,5,43,129,4,0,35]),jw={ext:!0,kty:"EC",crv:"P-256"},Gw={ext:!0,kty:"EC",crv:"P-384"},Ww={ext:!0,kty:"EC",crv:"P-521"},Eu=32,vu=48,Su=66;function Au(r){let e=Dt(r);return Ip(e)}function Ip(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Eu*2+1)return n=z(e.subarray(t,t+Eu),"base64url"),o=z(e.subarray(t+Eu),"base64url"),new wr({...jw,key_ops:["verify"],x:n,y:o});if(e.byteLength===vu*2+1)return n=z(e.subarray(t,t+vu),"base64url"),o=z(e.subarray(t+vu),"base64url"),new wr({...Gw,key_ops:["verify"],x:n,y:o});if(e.byteLength===Su*2+1)return n=z(e.subarray(t,t+Su),"base64url"),o=z(e.subarray(t+Su),"base64url"),new wr({...Ww,key_ops:["verify"],x:n,y:o});throw new R(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Tp(r){return nt([Ne(Uint8Array.from([1])),Cp(M(r.d??"","base64url")),nt([Dp(r.crv)],160),nt([Lo(new ee(Uint8Array.from([4]),M(r.x??"","base64url"),M(r.y??"","base64url")))],161)]).subarray()}function Lp(r){return nt([Ne(Uint8Array.from([1])),nt([Dp(r.crv)],160),nt([Lo(new ee(Uint8Array.from([4]),M(r.x??"","base64url"),M(r.y??"","base64url")))],161)]).subarray()}function Dp(r){if(r==="P-256")return $w;if(r==="P-384")return Vw;if(r==="P-521")return Hw;throw new R(`Invalid curve ${r}`)}async function Pp(r="P-256"){let e=await hp(r);return new ui(e.privateKey)}var wr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Lp(this.jwk)),this._raw}toMultihash(){return rt.digest(Qe(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}async verify(e,t,n){return mp(this.jwk,t,e,n)}},ui=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new wr({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Tp(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}async sign(e,t){return pp(this.jwk,e,t)}};function _u(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Zt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function He(r,e,t=""){let n=_u(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,u=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return r}function li(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Zt(r.outputLen),Zt(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function sn(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function fi(r,e){He(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function kt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function di(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ot(r,e){return r<<32-e|r>>>e}var Rp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Xw=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function hi(r){if(He(r),Rp)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Xw[r[t]];return e}var Pt={_0:48,_9:57,A:65,F:70,a:97,f:102};function kp(r){if(r>=Pt._0&&r<=Pt._9)return r-Pt._0;if(r>=Pt.A&&r<=Pt.F)return r-(Pt.A-10);if(r>=Pt.a&&r<=Pt.f)return r-(Pt.a-10)}function Do(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Rp)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=kp(r.charCodeAt(s)),a=kp(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Cu(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];He(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Iu(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function pi(r=32){Zt(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Tu=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Op(r,e,t){return r&e^~r&t}function Np(r,e,t){return r&e^r&t^e&t}var Po=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=di(this.buffer)}update(e){sn(this),He(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=di(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){sn(this),fi(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,kt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=di(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must 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:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Rt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Se=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var mi=BigInt(4294967295),Mp=BigInt(32);function Yw(r,e=!1){return e?{h:Number(r&mi),l:Number(r>>Mp&mi)}:{h:Number(r>>Mp&mi)|0,l:Number(r&mi)|0}}function Fp(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=Yw(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Lu=(r,e,t)=>r>>>t,Du=(r,e,t)=>r<<32-t|e>>>t,xr=(r,e,t)=>r>>>t|e<<32-t,Er=(r,e,t)=>r<<32-t|e>>>t,ko=(r,e,t)=>r<<64-t|e>>>t-32,Ro=(r,e,t)=>r>>>t-32|e<<64-t;function mt(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Bp=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Up=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Kp=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),zp=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,qp=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),$p=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Qw=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]),Qt=new Uint32Array(64),Pu=class extends Po{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Qt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Qt[f-15],h=Qt[f-2],p=ot(d,7)^ot(d,18)^d>>>3,g=ot(h,17)^ot(h,19)^h>>>10;Qt[f]=g+Qt[f-7]+p+Qt[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=ot(a,6)^ot(a,11)^ot(a,25),h=l+d+Op(a,c,u)+Qw[f]+Qt[f]|0,g=(ot(n,2)^ot(n,13)^ot(n,22))+Np(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(){kt(Qt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),kt(this.buffer)}},ku=class extends Pu{A=Rt[0]|0;B=Rt[1]|0;C=Rt[2]|0;D=Rt[3]|0;E=Rt[4]|0;F=Rt[5]|0;G=Rt[6]|0;H=Rt[7]|0;constructor(){super(32)}};var Vp=Fp(["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))),Jw=Vp[0],ex=Vp[1],Jt=new Uint32Array(80),er=new Uint32Array(80),Ru=class extends Po{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,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[e,t,n,o,s,i,a,c,u,l,f,d,h,p,g,m]}set(e,t,n,o,s,i,a,c,u,l,f,d,h,p,g,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=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(e,t){for(let x=0;x<16;x++,t+=4)Jt[x]=e.getUint32(t),er[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=Jt[x-15]|0,A=er[x-15]|0,D=xr(_,A,1)^xr(_,A,8)^Lu(_,A,7),I=Er(_,A,1)^Er(_,A,8)^Du(_,A,7),v=Jt[x-2]|0,O=er[x-2]|0,Y=xr(v,O,19)^ko(v,O,61)^Lu(v,O,6),q=Er(v,O,19)^Ro(v,O,61)^Du(v,O,6),b=Kp(I,q,er[x-7],er[x-16]),E=zp(b,D,Y,Jt[x-7],Jt[x-16]);Jt[x]=E|0,er[x]=b|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:y,Hl:w}=this;for(let x=0;x<80;x++){let _=xr(f,d,14)^xr(f,d,18)^ko(f,d,41),A=Er(f,d,14)^Er(f,d,18)^Ro(f,d,41),D=f&h^~f&g,I=d&p^~d&m,v=qp(w,A,I,ex[x],er[x]),O=$p(v,y,_,D,Jw[x],Jt[x]),Y=v|0,q=xr(n,o,28)^ko(n,o,34)^ko(n,o,39),b=Er(n,o,28)^Ro(n,o,34)^Ro(n,o,39),E=n&s^n&a^s&a,T=o&i^o&c^i&c;y=g|0,w=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=mt(u|0,l|0,O|0,Y|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let C=Bp(Y,b,T);n=Up(C,O,q,E),o=C|0}({h:n,l:o}=mt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=mt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=mt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=mt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=mt(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=mt(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=mt(this.Gh|0,this.Gl|0,g|0,m|0),{h:y,l:w}=mt(this.Hh|0,this.Hl|0,y|0,w|0),this.set(n,o,s,i,a,c,u,l,f,d,h,p,g,m,y,w)}roundClean(){kt(Jt,er)}destroy(){this.destroyed=!0,kt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ou=class extends Ru{Ah=Se[0]|0;Al=Se[1]|0;Bh=Se[2]|0;Bl=Se[3]|0;Ch=Se[4]|0;Cl=Se[5]|0;Dh=Se[6]|0;Dl=Se[7]|0;Eh=Se[8]|0;El=Se[9]|0;Fh=Se[10]|0;Fl=Se[11]|0;Gh=Se[12]|0;Gl=Se[13]|0;Hh=Se[14]|0;Hl=Se[15]|0;constructor(){super(64)}};var an=Iu(()=>new ku,Tu(1));var gi=Iu(()=>new Ou,Tu(3));var j=(r,e,t)=>He(r,e,t),Mu=Zt,cn=hi,ye=(...r)=>Cu(...r),un=r=>Do(r),vr=_u,Oo=r=>pi(r),bi=BigInt(0),Nu=BigInt(1);function st(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function wi(r){if(typeof r=="bigint"){if(!yi(r))throw new RangeError("positive bigint expected, got "+r)}else Mu(r);return r}function it(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function No(r){let e=wi(r).toString(16);return e.length&1?"0"+e:e}function Hp(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?bi:BigInt("0x"+r)}function Sr(r){return Hp(hi(r))}function gt(r){return Hp(hi(Mo(He(r)).reverse()))}function xi(r,e){if(Zt(e),e===0)throw new RangeError("zero length");r=wi(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Do(t.padStart(e*2,"0"))}function Fu(r,e){return xi(r,e).reverse()}function jp(r,e){if(r=j(r),e=j(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Mo(r){return Uint8Array.from(j(r))}function Ei(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var yi=r=>typeof r=="bigint"&&bi<=r;function tx(r,e,t){return yi(r)&&yi(e)&&yi(t)&&e<=r&&r<t}function ln(r,e,t,n){if(!tx(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function fn(r){if(r<bi)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>bi;r>>=Nu,e+=1);return e}var Fo=r=>(Nu<<BigInt(r))-Nu;function Gp(r,e,t){if(Zt(r,"hashLen"),Zt(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),l=0,f=()=>{c.fill(1),u.fill(0),l=0},d=(...m)=>t(u,ye(c,...m)),h=(m=o)=>{u=d(s,m),c=d(),m.length!==0&&(u=d(i,m),c=d())},p=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,y=[];for(;m<e;){c=d();let w=c.slice();y.push(w),m+=c.length}return ye(...y)};return(m,y)=>{f(),h(m);let w;for(;(w=y(p()))===void 0;)h();return f(),w}}function at(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var Bu=()=>{throw new Error("not implemented")};var Ae=BigInt(0),ue=BigInt(1),Ar=BigInt(2),Zp=BigInt(3),Qp=BigInt(4),Jp=BigInt(5),rx=BigInt(7),em=BigInt(8),nx=BigInt(9),tm=BigInt(16);function me(r,e){if(e<=Ae)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=Ae?t:e+t}function se(r,e,t){if(e<Ae)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >Ae;)n*=n,n%=t;return n}function Wp(r,e){if(r===Ae)throw new Error("invert: expected non-zero number");if(e<=Ae)throw new Error("invert: expected positive modulus, got "+e);let t=me(r,e),n=e,o=Ae,s=ue,i=ue,a=Ae;for(;t!==Ae;){let u=n/t,l=n-t*u,f=o-i*u,d=s-a*u;n=t,t=l,o=i,s=a,i=f,a=d}if(n!==ue)throw new Error("invert: does not exist");return me(o,e)}function Uu(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function rm(r,e){let t=r,n=(t.ORDER+ue)/Qp,o=t.pow(e,n);return Uu(t,o,e),o}function ox(r,e){let t=r,n=(t.ORDER-Jp)/em,o=t.mul(e,Ar),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,Ar),s),c=t.mul(i,t.sub(a,t.ONE));return Uu(t,c,e),c}function sx(r){let e=dn(r),t=nm(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+rx)/tm;return((a,c)=>{let u=a,l=u.pow(c,i),f=u.mul(l,n),d=u.mul(l,o),h=u.mul(l,s),p=u.eql(u.sqr(f),c),g=u.eql(u.sqr(d),c);l=u.cmov(l,f,p),f=u.cmov(h,d,g);let m=u.eql(u.sqr(f),c),y=u.cmov(l,f,m);return Uu(u,y,c),y})}function nm(r){if(r<Zp)throw new Error("sqrt is not defined for small field");let e=r-ue,t=0;for(;e%Ar===Ae;)e/=Ar,t++;let n=Ar,o=dn(r);for(;Xp(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return rm;let s=o.pow(n,e),i=(e+ue)/Ar;return function(c,u){let l=c;if(l.is0(u))return u;if(Xp(l,u)!==1)throw new Error("Cannot find square root");let f=t,d=l.mul(l.ONE,s),h=l.pow(u,e),p=l.pow(u,i);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let g=1,m=l.sqr(h);for(;!l.eql(m,l.ONE);)if(g++,m=l.sqr(m),g===f)throw new Error("Cannot find square root");let y=ue<<BigInt(f-g-1),w=l.pow(d,y);f=g,d=l.sqr(w),h=l.mul(h,d),p=l.mul(p,w)}return p}}function ix(r){return r%Qp===Zp?rm:r%em===Jp?ox:r%tm===nx?sx(r):nm(r)}var Ot=(r,e)=>(me(r,e)&ue)===ue,ax=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ku(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ax.reduce((n,o)=>(n[o]="function",n),e);if(at(r,t),it(r.BYTES,"BYTES"),it(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=ue)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function cx(r,e,t){let n=r;if(t<Ae)throw new Error("invalid exponent, negatives unsupported");if(t===Ae)return n.ONE;if(t===ue)return e;let o=n.ONE,s=e;for(;t>Ae;)t&ue&&(o=n.mul(o,s)),s=n.sqr(s),t>>=ue;return o}function Bo(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,u)=>n.is0(c)?a:(o[u]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,u)=>n.is0(c)?a:(o[u]=n.mul(a,o[u]),n.mul(a,c)),i),o}function Xp(r,e){let t=r,n=(t.ORDER-ue)/Ar,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function ux(r,e){if(e!==void 0&&Mu(e),r<=Ae)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=fn(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Yp=new WeakMap,vi=class{ORDER;BITS;BYTES;isLE;ZERO=Ae;ONE=ue;_lengths;_mod;constructor(e,t={}){if(e<=ue)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=ux(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return me(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Ae<=e&&e<this.ORDER}is0(e){return e===Ae}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ue)===ue}neg(e){return me(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return me(e*e,this.ORDER)}add(e,t){return me(e+t,this.ORDER)}sub(e,t){return me(e-t,this.ORDER)}mul(e,t){return me(e*t,this.ORDER)}pow(e,t){return cx(this,e,t)}div(e,t){return me(e*Wp(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Wp(e,this.ORDER)}sqrt(e){let t=Yp.get(this);return t||Yp.set(this,t=ix(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Fu(e,this.BYTES):xi(e,this.BYTES)}fromBytes(e,t=!1){j(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(o);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?gt(e):Sr(e);if(a&&(c=me(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Bo(this,e)}cmov(e,t,n){return st(n,"condition"),n?t:e}};Object.freeze(vi.prototype);function dn(r,e={}){return new vi(r,e)}function om(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=ue)throw new Error("field order must be greater than 1");let e=fn(r-ue);return Math.ceil(e/8)}function zu(r){let e=om(r);return e+Math.ceil(e/2)}function qu(r,e,t=!1){j(r);let n=r.length,o=om(e),s=Math.max(zu(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?gt(r):Sr(r),a=me(i,e-ue)+ue;return t?Fu(a,o):xi(a,o)}var hn=BigInt(0),_r=BigInt(1);function Uo(r,e){let t=e.negate();return r?t:e}function Cr(r,e){let t=Bo(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function cm(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function $u(r,e){cm(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=Fo(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function sm(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=_r);let u=e*n,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}var Vu=new WeakMap,um=new WeakMap;function Hu(r){return um.get(r)||1}function im(r){if(r!==hn)throw new Error("invalid wNAF")}var pn=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>hn;)t&_r&&(n=n.add(o)),o=o.double(),t>>=_r;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=$u(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=$u(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=sm(n,a,i);n=c,l?s=s.add(Uo(d,t[h])):o=o.add(Uo(f,t[u]))}return im(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=$u(e,this.bits);for(let i=0;i<s.windows&&n!==hn;i++){let{nextN:a,offset:c,isZero:u,isNeg:l}=sm(n,i,s);if(n=a,!u){let f=t[c];o=o.add(l?f.negate():f)}}return im(n),o}getPrecomputes(e,t,n){let o=Vu.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),Vu.set(t,o))),o}cached(e,t,n){let o=Hu(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Hu(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){cm(t,this.bits),um.set(e,t),Vu.delete(e)}hasCache(e){return Hu(e)!==1}};function lm(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>hn||n>hn;)t&_r&&(s=s.add(o)),n&_r&&(i=i.add(o)),o=o.double(),t>>=_r,n>>=_r;return{p1:s,p2:i}}function am(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ku(e),e}else return dn(r,{isLE:t})}function Si(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>hn))throw new Error(`CURVE.${c} must be positive bigint`)}let o=am(e.p,t.Fp,n),s=am(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Ai(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var tr=BigInt(0),xe=BigInt(1),ju=BigInt(2),lx=BigInt(8);function fx(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function fm(r,e={}){let t=e,n=Si("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;at(t,{},{uvRatio:"function"});let c=ju<<BigInt(s.BYTES*8)-xe,u=g=>o.create(g),l=t.uvRatio===void 0?(g,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(g,m))}}catch{return{isValid:!1,value:tr}}}:t.uvRatio;if(!fx(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(g,m,y=!1){let w=y?xe:tr;return ln("coordinate "+g,m,w,c),m}function d(g){if(!(g instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,xe,u(i.Gx*i.Gy));static ZERO=new h(tr,xe,xe,tr);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,y,w,x){this.X=f("x",m),this.Y=f("y",y),this.Z=f("z",w,!0),this.T=f("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:y,y:w}=m||{};return f("x",y),f("y",w),new h(y,w,xe,u(y*w))}static fromBytes(m,y=!1){let w=o.BYTES,{a:x,d:_}=i;m=Mo(j(m,w,"point")),st(y,"zip215");let A=Mo(m),D=m[w-1];A[w-1]=D&-129;let I=gt(A),v=y?c:o.ORDER;ln("point.y",I,tr,v);let O=u(I*I),Y=u(O-xe),q=u(_*O-x),{isValid:b,value:E}=l(Y,q);if(!b)throw new Error("bad point: invalid y coordinate");let T=(E&xe)===xe,C=(D&128)!==0;if(!y&&E===tr&&C)throw new Error("bad point: x=0 and x_0=1");return C!==T&&(E=u(-E)),h.fromAffine({x:E,y:I})}static fromHex(m,y=!1){return h.fromBytes(un(m),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return p.createCache(this,m),y||this.multiply(ju),this}assertValidity(){let m=this,{a:y,d:w}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:x,Y:_,Z:A,T:D}=m,I=u(x*x),v=u(_*_),O=u(A*A),Y=u(O*O),q=u(I*y),b=u(O*u(q+v)),E=u(Y+u(w*u(I*v)));if(b!==E)throw new Error("bad point: equation left != right (1)");let T=u(x*_),C=u(A*D);if(T!==C)throw new Error("bad point: equation left != right (2)")}equals(m){d(m);let{X:y,Y:w,Z:x}=this,{X:_,Y:A,Z:D}=m,I=u(y*D),v=u(_*x),O=u(w*D),Y=u(A*x);return I===v&&O===Y}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:m}=i,{X:y,Y:w,Z:x}=this,_=u(y*y),A=u(w*w),D=u(ju*u(x*x)),I=u(m*_),v=y+w,O=u(u(v*v)-_-A),Y=I+A,q=Y-D,b=I-A,E=u(O*q),T=u(Y*b),C=u(O*b),S=u(q*Y);return new h(E,T,S,C)}add(m){d(m);let{a:y,d:w}=i,{X:x,Y:_,Z:A,T:D}=this,{X:I,Y:v,Z:O,T:Y}=m,q=u(x*I),b=u(_*v),E=u(D*w*Y),T=u(A*O),C=u((x+_)*(I+v)-q-b),S=T-E,L=T+E,k=u(b-y*q),P=u(C*S),N=u(L*k),B=u(C*k),H=u(S*L);return new h(P,N,H,B)}subtract(m){return d(m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:w}=p.cached(this,m,x=>Cr(h,x));return Cr(h,[y,w])[0]}multiplyUnsafe(m){if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===tr?h.ZERO:this.is0()||m===xe?this:p.unsafe(this,m,y=>Cr(h,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(m){let y=this,w=m,{X:x,Y:_,Z:A}=y,D=y.is0();w==null&&(w=D?lx:o.inv(A));let I=u(x*w),v=u(_*w),O=o.mul(A,w);if(D)return{x:tr,y:xe};if(O!==xe)throw new Error("invZ was invalid");return{x:I,y:v}}clearCofactor(){return a===xe?this:this.multiplyUnsafe(a)}toBytes(){let{x:m,y}=this.toAffine(),w=o.toBytes(y);return w[w.length-1]|=m&xe?128:0,w}toHex(){return cn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new pn(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var _i=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Bu()}static fromHex(e){Bu()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return cn(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function dm(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;at(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,u=n.outputLen,l=2*a.BYTES;if(u!==void 0&&(it(u,"hash.outputLen"),u!==l))throw new Error(`hash.outputLen must be ${l}, got ${u}`);let f=o.randomBytes===void 0?Oo:o.randomBytes,d=o.adjustScalarBytes===void 0?b=>b:o.adjustScalarBytes,h=o.domain===void 0?(b,E,T)=>{if(st(T,"phflag"),E.length||T)throw new Error("Contexts/pre-hash are not supported");return b}:o.domain;function p(b){return c.create(gt(b))}function g(b){let E=I.secretKey;j(b,I.secretKey,"secretKey");let T=j(n(b),2*E,"hashedSecretKey"),C=d(T.slice(0,E)),S=T.slice(E,2*E),L=p(C);return{head:C,prefix:S,scalar:L}}function m(b){let{head:E,prefix:T,scalar:C}=g(b),S=i.multiply(C),L=S.toBytes();return{head:E,prefix:T,scalar:C,point:S,pointBytes:L}}function y(b){return m(b).pointBytes}function w(b=Uint8Array.of(),...E){let T=ye(...E);return p(n(h(T,j(b,void 0,"context"),!!s)))}function x(b,E,T={}){b=j(b,void 0,"message"),s&&(b=s(b));let{prefix:C,scalar:S,pointBytes:L}=m(E),k=w(T.context,C,b),P=i.multiply(k).toBytes(),N=w(T.context,P,L,b),B=c.create(k+N*S);if(!c.isValid(B))throw new Error("sign failed: invalid s");let H=ye(P,c.toBytes(B));return j(H,I.signature,"result")}let _={zip215:o.zip215};function A(b,E,T,C=_){let{context:S}=C,L=C.zip215===void 0?!!_.zip215:C.zip215,k=I.signature;b=j(b,k,"signature"),E=j(E,void 0,"message"),T=j(T,I.publicKey,"publicKey"),L!==void 0&&st(L,"zip215"),s&&(E=s(E));let P=k/2,N=b.subarray(0,P),B=gt(b.subarray(P,k)),H,X,$;try{H=r.fromBytes(T,L),X=r.fromBytes(N,L),$=i.multiplyUnsafe(B)}catch{return!1}if(!L&&H.isSmallOrder())return!1;let ge=w(S,N,T,E);return X.add(H.multiplyUnsafe(ge)).subtract($).clearCofactor().is0()}let D=a.BYTES,I={secretKey:D,publicKey:D,signature:2*D,seed:D};function v(b){return b=b===void 0?f(I.seed):b,j(b,I.seed,"seed")}function O(b){return vr(b)&&b.length===I.secretKey}function Y(b,E){try{return!!r.fromBytes(b,E===void 0?_.zip215:E)}catch{return!1}}let q={getExtendedPublicKey:m,randomSecretKey:v,isValidSecretKey:O,isValidPublicKey:Y,toMontgomery(b){let{y:E}=r.fromBytes(b),T=I.publicKey,C=T===32;if(!C&&T!==57)throw new Error("only defined for 25519 and 448");let S=C?a.div(xe+E,xe-E):a.div(E-xe,E+xe);return a.toBytes(S)},toMontgomerySecret(b){let E=I.secretKey;j(b,E);let T=n(b.subarray(0,E));return d(T).subarray(0,E)}};return Object.freeze(I),Object.freeze(q),Object.freeze({keygen:Ai(v,y),getPublicKey:y,sign:x,verify:A,utils:q,Point:r,lengths:I})}function Ko(r,e){if(it(r),it(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function dx(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function hx(r){if(!vr(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Ei(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function Gu(r,e,t,n){j(r),it(t),e=hx(e),e.length>255&&(e=n(ye(Ei("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ye(e,Ko(e.length,1)),c=new Uint8Array(s),u=Ko(t,2),l=new Array(i),f=n(ye(c,r,u,Ko(0,1),a));l[0]=n(ye(f,Ko(1,1),a));for(let h=1;h<i;h++){let p=[dx(f,l[h-1]),Ko(h+1,1),a];l[h]=n(ye(...p))}return ye(...l).slice(0,t)}var hm="HashToScalar-";var px=BigInt(0),Nt=BigInt(1),pm=BigInt(2);var mx=BigInt(5),gx=BigInt(8),mn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Zu={p:mn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:gx,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function yx(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=mn,a=r*r%s*r%s,c=se(a,pm,s)*a%s,u=se(c,Nt,s)*r%s,l=se(u,mx,s)*u%s,f=se(l,e,s)*l%s,d=se(f,t,s)*f%s,h=se(d,n,s)*d%s,p=se(h,o,s)*h%s,g=se(p,o,s)*h%s,m=se(g,e,s)*l%s;return{pow_p_5_8:se(m,pm,s)*r%s,b2:a}}function bx(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Wu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Qu(r,e){let t=mn,n=me(e*e*e,t),o=me(n*n*e,t),s=yx(r*o).pow_p_5_8,i=me(r*n*s,t),a=me(e*i*i,t),c=i,u=me(i*Wu,t),l=a===r,f=a===me(-r,t),d=a===me(-r*Wu,t);return l&&(i=c),(f||d)&&(i=u),Ot(i,t)&&(i=me(-i,t)),{isValid:l||f,value:i}}var nr=fm(Zu,{uvRatio:Qu}),rr=nr.Fp,ym=nr.Fn;function wx(r){return dm(nr,gi,Object.assign({adjustScalarBytes:bx,zip215:!0},r))}var zo=wx({});var Xu=Wu,xx=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ex=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),vx=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Sx=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),mm=r=>Qu(Nt,r),Ax=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Yu=r=>rr.create(gt(r)&Ax);function gm(r){let{d:e}=Zu,t=mn,n=y=>rr.create(y),o=n(Xu*r*r),s=n((o+Nt)*vx),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:u}=Qu(s,a),l=n(u*r);Ot(l,t)||(l=n(-l)),c||(u=l),c||(i=o);let f=n(i*(o-Nt)*Sx-a),d=u*u,h=n((u+u)*a),p=n(f*xx),g=n(Nt-d),m=n(Nt+d);return new nr(n(h*m),n(g*p),n(p*m),n(h*g))}var or=class r extends _i{static BASE=new r(nr.BASE);static ZERO=new r(nr.ZERO);static Fp=rr;static Fn=ym;constructor(e){super(e)}static fromAffine(e){return new r(nr.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){He(e,32);let{a:t,d:n}=Zu,o=mn,s=_=>rr.create(_),i=Yu(e);if(!jp(rr.toBytes(i),e)||Ot(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Nt+t*a),u=s(Nt-t*a),l=s(c*c),f=s(u*u),d=s(t*n*l-f),{isValid:h,value:p}=mm(s(d*f)),g=s(p*u),m=s(p*g*d),y=s((i+i)*g);Ot(y,o)&&(y=s(-y));let w=s(c*m),x=s(y*w);if(!h||Ot(x,o)||w===px)throw new Error("invalid ristretto255 encoding 2");return new r(new nr(y,w,Nt,x))}static fromHex(e){return r.fromBytes(Do(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=mn,i=m=>rr.create(m),a=i(i(n+t)*i(n-t)),c=i(e*t),u=i(c*c),{value:l}=mm(i(a*u)),f=i(l*a),d=i(l*c),h=i(f*d*o),p;if(Ot(o*h,s)){let m=i(t*Xu),y=i(e*Xu);e=m,t=y,p=i(f*Ex)}else p=d;Ot(e*h,s)&&(t=i(-t));let g=i((n-t)*p);return Ot(g,s)&&(g=i(-g)),rr.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=u=>rr.create(u),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(or.BASE);Object.freeze(or.ZERO);Object.freeze(or.prototype);Object.freeze(or);var _x=Object.freeze({Point:or,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Gu(r,t,64,gi);return _x.deriveToCurve(n)},hashToScalar(r,e={DST:hm}){let t=Gu(r,e.DST,64,gi);return ym.create(gt(t))},deriveToCurve(r){He(r,64);let e=Yu(r.subarray(0,32)),t=gm(e),n=Yu(r.subarray(32,64)),o=gm(n);return new or(t.add(o))}});var qo=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},$o=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ci=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var $e={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Ci("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Ii=32,Vo=64,Ju=32;var gn,bm=(async()=>{try{return await $e.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function wm(){let r=zo.utils.randomSecretKey(),e=zo.getPublicKey(r);return{privateKey:Dx(r,e),publicKey:e}}async function Cx(r,e){let t;r.length===Vo?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:z(r.subarray(32),"base64url"),d:z(t,"base64url"),ext:!0,key_ops:["sign"]},o=await $e.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await $e.get().subtle.sign({name:"Ed25519"},o,Oe(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(s,0,s.byteLength)}function Ix(r,e){let t=r.subarray(0,Ju);return zo.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function xm(r,e){return gn==null&&(gn=await bm),gn?Cx(r,e):Ix(r,e)}async function Tx(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await $e.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await $e.get().subtle.verify({name:"Ed25519"},n,Oe(e),Oe(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Lx(r,e,t){return zo.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Em(r,e,t){return gn==null&&(gn=await bm),gn?Tx(r,e,t):Lx(r,e,t)}function Dx(r,e){let t=new Uint8Array(Vo);for(let n=0;n<Ju;n++)t[n]=r[n],t[Ju+n]=e[n];return t}function Px(r){return r?.buffer instanceof ArrayBuffer}function el(r){if(Px(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Mt(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=br(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return el(t)}function yn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ho=class{type="Ed25519";raw;constructor(e){this.raw=Li(e,Ii)}toMultihash(){return rt.digest(Qe(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Em(this.raw,t,e);return yn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},Ti=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Li(e,Vo),this.publicKey=new Ho(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=xm(this.raw,e);return yn(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function tl(r){return r=Li(r,Ii),new Ho(r)}async function Sm(){let{privateKey:r,publicKey:e}=wm();return new Ti(r,e)}function Li(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new R(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function Am(r=0){return new Uint8Array(r)}var kx=Math.pow(2,7),Rx=Math.pow(2,14),Ox=Math.pow(2,21),rl=Math.pow(2,28),nl=Math.pow(2,35),ol=Math.pow(2,42),sl=Math.pow(2,49),Z=128,Ie=127;function je(r){if(r<kx)return 1;if(r<Rx)return 2;if(r<Ox)return 3;if(r<rl)return 4;if(r<nl)return 5;if(r<ol)return 6;if(r<sl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function il(r,e,t=0){switch(je(r)){case 8:e[t++]=r&255|Z,r/=128;case 7:e[t++]=r&255|Z,r/=128;case 6:e[t++]=r&255|Z,r/=128;case 5:e[t++]=r&255|Z,r/=128;case 4:e[t++]=r&255|Z,r>>>=7;case 3:e[t++]=r&255|Z,r>>>=7;case 2:e[t++]=r&255|Z,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Nx(r,e,t=0){switch(je(r)){case 8:e.set(t++,r&255|Z),r/=128;case 7:e.set(t++,r&255|Z),r/=128;case 6:e.set(t++,r&255|Z),r/=128;case 5:e.set(t++,r&255|Z),r/=128;case 4:e.set(t++,r&255|Z),r>>>=7;case 3:e.set(t++,r&255|Z),r>>>=7;case 2:e.set(t++,r&255|Z),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function al(r,e){let t=r[e],n=0;if(n+=t&Ie,t<Z||(t=r[e+1],n+=(t&Ie)<<7,t<Z)||(t=r[e+2],n+=(t&Ie)<<14,t<Z)||(t=r[e+3],n+=(t&Ie)<<21,t<Z)||(t=r[e+4],n+=(t&Ie)*rl,t<Z)||(t=r[e+5],n+=(t&Ie)*nl,t<Z)||(t=r[e+6],n+=(t&Ie)*ol,t<Z)||(t=r[e+7],n+=(t&Ie)*sl,t<Z))return n;throw new RangeError("Could not decode varint")}function Mx(r,e){let t=r.get(e),n=0;if(n+=t&Ie,t<Z||(t=r.get(e+1),n+=(t&Ie)<<7,t<Z)||(t=r.get(e+2),n+=(t&Ie)<<14,t<Z)||(t=r.get(e+3),n+=(t&Ie)<<21,t<Z)||(t=r.get(e+4),n+=(t&Ie)*rl,t<Z)||(t=r.get(e+5),n+=(t&Ie)*nl,t<Z)||(t=r.get(e+6),n+=(t&Ie)*ol,t<Z)||(t=r.get(e+7),n+=(t&Ie)*sl,t<Z))return n;throw new RangeError("Could not decode varint")}function sr(r,e,t=0){return e==null&&(e=Am(je(r))),e instanceof Uint8Array?il(r,e,t):Nx(r,e,t)}function Di(r,e=0){return r instanceof Uint8Array?al(r,e):Mx(r,e)}var cl=new Float32Array([-0]),ir=new Uint8Array(cl.buffer);function _m(r,e,t){cl[0]=r,e[t]=ir[0],e[t+1]=ir[1],e[t+2]=ir[2],e[t+3]=ir[3]}function Cm(r,e){return ir[0]=r[e],ir[1]=r[e+1],ir[2]=r[e+2],ir[3]=r[e+3],cl[0]}var ul=new Float64Array([-0]),Te=new Uint8Array(ul.buffer);function Im(r,e,t){ul[0]=r,e[t]=Te[0],e[t+1]=Te[1],e[t+2]=Te[2],e[t+3]=Te[3],e[t+4]=Te[4],e[t+5]=Te[5],e[t+6]=Te[6],e[t+7]=Te[7]}function Tm(r,e){return Te[0]=r[e],Te[1]=r[e+1],Te[2]=r[e+2],Te[3]=r[e+3],Te[4]=r[e+4],Te[5]=r[e+5],Te[6]=r[e+6],Te[7]=r[e+7],ul[0]}var Fx=BigInt(Number.MAX_SAFE_INTEGER),Bx=BigInt(Number.MIN_SAFE_INTEGER),Ge=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Ir;if(e<Fx&&e>Bx)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Lm&&(o=0n,++n>Lm&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Ir;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Ir}},Ir=new Ge(0,0);Ir.toBigInt=function(){return 0n};Ir.zzEncode=Ir.zzDecode=function(){return this};Ir.length=function(){return 1};var Lm=4294967296n;function Dm(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Pm(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function ll(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function ct(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ki(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var fl=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ct(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ct(this,4);return ki(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ct(this,4);return ki(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ct(this,4);let e=Cm(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ct(this,4);let e=Tm(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ct(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Pm(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ct(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ct(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ge(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ct(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ct(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ct(this,8);let e=ki(this.buf,this.pos+=4),t=ki(this.buf,this.pos+=4);return new Ge(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=al(this.buf,this.pos);return this.pos+=je(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function jo(r){return new fl(r instanceof Uint8Array?r:r.subarray())}function Me(r,e,t){let n=jo(r);return e.decode(n,void 0,t)}function Tr(r=0){return new Uint8Array(r)}var gl={};U(gl,{base10:()=>Hx});var tT=new Uint8Array(0);function Rm(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Ft(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 Om(r){return new TextEncoder().encode(r)}function Nm(r){return new TextDecoder().decode(r)}function Ux(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),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,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var x=(w-y)*l+1>>>0,_=new Uint8Array(x);y!==w;){for(var A=p[y],D=0,I=x-1;(A!==0||D<m)&&I!==-1;I--,D++)A+=256*_[I]>>>0,_[I]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=D,y++}for(var v=x-m;v!==x&&_[v]===0;)v++;for(var O=c.repeat(g);v<x;++v)O+=r.charAt(_[v]);return O}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,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,x=new Uint8Array(w);p[g];){var _=t[p.charCodeAt(g)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<y)&&D!==-1;D--,A++)_+=a*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}if(p[g]!==" "){for(var I=w-y;I!==w&&x[I]===0;)I++;for(var v=new Uint8Array(m+(w-I)),O=m;I!==w;)v[O++]=x[I++];return v}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Kx=Ux,zx=Kx,Fm=zx;var dl=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},hl=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Bm(this,e)}},pl=class{decoders;constructor(e){this.decoders=e}or(e){return Bm(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Bm(r,e){return new pl({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ml=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new dl(e,t,n),this.decoder=new hl(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function bn({name:r,prefix:e,encode:t,decode:n}){return new ml(r,e,t,n)}function ar({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Fm(t,r);return bn({prefix:e,name:r,encode:n,decode:s=>Ft(o(s))})}function qx(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function $x(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Vx(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function le({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Vx(n);return bn({prefix:e,name:r,encode(s){return $x(s,n,t)},decode(s){return qx(s,o,t,r)}})}var Hx=ar({prefix:"9",name:"base10",alphabet:"0123456789"});var yl={};U(yl,{base16:()=>jx,base16upper:()=>Gx});var jx=le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Gx=le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var bl={};U(bl,{base2:()=>Wx});var Wx=le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wl={};U(wl,{base256emoji:()=>Jx});var Um=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}"),Xx=Um.reduce((r,e,t)=>(r[t]=e,r),[]),Yx=Um.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Zx(r){return r.reduce((e,t)=>(e+=Xx[t],e),"")}function Qx(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Yx[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Jx=bn({prefix:"\u{1F680}",name:"base256emoji",encode:Zx,decode:Qx});var xl={};U(xl,{base32:()=>wn,base32hex:()=>nE,base32hexpad:()=>sE,base32hexpadupper:()=>iE,base32hexupper:()=>oE,base32pad:()=>tE,base32padupper:()=>rE,base32upper:()=>eE,base32z:()=>aE});var wn=le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),eE=le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tE=le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rE=le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),nE=le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),oE=le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sE=le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),iE=le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aE=le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var El={};U(El,{base36:()=>Go,base36upper:()=>cE});var Go=ar({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cE=ar({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vl={};U(vl,{base58btc:()=>yt,base58flickr:()=>uE});var yt=ar({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),uE=ar({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Sl={};U(Sl,{base64:()=>lE,base64pad:()=>fE,base64url:()=>dE,base64urlpad:()=>hE});var lE=le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fE=le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),dE=le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hE=le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Al={};U(Al,{base8:()=>pE});var pE=le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var _l={};U(_l,{identity:()=>mE});var mE=bn({prefix:"\0",name:"identity",encode:r=>Nm(r),decode:r=>Om(r)});var yT=new TextEncoder,bT=new TextDecoder;var Il={};U(Il,{identity:()=>BE});var bE=qm,Km=128,wE=127,xE=~wE,EE=Math.pow(2,31);function qm(r,e,t){e=e||[],t=t||0;for(var n=t;r>=EE;)e[t++]=r&255|Km,r/=128;for(;r&xE;)e[t++]=r&255|Km,r>>>=7;return e[t]=r|0,qm.bytes=t-n+1,e}var vE=Cl,SE=128,zm=127;function Cl(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Cl.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&zm)<<o:(i&zm)*Math.pow(2,o),o+=7}while(i>=SE);return Cl.bytes=s-n,t}var AE=Math.pow(2,7),_E=Math.pow(2,14),CE=Math.pow(2,21),IE=Math.pow(2,28),TE=Math.pow(2,35),LE=Math.pow(2,42),DE=Math.pow(2,49),PE=Math.pow(2,56),kE=Math.pow(2,63),RE=function(r){return r<AE?1:r<_E?2:r<CE?3:r<IE?4:r<TE?5:r<LE?6:r<DE?7:r<PE?8:r<kE?9:10},OE={encode:bE,decode:vE,encodingLength:RE},NE=OE,Wo=NE;function Xo(r,e=0){return[Wo.decode(r,e),Wo.decode.bytes]}function xn(r,e,t=0){return Wo.encode(r,e,t),e}function En(r){return Wo.encodingLength(r)}function Sn(r,e){let t=e.byteLength,n=En(r),o=n+En(t),s=new Uint8Array(o+t);return xn(r,s,0),xn(t,s,n),s.set(e,o),new vn(r,t,e,s)}function $m(r){let e=Ft(r),[t,n]=Xo(e),[o,s]=Xo(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new vn(t,o,i,e)}function Vm(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Rm(r.bytes,t.bytes)}}var vn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Hm=0,ME="identity",jm=Ft;function FE(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Sn(Hm,jm(r))}var BE={code:Hm,name:ME,encode:jm,digest:FE};var Dl={};U(Dl,{sha256:()=>KE,sha512:()=>zE});var UE=20;function Ll({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Tl(r,e,t,n,o)}var Tl=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??UE,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Gm(n,this.code,t?.truncate):n.then(o=>Gm(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Gm(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Sn(e,r)}function Xm(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var KE=Ll({name:"sha2-256",code:18,encode:Xm("SHA-256")}),zE=Ll({name:"sha2-512",code:19,encode:Xm("SHA-512")});function Ym(r,e){let{bytes:t,version:n}=r;return n===0?$E(t,Pl(r),e??yt.encoder):VE(t,Pl(r),e??wn.encoder)}var Zm=new WeakMap;function Pl(r){let e=Zm.get(r);if(e==null){let t=new Map;return Zm.set(r,t),t}return e}var Oi=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Zo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==HE)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Sn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Vm(e.multihash,n.multihash)}toString(e){return Ym(this,e)}toJSON(){return{"/":Ym(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Qm(n,o,s.bytes))}else if(t[jE]===!0){let{version:n,multihash:o,code:s}=t,i=$m(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Zo)throw new Error(`Version 0 CID must use dag-pb (code: ${Zo}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Qm(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Zo,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Ft(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new vn(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Xo(e.subarray(t));return t+=d,f},o=n(),s=Zo;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=qE(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Pl(s).set(n,e),s}};function qE(r,e){switch(r[0]){case"Q":{let t=e??yt;return[yt.prefix,t.decode(`${yt.prefix}${r}`)]}case yt.prefix:{let t=e??yt;return[yt.prefix,t.decode(r)]}case wn.prefix:{let t=e??wn;return[wn.prefix,t.decode(r)]}case Go.prefix:{let t=e??Go;return[Go.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function $E(r,e,t){let{prefix:n}=t;if(n!==yt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function VE(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Zo=112,HE=18;function Qm(r,e,t){let n=En(r),o=n+En(e),s=new Uint8Array(o+t.byteLength);return xn(r,s,0),xn(e,s,n),s.set(t,o),s}var jE=Symbol.for("@ipld/js-cid/CID");var kl={..._l,...bl,...Al,...gl,...yl,...xl,...El,...vl,...Sl,...wl},KT={...Dl,...Il};function eg(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Jm=eg("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Rl=eg("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Tr(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),GE={utf8:Jm,"utf-8":Jm,hex:kl.base16,latin1:Rl,ascii:Rl,binary:Rl,...kl},tg=GE;function rg(r,e="utf8"){let t=tg[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Ol(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Tr(i);o+i>e&&(n=Tr(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Lr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Nl(){}var Fl=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},WE=Ol();function XE(r){return globalThis.Buffer!=null?Tr(r):WE(r)}var Jo=class{len;head;tail;states;constructor(){this.len=0,this.head=new Lr(Nl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Lr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Bl((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ni,10,Ge.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ge.fromBigInt(e);return this._push(Ni,t.length(),t)}uint64Number(e){return this._push(il,je(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Ge.fromBigInt(e).zzEncode();return this._push(Ni,t.length(),t)}sint64Number(e){let t=Ge.fromNumber(e).zzEncode();return this._push(Ni,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ml,1,e?1:0)}fixed32(e){return this._push(Qo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ge.fromBigInt(e);return this._push(Qo,4,t.lo)._push(Qo,4,t.hi)}fixed64Number(e){let t=Ge.fromNumber(e);return this._push(Qo,4,t.lo)._push(Qo,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(_m,4,e)}double(e){return this._push(Im,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ml,1,0):this.uint32(t)._push(ZE,t,e)}string(e){let t=Dm(e);return t!==0?this.uint32(t)._push(ll,t,e):this._push(Ml,1,0)}fork(){return this.states=new Fl(this),this.head=this.tail=new Lr(Nl,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 Lr(Nl,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=XE(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Ml(r,e,t){e[t]=r&255}function YE(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Bl=class extends Lr{next;constructor(e,t){super(YE,e,t),this.next=void 0}};function Ni(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Qo(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function ZE(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Jo.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(QE,e,r),this},Jo.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(JE,e,r),this});function QE(r,e,t){e.set(r,t)}function JE(r,e,t){r.length<40?ll(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(rg(r),t)}function Ul(){return new Jo}function Fe(r,e){let t=Ul();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Be(r,e,t){let n=jo(r);yield*e.stream(n,void 0,"$",t)}var Mi={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Fi(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Kl(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Fi("enum",Mi.VARINT,t,n,o)}function Ue(r,e,t){return Fi("message",Mi.LENGTH_DELIMITED,r,e,t)}var Je=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},es=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ie;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ie||(ie={}));var zl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(zl||(zl={}));(function(r){r.codec=()=>Kl(zl)})(ie||(ie={}));var bt;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ie.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ie.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ie.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Be(s,r.codec(),i)}r.stream=o})(bt||(bt={}));var ql;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ie.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=ie.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:ie.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Be(s,r.codec(),i)}r.stream=o})(ql||(ql={}));function An(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return pi(r)}var rs={};U(rs,{MAX_RSA_KEY_SIZE:()=>$l,generateRSAKeyPair:()=>Ql,jwkToJWKKeyPair:()=>ag,jwkToPkcs1:()=>nv,jwkToPkix:()=>Gl,jwkToRSAPrivateKey:()=>Zl,pkcs1MessageToJwk:()=>Hl,pkcs1MessageToRSAPrivateKey:()=>Wl,pkcs1ToJwk:()=>rv,pkcs1ToRSAPrivateKey:()=>ig,pkixMessageToJwk:()=>jl,pkixMessageToRSAPublicKey:()=>Yl,pkixToJwk:()=>ov,pkixToRSAPublicKey:()=>Xl});var _n=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=rs.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}verify(e,t,n){return sg(this.jwk,t,e,n)}},ts=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=rs.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}sign(e,t){return og(this.jwk,e,t)}};var $l=8192,Vl=18,ev=1062,tv=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function rv(r){let e=Dt(r);return Hl(e)}function Hl(r){return{n:z(r[1],"base64url"),e:z(r[2],"base64url"),d:z(r[3],"base64url"),p:z(r[4],"base64url"),q:z(r[5],"base64url"),dp:z(r[6],"base64url"),dq:z(r[7],"base64url"),qi:z(r[8],"base64url"),kty:"RSA"}}function nv(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 R("JWK was missing components");return nt([Ne(Uint8Array.from([0])),Ne(M(r.n,"base64url")),Ne(M(r.e,"base64url")),Ne(M(r.d,"base64url")),Ne(M(r.p,"base64url")),Ne(M(r.q,"base64url")),Ne(M(r.dp,"base64url")),Ne(M(r.dq,"base64url")),Ne(M(r.qi,"base64url"))]).subarray()}function ov(r){let e=Dt(r,{offset:0});return jl(e)}function jl(r){let e=Dt(r[1],{offset:0});return{kty:"RSA",n:z(e[0],"base64url"),e:z(e[1],"base64url")}}function Gl(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return nt([tv,Lo(nt([Ne(M(r.n,"base64url")),Ne(M(r.e,"base64url"))]))]).subarray()}function ig(r){let e=Dt(r);return Wl(e)}function Wl(r){let e=Hl(r);return Zl(e)}function Xl(r,e){if(r.byteLength>=ev)throw new Zr("Key size is too large");let t=Dt(r,{offset:0});return Yl(t,r,e)}function Yl(r,e,t){let n=jl(r);if(t==null){let o=an(bt.encode({Type:ie.RSA,Data:e}));t=pt(Vl,o)}return new _n(n,t)}function Zl(r){if(ug(r)>$l)throw new R("Key size is too large");let e=ag(r),t=an(bt.encode({Type:ie.RSA,Data:Gl(e.publicKey)})),n=pt(Vl,t);return new ts(e.privateKey,new _n(e.publicKey,n))}async function Ql(r){if(r>$l)throw new R("Key size is too large");let e=await cg(r),t=an(bt.encode({Type:ie.RSA,Data:Gl(e.publicKey)})),n=pt(Vl,t);return new ts(e.privateKey,new _n(e.publicKey,n))}function ag(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function cg(r,e){let t=await $e.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await sv(t,e);return{privateKey:n[0],publicKey:n[1]}}async function og(r,e,t){let n=await $e.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await $e.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Oe(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function sg(r,e,t,n){let o=await $e.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await $e.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Oe(e),Oe(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function sv(r,e){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");let t=await Promise.all([$e.get().subtle.exportKey("jwk",r.privateKey),$e.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function ug(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return M(r.n,"base64url").length*8}var Bi=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(li(e),He(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),kt(o)}update(e){return sn(this),this.iHash.update(e),this}digestInto(e){sn(this),fi(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},lg=(()=>{let r=((e,t,n)=>new Bi(e,t).update(n).digest());return r.create=(e,t)=>new Bi(e,t),r})();var fg=(r,e)=>(r+(r>=0?e:-e)/dg)/e;function iv(r,e,t){ln("scalar",r,wt,t);let[[n,o],[s,i]]=e,a=fg(i*r,t),c=fg(-o*r,t),u=r-a*n-c*s,l=-a*o-c*i,f=u<wt,d=l<wt;f&&(u=-u),d&&(l=-l);let h=Fo(Math.ceil(fn(t)/2))+cr;if(u<wt||u>=h||l<wt||l>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:u,k2neg:d,k2:l}}function ef(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Jl(r,e){at(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return st(t.lowS,"lowS"),st(t.prehash,"prehash"),t.format!==void 0&&ef(t.format),t}var tf=class extends Error{constructor(e=""){super(e)}},ut={Err:tf,_tlv:{encode:(r,e)=>{let{Err:t}=ut;if(it(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=No(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?No(o.length/2|128):"";return No(r)+s+o+e},decode(r,e){let{Err:t}=ut;e=j(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=ut;if(wi(r),r<wt)throw new e("integer: negative integers are not allowed");let t=No(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=ut;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Sr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=ut,o=j(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=ut,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(ut._tlv);Object.freeze(ut._int);Object.freeze(ut);var wt=BigInt(0),cr=BigInt(1),dg=BigInt(2),Ui=BigInt(3),av=BigInt(4);function hg(r,e={}){let t=Si("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;at(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:u}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=mg(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(q,b,E){if(u&&b.is0())return Uint8Array.of(0);let{x:T,y:C}=b.toAffine(),S=n.toBytes(T);if(st(E,"isCompressed"),E){f();let L=!n.isOdd(C);return ye(pg(L),S)}else return ye(Uint8Array.of(4),S,n.toBytes(C))}function h(q){j(q,void 0,"Point");let{publicKey:b,publicKeyUncompressed:E}=l,T=q.length,C=q[0],S=q.subarray(1);if(u&&T===1&&C===0)return{x:n.ZERO,y:n.ZERO};if(T===b&&(C===2||C===3)){let L=n.fromBytes(S);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let k=m(L),P;try{P=n.sqrt(k)}catch(H){let X=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}f();let N=n.isOdd(P);return(C&1)===1!==N&&(P=n.neg(P)),{x:L,y:P}}else if(T===E&&C===4){let L=n.BYTES,k=n.fromBytes(S.subarray(0,L)),P=n.fromBytes(S.subarray(L,L*2));if(!y(k,P))throw new Error("bad point: is not on curve");return{x:k,y:P}}else throw new Error(`bad point: got length ${T}, expected compressed=${b} or uncompressed=${E}`)}let p=e.toBytes===void 0?d:e.toBytes,g=e.fromBytes===void 0?h:e.fromBytes;function m(q){let b=n.sqr(q),E=n.mul(b,q);return n.add(n.add(E,n.mul(q,s.a)),s.b)}function y(q,b){let E=n.sqr(b),T=m(q);return n.eql(E,T)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,Ui),av),x=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,x)))throw new Error("bad curve params: a or b");function _(q,b,E=!1){if(!n.isValid(b)||E&&n.is0(b))throw new Error(`bad point coordinate ${q}`);return b}function A(q){if(!(q instanceof v))throw new Error("Weierstrass Point expected")}function D(q){if(!c||!c.basises)throw new Error("no endo");return iv(q,c.basises,o.ORDER)}function I(q,b,E,T,C){return E=new v(n.mul(E.X,q),E.Y,E.Z),b=Uo(T,b),E=Uo(C,E),b.add(E)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,E,T){this.X=_("x",b),this.Y=_("y",E,!0),this.Z=_("z",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:E,y:T}=b||{};if(!b||!n.isValid(E)||!n.isValid(T))throw new Error("invalid affine point");if(b instanceof v)throw new Error("projective point not allowed");return n.is0(E)&&n.is0(T)?v.ZERO:new v(E,T,n.ONE)}static fromBytes(b){let E=v.fromAffine(g(j(b,void 0,"point")));return E.assertValidity(),E}static fromHex(b){return v.fromBytes(un(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,E=!0){return Y.createCache(this,b),E||this.multiply(Ui),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x:E,y:T}=b.toAffine();if(!n.isValid(E)||!n.isValid(T))throw new Error("bad point: x or y not field elements");if(!y(E,T))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){A(b);let{X:E,Y:T,Z:C}=this,{X:S,Y:L,Z:k}=b,P=n.eql(n.mul(E,k),n.mul(S,C)),N=n.eql(n.mul(T,k),n.mul(L,C));return P&&N}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:E}=s,T=n.mul(E,Ui),{X:C,Y:S,Z:L}=this,k=n.ZERO,P=n.ZERO,N=n.ZERO,B=n.mul(C,C),H=n.mul(S,S),X=n.mul(L,L),$=n.mul(C,S);return $=n.add($,$),N=n.mul(C,L),N=n.add(N,N),k=n.mul(b,N),P=n.mul(T,X),P=n.add(k,P),k=n.sub(H,P),P=n.add(H,P),P=n.mul(k,P),k=n.mul($,k),N=n.mul(T,N),X=n.mul(b,X),$=n.sub(B,X),$=n.mul(b,$),$=n.add($,N),N=n.add(B,B),B=n.add(N,B),B=n.add(B,X),B=n.mul(B,$),P=n.add(P,B),X=n.mul(S,L),X=n.add(X,X),B=n.mul(X,$),k=n.sub(k,B),N=n.mul(X,H),N=n.add(N,N),N=n.add(N,N),new v(k,P,N)}add(b){A(b);let{X:E,Y:T,Z:C}=this,{X:S,Y:L,Z:k}=b,P=n.ZERO,N=n.ZERO,B=n.ZERO,H=s.a,X=n.mul(s.b,Ui),$=n.mul(E,S),ge=n.mul(T,L),be=n.mul(C,k),we=n.add(E,T),he=n.add(S,L);we=n.mul(we,he),he=n.add($,ge),we=n.sub(we,he),he=n.add(E,C);let ze=n.add(S,k);return he=n.mul(he,ze),ze=n.add($,be),he=n.sub(he,ze),ze=n.add(T,C),P=n.add(L,k),ze=n.mul(ze,P),P=n.add(ge,be),ze=n.sub(ze,P),B=n.mul(H,he),P=n.mul(X,be),B=n.add(P,B),P=n.sub(ge,B),B=n.add(ge,B),N=n.mul(P,B),ge=n.add($,$),ge=n.add(ge,$),be=n.mul(H,be),he=n.mul(X,he),ge=n.add(ge,be),be=n.sub($,be),be=n.mul(H,be),he=n.add(he,be),$=n.mul(ge,he),N=n.add(N,$),$=n.mul(ze,he),P=n.mul(we,P),P=n.sub(P,$),$=n.mul(we,ge),B=n.mul(ze,B),B=n.add(B,$),new v(P,N,B)}subtract(b){return A(b),this.add(b.negate())}is0(){return this.equals(v.ZERO)}multiply(b){let{endo:E}=e;if(!o.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let T,C,S=L=>Y.cached(this,L,k=>Cr(v,k));if(E){let{k1neg:L,k1:k,k2neg:P,k2:N}=D(b),{p:B,f:H}=S(k),{p:X,f:$}=S(N);C=H.add($),T=I(E.beta,B,X,L,P)}else{let{p:L,f:k}=S(b);T=L,C=k}return Cr(v,[T,C])[0]}multiplyUnsafe(b){let{endo:E}=e,T=this,C=b;if(!o.isValid(C))throw new RangeError("invalid scalar: out of range");if(C===wt||T.is0())return v.ZERO;if(C===cr)return T;if(Y.hasCache(this))return this.multiply(C);if(E){let{k1neg:S,k1:L,k2neg:k,k2:P}=D(C),{p1:N,p2:B}=lm(v,T,L,P);return I(E.beta,N,B,S,k)}else return Y.unsafe(T,C)}toAffine(b){let E=this,T=b,{X:C,Y:S,Z:L}=E;if(n.eql(L,n.ONE))return{x:C,y:S};let k=E.is0();T==null&&(T=k?n.ONE:n.inv(L));let P=n.mul(C,T),N=n.mul(S,T),B=n.mul(L,T);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:P,y:N}}isTorsionFree(){let{isTorsionFree:b}=e;return i===cr?!0:b?b(v,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===cr?this:b?b(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===cr?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return st(b,"isCompressed"),this.assertValidity(),p(v,this,b)}toHex(b=!0){return cn(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let O=o.BITS,Y=new pn(v,e.endo?Math.ceil(O/2):O);return O>=8&&v.BASE.precompute(8),Object.freeze(v.prototype),Object.freeze(v),v}function pg(r){return Uint8Array.of(r?2:3)}function mg(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function cv(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Oo:e.randomBytes,o=Object.assign(mg(r.Fp,t),{seed:Math.max(zu(t.ORDER),16)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:g,publicKeyUncompressed:m}=o;try{let y=h.length;return p===!0&&y!==g||p===!1&&y!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,qu(j(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function u(h){let{secretKey:p,publicKey:g,publicKeyUncompressed:m}=o,y=t._lengths;if(!vr(h))return;let w=j(h,void 0,"key").length,x=w===g||w===m,_=w===p||!!y?.includes(w);if(!(x&&_))return x}function l(h,p,g=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(p).multiply(m).toBytes(g)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Ai(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:r,utils:f,lengths:o})}function gg(r,e,t={}){let n=e;li(n),at(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Oo:t.randomBytes,s=t.hmac===void 0?(C,S)=>lg(n,C,S):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:u}=a,{keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:p}=cv(r,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*dg+cr<i.ORDER;function y(C){let S=c>>cr;return C>S}function w(C,S){if(!a.isValidNot0(S))throw new Error(`invalid signature ${C}: out of range 1..Point.Fn.ORDER`);return S}function x(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function _(C,S){ef(S);let L=p.signature,k=S==="compact"?L:S==="recovered"?L+1:void 0;return j(C,k)}class A{r;s;recovery;constructor(S,L,k){if(this.r=w("r",S),this.s=w("s",L),k!=null){if(x(),![0,1,2,3].includes(k))throw new Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(S,L=g.format){_(S,L);let k;if(L==="der"){let{r:H,s:X}=ut.toSig(j(S));return new A(H,X)}L==="recovered"&&(k=S[0],L="compact",S=S.subarray(1));let P=p.signature/2,N=S.subarray(0,P),B=S.subarray(P,P*2);return new A(a.fromBytes(N),a.fromBytes(B),k)}static fromHex(S,L){return this.fromBytes(un(S),L)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new A(this.r,this.s,S)}recoverPublicKey(S){let{r:L,s:k}=this,P=this.assertRecovery(),N=P===2||P===3?L+c:L;if(!i.isValid(N))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=i.toBytes(N),H=r.fromBytes(ye(pg((P&1)===0),B)),X=a.inv(N),$=I(j(S,void 0,"msgHash")),ge=a.create(-$*X),be=a.create(k*X),we=r.BASE.multiplyUnsafe(ge).add(H.multiplyUnsafe(be));if(we.is0())throw new Error("invalid recovery: point at infinify");return we.assertValidity(),we}hasHighS(){return y(this.s)}toBytes(S=g.format){if(ef(S),S==="der")return un(ut.hexFromSig(this));let{r:L,s:k}=this,P=a.toBytes(L),N=a.toBytes(k);return S==="recovered"?(x(),ye(Uint8Array.of(this.assertRecovery()),P,N)):ye(P,N)}toHex(S){return cn(this.toBytes(S))}}Object.freeze(A.prototype),Object.freeze(A);let D=t.bits2int===void 0?function(S){if(S.length>8192)throw new Error("input is too large");let L=Sr(S),k=S.length*8-u;return k>0?L>>BigInt(k):L}:t.bits2int,I=t.bits2int_modN===void 0?function(S){return a.create(D(S))}:t.bits2int_modN,v=Fo(u);function O(C){return ln("num < 2^"+u,C,wt,v),a.toBytes(C)}function Y(C,S){return j(C,void 0,"message"),S?j(n(C),void 0,"prehashed message"):C}function q(C,S,L){let{lowS:k,prehash:P,extraEntropy:N}=Jl(L,g);C=Y(C,P);let B=I(C),H=a.fromBytes(S);if(!a.isValidNot0(H))throw new Error("invalid private key");let X=[O(H),O(B)];if(N!=null&&N!==!1){let we=N===!0?o(p.secretKey):N;X.push(j(we,void 0,"extraEntropy"))}let $=ye(...X),ge=B;function be(we){let he=D(we);if(!a.isValidNot0(he))return;let ze=a.inv(he),Yr=r.BASE.multiply(he).toAffine(),mo=a.create(Yr.x);if(mo===wt)return;let Gs=a.create(ze*a.create(ge+mo*H));if(Gs===wt)return;let jh=(Yr.x===mo?0:2)|Number(Yr.y&cr),Gh=Gs;return k&&y(Gs)&&(Gh=a.neg(Gs),jh^=1),new A(mo,Gh,m?void 0:jh)}return{seed:$,k2sig:be}}function b(C,S,L={}){let{seed:k,k2sig:P}=q(C,S,L);return Gp(n.outputLen,a.BYTES,s)(k,P).toBytes(L.format)}function E(C,S,L,k={}){let{lowS:P,prehash:N,format:B}=Jl(k,g);if(L=j(L,void 0,"publicKey"),S=Y(S,N),!vr(C)){let H=C instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+H)}_(C,B);try{let H=A.fromBytes(C,B),X=r.fromBytes(L);if(P&&H.hasHighS())return!1;let{r:$,s:ge}=H,be=I(S),we=a.inv(ge),he=a.create(be*we),ze=a.create($*we),Yr=r.BASE.multiplyUnsafe(he).add(X.multiplyUnsafe(ze));return Yr.is0()?!1:a.create(Yr.x)===$}catch{return!1}}function T(C,S,L={}){let{prehash:k}=Jl(L,g);return S=Y(S,k),A.fromBytes(C,"recovered").recoverPublicKey(S).toBytes()}return Object.freeze({keygen:l,getPublicKey:f,getSharedSecret:d,utils:h,lengths:p,Point:r,sign:b,verify:E,recoverPublicKey:T,Signature:A,hash:n})}var nf={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},uv={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var yg=BigInt(2);function lv(r){let e=nf.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=se(l,t,e)*l%e,d=se(f,t,e)*l%e,h=se(d,yg,e)*u%e,p=se(h,o,e)*h%e,g=se(p,s,e)*p%e,m=se(g,a,e)*g%e,y=se(m,c,e)*m%e,w=se(y,a,e)*g%e,x=se(w,t,e)*l%e,_=se(x,i,e)*p%e,A=se(_,n,e)*u%e,D=se(A,yg,e);if(!rf.eql(rf.sqr(D),r))throw new Error("Cannot find square root");return D}var rf=dn(nf.p,{sqrt:lv}),fv=hg(nf,{Fp:rf,endo:uv}),lt=gg(fv,an);function bg(r,e,t){let n=on.digest(e instanceof Uint8Array?e:e.subarray());if(yn(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),lt.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new qo(String(o))});try{return lt.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new qo(String(o))}}function wg(r,e,t,n){let o=on.digest(t instanceof Uint8Array?t:t.subarray());if(yn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),lt.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new $o(String(s))});try{return n?.signal?.throwIfAborted(),lt.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new $o(String(s))}}var ns=class{type="secp256k1";raw;_key;constructor(e){this._key=vg(e),this.raw=xg(this._key)}toMultihash(){return rt.digest(Qe(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}verify(e,t,n){return wg(this._key,t,e,n)}},Ki=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Eg(e),this.publicKey=new ns(t??Sg(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:J(this.raw,e.raw)}sign(e,t){return bg(this.raw,e,t)}};function of(r){return new ns(r)}async function Ag(){let r=dv();return new Ki(r)}function xg(r){return lt.Point.fromBytes(r).toBytes()}function Eg(r){try{return lt.getPublicKey(r,!0),r}catch(e){throw new yo(String(e))}}function vg(r){try{return lt.Point.fromBytes(r),r}catch(e){throw new Zr(String(e))}}function Sg(r){try{return lt.getPublicKey(r,!0)}catch(e){throw new yo(String(e))}}function dv(){return lt.utils.randomSecretKey()}async function _g(r,e){if(r==="Ed25519")return Sm();if(r==="secp256k1")return Ag();if(r==="RSA")return Ql(hv(e));if(r==="ECDSA")return Pp(pv(e));throw new Gt}function Cn(r,e){let{Type:t,Data:n}=bt.decode(r),o=n??new Uint8Array;switch(t){case ie.RSA:return Xl(o,e);case ie.Ed25519:return tl(o);case ie.secp256k1:return of(o);case ie.ECDSA:return Au(o);default:throw new Gt}}function Cg(r){let{Type:e,Data:t}=bt.decode(r.digest),n=t??new Uint8Array;switch(e){case ie.Ed25519:return tl(n);case ie.secp256k1:return of(n);case ie.ECDSA:return Au(n);default:throw new Gt}}function Qe(r){return bt.encode({Type:ie[r.type],Data:r.raw})}function hv(r){return r==null?2048:parseInt(r,10)}function pv(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 R("Unsupported curve, should be P-256, P-384 or P-521")}var Ig=Symbol.for("nodejs.util.inspect.custom"),mv=114,os=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[ni]=!0;toString(){return this.string==null&&(this.string=re.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(mv,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return J(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return J(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ig](){return`PeerId(${this.toString()})`}},ss=class extends os{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},is=class extends os{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},as=class extends os{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},gv=2336,cs=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=rt.digest(M(this.url))}[Ig](){return`PeerId(${this.url})`}[ni]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(gv,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};var yv=114,Tg=2336;function xt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Tt(re.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return us(pe.parse(r));if(e==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Tt(e.decode(r))}return In(t)}function sf(r){if(r.type==="Ed25519")return new is({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new as({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ss({multihash:r.toCID().multihash,publicKey:r});throw new Gt}function Lg(r){return sf(r.publicKey)}function In(r){if(wv(r))return new ss({multihash:r});if(bv(r))try{let e=Cg(r);if(e.type==="Ed25519")return new is({multihash:r,publicKey:e});if(e.type==="secp256k1")return new as({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new cs(new URL(t))}throw new Ys("Supplied PeerID Multihash is invalid")}function us(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==yv&&r.code!==Tg)throw new Xs("Supplied PeerID CID is invalid");if(r.code===Tg){let e=z(r.multihash.digest);return new cs(new URL(e))}return In(r.multihash)}function bv(r){return r.code===rt.code}function wv(r){return r.code===on.code}async function Dg(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return r}function zi(r,e){if(typeof r=="string")return xv(r);if(typeof r=="number")return Sv(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function xv(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw new Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function Ev(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function vv(r){let e=Math.abs(r);return e>=315576e5?Dr(r,e,315576e5,"year"):e>=26298e5?Dr(r,e,26298e5,"month"):e>=6048e5?Dr(r,e,6048e5,"week"):e>=864e5?Dr(r,e,864e5,"day"):e>=36e5?Dr(r,e,36e5,"hour"):e>=6e4?Dr(r,e,6e4,"minute"):e>=1e3?Dr(r,e,1e3,"second"):`${r} ms`}function Sv(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?vv(r):Ev(r)}function Dr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function af(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=zi,t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l,f){let d,h=null,p,g;function m(...y){if(!m.enabled)return;let w=m,x=Number(new Date),_=x-(d||x);w.diff=_,w.prev=d,w.curr=x,d=x,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let A=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(I,v)=>{if(I==="%%")return"%";A++;let O=t.formatters[v];if(typeof O=="function"){let Y=y[A];I=O.call(w,Y),y.splice(A,1),A--}return I}),t.formatArgs.call(w,y),f?.onLog!=null&&f.onLog(...y),(w.log||t.log).apply(w,y)}return m.namespace=l,m.useColors=t.useColors(),m.color=t.selectColor(l),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,g=t.enabled(l)),g),set:y=>{h=y}}),typeof t.init=="function"&&t.init(m),m}function n(l,f){let d=t(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){t.save(l),t.namespaces=l,t.names=[],t.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]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(l))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.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 t.setupFormatters(t.formatters),t.enable(t.load()),t}var qi=Dv(),Av=["#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 _v(){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 Cv(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+zi(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var Iv=console.debug??console.log??(()=>{});function Tv(r){try{r?qi?.setItem("debug",r):qi?.removeItem("debug")}catch{}}function Lv(){let r;try{r=qi?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Dv(){try{return localStorage}catch{}}function Pv(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Pg=af({formatArgs:Cv,save:Tv,load:Lv,useColors:_v,setupFormatters:Pv,colors:Av,storage:qi,log:Iv});var Ve=Pg;Ve.formatters.b=r=>r==null?"undefined":re.baseEncode(r);Ve.formatters.t=r=>r==null?"undefined":Ze.baseEncode(r);Ve.formatters.m=r=>r==null?"undefined":fu.baseEncode(r);Ve.formatters.p=r=>r==null?"undefined":r.toString();Ve.formatters.c=r=>r==null?"undefined":r.toString();Ve.formatters.k=r=>r==null?"undefined":r.toString();Ve.formatters.a=r=>r==null?"undefined":r.toString();function kg(r,e=""){let t=Rg(r.message),n=Rg(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
2
+ "use strict";var Libp2P=(()=>{var Fg=Object.create;var ps=Object.defineProperty;var Bg=Object.getOwnPropertyDescriptor;var Ug=Object.getOwnPropertyNames;var Kg=Object.getPrototypeOf,qg=Object.prototype.hasOwnProperty;var Hn=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},te=(r,e)=>{for(var t in e)ps(r,t,{get:e[t],enumerable:!0})},cd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ug(e))!qg.call(r,o)&&o!==t&&ps(r,o,{get:()=>e[o],enumerable:!(n=Bg(e,o))||n.enumerable});return r};var rc=(r,e,t)=>(t=r!=null?Fg(Kg(r)):{},cd(e||!r||!r.__esModule?ps(t,"default",{value:r,enumerable:!0}):t,r)),zg=r=>cd(ps({},"__esModule",{value:!0}),r);var nu=Hn(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.Netmask4Impl=void 0;mn.ip2long=pn;mn.long2ip=bt;function bt(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var Xb=48,Zb=97,Qb=65;function Jb(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-Xb)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-Zb)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-Qb)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[e,o]}function pn(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=Jb(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var ru=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=pn(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(pn(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=bt(this.netLong),this.mask=bt(this.maskLong),this.hostmask=bt(~this.maskLong),this.first=this.bitmask<=30?bt(this.netLong+1):this.base,this.last=this.bitmask<=30?bt(this.netLong+this.size-2):bt(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?bt(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(pn(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(bt(this.netLong+this.size*e),this.mask)}forEach(e){let t=pn(this.first),n=pn(this.last),o=0;for(;t<=n;)e(bt(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};mn.Netmask4Impl=ru});var Fp=Hn(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.Netmask6Impl=void 0;gn.ip6bigint=su;gn.bigint2ip6=Cr;var ew=nu(),ou=(1n<<128n)-1n;function su(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,ew.ip2long)(n),s=r.substring(0,t+1)+"0:0";return Mp(s)&~0xffffffffn|BigInt(o)}return Mp(r)}function Mp(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),s=r.substring(e+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let s=t[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function Cr(r){if(r<0n||r>ou)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)e[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(t=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(t=o,n=s),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var iu=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=ou>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=su(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Cr(this.netBigint),this.mask=Cr(this.maskBigint),this.hostmask=Cr(~this.maskBigint&ou),this.first=this.base,this.last=Cr(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(su(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(Cr(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;t<=o;)e(Cr(t),Number(t),s),s++,t++}toString(){return this.base+"/"+this.bitmask}};gn.Netmask6Impl=iu});var Bp=Hn(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.long2ip=er.ip2long=er.Netmask=void 0;var fi=nu();Object.defineProperty(er,"ip2long",{enumerable:!0,get:function(){return fi.ip2long}});Object.defineProperty(er,"long2ip",{enumerable:!0,get:function(){return fi.long2ip}});var tw=Fp(),au=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new tw.Netmask6Impl(e,t):this._impl=new fi.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof fi.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};er.Netmask=au});var Xm=Hn((R3,mf)=>{"use strict";var qx=Object.prototype.hasOwnProperty,Ue="~";function os(){}Object.create&&(os.prototype=Object.create(null),new os().__proto__||(Ue=!1));function zx(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ym(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new zx(t,n||r,o),i=Ue?Ue+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Na(r,e){--r._eventsCount===0?r._events=new os:delete r._events[e]}function ke(){this._events=new os,this._eventsCount=0}ke.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)qx.call(t,n)&&e.push(Ue?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};ke.prototype.listeners=function(e){var t=Ue?Ue+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};ke.prototype.listenerCount=function(e){var t=Ue?Ue+e:e,n=this._events[t];return n?n.fn?1:n.length:0};ke.prototype.emit=function(e,t,n,o,s,i){var a=Ue?Ue+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};ke.prototype.on=function(e,t,n){return Ym(this,e,t,n,!1)};ke.prototype.once=function(e,t,n){return Ym(this,e,t,n,!0)};ke.prototype.removeListener=function(e,t,n,o){var s=Ue?Ue+e:e;if(!this._events[s])return this;if(!t)return Na(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Na(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Na(this,s)}return this};ke.prototype.removeAllListeners=function(e){var t;return e?(t=Ue?Ue+e:e,this._events[t]&&Na(this,t)):(this._events=new os,this._eventsCount=0),this};ke.prototype.off=ke.prototype.removeListener;ke.prototype.addListener=ke.prototype.on;ke.prefixed=Ue;ke.EventEmitter=ke;typeof mf<"u"&&(mf.exports=ke)});var Ag=Hn((GP,Sg)=>{Sg.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Av={};te(Av,{createLibp2p:()=>Ev,dnsaddrResolver:()=>Br,isLibp2p:()=>Sv});var ld=Symbol.for("@libp2p/connection");var nc=Symbol.for("@libp2p/content-routing");var Je=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var R=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Kr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Wn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var sr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var ir=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},qr=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Bt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},ms=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},gs=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},ys=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},bs=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var ws=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},vt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var zr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var jn=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},xs=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Es=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ut=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var vs=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var oc=Symbol.for("@libp2p/peer-discovery");var Ss=Symbol.for("@libp2p/peer-id");function Kt(r){return!!r?.[Ss]}var sc=Symbol.for("@libp2p/peer-routing");var ic="keep-alive";function As(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ud(...r){let e=[];for(let t of r)As(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function fd(...r){let e=[];for(let t of r)As(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Gn;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Gn||(Gn={}));function $g(r){return typeof r?.handleEvent=="function"}function Vg(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Re=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Vg(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(i.type,a))}$g(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Yn=Symbol.for("@libp2p/service-capabilities"),ac=Symbol.for("@libp2p/service-dependencies");var dc={};te(dc,{base58btc:()=>re,base58flickr:()=>Qg});var c1=new Uint8Array(0);function dd(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function St(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return ar(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return ar(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function hd(r){return new TextEncoder().encode(r)}function pd(r){return new TextDecoder().decode(r)}function Hg(r){return r?.buffer instanceof ArrayBuffer}function ar(r){return Hg(r)?r:r.slice()}function Wg(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=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,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var v=(w-y)*u+1>>>0,T=new Uint8Array(v);y!==w;){for(var I=p[y],M=0,L=v-1;(I!==0||M<m)&&L!==-1;L--,M++)I+=256*T[L]>>>0,T[L]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");m=M,y++}for(var _=v-m;_!==v&&T[_]===0;)_++;for(var B=c.repeat(g);_<v;++_)B+=r.charAt(T[_]);return B}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,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*l+1>>>0,v=new Uint8Array(w);p[g];){var T=t[p.charCodeAt(g)];if(T===255)return;for(var I=0,M=w-1;(T!==0||I<y)&&M!==-1;M--,I++)T+=a*v[M]>>>0,v[M]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");y=I,g++}if(p[g]!==" "){for(var L=w-y;L!==w&&v[L]===0;)L++;for(var _=new Uint8Array(m+(w-L)),B=m;L!==w;)_[B++]=v[L++];return _}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var jg=Wg,Gg=jg,gd=Gg;var cc=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},lc=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return yd(this,e)}},uc=class{decoders;constructor(e){this.decoders=e}or(e){return yd(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function yd(r,e){return new uc({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var fc=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new cc(e,t,n),this.decoder=new lc(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function $r({name:r,prefix:e,encode:t,decode:n}){return new fc(r,e,t,n)}function qt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=gd(t,r);return $r({prefix:e,name:r,encode:n,decode:s=>St(o(s))})}function Yg(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Xg(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Zg(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ce({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Zg(n);return $r({prefix:e,name:r,encode(s){return Xg(s,n,t)},decode(s){return Yg(s,o,t,r)}})}var re=qt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Qg=qt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var hc={};te(hc,{base32:()=>Ge,base32hex:()=>r0,base32hexpad:()=>o0,base32hexpadupper:()=>s0,base32hexupper:()=>n0,base32pad:()=>e0,base32padupper:()=>t0,base32upper:()=>Jg,base32z:()=>i0});var Ge=ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Jg=ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),e0=ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),t0=ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),r0=ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),n0=ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),o0=ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),s0=ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),i0=ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var pc={};te(pc,{base36:()=>Xn,base36upper:()=>a0});var Xn=qt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),a0=qt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var c0=xd,bd=128,l0=127,u0=~l0,f0=Math.pow(2,31);function xd(r,e,t){e=e||[],t=t||0;for(var n=t;r>=f0;)e[t++]=r&255|bd,r/=128;for(;r&u0;)e[t++]=r&255|bd,r>>>=7;return e[t]=r|0,xd.bytes=t-n+1,e}var d0=mc,h0=128,wd=127;function mc(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw mc.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&wd)<<o:(i&wd)*Math.pow(2,o),o+=7}while(i>=h0);return mc.bytes=s-n,t}var p0=Math.pow(2,7),m0=Math.pow(2,14),g0=Math.pow(2,21),y0=Math.pow(2,28),b0=Math.pow(2,35),w0=Math.pow(2,42),x0=Math.pow(2,49),E0=Math.pow(2,56),v0=Math.pow(2,63),S0=function(r){return r<p0?1:r<m0?2:r<g0?3:r<y0?4:r<b0?5:r<w0?6:r<x0?7:r<E0?8:r<v0?9:10},A0={encode:c0,decode:d0,encodingLength:S0},_0=A0,Zn=_0;function Qn(r,e=0){return[Zn.decode(r,e),Zn.decode.bytes]}function Vr(r,e,t=0){return Zn.encode(r,e,t),e}function Hr(r){return Zn.encodingLength(r)}function dt(r,e){let t=e.byteLength,n=Hr(r),o=n+Hr(t),s=new Uint8Array(o+t);return Vr(r,s,0),Vr(t,s,n),s.set(e,o),new Wr(r,t,e,s)}function At(r){let e=St(r),[t,n]=Qn(e),[o,s]=Qn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Wr(t,o,i,e)}function Ed(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&dd(r.bytes,t.bytes)}}var Wr=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=ar(n),this.bytes=ar(o)}};function vd(r,e){let{bytes:t,version:n}=r;return n===0?I0(t,gc(r),e??re.encoder):T0(t,gc(r),e??Ge.encoder)}var Sd=new WeakMap;function gc(r){let e=Sd.get(r);if(e==null){let t=new Map;return Sd.set(r,t),t}return e}var de=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=ar(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Jn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==L0)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=dt(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Ed(e.multihash,n.multihash)}toString(e){return vd(this,e)}toJSON(){return{"/":vd(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Ad(n,o,s.bytes))}else if(t[P0]===!0){let{version:n,multihash:o,code:s}=t,i=At(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Jn)throw new Error(`Version 0 CID must use dag-pb (code: ${Jn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Ad(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Jn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=St(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Wr(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Qn(e.subarray(t));return t+=d,f},o=n(),s=Jn;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=C0(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gc(s).set(n,e),s}};function C0(r,e){switch(r[0]){case"Q":{let t=e??re;return[re.prefix,t.decode(`${re.prefix}${r}`)]}case re.prefix:{let t=e??re;return[re.prefix,t.decode(r)]}case Ge.prefix:{let t=e??Ge;return[Ge.prefix,t.decode(r)]}case Xn.prefix:{let t=e??Xn;return[Xn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function I0(r,e,t){let{prefix:n}=t;if(n!==re.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function T0(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Jn=112,L0=18;function Ad(r,e,t){let n=Hr(r),o=n+Hr(e),s=new Uint8Array(o+t.byteLength);return Vr(r,s,0),Vr(e,s,n),s.set(t,o),s}var P0=Symbol.for("@ipld/js-cid/CID");var yc={};te(yc,{identity:()=>et});var _d=0,D0="identity",Cd=St;function k0(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return dt(_d,Cd(r))}var et={code:_d,name:D0,encode:Cd,digest:k0};function X(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function R0(r){return r.buffer instanceof ArrayBuffer}function Se(r){return R0(r)?r:r.slice()}async function Id(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function Td(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,Se(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Ld(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Se(e),Se(t.subarray()));return n?.signal?.throwIfAborted(),s}function ie(r=0){return new Uint8Array(r)}function be(r=0){return new Uint8Array(r)}function O0(r){return r?.buffer instanceof ArrayBuffer}function bc(r){if(O0(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ye(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=be(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return bc(t)}var Dd=Symbol.for("@achingbrain/uint8arraylist");function Pd(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Cs(r){return!!r?.[Dd]}var J=class r{bufs;length;[Dd]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Cs(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Cs(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Pd(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Pd(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Cs(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Ye(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ye(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Cs(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let 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,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=be(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ie(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=be(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ie(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!X(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var wc={};te(wc,{base10:()=>N0});var N0=qt({prefix:"9",name:"base10",alphabet:"0123456789"});var xc={};te(xc,{base16:()=>M0,base16upper:()=>F0});var M0=ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),F0=ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ec={};te(Ec,{base2:()=>B0});var B0=ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var vc={};te(vc,{base256emoji:()=>$0});var kd=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}"),U0=kd.reduce((r,e,t)=>(r[t]=e,r),[]),K0=kd.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function q0(r){return r.reduce((e,t)=>(e+=U0[t],e),"")}function z0(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=K0[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var $0=$r({prefix:"\u{1F680}",name:"base256emoji",encode:q0,decode:z0});var _c={};te(_c,{base64:()=>Sc,base64pad:()=>V0,base64url:()=>Ac,base64urlpad:()=>H0});var Sc=ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),V0=ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ac=ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),H0=ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Cc={};te(Cc,{base8:()=>W0});var W0=ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ic={};te(Ic,{identity:()=>j0});var j0=$r({prefix:"\0",name:"identity",encode:r=>pd(r),decode:r=>hd(r)});var j1=new TextEncoder,G1=new TextDecoder;var Pc={};te(Pc,{sha256:()=>jr,sha512:()=>Z0});var X0=20;function Lc({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Tc(r,e,t,n,o)}var Tc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??X0,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Rd(n,this.code,t?.truncate):n.then(o=>Rd(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Rd(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return dt(e,r)}function Nd(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var jr=Lc({name:"sha2-256",code:18,encode:Nd("SHA-256")}),Z0=Lc({name:"sha2-512",code:19,encode:Nd("SHA-512")});var eo={...Ic,...Ec,...Cc,...wc,...xc,...hc,...pc,...dc,..._c,...vc},i2={...Pc,...yc};function Fd(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Md=Fd("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Dc=Fd("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=be(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Q0={utf8:Md,"utf-8":Md,hex:eo.base16,latin1:Dc,ascii:Dc,binary:Dc,...eo},Is=Q0;function k(r,e="utf8"){let t=Is[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function K(r,e="utf8"){let t=Is[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var J0=parseInt("11111",2),kc=parseInt("10000000",2),ey=parseInt("01111111",2),Bd={0:to,1:to,2:ty,3:oy,4:sy,5:ny,6:ry,16:to,22:to,48:to};function _t(r,e={offset:0}){let t=r[e.offset]&J0;if(e.offset++,Bd[t]!=null)return Bd[t](r,e);throw new Error("No decoder for tag "+t)}function ro(r,e){let t=0;if((r[e.offset]&kc)===kc){let n=r[e.offset]&ey,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function to(r,e){ro(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=_t(r,e);if(n===null)break;t.push(n)}return t}function ty(r,e){let t=ro(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function ry(r,e){let t=ro(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function ny(r,e){return e.offset++,null}function oy(r,e){let t=ro(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function sy(r,e){let t=ro(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function iy(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new J;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Ts(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=iy(r.byteLength);return new J(Uint8Array.from([e.byteLength|kc]),e)}function Oe(r){let e=new J,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new J(Uint8Array.from([2]),Ts(e),e)}function no(r){let e=Uint8Array.from([0]),t=new J(e,r);return new J(Uint8Array.from([3]),Ts(t),t)}function Ud(r){return new J(Uint8Array.from([4]),Ts(r),r)}function tt(r,e=48){let t=new J;for(let n of r)t.append(n);return new J(Uint8Array.from([e]),Ts(t),t)}var ay=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),cy=Uint8Array.from([6,5,43,129,4,0,34]),ly=Uint8Array.from([6,5,43,129,4,0,35]),uy={ext:!0,kty:"EC",crv:"P-256"},fy={ext:!0,kty:"EC",crv:"P-384"},dy={ext:!0,kty:"EC",crv:"P-521"},Rc=32,Oc=48,Nc=66;function Mc(r){let e=_t(r);return Kd(e)}function Kd(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Rc*2+1)return n=K(e.subarray(t,t+Rc),"base64url"),o=K(e.subarray(t+Rc),"base64url"),new cr({...uy,key_ops:["verify"],x:n,y:o});if(e.byteLength===Oc*2+1)return n=K(e.subarray(t,t+Oc),"base64url"),o=K(e.subarray(t+Oc),"base64url"),new cr({...fy,key_ops:["verify"],x:n,y:o});if(e.byteLength===Nc*2+1)return n=K(e.subarray(t,t+Nc),"base64url"),o=K(e.subarray(t+Nc),"base64url"),new cr({...dy,key_ops:["verify"],x:n,y:o});throw new R(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function qd(r){return tt([Oe(Uint8Array.from([1])),Ud(k(r.d??"","base64url")),tt([$d(r.crv)],160),tt([no(new J(Uint8Array.from([4]),k(r.x??"","base64url"),k(r.y??"","base64url")))],161)]).subarray()}function zd(r){return tt([Oe(Uint8Array.from([1])),tt([$d(r.crv)],160),tt([no(new J(Uint8Array.from([4]),k(r.x??"","base64url"),k(r.y??"","base64url")))],161)]).subarray()}function $d(r){if(r==="P-256")return ay;if(r==="P-384")return cy;if(r==="P-521")return ly;throw new R(`Invalid curve ${r}`)}async function Vd(r="P-256"){let e=await Id(r);return new Ls(e.privateKey)}var cr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=zd(this.jwk)),this._raw}toMultihash(){return et.digest(Xe(this))}toCID(){return de.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}async verify(e,t,n){return Ld(this.jwk,t,e,n)}},Ls=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new cr({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=qd(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}async sign(e,t){return Td(this.jwk,e,t)}};function Fc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function $t(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function $e(r,e,t=""){let n=Fc(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function Ps(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if($t(r.outputLen),$t(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Gr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Ds(r,e){$e(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function It(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ks(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function rt(r,e){return r<<32-e|r>>>e}var Wd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hy=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Rs(r){if($e(r),Wd)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=hy[r[t]];return e}var Ct={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hd(r){if(r>=Ct._0&&r<=Ct._9)return r-Ct._0;if(r>=Ct.A&&r<=Ct.F)return r-(Ct.A-10);if(r>=Ct.a&&r<=Ct.f)return r-(Ct.a-10)}function oo(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Wd)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Hd(r.charCodeAt(s)),a=Hd(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Bc(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];$e(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Uc(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function jd(r=32){$t(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var Kc=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Gd(r,e,t){return r&e^~r&t}function Yd(r,e,t){return r&e^r&t^e&t}var so=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ks(this.buffer)}update(e){Gr(this),$e(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=ks(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Gr(this),Ds(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,It(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=ks(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Tt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Os=BigInt(4294967295),Xd=BigInt(32);function py(r,e=!1){return e?{h:Number(r&Os),l:Number(r>>Xd&Os)}:{h:Number(r>>Xd&Os)|0,l:Number(r&Os)|0}}function Zd(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=py(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var qc=(r,e,t)=>r>>>t,zc=(r,e,t)=>r<<32-t|e>>>t,lr=(r,e,t)=>r>>>t|e<<32-t,ur=(r,e,t)=>r<<32-t|e>>>t,io=(r,e,t)=>r<<64-t|e>>>t-32,ao=(r,e,t)=>r>>>t-32|e<<64-t;function ht(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Qd=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Jd=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,eh=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),th=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,rh=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),nh=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var gy=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]),Vt=new Uint32Array(64),$c=class extends so{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Vt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Vt[f-15],h=Vt[f-2],p=rt(d,7)^rt(d,18)^d>>>3,g=rt(h,17)^rt(h,19)^h>>>10;Vt[f]=g+Vt[f-7]+p+Vt[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=rt(a,6)^rt(a,11)^rt(a,25),h=u+d+Gd(a,c,l)+gy[f]+Vt[f]|0,g=(rt(n,2)^rt(n,13)^rt(n,22))+Yd(n,o,s)|0;u=l,l=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,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){It(Vt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),It(this.buffer)}},Vc=class extends $c{A=Tt[0]|0;B=Tt[1]|0;C=Tt[2]|0;D=Tt[3]|0;E=Tt[4]|0;F=Tt[5]|0;G=Tt[6]|0;H=Tt[7]|0;constructor(){super(32)}};var oh=Zd(["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))),yy=oh[0],by=oh[1],Ht=new Uint32Array(80),Wt=new Uint32Array(80),Hc=class extends so{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,h,p,g,m]}set(e,t,n,o,s,i,a,c,l,u,f,d,h,p,g,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|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(e,t){for(let v=0;v<16;v++,t+=4)Ht[v]=e.getUint32(t),Wt[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){let T=Ht[v-15]|0,I=Wt[v-15]|0,M=lr(T,I,1)^lr(T,I,8)^qc(T,I,7),L=ur(T,I,1)^ur(T,I,8)^zc(T,I,7),_=Ht[v-2]|0,B=Wt[v-2]|0,Y=lr(_,B,19)^io(_,B,61)^qc(_,B,6),q=ur(_,B,19)^ao(_,B,61)^zc(_,B,6),b=eh(L,q,Wt[v-7],Wt[v-16]),x=th(b,M,Y,Ht[v-7],Ht[v-16]);Ht[v]=x|0,Wt[v]=b|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:y,Hl:w}=this;for(let v=0;v<80;v++){let T=lr(f,d,14)^lr(f,d,18)^io(f,d,41),I=ur(f,d,14)^ur(f,d,18)^ao(f,d,41),M=f&h^~f&g,L=d&p^~d&m,_=rh(w,I,L,by[v],Wt[v]),B=nh(_,y,T,M,yy[v],Ht[v]),Y=_|0,q=lr(n,o,28)^io(n,o,34)^io(n,o,39),b=ur(n,o,28)^ao(n,o,34)^ao(n,o,39),x=n&s^n&a^s&a,A=o&i^o&c^i&c;y=g|0,w=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=ht(l|0,u|0,B|0,Y|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let S=Qd(Y,b,A);n=Jd(S,B,q,x),o=S|0}({h:n,l:o}=ht(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ht(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ht(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ht(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ht(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ht(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=ht(this.Gh|0,this.Gl|0,g|0,m|0),{h:y,l:w}=ht(this.Hh|0,this.Hl|0,y|0,w|0),this.set(n,o,s,i,a,c,l,u,f,d,h,p,g,m,y,w)}roundClean(){It(Ht,Wt)}destroy(){this.destroyed=!0,It(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Wc=class extends Hc{Ah=Ae[0]|0;Al=Ae[1]|0;Bh=Ae[2]|0;Bl=Ae[3]|0;Ch=Ae[4]|0;Cl=Ae[5]|0;Dh=Ae[6]|0;Dl=Ae[7]|0;Eh=Ae[8]|0;El=Ae[9]|0;Fh=Ae[10]|0;Fl=Ae[11]|0;Gh=Ae[12]|0;Gl=Ae[13]|0;Hh=Ae[14]|0;Hl=Ae[15]|0;constructor(){super(64)}};var Yr=Uc(()=>new Vc,Kc(1));var Ns=Uc(()=>new Wc,Kc(3));var H=(r,e,t)=>$e(r,e,t),Gc=$t,Xr=Rs,me=(...r)=>Bc(...r),Zr=r=>oo(r),fr=Fc,co=r=>jd(r),Fs=BigInt(0),jc=BigInt(1);function nt(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Bs(r){if(typeof r=="bigint"){if(!Ms(r))throw new RangeError("positive bigint expected, got "+r)}else Gc(r);return r}function ot(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function lo(r){let e=Bs(r).toString(16);return e.length&1?"0"+e:e}function sh(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Fs:BigInt("0x"+r)}function dr(r){return sh(Rs(r))}function pt(r){return sh(Rs(uo($e(r)).reverse()))}function Us(r,e){if($t(e),e===0)throw new RangeError("zero length");r=Bs(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return oo(t.padStart(e*2,"0"))}function Yc(r,e){return Us(r,e).reverse()}function ih(r,e){if(r=H(r),e=H(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function uo(r){return Uint8Array.from(H(r))}function Ks(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Ms=r=>typeof r=="bigint"&&Fs<=r;function wy(r,e,t){return Ms(r)&&Ms(e)&&Ms(t)&&e<=r&&r<t}function Qr(r,e,t,n){if(!wy(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Jr(r){if(r<Fs)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Fs;r>>=jc,e+=1);return e}var fo=r=>(jc<<BigInt(r))-jc;function ah(r,e,t){if($t(r,"hashLen"),$t(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},d=(...m)=>t(l,me(c,...m)),h=(m=o)=>{l=d(s,m),c=d(),m.length!==0&&(l=d(i,m),c=d())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,y=[];for(;m<e;){c=d();let w=c.slice();y.push(w),m+=c.length}return me(...y)};return(m,y)=>{f(),h(m);let w;for(;(w=y(p()))===void 0;)h();return f(),w}}function st(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}var Xc=()=>{throw new Error("not implemented")};var _e=BigInt(0),le=BigInt(1),hr=BigInt(2),fh=BigInt(3),dh=BigInt(4),hh=BigInt(5),xy=BigInt(7),ph=BigInt(8),Ey=BigInt(9),mh=BigInt(16);function he(r,e){if(e<=_e)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=_e?t:e+t}function se(r,e,t){if(e<_e)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >_e;)n*=n,n%=t;return n}function ch(r,e){if(r===_e)throw new Error("invert: expected non-zero number");if(e<=_e)throw new Error("invert: expected positive modulus, got "+e);let t=he(r,e),n=e,o=_e,s=le,i=le,a=_e;for(;t!==_e;){let l=n/t,u=n-t*l,f=o-i*l,d=s-a*l;n=t,t=u,o=i,s=a,i=f,a=d}if(n!==le)throw new Error("invert: does not exist");return he(o,e)}function Zc(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function gh(r,e){let t=r,n=(t.ORDER+le)/dh,o=t.pow(e,n);return Zc(t,o,e),o}function vy(r,e){let t=r,n=(t.ORDER-hh)/ph,o=t.mul(e,hr),s=t.pow(o,n),i=t.mul(e,s),a=t.mul(t.mul(i,hr),s),c=t.mul(i,t.sub(a,t.ONE));return Zc(t,c,e),c}function Sy(r){let e=en(r),t=yh(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+xy)/mh;return((a,c)=>{let l=a,u=l.pow(c,i),f=l.mul(u,n),d=l.mul(u,o),h=l.mul(u,s),p=l.eql(l.sqr(f),c),g=l.eql(l.sqr(d),c);u=l.cmov(u,f,p),f=l.cmov(h,d,g);let m=l.eql(l.sqr(f),c),y=l.cmov(u,f,m);return Zc(l,y,c),y})}function yh(r){if(r<fh)throw new Error("sqrt is not defined for small field");let e=r-le,t=0;for(;e%hr===_e;)e/=hr,t++;let n=hr,o=en(r);for(;lh(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return gh;let s=o.pow(n,e),i=(e+le)/hr;return function(c,l){let u=c;if(u.is0(l))return l;if(lh(u,l)!==1)throw new Error("Cannot find square root");let f=t,d=u.mul(u.ONE,s),h=u.pow(l,e),p=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let g=1,m=u.sqr(h);for(;!u.eql(m,u.ONE);)if(g++,m=u.sqr(m),g===f)throw new Error("Cannot find square root");let y=le<<BigInt(f-g-1),w=u.pow(d,y);f=g,d=u.sqr(w),h=u.mul(h,d),p=u.mul(p,w)}return p}}function Ay(r){return r%dh===fh?gh:r%ph===hh?vy:r%mh===Ey?Sy(r):yh(r)}var Lt=(r,e)=>(he(r,e)&le)===le,_y=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Qc(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=_y.reduce((n,o)=>(n[o]="function",n),e);if(st(r,t),ot(r.BYTES,"BYTES"),ot(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=le)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Cy(r,e,t){let n=r;if(t<_e)throw new Error("invalid exponent, negatives unsupported");if(t===_e)return n.ONE;if(t===le)return e;let o=n.ONE,s=e;for(;t>_e;)t&le&&(o=n.mul(o,s)),s=n.sqr(s),t>>=le;return o}function ho(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function lh(r,e){let t=r,n=(t.ORDER-le)/hr,o=t.pow(e,n),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Iy(r,e){if(e!==void 0&&Gc(e),r<=_e)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Jr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var uh=new WeakMap,qs=class{ORDER;BITS;BYTES;isLE;ZERO=_e;ONE=le;_lengths;_mod;constructor(e,t={}){if(e<=le)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=Iy(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return he(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return _e<=e&&e<this.ORDER}is0(e){return e===_e}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&le)===le}neg(e){return he(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return he(e*e,this.ORDER)}add(e,t){return he(e+t,this.ORDER)}sub(e,t){return he(e-t,this.ORDER)}mul(e,t){return he(e*t,this.ORDER)}pow(e,t){return Cy(this,e,t)}div(e,t){return he(e*ch(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return ch(e,this.ORDER)}sqrt(e){let t=uh.get(this);return t||uh.set(this,t=Ay(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Yc(e,this.BYTES):Us(e,this.BYTES)}fromBytes(e,t=!1){H(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?pt(e):dr(e);if(a&&(c=he(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ho(this,e)}cmov(e,t,n){return nt(n,"condition"),n?t:e}};Object.freeze(qs.prototype);function en(r,e={}){return new qs(r,e)}function bh(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=le)throw new Error("field order must be greater than 1");let e=Jr(r-le);return Math.ceil(e/8)}function Jc(r){let e=bh(r);return e+Math.ceil(e/2)}function el(r,e,t=!1){H(r);let n=r.length,o=bh(e),s=Math.max(Jc(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?pt(r):dr(r),a=he(i,e-le)+le;return t?Yc(a,o):Us(a,o)}var tn=BigInt(0),pr=BigInt(1);function po(r,e){let t=e.negate();return r?t:e}function mr(r,e){let t=ho(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function vh(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function tl(r,e){vh(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=fo(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function wh(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=pr);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}var rl=new WeakMap,Sh=new WeakMap;function nl(r){return Sh.get(r)||1}function xh(r){if(r!==tn)throw new Error("invalid wNAF")}var rn=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>tn;)t&pr&&(n=n.add(o)),o=o.double(),t>>=pr;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=tl(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=tl(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=wh(n,a,i);n=c,u?s=s.add(po(d,t[h])):o=o.add(po(f,t[l]))}return xh(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=tl(e,this.bits);for(let i=0;i<s.windows&&n!==tn;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=wh(n,i,s);if(n=a,!l){let f=t[c];o=o.add(u?f.negate():f)}}return xh(n),o}getPrecomputes(e,t,n){let o=rl.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),rl.set(t,o))),o}cached(e,t,n){let o=nl(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=nl(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){vh(t,this.bits),Sh.set(e,t),rl.delete(e)}hasCache(e){return nl(e)!==1}};function Ah(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>tn||n>tn;)t&pr&&(s=s.add(o)),n&pr&&(i=i.add(o)),o=o.double(),t>>=pr,n>>=pr;return{p1:s,p2:i}}function Eh(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Qc(e),e}else return en(r,{isLE:t})}function zs(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>tn))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Eh(e.p,t.Fp,n),s=Eh(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function $s(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var jt=BigInt(0),we=BigInt(1),ol=BigInt(2),Ty=BigInt(8);function Ly(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function _h(r,e={}){let t=e,n=zs("edwards",r,t,t.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;st(t,{},{uvRatio:"function"});let c=ol<<BigInt(s.BYTES*8)-we,l=g=>o.create(g),u=t.uvRatio===void 0?(g,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(g,m))}}catch{return{isValid:!1,value:jt}}}:t.uvRatio;if(!Ly(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function f(g,m,y=!1){let w=y?we:jt;return Qr("coordinate "+g,m,w,c),m}function d(g){if(!(g instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(i.Gx,i.Gy,we,l(i.Gx*i.Gy));static ZERO=new h(jt,we,we,jt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(m,y,w,v){this.X=f("x",m),this.Y=f("y",y),this.Z=f("z",w,!0),this.T=f("t",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:y,y:w}=m||{};return f("x",y),f("y",w),new h(y,w,we,l(y*w))}static fromBytes(m,y=!1){let w=o.BYTES,{a:v,d:T}=i;m=uo(H(m,w,"point")),nt(y,"zip215");let I=uo(m),M=m[w-1];I[w-1]=M&-129;let L=pt(I),_=y?c:o.ORDER;Qr("point.y",L,jt,_);let B=l(L*L),Y=l(B-we),q=l(T*B-v),{isValid:b,value:x}=u(Y,q);if(!b)throw new Error("bad point: invalid y coordinate");let A=(x&we)===we,S=(M&128)!==0;if(!y&&x===jt&&S)throw new Error("bad point: x=0 and x_0=1");return S!==A&&(x=l(-x)),h.fromAffine({x,y:L})}static fromHex(m,y=!1){return h.fromBytes(Zr(m),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return p.createCache(this,m),y||this.multiply(ol),this}assertValidity(){let m=this,{a:y,d:w}=i;if(m.is0())throw new Error("bad point: ZERO");let{X:v,Y:T,Z:I,T:M}=m,L=l(v*v),_=l(T*T),B=l(I*I),Y=l(B*B),q=l(L*y),b=l(B*l(q+_)),x=l(Y+l(w*l(L*_)));if(b!==x)throw new Error("bad point: equation left != right (1)");let A=l(v*T),S=l(I*M);if(A!==S)throw new Error("bad point: equation left != right (2)")}equals(m){d(m);let{X:y,Y:w,Z:v}=this,{X:T,Y:I,Z:M}=m,L=l(y*M),_=l(T*v),B=l(w*M),Y=l(I*v);return L===_&&B===Y}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:m}=i,{X:y,Y:w,Z:v}=this,T=l(y*y),I=l(w*w),M=l(ol*l(v*v)),L=l(m*T),_=y+w,B=l(l(_*_)-T-I),Y=L+I,q=Y-M,b=L-I,x=l(B*q),A=l(Y*b),S=l(B*b),E=l(q*Y);return new h(x,A,E,S)}add(m){d(m);let{a:y,d:w}=i,{X:v,Y:T,Z:I,T:M}=this,{X:L,Y:_,Z:B,T:Y}=m,q=l(v*L),b=l(T*_),x=l(M*w*Y),A=l(I*B),S=l((v+T)*(L+_)-q-b),E=A-x,C=A+x,D=l(b-y*q),P=l(S*E),O=l(C*D),F=l(S*D),V=l(E*C);return new h(P,O,V,F)}subtract(m){return d(m),this.add(m.negate())}multiply(m){if(!s.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:w}=p.cached(this,m,v=>mr(h,v));return mr(h,[y,w])[0]}multiplyUnsafe(m){if(!s.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===jt?h.ZERO:this.is0()||m===we?this:p.unsafe(this,m,y=>mr(h,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,i.n).is0()}toAffine(m){let y=this,w=m,{X:v,Y:T,Z:I}=y,M=y.is0();w==null&&(w=M?Ty:o.inv(I));let L=l(v*w),_=l(T*w),B=o.mul(I,w);if(M)return{x:jt,y:we};if(B!==we)throw new Error("invZ was invalid");return{x:L,y:_}}clearCofactor(){return a===we?this:this.multiplyUnsafe(a)}toBytes(){let{x:m,y}=this.toAffine(),w=o.toBytes(y);return w[w.length-1]|=m&we?128:0,w}toHex(){return Xr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new rn(h,s.BITS);return s.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Vs=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Xc()}static fromHex(e){Xc()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Xr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function Ch(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;st(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(ot(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let f=o.randomBytes===void 0?co:o.randomBytes,d=o.adjustScalarBytes===void 0?b=>b:o.adjustScalarBytes,h=o.domain===void 0?(b,x,A)=>{if(nt(A,"phflag"),x.length||A)throw new Error("Contexts/pre-hash are not supported");return b}:o.domain;function p(b){return c.create(pt(b))}function g(b){let x=L.secretKey;H(b,L.secretKey,"secretKey");let A=H(n(b),2*x,"hashedSecretKey"),S=d(A.slice(0,x)),E=A.slice(x,2*x),C=p(S);return{head:S,prefix:E,scalar:C}}function m(b){let{head:x,prefix:A,scalar:S}=g(b),E=i.multiply(S),C=E.toBytes();return{head:x,prefix:A,scalar:S,point:E,pointBytes:C}}function y(b){return m(b).pointBytes}function w(b=Uint8Array.of(),...x){let A=me(...x);return p(n(h(A,H(b,void 0,"context"),!!s)))}function v(b,x,A={}){b=H(b,void 0,"message"),s&&(b=s(b));let{prefix:S,scalar:E,pointBytes:C}=m(x),D=w(A.context,S,b),P=i.multiply(D).toBytes(),O=w(A.context,P,C,b),F=c.create(D+O*E);if(!c.isValid(F))throw new Error("sign failed: invalid s");let V=me(P,c.toBytes(F));return H(V,L.signature,"result")}let T={zip215:o.zip215};function I(b,x,A,S=T){let{context:E}=S,C=S.zip215===void 0?!!T.zip215:S.zip215,D=L.signature;b=H(b,D,"signature"),x=H(x,void 0,"message"),A=H(A,L.publicKey,"publicKey"),C!==void 0&&nt(C,"zip215"),s&&(x=s(x));let P=D/2,O=b.subarray(0,P),F=pt(b.subarray(P,D)),V,G,z;try{V=r.fromBytes(A,C),G=r.fromBytes(O,C),z=i.multiplyUnsafe(F)}catch{return!1}if(!C&&V.isSmallOrder())return!1;let pe=w(E,O,A,x);return G.add(V.multiplyUnsafe(pe)).subtract(z).clearCofactor().is0()}let M=a.BYTES,L={secretKey:M,publicKey:M,signature:2*M,seed:M};function _(b){return b=b===void 0?f(L.seed):b,H(b,L.seed,"seed")}function B(b){return fr(b)&&b.length===L.secretKey}function Y(b,x){try{return!!r.fromBytes(b,x===void 0?T.zip215:x)}catch{return!1}}let q={getExtendedPublicKey:m,randomSecretKey:_,isValidSecretKey:B,isValidPublicKey:Y,toMontgomery(b){let{y:x}=r.fromBytes(b),A=L.publicKey,S=A===32;if(!S&&A!==57)throw new Error("only defined for 25519 and 448");let E=S?a.div(we+x,we-x):a.div(x-we,x+we);return a.toBytes(E)},toMontgomerySecret(b){let x=L.secretKey;H(b,x);let A=n(b.subarray(0,x));return d(A).subarray(0,x)}};return Object.freeze(L),Object.freeze(q),Object.freeze({keygen:$s(_,y),getPublicKey:y,sign:v,verify:I,utils:q,Point:r,lengths:L})}function mo(r,e){if(ot(r),ot(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function Py(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function Dy(r){if(!fr(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Ks(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function sl(r,e,t,n){H(r),ot(t),e=Dy(e),e.length>255&&(e=n(me(Ks("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(t/o);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=me(e,mo(e.length,1)),c=new Uint8Array(s),l=mo(t,2),u=new Array(i),f=n(me(c,r,l,mo(0,1),a));u[0]=n(me(f,mo(1,1),a));for(let h=1;h<i;h++){let p=[Py(f,u[h-1]),mo(h+1,1),a];u[h]=n(me(...p))}return me(...u).slice(0,t)}var Ih="HashToScalar-";var ky=BigInt(0),Pt=BigInt(1),Th=BigInt(2);var Ry=BigInt(5),Oy=BigInt(8),nn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ll={p:nn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Oy,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ny(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=nn,a=r*r%s*r%s,c=se(a,Th,s)*a%s,l=se(c,Pt,s)*r%s,u=se(l,Ry,s)*l%s,f=se(u,e,s)*u%s,d=se(f,t,s)*f%s,h=se(d,n,s)*d%s,p=se(h,o,s)*h%s,g=se(p,o,s)*h%s,m=se(g,e,s)*u%s;return{pow_p_5_8:se(m,Th,s)*r%s,b2:a}}function My(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var il=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ul(r,e){let t=nn,n=he(e*e*e,t),o=he(n*n*e,t),s=Ny(r*o).pow_p_5_8,i=he(r*n*s,t),a=he(e*i*i,t),c=i,l=he(i*il,t),u=a===r,f=a===he(-r,t),d=a===he(-r*il,t);return u&&(i=c),(f||d)&&(i=l),Lt(i,t)&&(i=he(-i,t)),{isValid:u||f,value:i}}var Yt=_h(ll,{uvRatio:ul}),Gt=Yt.Fp,Dh=Yt.Fn;function Fy(r){return Ch(Yt,Ns,Object.assign({adjustScalarBytes:My,zip215:!0},r))}var go=Fy({});var al=il,By=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Uy=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Ky=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),qy=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Lh=r=>ul(Pt,r),zy=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),cl=r=>Gt.create(pt(r)&zy);function Ph(r){let{d:e}=ll,t=nn,n=y=>Gt.create(y),o=n(al*r*r),s=n((o+Pt)*Ky),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:l}=ul(s,a),u=n(l*r);Lt(u,t)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-Pt)*qy-a),d=l*l,h=n((l+l)*a),p=n(f*By),g=n(Pt-d),m=n(Pt+d);return new Yt(n(h*m),n(g*p),n(p*m),n(h*g))}var Xt=class r extends Vs{static BASE=new r(Yt.BASE);static ZERO=new r(Yt.ZERO);static Fp=Gt;static Fn=Dh;constructor(e){super(e)}static fromAffine(e){return new r(Yt.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){$e(e,32);let{a:t,d:n}=ll,o=nn,s=T=>Gt.create(T),i=cl(e);if(!ih(Gt.toBytes(i),e)||Lt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Pt+t*a),l=s(Pt-t*a),u=s(c*c),f=s(l*l),d=s(t*n*u-f),{isValid:h,value:p}=Lh(s(d*f)),g=s(p*l),m=s(p*g*d),y=s((i+i)*g);Lt(y,o)&&(y=s(-y));let w=s(c*m),v=s(y*w);if(!h||Lt(v,o)||w===ky)throw new Error("invalid ristretto255 encoding 2");return new r(new Yt(y,w,Pt,v))}static fromHex(e){return r.fromBytes(oo(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=nn,i=m=>Gt.create(m),a=i(i(n+t)*i(n-t)),c=i(e*t),l=i(c*c),{value:u}=Lh(i(a*l)),f=i(u*a),d=i(u*c),h=i(f*d*o),p;if(Lt(o*h,s)){let m=i(t*al),y=i(e*al);e=m,t=y,p=i(f*Uy)}else p=d;Lt(e*h,s)&&(t=i(-t));let g=i((n-t)*p);return Lt(g,s)&&(g=i(-g)),Gt.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=l=>Gt.create(l),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Xt.BASE);Object.freeze(Xt.ZERO);Object.freeze(Xt.prototype);Object.freeze(Xt);var $y=Object.freeze({Point:Xt,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=sl(r,t,64,Ns);return $y.deriveToCurve(n)},hashToScalar(r,e={DST:Ih}){let t=sl(r,e.DST,64,Ns);return Dh.create(pt(t))},deriveToCurve(r){$e(r,64);let e=cl(r.subarray(0,32)),t=Ph(e),n=cl(r.subarray(32,64)),o=Ph(n);return new Xt(t.add(o))}});var yo=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},bo=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Hs=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var qe={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Hs("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Ws=32,wo=64,fl=32;var on,kh=(async()=>{try{return await qe.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Rh(){let r=go.utils.randomSecretKey(),e=go.getPublicKey(r);return{privateKey:Gy(r,e),publicKey:e}}async function Vy(r,e){let t;r.length===wo?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:K(r.subarray(32),"base64url"),d:K(t,"base64url"),ext:!0,key_ops:["sign"]},o=await qe.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await qe.get().subtle.sign({name:"Ed25519"},o,Se(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(s,0,s.byteLength)}function Hy(r,e){let t=r.subarray(0,fl);return go.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function Oh(r,e){return on==null&&(on=await kh),on?Vy(r,e):Hy(r,e)}async function Wy(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await qe.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await qe.get().subtle.verify({name:"Ed25519"},n,Se(e),Se(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function jy(r,e,t){return go.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Nh(r,e,t){return on==null&&(on=await kh),on?Wy(r,e,t):jy(r,e,t)}function Gy(r,e){let t=new Uint8Array(wo);for(let n=0;n<fl;n++)t[n]=r[n],t[fl+n]=e[n];return t}function sn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var xo=class{type="Ed25519";raw;constructor(e){this.raw=Gs(e,Ws)}toMultihash(){return et.digest(Xe(this))}toCID(){return de.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Nh(this.raw,t,e);return sn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},js=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Gs(e,wo),this.publicKey=new xo(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=Oh(this.raw,e);return sn(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function dl(r){return r=Gs(r,Ws),new xo(r)}async function Fh(){let{privateKey:r,publicKey:e}=Rh();return new js(r,e)}function Gs(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new R(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var Yy=Math.pow(2,7),Xy=Math.pow(2,14),Zy=Math.pow(2,21),hl=Math.pow(2,28),pl=Math.pow(2,35),ml=Math.pow(2,42),gl=Math.pow(2,49),Z=128,Te=127;function xe(r){if(r<Yy)return 1;if(r<Xy)return 2;if(r<Zy)return 3;if(r<hl)return 4;if(r<pl)return 5;if(r<ml)return 6;if(r<gl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function an(r,e,t=0){switch(xe(r)){case 8:e[t++]=r&255|Z,r/=128;case 7:e[t++]=r&255|Z,r/=128;case 6:e[t++]=r&255|Z,r/=128;case 5:e[t++]=r&255|Z,r/=128;case 4:e[t++]=r&255|Z,r>>>=7;case 3:e[t++]=r&255|Z,r>>>=7;case 2:e[t++]=r&255|Z,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Qy(r,e,t=0){switch(xe(r)){case 8:e.set(t++,r&255|Z),r/=128;case 7:e.set(t++,r&255|Z),r/=128;case 6:e.set(t++,r&255|Z),r/=128;case 5:e.set(t++,r&255|Z),r/=128;case 4:e.set(t++,r&255|Z),r>>>=7;case 3:e.set(t++,r&255|Z),r>>>=7;case 2:e.set(t++,r&255|Z),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function yl(r,e){let t=r[e],n=0;if(n+=t&Te,t<Z||(t=r[e+1],n+=(t&Te)<<7,t<Z)||(t=r[e+2],n+=(t&Te)<<14,t<Z)||(t=r[e+3],n+=(t&Te)<<21,t<Z)||(t=r[e+4],n+=(t&Te)*hl,t<Z)||(t=r[e+5],n+=(t&Te)*pl,t<Z)||(t=r[e+6],n+=(t&Te)*ml,t<Z)||(t=r[e+7],n+=(t&Te)*gl,t<Z))return n;throw new RangeError("Could not decode varint")}function Jy(r,e){let t=r.get(e),n=0;if(n+=t&Te,t<Z||(t=r.get(e+1),n+=(t&Te)<<7,t<Z)||(t=r.get(e+2),n+=(t&Te)<<14,t<Z)||(t=r.get(e+3),n+=(t&Te)<<21,t<Z)||(t=r.get(e+4),n+=(t&Te)*hl,t<Z)||(t=r.get(e+5),n+=(t&Te)*pl,t<Z)||(t=r.get(e+6),n+=(t&Te)*ml,t<Z)||(t=r.get(e+7),n+=(t&Te)*gl,t<Z))return n;throw new RangeError("Could not decode varint")}function Zt(r,e,t=0){return e==null&&(e=be(xe(r))),e instanceof Uint8Array?an(r,e,t):Qy(r,e,t)}function gr(r,e=0){return r instanceof Uint8Array?yl(r,e):Jy(r,e)}var bl=new Float32Array([-0]),Qt=new Uint8Array(bl.buffer);function Bh(r,e,t){bl[0]=r,e[t]=Qt[0],e[t+1]=Qt[1],e[t+2]=Qt[2],e[t+3]=Qt[3]}function Uh(r,e){return Qt[0]=r[e],Qt[1]=r[e+1],Qt[2]=r[e+2],Qt[3]=r[e+3],bl[0]}var wl=new Float64Array([-0]),Le=new Uint8Array(wl.buffer);function Kh(r,e,t){wl[0]=r,e[t]=Le[0],e[t+1]=Le[1],e[t+2]=Le[2],e[t+3]=Le[3],e[t+4]=Le[4],e[t+5]=Le[5],e[t+6]=Le[6],e[t+7]=Le[7]}function qh(r,e){return Le[0]=r[e],Le[1]=r[e+1],Le[2]=r[e+2],Le[3]=r[e+3],Le[4]=r[e+4],Le[5]=r[e+5],Le[6]=r[e+6],Le[7]=r[e+7],wl[0]}var eb=BigInt(Number.MAX_SAFE_INTEGER),tb=BigInt(Number.MIN_SAFE_INTEGER),Ve=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return yr;if(e<eb&&e>tb)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>zh&&(o=0n,++n>zh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return yr;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):yr}},yr=new Ve(0,0);yr.toBigInt=function(){return 0n};yr.zzEncode=yr.zzDecode=function(){return this};yr.length=function(){return 1};var zh=4294967296n;function $h(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Vh(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function xl(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function it(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ys(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var El=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Se(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,it(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw it(this,4);return Ys(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw it(this,4);return Ys(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw it(this,4);let e=Uh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw it(this,4);let e=qh(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw it(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Vh(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw it(this,e);this.pos+=e}else do if(this.pos>=this.len)throw it(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Ve(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw it(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw it(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw it(this,8);let e=Ys(this.buf,this.pos+=4),t=Ys(this.buf,this.pos+=4);return new Ve(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=yl(this.buf,this.pos);return this.pos+=xe(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function vo(r){return new El(r instanceof Uint8Array?r:r.subarray())}function Ne(r,e,t){let n=vo(r);return e.decode(n,void 0,t)}function vl(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return be(i);o+i>e&&(n=be(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var br=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Sl(){}var _l=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},rb=vl();function nb(r){return globalThis.Buffer!=null?be(r):rb(r)}var Ao=class{len;head;tail;states;constructor(){this.len=0,this.head=new br(Sl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new br(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Cl((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Xs,10,Ve.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ve.fromBigInt(e);return this._push(Xs,t.length(),t)}uint64Number(e){return this._push(an,xe(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Ve.fromBigInt(e).zzEncode();return this._push(Xs,t.length(),t)}sint64Number(e){let t=Ve.fromNumber(e).zzEncode();return this._push(Xs,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Al,1,e?1:0)}fixed32(e){return this._push(So,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ve.fromBigInt(e);return this._push(So,4,t.lo)._push(So,4,t.hi)}fixed64Number(e){let t=Ve.fromNumber(e);return this._push(So,4,t.lo)._push(So,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Bh,4,e)}double(e){return this._push(Kh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Al,1,0):this.uint32(t)._push(sb,t,e)}string(e){let t=$h(e);return t!==0?this.uint32(t)._push(xl,t,e):this._push(Al,1,0)}fork(){return this.states=new _l(this),this.head=this.tail=new br(Sl,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 br(Sl,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=nb(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Al(r,e,t){e[t]=r&255}function ob(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Cl=class extends br{next;constructor(e,t){super(ob,e,t),this.next=void 0}};function Xs(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function So(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function sb(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Ao.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(ib,e,r),this},Ao.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(ab,e,r),this});function ib(r,e,t){e.set(r,t)}function ab(r,e,t){r.length<40?xl(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(k(r),t)}function Il(){return new Ao}function Me(r,e){let t=Il();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*Fe(r,e,t){let n=vo(r);yield*e.stream(n,void 0,"$",t)}var Zs={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Qs(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Tl(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return Qs("enum",Zs.VARINT,t,n,o)}function Be(r,e,t){return Qs("message",Zs.LENGTH_DELIMITED,r,e,t)}var Ze=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},_o=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ae;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ae||(ae={}));var Ll;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ll||(Ll={}));(function(r){r.codec=()=>Tl(Ll)})(ae||(ae={}));var mt;(function(r){let e;r.codec=()=>(e==null&&(e=Be((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ae.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ae.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ae.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Me(s,r.codec())}r.encode=t;function n(s,i){return Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(mt||(mt={}));var Pl;(function(r){let e;r.codec=()=>(e==null&&(e=Be((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ae.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.Type=ae.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ae.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Me(s,r.codec())}r.encode=t;function n(s,i){return Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Pl||(Pl={}));var Io={};te(Io,{MAX_RSA_KEY_SIZE:()=>Dl,generateRSAKeyPair:()=>Kl,jwkToJWKKeyPair:()=>Xh,jwkToPkcs1:()=>fb,jwkToPkix:()=>Nl,jwkToRSAPrivateKey:()=>Ul,pkcs1MessageToJwk:()=>Rl,pkcs1MessageToRSAPrivateKey:()=>Ml,pkcs1ToJwk:()=>ub,pkcs1ToRSAPrivateKey:()=>Yh,pkixMessageToJwk:()=>Ol,pkixMessageToRSAPublicKey:()=>Bl,pkixToJwk:()=>db,pkixToRSAPublicKey:()=>Fl});var cn=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Io.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return de.createV1(114,this._multihash)}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}verify(e,t,n){return Gh(this.jwk,t,e,n)}},Co=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Io.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}sign(e,t){return jh(this.jwk,e,t)}};var Dl=8192,kl=18,cb=1062,lb=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ub(r){let e=_t(r);return Rl(e)}function Rl(r){return{n:K(r[1],"base64url"),e:K(r[2],"base64url"),d:K(r[3],"base64url"),p:K(r[4],"base64url"),q:K(r[5],"base64url"),dp:K(r[6],"base64url"),dq:K(r[7],"base64url"),qi:K(r[8],"base64url"),kty:"RSA"}}function fb(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 R("JWK was missing components");return tt([Oe(Uint8Array.from([0])),Oe(k(r.n,"base64url")),Oe(k(r.e,"base64url")),Oe(k(r.d,"base64url")),Oe(k(r.p,"base64url")),Oe(k(r.q,"base64url")),Oe(k(r.dp,"base64url")),Oe(k(r.dq,"base64url")),Oe(k(r.qi,"base64url"))]).subarray()}function db(r){let e=_t(r,{offset:0});return Ol(e)}function Ol(r){let e=_t(r[1],{offset:0});return{kty:"RSA",n:K(e[0],"base64url"),e:K(e[1],"base64url")}}function Nl(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return tt([lb,no(tt([Oe(k(r.n,"base64url")),Oe(k(r.e,"base64url"))]))]).subarray()}function Yh(r){let e=_t(r);return Ml(e)}function Ml(r){let e=Rl(r);return Ul(e)}function Fl(r,e){if(r.byteLength>=cb)throw new Kr("Key size is too large");let t=_t(r,{offset:0});return Bl(t,r,e)}function Bl(r,e,t){let n=Ol(r);if(t==null){let o=Yr(mt.encode({Type:ae.RSA,Data:e}));t=dt(kl,o)}return new cn(n,t)}function Ul(r){if(Qh(r)>Dl)throw new R("Key size is too large");let e=Xh(r),t=Yr(mt.encode({Type:ae.RSA,Data:Nl(e.publicKey)})),n=dt(kl,t);return new Co(e.privateKey,new cn(e.publicKey,n))}async function Kl(r){if(r>Dl)throw new R("Key size is too large");let e=await Zh(r),t=Yr(mt.encode({Type:ae.RSA,Data:Nl(e.publicKey)})),n=dt(kl,t);return new Co(e.privateKey,new cn(e.publicKey,n))}function Xh(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Zh(r,e){let t=await qe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await hb(t,e);return{privateKey:n[0],publicKey:n[1]}}async function jh(r,e,t){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Se(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Gh(r,e,t,n){let o=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Se(e),Se(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),s}async function hb(r,e){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");let t=await Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Qh(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return k(r.n,"base64url").length*8}var Js=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ps(e),$e(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),It(o)}update(e){return Gr(this),this.iHash.update(e),this}digestInto(e){Gr(this),Ds(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Jh=(()=>{let r=((e,t,n)=>new Js(e,t).update(n).digest());return r.create=(e,t)=>new Js(e,t),r})();var ep=(r,e)=>(r+(r>=0?e:-e)/tp)/e;function pb(r,e,t){Qr("scalar",r,gt,t);let[[n,o],[s,i]]=e,a=ep(i*r,t),c=ep(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,f=l<gt,d=u<gt;f&&(l=-l),d&&(u=-u);let h=fo(Math.ceil(Jr(t)/2))+Jt;if(l<gt||l>=h||u<gt||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:d,k2:u}}function zl(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ql(r,e){st(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return nt(t.lowS,"lowS"),nt(t.prehash,"prehash"),t.format!==void 0&&zl(t.format),t}var $l=class extends Error{constructor(e=""){super(e)}},at={Err:$l,_tlv:{encode:(r,e)=>{let{Err:t}=at;if(ot(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=lo(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?lo(o.length/2|128):"";return lo(r)+s+o+e},decode(r,e){let{Err:t}=at;e=H(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=at;if(Bs(r),r<gt)throw new e("integer: negative integers are not allowed");let t=lo(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=at;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return dr(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=at,o=H(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=at,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}};Object.freeze(at._tlv);Object.freeze(at._int);Object.freeze(at);var gt=BigInt(0),Jt=BigInt(1),tp=BigInt(2),ei=BigInt(3),mb=BigInt(4);function rp(r,e={}){let t=zs("weierstrass",r,e),n=t.Fp,o=t.Fn,s=t.CURVE,{h:i,n:a}=s;st(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=op(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(q,b,x){if(l&&b.is0())return Uint8Array.of(0);let{x:A,y:S}=b.toAffine(),E=n.toBytes(A);if(nt(x,"isCompressed"),x){f();let C=!n.isOdd(S);return me(np(C),E)}else return me(Uint8Array.of(4),E,n.toBytes(S))}function h(q){H(q,void 0,"Point");let{publicKey:b,publicKeyUncompressed:x}=u,A=q.length,S=q[0],E=q.subarray(1);if(l&&A===1&&S===0)return{x:n.ZERO,y:n.ZERO};if(A===b&&(S===2||S===3)){let C=n.fromBytes(E);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let D=m(C),P;try{P=n.sqrt(D)}catch(V){let G=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}f();let O=n.isOdd(P);return(S&1)===1!==O&&(P=n.neg(P)),{x:C,y:P}}else if(A===x&&S===4){let C=n.BYTES,D=n.fromBytes(E.subarray(0,C)),P=n.fromBytes(E.subarray(C,C*2));if(!y(D,P))throw new Error("bad point: is not on curve");return{x:D,y:P}}else throw new Error(`bad point: got length ${A}, expected compressed=${b} or uncompressed=${x}`)}let p=e.toBytes===void 0?d:e.toBytes,g=e.fromBytes===void 0?h:e.fromBytes;function m(q){let b=n.sqr(q),x=n.mul(b,q);return n.add(n.add(x,n.mul(q,s.a)),s.b)}function y(q,b){let x=n.sqr(b),A=m(q);return n.eql(x,A)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let w=n.mul(n.pow(s.a,ei),mb),v=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,v)))throw new Error("bad curve params: a or b");function T(q,b,x=!1){if(!n.isValid(b)||x&&n.is0(b))throw new Error(`bad point coordinate ${q}`);return b}function I(q){if(!(q instanceof _))throw new Error("Weierstrass Point expected")}function M(q){if(!c||!c.basises)throw new Error("no endo");return pb(q,c.basises,o.ORDER)}function L(q,b,x,A,S){return x=new _(n.mul(x.X,q),x.Y,x.Z),b=po(A,b),x=po(S,x),b.add(x)}class _{static BASE=new _(s.Gx,s.Gy,n.ONE);static ZERO=new _(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,x,A){this.X=T("x",b),this.Y=T("y",x,!0),this.Z=T("z",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x,y:A}=b||{};if(!b||!n.isValid(x)||!n.isValid(A))throw new Error("invalid affine point");if(b instanceof _)throw new Error("projective point not allowed");return n.is0(x)&&n.is0(A)?_.ZERO:new _(x,A,n.ONE)}static fromBytes(b){let x=_.fromAffine(g(H(b,void 0,"point")));return x.assertValidity(),x}static fromHex(b){return _.fromBytes(Zr(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,x=!0){return Y.createCache(this,b),x||this.multiply(ei),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x,y:A}=b.toAffine();if(!n.isValid(x)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!y(x,A))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){I(b);let{X:x,Y:A,Z:S}=this,{X:E,Y:C,Z:D}=b,P=n.eql(n.mul(x,D),n.mul(E,S)),O=n.eql(n.mul(A,D),n.mul(C,S));return P&&O}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:x}=s,A=n.mul(x,ei),{X:S,Y:E,Z:C}=this,D=n.ZERO,P=n.ZERO,O=n.ZERO,F=n.mul(S,S),V=n.mul(E,E),G=n.mul(C,C),z=n.mul(S,E);return z=n.add(z,z),O=n.mul(S,C),O=n.add(O,O),D=n.mul(b,O),P=n.mul(A,G),P=n.add(D,P),D=n.sub(V,P),P=n.add(V,P),P=n.mul(D,P),D=n.mul(z,D),O=n.mul(A,O),G=n.mul(b,G),z=n.sub(F,G),z=n.mul(b,z),z=n.add(z,O),O=n.add(F,F),F=n.add(O,F),F=n.add(F,G),F=n.mul(F,z),P=n.add(P,F),G=n.mul(E,C),G=n.add(G,G),F=n.mul(G,z),D=n.sub(D,F),O=n.mul(G,V),O=n.add(O,O),O=n.add(O,O),new _(D,P,O)}add(b){I(b);let{X:x,Y:A,Z:S}=this,{X:E,Y:C,Z:D}=b,P=n.ZERO,O=n.ZERO,F=n.ZERO,V=s.a,G=n.mul(s.b,ei),z=n.mul(x,E),pe=n.mul(A,C),ge=n.mul(S,D),ye=n.add(x,A),fe=n.add(E,C);ye=n.mul(ye,fe),fe=n.add(z,pe),ye=n.sub(ye,fe),fe=n.add(x,S);let Ke=n.add(E,D);return fe=n.mul(fe,Ke),Ke=n.add(z,ge),fe=n.sub(fe,Ke),Ke=n.add(A,S),P=n.add(C,D),Ke=n.mul(Ke,P),P=n.add(pe,ge),Ke=n.sub(Ke,P),F=n.mul(V,fe),P=n.mul(G,ge),F=n.add(P,F),P=n.sub(pe,F),F=n.add(pe,F),O=n.mul(P,F),pe=n.add(z,z),pe=n.add(pe,z),ge=n.mul(V,ge),fe=n.mul(G,fe),pe=n.add(pe,ge),ge=n.sub(z,ge),ge=n.mul(V,ge),fe=n.add(fe,ge),z=n.mul(pe,fe),O=n.add(O,z),z=n.mul(Ke,fe),P=n.mul(ye,P),P=n.sub(P,z),z=n.mul(ye,pe),F=n.mul(Ke,F),F=n.add(F,z),new _(P,O,F)}subtract(b){return I(b),this.add(b.negate())}is0(){return this.equals(_.ZERO)}multiply(b){let{endo:x}=e;if(!o.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let A,S,E=C=>Y.cached(this,C,D=>mr(_,D));if(x){let{k1neg:C,k1:D,k2neg:P,k2:O}=M(b),{p:F,f:V}=E(D),{p:G,f:z}=E(O);S=V.add(z),A=L(x.beta,F,G,C,P)}else{let{p:C,f:D}=E(b);A=C,S=D}return mr(_,[A,S])[0]}multiplyUnsafe(b){let{endo:x}=e,A=this,S=b;if(!o.isValid(S))throw new RangeError("invalid scalar: out of range");if(S===gt||A.is0())return _.ZERO;if(S===Jt)return A;if(Y.hasCache(this))return this.multiply(S);if(x){let{k1neg:E,k1:C,k2neg:D,k2:P}=M(S),{p1:O,p2:F}=Ah(_,A,C,P);return L(x.beta,O,F,E,D)}else return Y.unsafe(A,S)}toAffine(b){let x=this,A=b,{X:S,Y:E,Z:C}=x;if(n.eql(C,n.ONE))return{x:S,y:E};let D=x.is0();A==null&&(A=D?n.ONE:n.inv(C));let P=n.mul(S,A),O=n.mul(E,A),F=n.mul(C,A);if(D)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:P,y:O}}isTorsionFree(){let{isTorsionFree:b}=e;return i===Jt?!0:b?b(_,this):Y.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===Jt?this:b?b(_,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Jt?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return nt(b,"isCompressed"),this.assertValidity(),p(_,this,b)}toHex(b=!0){return Xr(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let B=o.BITS,Y=new rn(_,e.endo?Math.ceil(B/2):B);return B>=8&&_.BASE.precompute(8),Object.freeze(_.prototype),Object.freeze(_),_}function np(r){return Uint8Array.of(r?2:3)}function op(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function gb(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?co:e.randomBytes,o=Object.assign(op(r.Fp,t),{seed:Math.max(Jc(t.ORDER),16)});function s(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:g,publicKeyUncompressed:m}=o;try{let y=h.length;return p===!0&&y!==g||p===!1&&y!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,el(H(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:g,publicKeyUncompressed:m}=o,y=t._lengths;if(!fr(h))return;let w=H(h,void 0,"key").length,v=w===g||w===m,T=w===p||!!y?.includes(w);if(!(v&&T))return v}function u(h,p,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(p).multiply(m).toBytes(g)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=$s(a,c);return Object.freeze(f),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:f,lengths:o})}function sp(r,e,t={}){let n=e;Ps(n),st(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?co:t.randomBytes,s=t.hmac===void 0?(S,E)=>Jh(n,S,E):t.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:f,getSharedSecret:d,utils:h,lengths:p}=gb(r,t),g={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*tp+Jt<i.ORDER;function y(S){let E=c>>Jt;return S>E}function w(S,E){if(!a.isValidNot0(E))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return E}function v(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function T(S,E){zl(E);let C=p.signature,D=E==="compact"?C:E==="recovered"?C+1:void 0;return H(S,D)}class I{r;s;recovery;constructor(E,C,D){if(this.r=w("r",E),this.s=w("s",C),D!=null){if(v(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(E,C=g.format){T(E,C);let D;if(C==="der"){let{r:V,s:G}=at.toSig(H(E));return new I(V,G)}C==="recovered"&&(D=E[0],C="compact",E=E.subarray(1));let P=p.signature/2,O=E.subarray(0,P),F=E.subarray(P,P*2);return new I(a.fromBytes(O),a.fromBytes(F),D)}static fromHex(E,C){return this.fromBytes(Zr(E),C)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new I(this.r,this.s,E)}recoverPublicKey(E){let{r:C,s:D}=this,P=this.assertRecovery(),O=P===2||P===3?C+c:C;if(!i.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let F=i.toBytes(O),V=r.fromBytes(me(np((P&1)===0),F)),G=a.inv(O),z=L(H(E,void 0,"msgHash")),pe=a.create(-z*G),ge=a.create(D*G),ye=r.BASE.multiplyUnsafe(pe).add(V.multiplyUnsafe(ge));if(ye.is0())throw new Error("invalid recovery: point at infinify");return ye.assertValidity(),ye}hasHighS(){return y(this.s)}toBytes(E=g.format){if(zl(E),E==="der")return Zr(at.hexFromSig(this));let{r:C,s:D}=this,P=a.toBytes(C),O=a.toBytes(D);return E==="recovered"?(v(),me(Uint8Array.of(this.assertRecovery()),P,O)):me(P,O)}toHex(E){return Xr(this.toBytes(E))}}Object.freeze(I.prototype),Object.freeze(I);let M=t.bits2int===void 0?function(E){if(E.length>8192)throw new Error("input is too large");let C=dr(E),D=E.length*8-l;return D>0?C>>BigInt(D):C}:t.bits2int,L=t.bits2int_modN===void 0?function(E){return a.create(M(E))}:t.bits2int_modN,_=fo(l);function B(S){return Qr("num < 2^"+l,S,gt,_),a.toBytes(S)}function Y(S,E){return H(S,void 0,"message"),E?H(n(S),void 0,"prehashed message"):S}function q(S,E,C){let{lowS:D,prehash:P,extraEntropy:O}=ql(C,g);S=Y(S,P);let F=L(S),V=a.fromBytes(E);if(!a.isValidNot0(V))throw new Error("invalid private key");let G=[B(V),B(F)];if(O!=null&&O!==!1){let ye=O===!0?o(p.secretKey):O;G.push(H(ye,void 0,"extraEntropy"))}let z=me(...G),pe=F;function ge(ye){let fe=M(ye);if(!a.isValidNot0(fe))return;let Ke=a.inv(fe),Ur=r.BASE.multiply(fe).toAffine(),Vn=a.create(Ur.x);if(Vn===gt)return;let hs=a.create(Ke*a.create(pe+Vn*V));if(hs===gt)return;let id=(Ur.x===Vn?0:2)|Number(Ur.y&Jt),ad=hs;return D&&y(hs)&&(ad=a.neg(hs),id^=1),new I(Vn,ad,m?void 0:id)}return{seed:z,k2sig:ge}}function b(S,E,C={}){let{seed:D,k2sig:P}=q(S,E,C);return ah(n.outputLen,a.BYTES,s)(D,P).toBytes(C.format)}function x(S,E,C,D={}){let{lowS:P,prehash:O,format:F}=ql(D,g);if(C=H(C,void 0,"publicKey"),E=Y(E,O),!fr(S)){let V=S instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+V)}T(S,F);try{let V=I.fromBytes(S,F),G=r.fromBytes(C);if(P&&V.hasHighS())return!1;let{r:z,s:pe}=V,ge=L(E),ye=a.inv(pe),fe=a.create(ge*ye),Ke=a.create(z*ye),Ur=r.BASE.multiplyUnsafe(fe).add(G.multiplyUnsafe(Ke));return Ur.is0()?!1:a.create(Ur.x)===z}catch{return!1}}function A(S,E,C={}){let{prehash:D}=ql(C,g);return E=Y(E,D),I.fromBytes(S,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:d,utils:h,lengths:p,Point:r,sign:b,verify:x,recoverPublicKey:A,Signature:I,hash:n})}var Hl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},yb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var ip=BigInt(2);function bb(r){let e=Hl.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=se(u,t,e)*u%e,d=se(f,t,e)*u%e,h=se(d,ip,e)*l%e,p=se(h,o,e)*h%e,g=se(p,s,e)*p%e,m=se(g,a,e)*g%e,y=se(m,c,e)*m%e,w=se(y,a,e)*g%e,v=se(w,t,e)*u%e,T=se(v,i,e)*p%e,I=se(T,n,e)*l%e,M=se(I,ip,e);if(!Vl.eql(Vl.sqr(M),r))throw new Error("Cannot find square root");return M}var Vl=en(Hl.p,{sqrt:bb}),wb=rp(Hl,{Fp:Vl,endo:yb}),ct=sp(wb,Yr);function ap(r,e,t){let n=jr.digest(e instanceof Uint8Array?e:e.subarray());if(sn(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),ct.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new yo(String(o))});try{return ct.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new yo(String(o))}}function cp(r,e,t,n){let o=jr.digest(t instanceof Uint8Array?t:t.subarray());if(sn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ct.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new bo(String(s))});try{return n?.signal?.throwIfAborted(),ct.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new bo(String(s))}}var To=class{type="secp256k1";raw;_key;constructor(e){this._key=fp(e),this.raw=lp(this._key)}toMultihash(){return et.digest(Xe(this))}toCID(){return de.createV1(114,this.toMultihash())}toString(){return re.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}verify(e,t,n){return cp(this._key,t,e,n)}},ti=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=up(e),this.publicKey=new To(t??dp(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:X(this.raw,e.raw)}sign(e,t){return ap(this.raw,e,t)}};function Wl(r){return new To(r)}async function hp(){let r=xb();return new ti(r)}function lp(r){return ct.Point.fromBytes(r).toBytes()}function up(r){try{return ct.getPublicKey(r,!0),r}catch(e){throw new Wn(String(e))}}function fp(r){try{return ct.Point.fromBytes(r),r}catch(e){throw new Kr(String(e))}}function dp(r){try{return ct.getPublicKey(r,!0)}catch(e){throw new Wn(String(e))}}function xb(){return ct.utils.randomSecretKey()}async function pp(r,e){if(r==="Ed25519")return Fh();if(r==="secp256k1")return hp();if(r==="RSA")return Kl(Eb(e));if(r==="ECDSA")return Vd(vb(e));throw new Ut}function ln(r,e){let{Type:t,Data:n}=mt.decode(r),o=n??new Uint8Array;switch(t){case ae.RSA:return Fl(o,e);case ae.Ed25519:return dl(o);case ae.secp256k1:return Wl(o);case ae.ECDSA:return Mc(o);default:throw new Ut}}function mp(r){let{Type:e,Data:t}=mt.decode(r.digest),n=t??new Uint8Array;switch(e){case ae.Ed25519:return dl(n);case ae.secp256k1:return Wl(n);case ae.ECDSA:return Mc(n);default:throw new Ut}}function Xe(r){return mt.encode({Type:ae[r.type],Data:r.raw})}function Eb(r){return r==null?2048:parseInt(r,10)}function vb(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 R("Unsupported curve, should be P-256, P-384 or P-521")}var gp=Symbol.for("nodejs.util.inspect.custom"),Sb=114,Lo=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ss]=!0;toString(){return this.string==null&&(this.string=re.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return de.createV1(Sb,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return X(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return X(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[gp](){return`PeerId(${this.toString()})`}},Po=class extends Lo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Do=class extends Lo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ko=class extends Lo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Ab=2336,Ro=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=et.digest(k(this.url))}[gp](){return`PeerId(${this.url})`}[Ss]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return de.createV1(Ab,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=K(e)),e.toString()===this.toString())}};var _b=114,yp=2336;function yt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=At(re.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Oo(de.parse(r));if(e==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=At(e.decode(r))}return un(t)}function jl(r){if(r.type==="Ed25519")return new Do({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new ko({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Po({multihash:r.toCID().multihash,publicKey:r});throw new Ut}function bp(r){return jl(r.publicKey)}function un(r){if(Ib(r))return new Po({multihash:r});if(Cb(r))try{let e=mp(r);if(e.type==="Ed25519")return new Do({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ko({multihash:r,publicKey:e})}catch{let t=K(r.digest);return new Ro(new URL(t))}throw new gs("Supplied PeerID Multihash is invalid")}function Oo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==_b&&r.code!==yp)throw new ms("Supplied PeerID CID is invalid");if(r.code===yp){let e=K(r.multihash.digest);return new Ro(new URL(e))}return un(r.multihash)}function Cb(r){return r.code===et.code}function Ib(r){return r.code===jr.code}async function wp(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return r}function ri(r,e){if(typeof r=="string")return Tb(r);if(typeof r=="number")return Db(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function Tb(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw new Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function Lb(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Pb(r){let e=Math.abs(r);return e>=315576e5?wr(r,e,315576e5,"year"):e>=26298e5?wr(r,e,26298e5,"month"):e>=6048e5?wr(r,e,6048e5,"week"):e>=864e5?wr(r,e,864e5,"day"):e>=36e5?wr(r,e,36e5,"hour"):e>=6e4?wr(r,e,6e4,"minute"):e>=1e3?wr(r,e,1e3,"second"):`${r} ms`}function Db(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?Pb(r):Lb(r)}function wr(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Gl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=ri,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u,f){let d,h=null,p,g;function m(...y){if(!m.enabled)return;let w=m,v=Number(new Date),T=v-(d||v);w.diff=T,w.prev=d,w.curr=v,d=v,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let I=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(L,_)=>{if(L==="%%")return"%";I++;let B=t.formatters[_];if(typeof B=="function"){let Y=y[I];L=B.call(w,Y),y.splice(I,1),I--}return L}),t.formatArgs.call(w,y),f?.onLog!=null&&f.onLog(...y),(w.log||t.log).apply(w,y)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,g=t.enabled(u)),g),set:y=>{h=y}}),typeof t.init=="function"&&t.init(m),m}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var ni=Bb(),kb=["#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 Rb(){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 Ob(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+ri(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var Nb=console.debug??console.log??(()=>{});function Mb(r){try{r?ni?.setItem("debug",r):ni?.removeItem("debug")}catch{}}function Fb(){let r;try{r=ni?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Bb(){try{return localStorage}catch{}}function Ub(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var xp=Gl({formatArgs:Ob,save:Mb,load:Fb,useColors:Rb,setupFormatters:Ub,colors:kb,storage:ni,log:Nb});var ze=xp;ze.formatters.b=r=>r==null?"undefined":re.baseEncode(r);ze.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);ze.formatters.m=r=>r==null?"undefined":Sc.baseEncode(r);ze.formatters.p=r=>r==null?"undefined":r.toString();ze.formatters.c=r=>r==null?"undefined":r.toString();ze.formatters.k=r=>r==null?"undefined":r.toString();ze.formatters.a=r=>r==null?"undefined":r.toString();function Ep(r,e=""){let t=vp(r.message),n=vp(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
3
3
  `).join(`
4
4
  ${e}`)}`:`${t}
5
5
  ${e}${n.split(`
6
6
  `).join(`
7
7
  ${e}`)}`:n!=null?`${n.split(`
8
8
  `).join(`
9
- ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function kv(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Og(r,e=""){if(kv(r)){let t=kg(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
- ${e}${r.errors.map(n=>`${Og(n,`${e}`)}`).join(`
9
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Kb(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Sp(r,e=""){if(Kb(r)){let t=Ep(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
+ ${e}${r.errors.map(n=>`${Sp(n,`${e}`)}`).join(`
11
11
  ${e}`)}`):t+=`
12
- ${e}[Error list was empty]`,t.trim()}return kg(r,e)}Ve.formatters.e=r=>r==null?"undefined":Og(r);function Rv(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function $i(r){return{forComponent(e){return Ng(e,r)}}}function Ng(r,e){let t=Rv(`${r}:trace`);return Ve.enabled(`${r}:trace`)&&Ve.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=Ve(`${r}:trace`,e)),Object.assign(Ve(r,e),{error:Ve(`${r}:error`,e),trace:t,newScope:n=>Ng(`${r}:${n}`,e)})}function Rg(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Pr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Vi(r){let e=Tt(re.decode(`z${r}`));return In(e)}var et=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Pr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Pr(this.map.values(),e=>e.key)}values(){return Pr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var kr=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Pr(this.set.entries(),e=>{let t=Vi(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Vi(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Pr(this.set.values(),e=>Vi(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var cf={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Mg={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Fg=new globalThis.TextEncoder;function Ov(r,e){let t=cf[e],n=Mg[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Nv(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=cf[e],o=Mg[e],s=r;for(;s.length>0;){let i=Fg.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function uf(r,{size:e=32,utf8Buffer:t}={}){if(!cf[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Nv(r,e,t);r=Fg.encode(r)}return Ov(r,e)}var ls={hash:r=>Number(uf(r,{size:32})),hashV:(r,e)=>Mv(ls.hash(r,e))};function Mv(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),M(e,"base16")}var lf=64,ft=class{fp;h;seed;constructor(e,t,n,o=2){if(o>lf)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=qe(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?J(this.fp,e.fp):!1}};function Rr(r,e){return Math.floor(Math.random()*(e-r))+r}var Or=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ft))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ft))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof ft))throw new TypeError("Invalid Fingerprint");let t=Rr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ft))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Fv=500,fs=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??ls,this.seed=e.seed??Rr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=M(e));let t=new ft(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Or(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Or(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Rr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Or(this.bucketSize));for(let a=0;a<Fv;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Or(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=M(e));let t=new ft(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=M(e));let t=new ft(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Bv={1:.5,2:.84,4:.95,8:.98};function Uv(r=.001){return r>.002?2:r>1e-5?4:8}function Bg(r,e=.001){let t=Uv(e),n=Bv[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),lf);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Hi=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??ls,this.seed=e.seed??Rr(0,Math.pow(2,10)),this.filterSeries=[new fs({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=M(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new fs({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function ds(r,e=.001,t){return new Hi({...Bg(r,e),...t??{}})}function ff(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function G(r){let e=ff(r);if(e==null)throw new R(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var ji=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ug=45,Kv=15,Tn=new ji;function Gi(r){if(!(r.length>Kv))return Tn.new(r).parseWith(()=>Tn.readIPv4Addr())}function Wi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ug))return Tn.new(r).parseWith(()=>Tn.readIPv6Addr())}function Ln(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Ug)return;let t=Tn.new(r).parseWith(()=>Tn.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function Kg(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function zg(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function df(r){switch(r.length){case Nr:return r.join(".");case Mr:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function qg(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function $g(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Nr=4,Mr=16,XL=parseInt("0xFFFF",16),zv=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function hs(r,e){e.length===Mr&&r.length===Nr&&Kg(e,0,11)&&(e=e.slice(12)),e.length===Nr&&r.length===Mr&&zg(r,zv,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function Vg(r,e){if(typeof e=="string"&&(e=Ln(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function hf(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Nr,o=Gi(e);if(o==null&&(n=Mr,o=Wi(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=pf(s,8*n);return{network:hs(o,i),mask:i}}function pf(r,e){if(e!==8*Nr&&e!==8*Mr)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Dn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=hf(e));else{let n=Ln(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=Ln(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=pf(o,8*n.length);this.network=hs(n,this.mask)}}contains(e){return Vg({network:this.network,mask:this.mask},e)}toString(){let e=qg(this.mask),t=e!==-1?String(e):$g(this.mask);return df(this.network)+"/"+t}};function Hg(r){try{let e=G(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function jg(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function ps(r){try{let e=G(r);switch(e.type){case"ip4":case"ip6":return jg(e.host);default:return!1}}catch{return!1}}function _e(r){return ff(r)!==null}function dt(r){return!!Gi(r)}function Xi(r){return!!Wi(r)}var Yg=Vc(Xg(),1),Wv=["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"],Xv=Wv.map(r=>new Yg.Netmask(r));function Ef(r){for(let e of Xv)if(e.contains(r))return!0;return!1}function Yv(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Zv(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Ef(o)}function Qv(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Jv(r){let e=r.split(":"),t=e[e.length-1];return Ef(t)}function e1(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 On(r){if(dt(r))return Ef(r);if(Yv(r))return Zv(r);if(Qv(r))return Jv(r);if(Xi(r))return e1(r)}function Bt(r){try{let e=G(r);switch(e.type){case"ip4":case"ip6":return On(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}var t1=Math.pow(2,7),r1=Math.pow(2,14),n1=Math.pow(2,21),vf=Math.pow(2,28),Sf=Math.pow(2,35),Af=Math.pow(2,42),_f=Math.pow(2,49),ae=128,Le=127;function Nn(r){if(r<t1)return 1;if(r<r1)return 2;if(r<n1)return 3;if(r<vf)return 4;if(r<Sf)return 5;if(r<Af)return 6;if(r<_f)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Cf(r,e,t=0){switch(Nn(r)){case 8:e[t++]=r&255|ae,r/=128;case 7:e[t++]=r&255|ae,r/=128;case 6:e[t++]=r&255|ae,r/=128;case 5:e[t++]=r&255|ae,r/=128;case 4:e[t++]=r&255|ae,r>>>=7;case 3:e[t++]=r&255|ae,r>>>=7;case 2:e[t++]=r&255|ae,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function o1(r,e){let t=r[e],n=0;if(n+=t&Le,t<ae||(t=r[e+1],n+=(t&Le)<<7,t<ae)||(t=r[e+2],n+=(t&Le)<<14,t<ae)||(t=r[e+3],n+=(t&Le)<<21,t<ae)||(t=r[e+4],n+=(t&Le)*vf,t<ae)||(t=r[e+5],n+=(t&Le)*Sf,t<ae)||(t=r[e+6],n+=(t&Le)*Af,t<ae)||(t=r[e+7],n+=(t&Le)*_f,t<ae))return n;throw new RangeError("Could not decode varint")}function s1(r,e){let t=r.get(e),n=0;if(n+=t&Le,t<ae||(t=r.get(e+1),n+=(t&Le)<<7,t<ae)||(t=r.get(e+2),n+=(t&Le)<<14,t<ae)||(t=r.get(e+3),n+=(t&Le)<<21,t<ae)||(t=r.get(e+4),n+=(t&Le)*vf,t<ae)||(t=r.get(e+5),n+=(t&Le)*Sf,t<ae)||(t=r.get(e+6),n+=(t&Le)*Af,t<ae)||(t=r.get(e+7),n+=(t&Le)*_f,t<ae))return n;throw new RangeError("Could not decode varint")}function If(r,e=0){return r instanceof Uint8Array?o1(r,e):s1(r,e)}var Ce=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ut=class extends Error{static name="ValidationError";name="ValidationError"},Zi=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Qi=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Lf(r){return e=>z(e,r)}function Df(r){return e=>M(e,r)}function Mn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Br(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Zg(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=M(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Br(n);return Mt([t,o],t.length+o.length)}function Qg(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ze.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Br(n);return Mt([t,o],t.length+o.length)}function Pf(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),o=Mn(t);return`${n}:${o}`}var kf=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Ce("Invalid byte value in IP address");e[n]=o}),e},Jg=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=dt(t[n]),i;s&&(i=kf(t[n]),t[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Ce("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},e0=function(r){if(r.byteLength!==4)throw new Ce("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},t0=function(r){if(r.byteLength!==16)throw new Ce("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ce(`Invalid IPv6 address "${t}"`)}};function r0(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ce(`Invalid IPv6 address "${r}"`)}}var Tf=Object.values(Co).map(r=>r.decoder),a1=(function(){let r=Tf[0].or(Tf[1]);return Tf.slice(2).forEach(e=>r=r.or(e)),r})();function n0(r){return a1.decode(r)}function o0(r){return e=>r.encoder.encode(e)}function c1(r){if(parseInt(r).toString()!==r)throw new Ut("Value must be an integer")}function u1(r){if(r<0)throw new Ut("Value must be a positive integer, or zero")}function l1(r){return e=>{if(e>r)throw new Ut(`Value must be smaller than or equal to ${r}`)}}function f1(...r){return e=>{for(let t of r)t(e)}}var ms=f1(c1,u1,l1(65535));var Ee=-1,Rf=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Qi(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},zt=new Rf,_1=[{code:4,name:"ip4",size:32,valueToBytes:kf,bytesToValue:e0,validate:r=>{if(!dt(r))throw new Ut(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Br,bytesToValue:Mn,validate:ms},{code:273,name:"udp",size:16,valueToBytes:Br,bytesToValue:Mn,validate:ms},{code:33,name:"dccp",size:16,valueToBytes:Br,bytesToValue:Mn,validate:ms},{code:41,name:"ip6",size:128,valueToBytes:Jg,bytesToValue:t0,stringToValue:r0,validate:r=>{if(!Xi(r))throw new Ut(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Ee},{code:43,name:"ipcidr",size:8,bytesToValue:Lf("base10"),valueToBytes:Df("base10")},{code:53,name:"dns",size:Ee},{code:54,name:"dns4",size:Ee},{code:55,name:"dns6",size:Ee},{code:56,name:"dnsaddr",size:Ee},{code:132,name:"sctp",size:16,valueToBytes:Br,bytesToValue:Mn,validate:ms},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ee,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Ee,bytesToValue:Lf("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Df("base58btc")(r):pe.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Pf,valueToBytes:Zg},{code:445,name:"onion3",size:296,bytesToValue:Pf,valueToBytes:Qg},{code:446,name:"garlic64",size:Ee},{code:447,name:"garlic32",size:Ee},{code:448,name:"tls"},{code:449,name:"sni",size:Ee},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ee,bytesToValue:o0(du),valueToBytes:n0},{code:480,name:"http"},{code:481,name:"http-path",size:Ee,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:Ee}];_1.forEach(r=>{zt.addProtocol(r)});function s0(r){let e=[],t=0;for(;t<r.length;){let n=If(r,t),o=zt.getProtocol(n),s=Nn(n),i=C1(o,r,t+s),a=0;i>0&&o.size===Ee&&(a=Nn(i));let c=s+a+i,u={code:n,name:o.name,bytes:Oe(r.subarray(t,t+c))};if(i>0){let l=t+s+a,f=r.subarray(l,l+i);u.value=o.bytesToValue?.(f)??z(f)}e.push(u),t+=c}return e}function i0(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=zt.getProtocol(n.code),s=Nn(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??M(n.value),a=i.byteLength,o.size===Ee&&(c=Nn(a)));let u=new Uint8Array(s+c+a),l=0;Cf(n.code,u,l),l+=s,i!=null&&(o.size===Ee&&(Cf(a,u,l),l+=c),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return Mt(t,e)}function a0(r){if(r.charAt(0)!=="/")throw new Ce('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=zt.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Ce(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ce(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ce("Incomplete multiaddr");return e}function c0(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=zt.getProtocol(e.code);if(t==null)throw new Ce(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function C1(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:If(e,t)}var I1=Symbol.for("nodejs.util.inspect.custom"),Gf=Symbol.for("@multiformats/multiaddr");function T1(r){if(r==null&&(r="/"),fr(r))return r.getComponents();if(r instanceof Uint8Array)return s0(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),a0(r);if(Array.isArray(r))return r;throw new Ce("Must be a string, Uint8Array, Component[], or another Multiaddr")}var oa=class r{[Gf]=!0;#e;#t;#n;constructor(e="/",t={}){this.#e=T1(e),t.validate!==!1&&L1(this)}get bytes(){return this.#n==null&&(this.#n=i0(this.#e)),this.#n}toString(){return this.#t==null&&(this.#t=c0(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Zi(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return J(this.bytes,e.bytes)}[I1](){return`Multiaddr(${this.toString()})`}};function L1(r){r.getComponents().forEach(e=>{let t=zt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function fr(r){return!!r?.[Gf]}function Q(r){return new oa(r)}var ne=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),F=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),u0=r=>({match:e=>r.match(e)===!1?e:!1}),V=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),De=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),W=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function oe(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var D1=F(421),l0=oe(D1),ia=F(54),aa=F(55),ca=F(56),Xf=F(53),M5=oe(ia,V(F(421))),F5=oe(aa,V(F(421))),B5=oe(ca,V(F(421))),U5=oe(De(Xf,ca,ia,aa),V(F(421))),f0=W(F(4),V(F(43))),d0=W(V(F(42)),F(41),V(F(43))),Yf=De(f0,d0),qn=De(Yf,Xf,ia,aa,ca),K5=oe(De(Yf,W(De(Xf,ca,ia,aa),V(F(421))))),Zf=oe(f0),Qf=oe(d0),z5=oe(Yf),Jf=W(qn,F(6)),gs=W(qn,F(273)),ys=oe(W(Jf,V(F(421)))),q5=oe(gs),ed=W(gs,ne(460),V(F(421))),ua=W(gs,ne(461),V(F(421))),P1=De(ed,ua),$5=oe(ed),h0=oe(ua),Wf=De(qn,Jf,gs,ed,ua),p0=De(W(Wf,ne(477),V(F(421)))),Kr=oe(p0),m0=De(W(Wf,ne(478),V(F(421))),W(Wf,ne(448),V(F(449)),ne(477),V(F(421)))),bs=oe(m0),g0=W(gs,ne(280),V(F(466)),V(F(466)),V(F(421))),td=oe(g0),y0=W(ua,ne(465),V(F(466)),V(F(466)),V(F(421))),rd=oe(y0),sa=De(p0,m0,W(Jf,V(F(421))),W(P1,V(F(421))),W(qn,V(F(421))),g0,y0,F(421)),V5=oe(sa),k1=W(V(sa),ne(290),u0(ne(281)),V(F(421))),zr=oe(k1),R1=De(W(sa,ne(290),ne(281),V(F(421))),W(sa,ne(281),V(F(421))),W(ne(281),V(F(421)))),nd=oe(R1),O1=W(qn,De(W(F(6,"80")),W(F(6),ne(480)),ne(480)),V(F(481)),V(F(421))),H5=oe(O1),N1=W(qn,De(W(F(6,"443")),W(F(6,"443"),ne(480)),W(F(6),ne(443)),W(F(6),ne(448),ne(480)),W(ne(448),ne(480)),ne(448),ne(443)),V(F(481)),V(F(421))),j5=oe(N1),M1=De(W(F(777),V(F(421)))),G5=oe(M1),F1=De(W(F(400),V(F(421)))),W5=oe(F1);function b0(r,e){let t=ys.exactMatch(r),n=ys.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=bs.exactMatch(r),s=bs.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=Kr.exactMatch(r),a=Kr.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=nd.exactMatch(r),u=nd.exactMatch(e);if(c&&!u)return-1;if(!c&&u)return 1;let l=td.exactMatch(r),f=td.exactMatch(e);if(l&&!f)return-1;if(!l&&f)return 1;let d=rd.exactMatch(r),h=rd.exactMatch(e);return d&&!h?-1:!d&&h?1:0}function w0(r,e){let t=ps(r),n=ps(e);return t&&!n?1:!t&&n?-1:0}function x0(r,e){let t=Bt(r),n=Bt(e);return t&&!n?1:!t&&n?-1:0}function E0(r,e){let t=zr.exactMatch(r),n=zr.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function ve(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var la=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},$n=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new la(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new la(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var od=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Vn(r={}){return B1(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function B1(r,e){e=e??{};let t=e.onEnd,n=new $n,o,s,i,a=ve(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,y)=>{s=w=>{s=null,n.push(w);try{m(r(n))}catch(x){y(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ve()})}},u=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new $n,s!=null?s({error:m}):(n.push({error:m}),o)),f=m=>{if(i)return o;if(e?.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 $n,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 y=m?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let w,x;y!=null&&(w=new Promise((_,A)=>{x=()=>{A(new od)},y.addEventListener("abort",x)}));try{await Promise.race([a.promise,w])}finally{x!=null&&y!=null&&y?.removeEventListener("abort",x)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(m){return g.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(m){return g.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:m=>g.onEmpty(m)},o}var sd=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},v0=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function ws(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(v0(i));return}if(i&&(c=()=>{d(v0(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new sd;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var U1=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function K1(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:u,removeListener:l}=U1(r),f=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d)};for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=ws(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function ht(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=K1(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function xs(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var fa=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},da=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},qr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function z1(r){return r.reason}async function We(r,e,t){if(e==null)return r;let n=t?.translateError??z1;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var ha=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=ve(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new tt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function q1(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var pa=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=q1(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new tt),this.cleanup())}async join(e){let t=new ha(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await We(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Hn=class extends Re{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=xs(this.emitEmpty.bind(this),1),this.emitIdle=xs(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new da;let n=new pa(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new tt)}),this.clear()}async onEmpty(e){this.size!==0&&await ht(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ht(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ht(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Vn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new tt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function vt(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var jn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var $1=1.2,V1=2,H1=5e3,j1=6e4,G1=5e3,ma=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??G1;this.success=new jn(t),this.failure=new jn(t),this.next=new jn(t),this.failureMultiplier=e.failureMultiplier??V1,this.timeoutMultiplier=e.timeoutMultiplier??$1,this.minTimeout=e.minTimeout??H1,this.maxTimeout=e.maxTimeout??j1,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=vt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var id=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ve(),this.haveNext=ve()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ve(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ve(),await We(this.readNext.promise,t?.signal,t)}};function S0(){return new id}function W1(r){return r[Symbol.asyncIterator]!=null}async function X1(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Y1(r){let e=new AbortController,t=S0();X1(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Z1(r){for(let e of r)yield*e}function Q1(...r){let e=[];for(let t of r)W1(t)||e.push(t);return e.length===r.length?Z1(e):Y1(r)}var Gn=Q1;var J1=4194304,ga=class extends Error{static name="UnwrappedError";name="UnwrappedError"},cd=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ud=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ld=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function e2(r){return typeof r?.closeRead=="function"}function t2(r){return typeof r?.close=="function"}function ad(r){return e2(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:t2(r)?r.status!=="open":!1}function r2(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function fd(r,e){let t=e?.maxBufferSize??J1,n=new ee,o,s=!1;if(!r2(r))throw new R("Argument should be a Stream or a Multiaddr");let i=l=>{if(n.append(l.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=l=>{l.error!=null?o?.reject(l.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(l){if(s===!0)throw new ga("Stream was unwrapped");if(ad(r)){if(n.byteLength===0&&l?.bytes==null)return null;if(l?.bytes!=null&&n.byteLength<l.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,l.bytes),new qr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${l.bytes} bytes`)}let f=l?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await We(o.promise,l?.signal),ad(r)){if(n.byteLength===0&&l?.bytes==null)return null;break}o=Promise.withResolvers()}let d=l?.bytes??n.byteLength;if(n.byteLength<d){if(ad(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new qr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(l)}let h=n.sublist(0,d);return n.consume(d),h},async write(l,f){if(s===!0)throw new ga("Stream was unwrapped");r.send(l)||await ht(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function ya(r,e={}){let t=fd(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=je(e.maxDataLength));let n=e?.lengthDecoder??Di,o=e?.lengthEncoder??sr;return{async read(i){let a=-1,c=new ee;for(;;){let l=await t.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new cd("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new ld(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new ud(`Message length too long - ${a} > ${e.maxDataLength}`);let u=await t.read({...i,bytes:a});if(u==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new qr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new qr(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await t.write(new ee(o(i.byteLength),i),a)},async writeV(i,a){let c=new ee(...i.flatMap(u=>[o(u.byteLength),u]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function A0(r=0){return new Uint8Array(r)}var ba=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Wn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},wa=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Es=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function xa(r){return r[Symbol.asyncIterator]!=null}function _0(r,e){if(r.byteLength>e)throw new Wn("Message length too long")}var va=r=>{let e=je(r),t=A0(e);return sr(r,t),va.bytes=e,t};va.bytes=0;function Sa(r,e){e=e??{};let t=e.lengthEncoder??va,n=e?.maxDataLength??4194304;function*o(s){_0(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return xa(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Sa.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??va,n=e?.maxDataLength??4194304;return _0(r,n),new ee(t(r.byteLength),r)};var $r;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})($r||($r={}));var hd=r=>{let e=Di(r);return hd.bytes=je(e),e};hd.bytes=0;function dd(r,e){let t=new ee,n=$r.LENGTH,o=-1,s=e?.lengthDecoder??hd,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===$r.LENGTH)try{if(o=s(t),o<0)throw new ba("Invalid message length");if(o>a)throw new Wn("Message length too long");let u=s.bytes;t.consume(u),e?.onLength!=null&&e.onLength(o),n=$r.DATA}catch(u){if(u instanceof RangeError){if(t.byteLength>i)throw new wa("Message length length too long");break}throw u}if(n===$r.DATA){if(t.byteLength<o)break;let u=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(u),yield u,n=$r.LENGTH}}}return xa(r)?(async function*(){for await(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Es("Unexpected end of input")})():(function*(){for(let u of r)t.append(u),yield*c();if(t.byteLength>0)throw new Es("Unexpected end of input")})()}dd.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return dd(n,{...e??{},onLength:s=>{t=s}})};var Aa=class extends Hn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var _a=class extends Hn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var Ca=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new pd}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new fa("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},pd=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var md=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Pe(r){let{name:e,metrics:t}=r,n;return t!=null?n=new md({name:e,metrics:t}):n=new Map,n}var gd=class extends et{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function yd(r){let{name:e,metrics:t}=r,n;return t!=null?n=new gd({name:e,metrics:t}):n=new et,n}var vs;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:qe(0),payloadType:qe(0),payload:qe(0),signature:qe(0)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Be(s,r.codec(),i)}r.stream=o})(vs||(vs={}));var Ia=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Xn=class r{static createFromProtobuf=e=>{let t=vs.decode(e),n=Cn(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=C0(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new Ia("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=vs.encode({publicKey:Qe(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:J(this.marshal(),e.marshal())}async validate(e,t){let n=C0(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},C0=(r,e,t)=>{let n=M(r),o=sr(n.byteLength),s=sr(e.length),i=sr(t.length);return new ee(o,n,s,e,i,t)};var I0="libp2p-peer-record",T0=Uint8Array.from([3,1]);var Ss;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Ue((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let p={multiaddr:qe(0)},g=d==null?f.len:f.pos+d;for(;f.pos<g;){let m=f.uint32();m>>>3===1?p.multiaddr=f.bytes():f.skipType(m&7)}return p},function*(f,d,h,p={}){let g=d==null?f.len:f.pos+d;for(;f.pos<g;){let m=f.uint32();m>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(m&7)}})),a);function c(f){return Fe(f,i.codec())}i.encode=c;function u(f,d){return Me(f,i.codec(),d)}i.decode=u;function l(f,d){return Be(f,i.codec(),d)}i.stream=l})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ue((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let u of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(u,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={peerId:qe(0),seq:0n,addresses:[]},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.peerId=i.bytes();break}case 2:{u.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&u.addresses.length===c.limits.addresses)throw new Je('Decode error - repeated field "addresses" had too many elements');u.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(f&7);break}}}return u},function*(i,a,c,u={}){let l={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(u.limits?.addresses!=null&&l.addresses===u.limits.addresses)throw new Je('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:u.limits?.addresses$}))yield{...h,index:l.addresses};l.addresses++;break}default:{i.skipType(d&7);break}}}})),t);function n(i){return Fe(i,r.codec())}r.encode=n;function o(i,a){return Me(i,r.codec(),a)}r.decode=o;function s(i,a){return Be(i,r.codec(),a)}r.stream=s})(Ss||(Ss={}));function L0(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Vr=class r{static createFromProtobuf=e=>{let t=Ss.decode(e),n=In(Tt(t.peerId)),o=(t.addresses??[]).map(i=>Q(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=I0;static CODEC=T0;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Ss.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!L0(this.multiaddrs,e.multiaddrs))}};function o2(r){return r[Symbol.asyncIterator]!=null}function s2(r){if(o2(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var As=s2;var Xe=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Ta(r,e,t,n){let o=new Xe(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){wd(t,"abort",f),wd(r,e,u),wd(r,s,l)}let u=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},l=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};bd(t,"abort",f),bd(r,e,u),bd(r,s,l)})}function bd(r,e,t){r!=null&&(D0(r)?r.addEventListener(e,t):r.addListener(e,t))}function wd(r,e,t){r!=null&&(D0(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function D0(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var La=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Da=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Xe)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function i2(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Pa=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=i2(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Xe),this.cleanup())}async join(e={}){let t=new Da(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await We(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function xd(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var _s=class extends Re{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=xd(this.emitEmpty.bind(this),1),this.emitIdle=xd(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new La;let n=new Pa(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Xe)}),this.clear()}async onEmpty(e){this.size!==0&&await Ta(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ta(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ta(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Vn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Xe("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var ka="lock:worker:request-read",Ra="lock:worker:abort-read-request",Oa="lock:worker:release-read",Na="lock:master:grant-read",Ma="lock:master:error-read",Fa="lock:worker:request-write",Ba="lock:worker:abort-write-request",Ua="lock:worker:release-write",Ka="lock:master:grant-write",za="lock:master:error-write",qa="lock:worker:finalize",$a="mortice",P0={singleProcess:!1};var Ed=(r,e,t,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(t,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{e.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&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.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===qa&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}})};var k0=(r=10)=>Math.random().toString().substring(2,r+2);var Va=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel($a)}readLock(e){return this.sendRequest(ka,Ra,Na,Ma,Oa,e)}writeLock(e){return this.sendRequest(Fa,Ba,Ka,za,Ua,e)}finalize(){this.channel.postMessage({type:qa,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=k0();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,u)=>{let l=()=>{this.channel.postMessage({type:t,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 R0=r=>{if(r=Object.assign({},P0,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel($a),n=new Re;return t.addEventListener("message",Ed(n,t,"requestReadLock","abortReadLockRequest",ka,Ra,Ma,Oa,Na)),t.addEventListener("message",Ed(n,t,"requestWriteLock","abortWriteLockRequest",Fa,Ba,za,Ua,Ka)),n}return new Va(r.name)};var Hr=new Map,Cs;function O0(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function a2(r){if(Cs==null&&(Cs=R0(r),!O0(Cs))){let e=Cs;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Hr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Hr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Hr.get(n);o?.finalize()})}return Cs}async function vd(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new Xe)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var N0=(r,e)=>{let t=Hr.get(r);if(t!=null)return t;let n=a2(e);if(O0(n))return t=n,Hr.set(r,t),t;let o=new _s({concurrency:1}),s;return t={async readLock(i){if(s!=null)return vd(s,i);s=new _s({concurrency:e.concurrency,autoStart:!1});let a=s,c=vd(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,vd(o,i)},finalize:()=>{Hr.delete(r)},queue:o},Hr.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var c2={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Sd(r){let e=Object.assign({},c2,r);return N0(e.name,e)}var qt;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Ue((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let g={key:"",value:qe(0)},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=d.bytes();break}default:{d.skipType(y&7);break}}}return g},function*(d,h,p,g={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield{field:`${p}.value`,value:d.bytes()};break}default:{d.skipType(y&7);break}}}})),c);function u(d){return Fe(d,a.codec())}a.encode=u;function l(d,h){return Me(d,a.codec(),h)}a.decode=l;function f(d,h){return Be(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=Ue((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Ts.codec().encode(d.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let g={key:""},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=Ts.codec().decode(d,d.uint32(),{limits:p.limits?.value});break}default:{d.skipType(y&7);break}}}return g},function*(d,h,p,g={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield*Ts.codec().stream(d,d.uint32(),`${p}.value`,{limits:g.limits?.value});break}default:{d.skipType(y&7);break}}}})),c);function u(d){return Fe(d,a.codec())}a.encode=u;function l(d,h){return Me(d,a.codec(),h)}a.decode=l;function f(d,h){return Be(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ue((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let l of a.addresses)c.uint32(10),Is.codec().encode(l,c);if(a.protocols!=null&&a.protocols.length>0)for(let l of a.protocols)c.uint32(18),c.string(l);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[l,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:l,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[l,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:l,value:f},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={addresses:[],protocols:[],metadata:new Map,tags:new Map},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(u.limits?.addresses!=null&&l.addresses.length===u.limits.addresses)throw new Je('Decode error - repeated field "addresses" had too many elements');l.addresses.push(Is.codec().decode(a,a.uint32(),{limits:u.limits?.addresses$}));break}case 2:{if(u.limits?.protocols!=null&&l.protocols.length===u.limits.protocols)throw new Je('Decode error - repeated field "protocols" had too many elements');l.protocols.push(a.string());break}case 4:{l.publicKey=a.bytes();break}case 5:{l.peerRecordEnvelope=a.bytes();break}case 6:{if(u.limits?.metadata!=null&&l.metadata.size===u.limits.metadata)throw new es('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.metadata$value}});l.metadata.set(h.key,h.value);break}case 7:{if(u.limits?.tags!=null&&l.tags.size===u.limits.tags)throw new es('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:u.limits?.tags$value}});l.tags.set(h.key,h.value);break}case 8:{l.updated=a.uint64Number();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,u,l={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(l.limits?.addresses!=null&&f.addresses===l.limits.addresses)throw new Je('Streaming decode error - repeated field "addresses" had too many elements');for(let p of Is.codec().stream(a,a.uint32(),`${u}.addresses[]`,{limits:l.limits?.addresses$}))yield{...p,index:f.addresses};f.addresses++;break}case 2:{if(l.limits?.protocols!=null&&f.protocols===l.limits.protocols)throw new Je('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${u}.protocols[]`,index:f.protocols,value:a.string()},f.protocols++;break}case 4:{yield{field:`${u}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${u}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(l.limits?.metadata!=null&&f.metadata===l.limits.metadata)throw new Je('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${u}.metadata{}`,{limits:{value:l.limits?.metadata$value}}),f.metadata++;break}case 7:{if(l.limits?.tags!=null&&f.tags===l.limits.tags)throw new Je('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${u}.tags{}`,{limits:{value:l.limits?.tags$value}}),f.tags++;break}case 8:{yield{field:`${u}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Fe(a,r.codec())}r.encode=o;function s(a,c){return Me(a,r.codec(),c)}r.decode=s;function i(a,c){return Be(a,r.codec(),c)}r.stream=i})(qt||(qt={}));var Is;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:qe(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}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Be(s,r.codec(),i)}r.stream=o})(Is||(Is={}));var Ts;(function(r){let e;r.codec=()=>(e==null&&(e=Ue((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return Fe(s,r.codec())}r.encode=t;function n(s,i){return Me(s,r.codec(),i)}r.decode=n;function o(s,i){return Be(s,r.codec(),i)}r.stream=o})(Ts||(Ts={}));function u2(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=Cn(e.publicKey,t);return sf(n)}function M0(r,e,t){let n=qt.decode(e);return Yn(r,n,t)}function Yn(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:u2(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:Q(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function F0(r,e){return l2(r.addresses,e.addresses)&&f2(r.protocols,e.protocols)&&d2(r.publicKey,e.publicKey)&&h2(r.peerRecordEnvelope,e.peerRecordEnvelope)&&p2(r.metadata,e.metadata)&&m2(r.tags,e.tags)}function l2(r,e){return U0(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!J(t.multiaddr,n.multiaddr)))}function f2(r,e){return U0(r,e,(t,n)=>t===n)}function d2(r,e){return B0(r,e)}function h2(r,e){return B0(r,e)}function p2(r,e){return K0(r,e,(t,n)=>J(t,n))}function m2(r,e){return K0(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function B0(r,e){return r==null&&e==null?!0:r!=null&&e!=null?J(r,e):!1}function U0(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function K0(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Td={};U(Td,{base10:()=>v2});var Yk=new Uint8Array(0);function z0(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function $t(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 q0(r){return new TextEncoder().encode(r)}function $0(r){return new TextDecoder().decode(r)}function g2(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),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,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var x=(w-y)*l+1>>>0,_=new Uint8Array(x);y!==w;){for(var A=p[y],D=0,I=x-1;(A!==0||D<m)&&I!==-1;I--,D++)A+=256*_[I]>>>0,_[I]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=D,y++}for(var v=x-m;v!==x&&_[v]===0;)v++;for(var O=c.repeat(g);v<x;++v)O+=r.charAt(_[v]);return O}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,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,x=new Uint8Array(w);p[g];){var _=t[p.charCodeAt(g)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<y)&&D!==-1;D--,A++)_+=a*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}if(p[g]!==" "){for(var I=w-y;I!==w&&x[I]===0;)I++;for(var v=new Uint8Array(m+(w-I)),O=m;I!==w;)v[O++]=x[I++];return v}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var y2=g2,b2=y2,H0=b2;var Ad=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},_d=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return j0(this,e)}},Cd=class{decoders;constructor(e){this.decoders=e}or(e){return j0(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function j0(r,e){return new Cd({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Id=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ad(e,t,n),this.decoder=new _d(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Zn({name:r,prefix:e,encode:t,decode:n}){return new Id(r,e,t,n)}function dr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=H0(t,r);return Zn({prefix:e,name:r,encode:n,decode:s=>$t(o(s))})}function w2(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function x2(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function E2(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function fe({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=E2(n);return Zn({prefix:e,name:r,encode(s){return x2(s,n,t)},decode(s){return w2(s,o,t,r)}})}var v2=dr({prefix:"9",name:"base10",alphabet:"0123456789"});var Ld={};U(Ld,{base16:()=>S2,base16upper:()=>A2});var S2=fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),A2=fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Dd={};U(Dd,{base2:()=>_2});var _2=fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Pd={};U(Pd,{base256emoji:()=>D2});var G0=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}"),C2=G0.reduce((r,e,t)=>(r[t]=e,r),[]),I2=G0.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function T2(r){return r.reduce((e,t)=>(e+=C2[t],e),"")}function L2(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=I2[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var D2=Zn({prefix:"\u{1F680}",name:"base256emoji",encode:T2,decode:L2});var kd={};U(kd,{base32:()=>Qn,base32hex:()=>O2,base32hexpad:()=>M2,base32hexpadupper:()=>F2,base32hexupper:()=>N2,base32pad:()=>k2,base32padupper:()=>R2,base32upper:()=>P2,base32z:()=>B2});var Qn=fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),P2=fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),k2=fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),R2=fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),O2=fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),N2=fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),M2=fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),F2=fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),B2=fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Rd={};U(Rd,{base36:()=>Ls,base36upper:()=>U2});var Ls=dr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),U2=dr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Od={};U(Od,{base58btc:()=>St,base58flickr:()=>K2});var St=dr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),K2=dr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Nd={};U(Nd,{base64:()=>z2,base64pad:()=>q2,base64url:()=>$2,base64urlpad:()=>V2});var z2=fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),q2=fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$2=fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),V2=fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Md={};U(Md,{base8:()=>H2});var H2=fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Fd={};U(Fd,{identity:()=>j2});var j2=Zn({prefix:"\0",name:"identity",encode:r=>$0(r),decode:r=>q0(r)});var dR=new TextEncoder,hR=new TextDecoder;var Ud={};U(Ud,{identity:()=>mS});var X2=Y0,W0=128,Y2=127,Z2=~Y2,Q2=Math.pow(2,31);function Y0(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Q2;)e[t++]=r&255|W0,r/=128;for(;r&Z2;)e[t++]=r&255|W0,r>>>=7;return e[t]=r|0,Y0.bytes=t-n+1,e}var J2=Bd,eS=128,X0=127;function Bd(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Bd.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&X0)<<o:(i&X0)*Math.pow(2,o),o+=7}while(i>=eS);return Bd.bytes=s-n,t}var tS=Math.pow(2,7),rS=Math.pow(2,14),nS=Math.pow(2,21),oS=Math.pow(2,28),sS=Math.pow(2,35),iS=Math.pow(2,42),aS=Math.pow(2,49),cS=Math.pow(2,56),uS=Math.pow(2,63),lS=function(r){return r<tS?1:r<rS?2:r<nS?3:r<oS?4:r<sS?5:r<iS?6:r<aS?7:r<cS?8:r<uS?9:10},fS={encode:X2,decode:J2,encodingLength:lS},dS=fS,Ds=dS;function Ps(r,e=0){return[Ds.decode(r,e),Ds.decode.bytes]}function Jn(r,e,t=0){return Ds.encode(r,e,t),e}function eo(r){return Ds.encodingLength(r)}function ro(r,e){let t=e.byteLength,n=eo(r),o=n+eo(t),s=new Uint8Array(o+t);return Jn(r,s,0),Jn(t,s,n),s.set(e,o),new to(r,t,e,s)}function Z0(r){let e=$t(r),[t,n]=Ps(e),[o,s]=Ps(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new to(t,o,i,e)}function Q0(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&z0(r.bytes,t.bytes)}}var to=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var J0=0,hS="identity",ey=$t;function pS(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ro(J0,ey(r))}var mS={code:J0,name:hS,encode:ey,digest:pS};var qd={};U(qd,{sha256:()=>yS,sha512:()=>bS});var gS=20;function zd({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Kd(r,e,t,n,o)}var Kd=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??gS,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ty(n,this.code,t?.truncate):n.then(o=>ty(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ty(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ro(e,r)}function ny(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var yS=zd({name:"sha2-256",code:18,encode:ny("SHA-256")}),bS=zd({name:"sha2-512",code:19,encode:ny("SHA-512")});function oy(r,e){let{bytes:t,version:n}=r;return n===0?xS(t,$d(r),e??St.encoder):ES(t,$d(r),e??Qn.encoder)}var sy=new WeakMap;function $d(r){let e=sy.get(r);if(e==null){let t=new Map;return sy.set(r,t),t}return e}var ja=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Rs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==vS)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=ro(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Q0(e.multihash,n.multihash)}toString(e){return oy(this,e)}toJSON(){return{"/":oy(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??iy(n,o,s.bytes))}else if(t[SS]===!0){let{version:n,multihash:o,code:s}=t,i=Z0(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Rs)throw new Error(`Version 0 CID must use dag-pb (code: ${Rs}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=iy(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Rs,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=$t(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new to(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Ps(e.subarray(t));return t+=d,f},o=n(),s=Rs;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=wS(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $d(s).set(n,e),s}};function wS(r,e){switch(r[0]){case"Q":{let t=e??St;return[St.prefix,t.decode(`${St.prefix}${r}`)]}case St.prefix:{let t=e??St;return[St.prefix,t.decode(r)]}case Qn.prefix:{let t=e??Qn;return[Qn.prefix,t.decode(r)]}case Ls.prefix:{let t=e??Ls;return[Ls.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function xS(r,e,t){let{prefix:n}=t;if(n!==St.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function ES(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Rs=112,vS=18;function iy(r,e,t){let n=eo(r),o=n+eo(e),s=new Uint8Array(o+t.byteLength);return Jn(r,s,0),Jn(e,s,n),s.set(t,o),s}var SS=Symbol.for("@ipld/js-cid/CID");var Vd={...Fd,...Dd,...Md,...Td,...Ld,...kd,...Rd,...Od,...Nd,...Pd},NR={...qd,...Ud};function ay(r=0){return new Uint8Array(r)}function uy(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var cy=uy("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Hd=uy("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ay(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),AS={utf8:cy,"utf-8":cy,hex:Vd.base16,latin1:Hd,ascii:Hd,binary:Hd,...Vd},Ga=AS;function ly(r,e="utf8"){let t=Ga[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function fy(r,e="utf8"){let t=Ga[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Vt="/",dy=new TextEncoder().encode(Vt),Wa=dy[0],jr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=ly(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Wa)throw new Error("Invalid key")}toString(e="utf8"){return fy(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Vt))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=dy),this._buf[0]!==Wa){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Wa,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Wa;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Vt).slice(1)}type(){return _S(this.baseNamespace())}name(){return CS(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Vt)||(e+=Vt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Vt):new r(e.slice(0,-1).join(Vt))}child(e){return this.toString()===Vt?e:e.toString()===Vt?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...IS(e.map(t=>t.namespaces()))])}};function _S(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function CS(r){let e=r.split(":");return e[e.length-1]}function IS(r){return[].concat(...r)}var jd="/peers/";function Os(r){if(!Wt(r)||r.type==null)throw new R("Invalid PeerId");let e=r.toCID().toString();return new jr(`${jd}${e}`)}async function hy(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=Q(i.multiaddr)),!fr(i.multiaddr))throw new R("Multiaddr was invalid");if(!await e(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.getComponents().find(u=>u.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(Q(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Ya(r,e,t,n){if(e==null)throw new R("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new R("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new R("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(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Xa(d,{validate:py})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Xa(d,{validate:my,map:gy})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Xa([...a.entries()],{validate:py})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,g]of d)g==null?h.delete(p):h.set(p,g);c=Xa([...h.entries()],{validate:my,map:gy})}e.peerRecordEnvelope!=null&&(u=e.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=Qe(o.id.publicKey):e.publicKey!=null?l=Qe(e.publicKey):r.publicKey!=null&&(l=Qe(r.publicKey));let f={addresses:await hy(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=>J(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Xa(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function py(r,e){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function my(r,e){if(typeof r!="string")throw new R("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new R("Tag value must be an integer");if(e.value<0||e.value>100)throw new R("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new R("Tag ttl must be an integer");if(e.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function gy(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function yy(r){let e=r.toString().split("/")[2],t=pe.parse(e,Ze);return us(t)}function Gd(r,e,t){let n=yy(r);return M0(n,e,t)}function TS(r,e){return{prefix:jd,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(Gd(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(Gd(n.key,n.value,e),Gd(o.key,o.value,e)))}}var Za=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=yd({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:Sd({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Os(e),t)}async load(e,t){let n=Os(e),o=await this.datastore.get(n,t),s=qt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new gr;return Yn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await Ya(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await Ya(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await Ya(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(TS(e??{},this.maxAddressAge),e)){let o=yy(t);if(o.equals(this.peerId))continue;let s=qt.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield Yn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Os(e),o=await this.datastore.get(n,t),s=qt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new gr;return{peerPB:s,peer:Yn(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=qt.encode(t);return await this.datastore.put(Os(e),s,o),{peer:Yn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!F0(t,n.peerPB)}}#n(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var Wd=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Za(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return As(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Wt(t)?t:Wt(t?.expectedPeer)?t.expectedPeer:void 0,s=Wt(t)||t===void 0?n:t,i=await Xn.openAndCertify(e,Vr.DOMAIN,s),a=us(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=Vr.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=Xn.createFromProtobuf(u.peerRecordEnvelope),f=Vr.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:e,addresses:c.multiaddrs.map(l=>({isCertified:!0,multiaddr:l}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function by(r,e={}){return new Wd(r,e)}var Qa=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function LS(r){return r[Symbol.asyncIterator]!=null}function DS(r){if(LS(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Xd=DS;function PS(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var wy=PS;function kS(r){return r[Symbol.asyncIterator]!=null}function RS(r,e){let t=0;if(kS(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=wy(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Gr=RS;function OS(r){return r[Symbol.asyncIterator]!=null}function NS(r,e){return OS(r)?(async function*(){yield*(await As(r)).sort(e)})():(function*(){yield*As(r).sort(e)})()}var Yd=NS;function MS(r){return r[Symbol.asyncIterator]!=null}function FS(r,e){return MS(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var Zd=FS;var Ja=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Xd(this.putMany(e,n)),e=[],await Xd(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Gr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Gr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Yd(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Gr(n,()=>o++>=s)}return e.limit!=null&&(n=Zd(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Gr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Gr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Yd(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Gr(n,()=>s++>=o)}return e.limit!=null&&(n=Zd(n,e.limit)),n}};var ec=class extends Ja{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Qa;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new jr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new jr(n),t?.signal?.throwIfAborted()}};var xy=864e13;var tc=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Pe({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=G(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=On(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?xy-Date.now():0,lastVerified:o?xy-Date.now():void 0})})}remove(e){let t=G(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!_e(o))continue;let s=G(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),Q(n)}confirm(e,t){let n=G(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=G(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var rc=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Pe({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=G(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:dt(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=G(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!_e(n))continue;let o=G(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(u=>u.code===4||u.code===41),c=i.findIndex(u=>u.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,Q(i)):e}confirm(e,t){if(!_e(e))return!1;let n=G(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!_e(e))return!1;let n=G(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var BS={maxObservedAddresses:10},nc=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Pe({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??BS.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Bt(e)||Hg(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:Q(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var US={maxObservedAddresses:10},oc=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Pe({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??US.maxObservedAddresses}get(e,t){if(Bt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!_e(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!_e(e))return e.toString();let t=G(e);return`${t.host}-${t.port}-${t.protocol}`}};var Ey=6e4,vy={maxObservedAddresses:10,addressVerificationTTL:Ey*10,addressVerificationRetry:Ey*5},KS=r=>r;function Qd(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&xt(t).equals(e)&&(r=r.decapsulate(Q(`/p2p/${e.toString()}`))),r}var sc=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new nc(e,t),this.dnsMappings=new tc(e,t),this.ipMappings=new rc(e,t),this.transportAddresses=new oc(e,t),this.announceFilter=t.announceFilter??KS,this.observedAddressFilter=ds(1024),this.addressVerificationTTL=t.addressVerificationTTL??vy.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??vy.addressVerificationRetry,this._updatePeerStoreAddresses=xs(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>Q(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Q(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Q(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=G(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Qd(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Qd(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Qd(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=Q(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Q(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${dt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(Q(`/ip${dt(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!_e(e))return!1;let t=G(e);if(t.type!=="ip4"||On(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Kr.exactMatch(s)||bs.exactMatch(s),s=>ys.exactMatch(s),s=>h0.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(u=>u.getAddrs().filter(l=>G(l).type==="ip4"&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>!ps(u)).pop();if(a==null)continue;let c=G(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var Sy;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Sy||(Sy={}));var ic=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},ac=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},no=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ns=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},cc=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},uc=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},lc=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Ms=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},fc=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},dc=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},hc=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},pc=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},mc=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},hr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Wr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},gc=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},yc=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Jd=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=$i())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>oi(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},zS=["metrics","connectionProtector","dns"],qS=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Ay(r={}){let e=new Jd(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!qS.includes(o)){let i=e.components[o];if(i==null&&!zS.includes(o))throw new ic(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function _y(r){let e={};for(let t of Object.values(r.components))for(let n of $S(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of VS(t))if(e[n]!==!0)throw new ac(`Service "${HS(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function $S(r){return Array.isArray(r?.[xo])?r[xo]:[]}function VS(r){return Array.isArray(r?.[Xc])?r[Xc]:[]}function HS(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function Cy(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Kr.matches(e)?!0:Bt(e)),r}var te=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function bc(r){if(Wt(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:xt(n),e.forEach(o=>{if(!fr(o))throw new jt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let i=xt(s);if(t?.equals(i)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!l0.exactMatch(n)),{peerId:t,multiaddrs:e}}var jS=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Iy(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??jS;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function Fs(r){let e=G(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new R(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new R(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Dn(e.host,t)}function eh(r){return!zr.exactMatch(r)}function wc(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>eh(s)))return n}var xc=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Fs(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new et;for(let c of e){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 - %e",l)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(l=>{if(_e(c.remoteAddr)){let f=G(c.remoteAddr);return l.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Iy(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Ty="last-dial-failure",Ly="last-dial-success";var Dy=100,Ec=50;function GS(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Py(r){return r.sort((e,t)=>w0(e.multiaddr,t.multiaddr)||x0(e.multiaddr,t.multiaddr)||E0(e.multiaddr,t.multiaddr)||GS(e,t)||b0(e.multiaddr,t.multiaddr))}var vc=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var rh=Vc(Ry(),1);function nh(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var YS=100,oo=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:s}=this,i={priority:n,id:o,run:e};if(s===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#n();let a=nh(this.#e,i,(c,u)=>u.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((s,i)=>i>=this.#t&&s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>YS&&this.#t>this.#e.length/2&&this.#n(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#n(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var Us=class extends rh.default{#e;#t;#n=0;#h;#m=!1;#w=!1;#c;#I=0;#x=0;#u;#l;#a;#i=[];#s=0;#r;#T;#o=0;#g;#f;#R=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:oo,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#T=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#z()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#c)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#O(e){this.#a?this.#i.push(e):this.#n++}#N(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#S(){return this.#i.length-this.#s}get#M(){return this.#t?!0:this.#a?this.#S()<this.#h:this.#n<this.#h}get#F(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#U(){this.#l=void 0,this.#P(),this.#D()}#K(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#A(o),!0}return!1}if(this.#u===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#A(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#A(t),!0}return!1}#A(e){this.#l===void 0&&(this.#l=setTimeout(()=>{this.#U()},e))}#_(){this.#u&&(clearInterval(this.#u),this.#u=void 0)}#L(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#b(){if(this.#r.size===0){if(this.#_(),this.emit("empty"),this.#o===0){if(this.#L(),this.#a&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#K(t);if(this.#M&&this.#F){let o=this.#r.dequeue();this.#t||(this.#O(t),this.#p()),this.emit("active"),o(),n&&this.#D(),e=!0}}return e}#D(){this.#t||this.#u!==void 0||this.#a||(this.#u=setInterval(()=>{this.#P()},this.#c),this.#I=Date.now()+this.#c)}#P(){this.#a||(this.#n===0&&this.#o===0&&this.#u&&this.#_(),this.#n=this.#e?this.#o:0),this.#C(),this.#p()}#C(){for(;this.#b(););}get concurrency(){return this.#g}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#g=e,this.#C()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#r.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let u;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#q(),this.#y.delete(s),d}this.#x=Date.now();let l=e({signal:t.signal});if(t.timeout&&(l=ws(Promise.resolve(l),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#r.size} waiting)`})),t.signal){let{signal:d}=t;l=Promise.race([l,new Promise((h,p)=>{u=()=>{p(d.reason)},d.addEventListener("abort",u,{once:!0})})])}let f=await l;n(f),this.emit("completed",f)}catch(l){o(l),this.emit("error",l)}finally{u&&t.signal?.removeEventListener("abort",u),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof oo){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:u}=t,l=()=>{i(),c(),o(u.reason),this.#b(),this.emit("next")};if(i=()=>{u.removeEventListener("abort",l),this.#E.delete(i)},u.aborted){l();return}u.addEventListener("abort",l,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#C(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#T,this.#_(),this.#k(),this.emit("empty"),this.#o===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async onPendingZero(){this.#o!==0&&await this.#d("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#d("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#d("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#z(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#k()}))}#q(){this.#t||(this.#N(),this.#p())}#k(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#n;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function Ac(r){let e=[Ye.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var ch={};U(ch,{base10:()=>nA});var JN=new Uint8Array(0);function Oy(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Ht(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 Ny(r){return new TextEncoder().encode(r)}function My(r){return new TextDecoder().decode(r)}function ZS(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),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,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var x=(w-y)*l+1>>>0,_=new Uint8Array(x);y!==w;){for(var A=p[y],D=0,I=x-1;(A!==0||D<m)&&I!==-1;I--,D++)A+=256*_[I]>>>0,_[I]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=D,y++}for(var v=x-m;v!==x&&_[v]===0;)v++;for(var O=c.repeat(g);v<x;++v)O+=r.charAt(_[v]);return O}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,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*u+1>>>0,x=new Uint8Array(w);p[g];){var _=t[p.charCodeAt(g)];if(_===255)return;for(var A=0,D=w-1;(_!==0||A<y)&&D!==-1;D--,A++)_+=a*x[D]>>>0,x[D]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=A,g++}if(p[g]!==" "){for(var I=w-y;I!==w&&x[I]===0;)I++;for(var v=new Uint8Array(m+(w-I)),O=m;I!==w;)v[O++]=x[I++];return v}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var QS=ZS,JS=QS,By=JS;var oh=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},sh=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Uy(this,e)}},ih=class{decoders;constructor(e){this.decoders=e}or(e){return Uy(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Uy(r,e){return new ih({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ah=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new oh(e,t,n),this.decoder=new sh(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function so({name:r,prefix:e,encode:t,decode:n}){return new ah(r,e,t,n)}function pr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=By(t,r);return so({prefix:e,name:r,encode:n,decode:s=>Ht(o(s))})}function eA(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function tA(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function rA(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function de({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=rA(n);return so({prefix:e,name:r,encode(s){return tA(s,n,t)},decode(s){return eA(s,o,t,r)}})}var nA=pr({prefix:"9",name:"base10",alphabet:"0123456789"});var uh={};U(uh,{base16:()=>oA,base16upper:()=>sA});var oA=de({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),sA=de({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var lh={};U(lh,{base2:()=>iA});var iA=de({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fh={};U(fh,{base256emoji:()=>fA});var Ky=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}"),aA=Ky.reduce((r,e,t)=>(r[t]=e,r),[]),cA=Ky.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function uA(r){return r.reduce((e,t)=>(e+=aA[t],e),"")}function lA(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=cA[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var fA=so({prefix:"\u{1F680}",name:"base256emoji",encode:uA,decode:lA});var dh={};U(dh,{base32:()=>io,base32hex:()=>mA,base32hexpad:()=>yA,base32hexpadupper:()=>bA,base32hexupper:()=>gA,base32pad:()=>hA,base32padupper:()=>pA,base32upper:()=>dA,base32z:()=>wA});var io=de({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),dA=de({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hA=de({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pA=de({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mA=de({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gA=de({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yA=de({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),bA=de({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),wA=de({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var hh={};U(hh,{base36:()=>Ks,base36upper:()=>xA});var Ks=pr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xA=pr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ph={};U(ph,{base58btc:()=>At,base58flickr:()=>EA});var At=pr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),EA=pr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var mh={};U(mh,{base64:()=>vA,base64pad:()=>SA,base64url:()=>AA,base64urlpad:()=>_A});var vA=de({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),SA=de({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),AA=de({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_A=de({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var gh={};U(gh,{base8:()=>CA});var CA=de({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var yh={};U(yh,{identity:()=>IA});var IA=so({prefix:"\0",name:"identity",encode:r=>My(r),decode:r=>Ny(r)});var mM=new TextEncoder,gM=new TextDecoder;var wh={};U(wh,{identity:()=>YA});var DA=$y,zy=128,PA=127,kA=~PA,RA=Math.pow(2,31);function $y(r,e,t){e=e||[],t=t||0;for(var n=t;r>=RA;)e[t++]=r&255|zy,r/=128;for(;r&kA;)e[t++]=r&255|zy,r>>>=7;return e[t]=r|0,$y.bytes=t-n+1,e}var OA=bh,NA=128,qy=127;function bh(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw bh.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&qy)<<o:(i&qy)*Math.pow(2,o),o+=7}while(i>=NA);return bh.bytes=s-n,t}var MA=Math.pow(2,7),FA=Math.pow(2,14),BA=Math.pow(2,21),UA=Math.pow(2,28),KA=Math.pow(2,35),zA=Math.pow(2,42),qA=Math.pow(2,49),$A=Math.pow(2,56),VA=Math.pow(2,63),HA=function(r){return r<MA?1:r<FA?2:r<BA?3:r<UA?4:r<KA?5:r<zA?6:r<qA?7:r<$A?8:r<VA?9:10},jA={encode:DA,decode:OA,encodingLength:HA},GA=jA,zs=GA;function qs(r,e=0){return[zs.decode(r,e),zs.decode.bytes]}function ao(r,e,t=0){return zs.encode(r,e,t),e}function co(r){return zs.encodingLength(r)}function lo(r,e){let t=e.byteLength,n=co(r),o=n+co(t),s=new Uint8Array(o+t);return ao(r,s,0),ao(t,s,n),s.set(e,o),new uo(r,t,e,s)}function Vy(r){let e=Ht(r),[t,n]=qs(e),[o,s]=qs(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new uo(t,o,i,e)}function Hy(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Oy(r.bytes,t.bytes)}}var uo=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var jy=0,WA="identity",Gy=Ht;function XA(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return lo(jy,Gy(r))}var YA={code:jy,name:WA,encode:Gy,digest:XA};var vh={};U(vh,{sha256:()=>QA,sha512:()=>JA});var ZA=20;function Eh({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new xh(r,e,t,n,o)}var xh=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??ZA,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Wy(n,this.code,t?.truncate):n.then(o=>Wy(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Wy(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return lo(e,r)}function Yy(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var QA=Eh({name:"sha2-256",code:18,encode:Yy("SHA-256")}),JA=Eh({name:"sha2-512",code:19,encode:Yy("SHA-512")});function Zy(r,e){let{bytes:t,version:n}=r;return n===0?t_(t,Sh(r),e??At.encoder):r_(t,Sh(r),e??io.encoder)}var Qy=new WeakMap;function Sh(r){let e=Qy.get(r);if(e==null){let t=new Map;return Qy.set(r,t),t}return e}var Cc=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Vs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==n_)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=lo(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Hy(e.multihash,n.multihash)}toString(e){return Zy(this,e)}toJSON(){return{"/":Zy(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Jy(n,o,s.bytes))}else if(t[o_]===!0){let{version:n,multihash:o,code:s}=t,i=Vy(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Vs)throw new Error(`Version 0 CID must use dag-pb (code: ${Vs}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Jy(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Vs,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Ht(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new uo(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=qs(e.subarray(t));return t+=d,f},o=n(),s=Vs;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),u=t+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=e_(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Sh(s).set(n,e),s}};function e_(r,e){switch(r[0]){case"Q":{let t=e??At;return[At.prefix,t.decode(`${At.prefix}${r}`)]}case At.prefix:{let t=e??At;return[At.prefix,t.decode(r)]}case io.prefix:{let t=e??io;return[io.prefix,t.decode(r)]}case Ks.prefix:{let t=e??Ks;return[Ks.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function t_(r,e,t){let{prefix:n}=t;if(n!==At.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function r_(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Vs=112,n_=18;function Jy(r,e,t){let n=co(r),o=n+co(e),s=new Uint8Array(o+t.byteLength);return ao(r,s,0),ao(e,s,n),s.set(t,o),s}var o_=Symbol.for("@ipld/js-cid/CID");var Ah={...yh,...lh,...gh,...ch,...uh,...dh,...hh,...ph,...mh,...fh},BM={...vh,...wh};function eb(r=0){return new Uint8Array(r)}function rb(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var tb=rb("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),_h=rb("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=eb(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),s_={utf8:tb,"utf-8":tb,hex:Ah.base16,latin1:_h,ascii:_h,binary:_h,...Ah},nb=s_;function ob(r,e="utf8"){let t=nb[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ch=60;function Ic(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Ye[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Ye[e.type],TTL:e.TTL??e.ttl??Ch,data:e.data instanceof Uint8Array?ob(e.data):e.data}))}}var i_=4;function Ih(r,e={}){let t=new Us({concurrency:e.queryConcurrency??i_});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Ac(o.types).forEach(c=>{i.append("type",Ye[c])}),o.onProgress?.(new te("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let u=Ic(await c.json());return o.onProgress?.(new te("dns:response",u)),u},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function sb(){return[Ih("https://cloudflare-dns.com/dns-query"),Ih("https://dns.google/resolve")]}var cb=Vc(ab(),1);var Th=class{lru;constructor(e){this.lru=(0,cb.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return Ic({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ye[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Ch)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function ub(r){return new Th(r)}var a_=1e3,Tc=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=ub(e.cacheSize??a_),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=sb())}async query(e,t={}){let n=Ac(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new te("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,logger:this.logger,types:n});for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new te("dns:error",u))}}throw new vc(a,`DNS lookup of ${e} ${n} failed`)}};var Ye;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ye||(Ye={}));function lb(r={}){return new Tc(r)}var Lh=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[Ye.TXT]}),i=e.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(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=lb()),this.dns)}},Xr=new Lh;async function Dh(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new yc("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Dh(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var fo={maxParallelDials:Ec,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:Xr}},Lc=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??fo.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??fo.maxDialQueueLength,this.dialTimeout=t.dialTimeout??fo.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??fo.addressDialTimeout,this.connections=t.connections??new et,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??fo.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new _a({concurrency:t.maxParallelDials??fo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==tt.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=bc(e);if(n!=null&&t.force!==!0){let i=wc(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new te("dial-queue:already-connected",i)),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new te("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Jr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new te("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new te("dial-queue:start-dial"));let a=vt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Nh,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}l.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(h=>h.multiaddr.toString())),e?.onProgress?.(new te("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,e.peerId),new Jr("Peer had more than maxPeerAddrsToDial");a++;let p=vt([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let g=await this.components.transportManager.dial(h.multiaddr,{...e,signal:p});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[Ly]:M(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}return g}catch(g){if(this.log.error("dial failed to %a - %e",h.multiaddr,g),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Ty]:M(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}if(t.aborted)throw new Js(g.message);u.push(g)}finally{p.clear()}}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:Q(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Jr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Ms("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,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",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await Dh(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(e!=null){let f=`/p2p/${e.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.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.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 hc(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);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?Py(u):u.sort(this.addressSorter);if(l.length===0)throw new Ms(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!zr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var c_=Object.prototype.toString,u_=r=>c_.call(r)==="[object Error]",l_=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Mh(r){if(!(r&&u_(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:l_.has(t)}function f_(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Dc(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}function Fh(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var Bh=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function d_(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function Pc(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function h_(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),e.signal?.removeEventListener("abort",o),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}async function p_({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(s instanceof Bh)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=d_(t,o);if(Pc(n,a)<=0){let y=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(y),s}let l=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),f=await o.shouldConsumeRetry(l),d=f&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:d});if(await o.onFailedAttempt(h),Pc(n,a)<=0||Pc(n,a)<=0||i<=0||s instanceof TypeError&&!Mh(s)||!await o.shouldRetry(h))throw s;let g=Pc(n,a);if(g<=0)throw s;if(!f)return o.signal?.throwIfAborted(),!1;let m=Math.min(d,g);return o.signal?.throwIfAborted(),await h_(m,o),o.signal?.throwIfAborted(),!0}async function Uh(r,e={}){if(e={...e},f_(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Fh("onFailedAttempt",e.onFailedAttempt),Fh("shouldRetry",e.shouldRetry),Fh("shouldConsumeRetry",e.shouldConsumeRetry),Dc("factor",e.factor,{min:0,allowInfinity:!1}),Dc("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Dc("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Dc("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await p_({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var kc=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Aa({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);fb(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Uh(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(Wc)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>fb(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function fb(r){for(let e of r.tags.keys())if(e.startsWith(Wc))return!0;return!1}var Nh=50,Kh={maxConnections:Dy,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Rc=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Kh.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new et,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Fs(Q(n))),this.deny=(t.deny??[]).map(n=>Fs(Q(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Kh.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Ca({points:t.inboundConnectionThreshold??Kh.inboundConnectionThreshold,duration:1}),this.connectionPruner=new xc({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>Q(n))}),this.dialQueue=new Lc(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Ec,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:Xr},connections:this.connections}),this.reconnectQueue=new kc({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Yh(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 Zh(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([ht(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new R("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Ct("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new te("connection:open",e));let{peerId:n,multiaddrs:o}=bc(e);if(this.peerId.equals(n))throw new Qr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=wc(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new te("dial-queue:already-connected")),t.onProgress?.(new te("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Nh});if(s.status!=="open")throw new mr("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new jt("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new te("connection:opened",s)),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([ht(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(_e(e.remoteAddr)){let s=G(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(_e(e.remoteAddr)){let s=G(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(_e(e.remoteAddr)){let o=G(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>Q(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var y_=1e4,b_="1.0.0",w_="ping",x_="ipfs",db=32,E_=!0,Oc=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??x_}/${w_}/${b_}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??y_,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??E_,this.timeout=new ma({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[xo]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o;try{o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let s=fd(o);t=Date.now(),await Promise.all([s.write(An(db),{signal:n}),s.read({bytes:db,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(s){if(o?.abort(s),s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var Nc=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new no("No content routers available");let n=this,o=new kr;for await(let s of Gn(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new no("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new no("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Ct;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Ct;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Mc=globalThis.CustomEvent??Event;async function*zh(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=ve(),a=ve(),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===t&&(i=ve(),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 Mc("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new Mc("task-complete"))})}c=!0,o.dispatchEvent(new Mc("task-complete"))}catch(p){u=p,o.dispatchEvent(new Mc("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=ve(),await a.promise),u!=null||(n?yield*d():yield*h(),u!=null))throw u;if(c&&s.length===0)break}}var Fc=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:z(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Ns("No peer routers available");if(e.toString()===this.peerId.toString())throw new cc("Should not try to find self");let n=this,o=Gn(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new gr}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ns("No peer routers available");let n=this,o=ds(1024);for await(let s of zh((async function*(){let i=Gn(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Bc=class extends Re{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=vt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ve(),yield(await ht(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=vt([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=An(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await We(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var qh=32,$h=64,Uc=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Pe({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new uc(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new lc(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:qh,maxOutboundStreams:$h,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var Kc=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Pe({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Pe({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??wo.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new R("Transport must have a valid tag");if(this.transports.has(t))throw new R(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new gc(`No transport available for address ${String(e)}`);return t?.onProgress?.(new te("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Ct("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new fc)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let 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})}),Zf.matches(c)?t.ipv4.attempts++:Qf.matches(c)&&t.ipv6.attempts++,n.push(u.listen(c).then(()=>{t.errors.delete(c.toString()),Zf.matches(c)&&t.ipv4.success++,Qf.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.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(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===wo.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new dc(`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:
12
+ ${e}[Error list was empty]`,t.trim()}return Ep(r,e)}ze.formatters.e=r=>r==null?"undefined":Sp(r);function qb(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function oi(r){return{forComponent(e){return Ap(e,r)}}}function Ap(r,e){let t=qb(`${r}:trace`);return ze.enabled(`${r}:trace`)&&ze.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=ze(`${r}:trace`,e)),Object.assign(ze(r,e),{error:ze(`${r}:error`,e),trace:t,newScope:n=>Ap(`${r}:${n}`,e)})}function vp(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function xr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function si(r){let e=At(re.decode(`z${r}`));return un(e)}var Qe=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return xr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return xr(this.map.values(),e=>e.key)}values(){return xr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Er=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return xr(this.set.entries(),e=>{let t=si(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=si(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return xr(this.set.values(),e=>si(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Yl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},_p={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Cp=new globalThis.TextEncoder;function zb(r,e){let t=Yl[e],n=_p[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function $b(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Yl[e],o=_p[e],s=r;for(;s.length>0;){let i=Cp.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Xl(r,{size:e=32,utf8Buffer:t}={}){if(!Yl[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return $b(r,e,t);r=Cp.encode(r)}return zb(r,e)}var No={hash:r=>Number(Xl(r,{size:32})),hashV:(r,e)=>Vb(No.hash(r,e))};function Vb(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),k(e,"base16")}var Zl=64,lt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Zl)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=ie(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?X(this.fp,e.fp):!1}};function vr(r,e){return Math.floor(Math.random()*(e-r))+r}var Sr=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");let t=vr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof lt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Hb=500,Mo=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??No,this.seed=e.seed??vr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=k(e));let t=new lt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Sr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Sr(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[vr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Sr(this.bucketSize));for(let a=0;a<Hb;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Sr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=k(e));let t=new lt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=k(e));let t=new lt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Wb={1:.5,2:.84,4:.95,8:.98};function jb(r=.001){return r>.002?2:r>1e-5?4:8}function Ip(r,e=.001){let t=jb(e),n=Wb[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Zl);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var ii=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??No,this.seed=e.seed??vr(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(e){if(typeof e=="string"&&(e=k(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Mo({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=k(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=k(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Fo(r,e=.001,t){return new ii({...Ip(r,e),...t??{}})}function Ql(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function W(r){let e=Ql(r);if(e==null)throw new R(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var ai=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Tp=45,Gb=15,fn=new ai;function ci(r){if(!(r.length>Gb))return fn.new(r).parseWith(()=>fn.readIPv4Addr())}function li(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Tp))return fn.new(r).parseWith(()=>fn.readIPv6Addr())}function dn(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Tp)return;let t=fn.new(r).parseWith(()=>fn.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function Lp(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function Pp(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function Jl(r){switch(r.length){case Ar:return r.join(".");case _r:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Dp(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function kp(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Ar=4,_r=16,FC=parseInt("0xFFFF",16),Yb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Bo(r,e){e.length===_r&&r.length===Ar&&Lp(e,0,11)&&(e=e.slice(12)),e.length===Ar&&r.length===_r&&Pp(r,Yb,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function Rp(r,e){if(typeof e=="string"&&(e=dn(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function eu(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Ar,o=ci(e);if(o==null&&(n=_r,o=li(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=tu(s,8*n);return{network:Bo(o,i),mask:i}}function tu(r,e){if(e!==8*Ar&&e!==8*_r)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var hn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=eu(e));else{let n=dn(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=dn(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=tu(o,8*n.length);this.network=Bo(n,this.mask)}}contains(e){return Rp({network:this.network,mask:this.mask},e)}toString(){let e=Dp(this.mask),t=e!==-1?String(e):kp(this.mask);return Jl(this.network)+"/"+t}};function Op(r){try{let e=W(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Np(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Uo(r){try{let e=W(r);switch(e.type){case"ip4":case"ip6":return Np(e.host);default:return!1}}catch{return!1}}function Ce(r){return Ql(r)!==null}function ut(r){return!!ci(r)}function ui(r){return!!li(r)}var Up=rc(Bp(),1),rw=["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"],nw=rw.map(r=>new Up.Netmask(r));function cu(r){for(let e of nw)if(e.contains(r))return!0;return!1}function ow(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function sw(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return cu(o)}function iw(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function aw(r){let e=r.split(":"),t=e[e.length-1];return cu(t)}function cw(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 yn(r){if(ut(r))return cu(r);if(ow(r))return sw(r);if(iw(r))return aw(r);if(ui(r))return cw(r)}function Dt(r){try{let e=W(r);switch(e.type){case"ip4":case"ip6":return yn(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}var Ie=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},kt=class extends Error{static name="ValidationError";name="ValidationError"},di=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},hi=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function uu(r){return e=>K(e,r)}function fu(r){return e=>k(e,r)}function bn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ir(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Kp(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=k(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ir(n);return Ye([t,o],t.length+o.length)}function qp(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ge.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ir(n);return Ye([t,o],t.length+o.length)}function du(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=K(e,"base32"),o=bn(t);return`${n}:${o}`}var hu=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Ie("Invalid byte value in IP address");e[n]=o}),e},zp=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ut(t[n]),i;s&&(i=hu(t[n]),t[n]=K(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,K(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Ie("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},$p=function(r){if(r.byteLength!==4)throw new Ie("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Vp=function(r){if(r.byteLength!==16)throw new Ie("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ie(`Invalid IPv6 address "${t}"`)}};function Hp(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ie(`Invalid IPv6 address "${r}"`)}}var lu=Object.values(eo).map(r=>r.decoder),lw=(function(){let r=lu[0].or(lu[1]);return lu.slice(2).forEach(e=>r=r.or(e)),r})();function Wp(r){return lw.decode(r)}function jp(r){return e=>r.encoder.encode(e)}function uw(r){if(parseInt(r).toString()!==r)throw new kt("Value must be an integer")}function fw(r){if(r<0)throw new kt("Value must be a positive integer, or zero")}function dw(r){return e=>{if(e>r)throw new kt(`Value must be smaller than or equal to ${r}`)}}function hw(...r){return e=>{for(let t of r)t(e)}}var Ko=hw(uw,fw,dw(65535));var Ee=-1,pu=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new hi(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Ot=new pu,Iw=[{code:4,name:"ip4",size:32,valueToBytes:hu,bytesToValue:$p,validate:r=>{if(!ut(r))throw new kt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ir,bytesToValue:bn,validate:Ko},{code:273,name:"udp",size:16,valueToBytes:Ir,bytesToValue:bn,validate:Ko},{code:33,name:"dccp",size:16,valueToBytes:Ir,bytesToValue:bn,validate:Ko},{code:41,name:"ip6",size:128,valueToBytes:zp,bytesToValue:Vp,stringToValue:Hp,validate:r=>{if(!ui(r))throw new kt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Ee},{code:43,name:"ipcidr",size:8,bytesToValue:uu("base10"),valueToBytes:fu("base10")},{code:53,name:"dns",size:Ee},{code:54,name:"dns4",size:Ee},{code:55,name:"dns6",size:Ee},{code:56,name:"dnsaddr",size:Ee},{code:132,name:"sctp",size:16,valueToBytes:Ir,bytesToValue:bn,validate:Ko},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ee,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Ee,bytesToValue:uu("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?fu("base58btc")(r):de.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:du,valueToBytes:Kp},{code:445,name:"onion3",size:296,bytesToValue:du,valueToBytes:qp},{code:446,name:"garlic64",size:Ee},{code:447,name:"garlic32",size:Ee},{code:448,name:"tls"},{code:449,name:"sni",size:Ee},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ee,bytesToValue:jp(Ac),valueToBytes:Wp},{code:480,name:"http"},{code:481,name:"http-path",size:Ee,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:Ee}];Iw.forEach(r=>{Ot.addProtocol(r)});function Gp(r){let e=[],t=0;for(;t<r.length;){let n=gr(r,t),o=Ot.getProtocol(n),s=xe(n),i=Tw(o,r,t+s),a=0;i>0&&o.size===Ee&&(a=xe(i));let c=s+a+i,l={code:n,name:o.name,bytes:Se(r.subarray(t,t+c))};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??K(f)}e.push(l),t+=c}return e}function Yp(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ot.getProtocol(n.code),s=xe(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??k(n.value),a=i.byteLength,o.size===Ee&&(c=xe(a)));let l=new Uint8Array(s+c+a),u=0;an(n.code,l,u),u+=s,i!=null&&(o.size===Ee&&(an(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ye(t,e)}function Xp(r){if(r.charAt(0)!=="/")throw new Ie('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Ot.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Ie(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ie(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ie("Incomplete multiaddr");return e}function Zp(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ot.getProtocol(e.code);if(t==null)throw new Ie(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Tw(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:gr(e,t)}var Lw=Symbol.for("nodejs.util.inspect.custom"),Tu=Symbol.for("@multiformats/multiaddr");function Pw(r){if(r==null&&(r="/"),rr(r))return r.getComponents();if(r instanceof Uint8Array)return Gp(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Xp(r);if(Array.isArray(r))return r;throw new Ie("Must be a string, Uint8Array, Component[], or another Multiaddr")}var wi=class r{[Tu]=!0;#e;#t;#n;constructor(e="/",t={}){this.#e=Pw(e),t.validate!==!1&&Dw(this)}get bytes(){return this.#n==null&&(this.#n=Yp(this.#e)),this.#n}toString(){return this.#t==null&&(this.#t=Zp(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new di(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return X(this.bytes,e.bytes)}[Lw](){return`Multiaddr(${this.toString()})`}};function Dw(r){r.getComponents().forEach(e=>{let t=Ot.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function rr(r){return!!r?.[Tu]}function Q(r){return new wi(r)}var ne=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),N=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Qp=r=>({match:e=>r.match(e)===!1?e:!1}),$=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Pe=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),j=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function oe(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var kw=N(421),Jp=oe(kw),Ei=N(54),vi=N(55),Si=N(56),Pu=N(53),S6=oe(Ei,$(N(421))),A6=oe(vi,$(N(421))),_6=oe(Si,$(N(421))),C6=oe(Pe(Pu,Si,Ei,vi),$(N(421))),em=j(N(4),$(N(43))),tm=j($(N(42)),N(41),$(N(43))),Du=Pe(em,tm),An=Pe(Du,Pu,Ei,vi,Si),I6=oe(Pe(Du,j(Pe(Pu,Si,Ei,vi),$(N(421))))),ku=oe(em),Ru=oe(tm),T6=oe(Du),Ou=j(An,N(6)),qo=j(An,N(273)),zo=oe(j(Ou,$(N(421)))),L6=oe(qo),Nu=j(qo,ne(460),$(N(421))),Ai=j(qo,ne(461),$(N(421))),Rw=Pe(Nu,Ai),P6=oe(Nu),rm=oe(Ai),Lu=Pe(An,Ou,qo,Nu,Ai),nm=Pe(j(Lu,ne(477),$(N(421)))),Lr=oe(nm),om=Pe(j(Lu,ne(478),$(N(421))),j(Lu,ne(448),$(N(449)),ne(477),$(N(421)))),$o=oe(om),sm=j(qo,ne(280),$(N(466)),$(N(466)),$(N(421))),Mu=oe(sm),im=j(Ai,ne(465),$(N(466)),$(N(466)),$(N(421))),Fu=oe(im),xi=Pe(nm,om,j(Ou,$(N(421))),j(Rw,$(N(421))),j(An,$(N(421))),sm,im,N(421)),D6=oe(xi),Ow=j($(xi),ne(290),Qp(ne(281)),$(N(421))),Pr=oe(Ow),Nw=Pe(j(xi,ne(290),ne(281),$(N(421))),j(xi,ne(281),$(N(421))),j(ne(281),$(N(421)))),Bu=oe(Nw),Mw=j(An,Pe(j(N(6,"80")),j(N(6),ne(480)),ne(480)),$(N(481)),$(N(421))),k6=oe(Mw),Fw=j(An,Pe(j(N(6,"443")),j(N(6,"443"),ne(480)),j(N(6),ne(443)),j(N(6),ne(448),ne(480)),j(ne(448),ne(480)),ne(448),ne(443)),$(N(481)),$(N(421))),R6=oe(Fw),Bw=Pe(j(N(777),$(N(421)))),O6=oe(Bw),Uw=Pe(j(N(400),$(N(421)))),N6=oe(Uw);function am(r,e){let t=zo.exactMatch(r),n=zo.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=$o.exactMatch(r),s=$o.exactMatch(e);if(o&&!s)return-1;if(!o&&s)return 1;let i=Lr.exactMatch(r),a=Lr.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=Bu.exactMatch(r),l=Bu.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=Mu.exactMatch(r),f=Mu.exactMatch(e);if(u&&!f)return-1;if(!u&&f)return 1;let d=Fu.exactMatch(r),h=Fu.exactMatch(e);return d&&!h?-1:!d&&h?1:0}function cm(r,e){let t=Uo(r),n=Uo(e);return t&&!n?1:!t&&n?-1:0}function lm(r,e){let t=Dt(r),n=Dt(e);return t&&!n?1:!t&&n?-1:0}function um(r,e){let t=Pr.exactMatch(r),n=Pr.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function ve(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var _i=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},_n=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new _i(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new _i(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Uu=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Cn(r={}){return Kw(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Kw(r,e){e=e??{};let t=e.onEnd,n=new _n,o,s,i,a=ve(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,y)=>{s=w=>{s=null,n.push(w);try{m(r(n))}catch(v){y(v)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ve()})}},l=m=>s!=null?s(m):(n.push(m),o),u=m=>(n=new _n,s!=null?s({error:m}):(n.push({error:m}),o)),f=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?u(m):l({done:!0})),h=()=>(n=new _n,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 y=m?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let w,v;y!=null&&(w=new Promise((T,I)=>{v=()=>{I(new Uu)},y.addEventListener("abort",v)}));try{await Promise.race([a.promise,w])}finally{v!=null&&y!=null&&y?.removeEventListener("abort",v)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(m){return g.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(m){return g.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:m=>g.onEmpty(m)},o}var Ku=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},fm=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Vo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((f,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){d(fm(i));return}if(i&&(c=()=>{d(fm(i))},i.addEventListener("abort",c,{once:!0})),r.then(f,d),t===Number.POSITIVE_INFINITY)return;let h=new Ku;a=s.setTimeout.call(void 0,()=>{if(n){try{f(n())}catch(p){d(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?f():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var qw=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function zw(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=qw(r),f=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d)};for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Vo(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function ft(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=zw(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Ho(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Ci=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Ii=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Dr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function $w(r){return r.reason}async function He(r,e,t){if(e==null)return r;let n=t?.translateError??$w;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Ti=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=ve(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Vw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Li=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=Vw(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Je),this.cleanup())}async join(e){let t=new Ti(e);return this.recipients.push(t),e?.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await He(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var In=class extends Re{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ho(this.emitEmpty.bind(this),1),this.emitIdle=Ho(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ii;let n=new Li(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Je)}),this.clear()}async onEmpty(e){this.size!==0&&await ft(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ft(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ft(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Cn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Je("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};function wt(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Tn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var Hw=1.2,Ww=2,jw=5e3,Gw=6e4,Yw=5e3,Pi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??Yw;this.success=new Tn(t),this.failure=new Tn(t),this.next=new Tn(t),this.failureMultiplier=e.failureMultiplier??Ww,this.timeoutMultiplier=e.timeoutMultiplier??Hw,this.minTimeout=e.minTimeout??jw,this.maxTimeout=e.maxTimeout??Gw,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=wt([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var qu=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ve(),this.haveNext=ve()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ve(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ve(),await He(this.readNext.promise,t?.signal,t)}};function dm(){return new qu}function Xw(r){return r[Symbol.asyncIterator]!=null}async function Zw(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Qw(r){let e=new AbortController,t=dm();Zw(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Jw(r){for(let e of r)yield*e}function ex(...r){let e=[];for(let t of r)Xw(t)||e.push(t);return e.length===r.length?Jw(e):Qw(r)}var Ln=ex;var tx=4194304,Di=class extends Error{static name="UnwrappedError";name="UnwrappedError"},$u=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Vu=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Hu=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function rx(r){return typeof r?.closeRead=="function"}function nx(r){return typeof r?.close=="function"}function zu(r){return rx(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:nx(r)?r.status!=="open":!1}function ox(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Wu(r,e){let t=e?.maxBufferSize??tx,n=new J,o,s=!1;if(!ox(r))throw new R("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new Di("Stream was unwrapped");if(zu(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Dr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await He(o.promise,u?.signal),zu(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let d=u?.bytes??n.byteLength;if(n.byteLength<d){if(zu(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new Dr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(u)}let h=n.sublist(0,d);return n.consume(d),h},async write(u,f){if(s===!0)throw new Di("Stream was unwrapped");r.send(u)||await ft(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return l}function ki(r,e={}){let t=Wu(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=xe(e.maxDataLength));let n=e?.lengthDecoder??gr,o=e?.lengthEncoder??Zt;return{async read(i){let a=-1,c=new J;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new $u("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Hu(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Vu(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Dr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Dr(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new J(o(i.byteLength),i),a)},async writeV(i,a){let c=new J(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var Ri=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Pn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Oi=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Wo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ni(r){return r[Symbol.asyncIterator]!=null}function hm(r,e){if(r.byteLength>e)throw new Pn("Message length too long")}var Fi=r=>{let e=xe(r),t=be(e);return Zt(r,t),Fi.bytes=e,t};Fi.bytes=0;function Bi(r,e){e=e??{};let t=e.lengthEncoder??Fi,n=e?.maxDataLength??4194304;function*o(s){hm(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ni(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}Bi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Fi,n=e?.maxDataLength??4194304;return hm(r,n),new J(t(r.byteLength),r)};var kr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(kr||(kr={}));var Gu=r=>{let e=gr(r);return Gu.bytes=xe(e),e};Gu.bytes=0;function ju(r,e){let t=new J,n=kr.LENGTH,o=-1,s=e?.lengthDecoder??Gu,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===kr.LENGTH)try{if(o=s(t),o<0)throw new Ri("Invalid message length");if(o>a)throw new Pn("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=kr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Oi("Message length length too long");break}throw l}if(n===kr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=kr.LENGTH}}}return Ni(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Wo("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Wo("Unexpected end of input")})()}ju.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return ju(n,{...e??{},onLength:s=>{t=s}})};var Ui=class extends In{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Ki=class extends In{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var qi=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Yu}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Ci("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Yu=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var Xu=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function De(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Xu({name:e,metrics:t}):n=new Map,n}var Zu=class extends Qe{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Qu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Zu({name:e,metrics:t}):n=new Qe,n}var jo;(function(r){let e;r.codec=()=>(e==null&&(e=Be((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&s.payload.byteLength>0&&(i.uint32(26),i.bytes(s.payload)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:ie(0),payloadType:ie(0),payload:ie(0),signature:ie(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=s.bytes();break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield{field:`${a}.payload`,value:s.bytes()};break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Me(s,r.codec())}r.encode=t;function n(s,i){return Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(jo||(jo={}));var zi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Dn=class r{static createFromProtobuf=e=>{let t=jo.decode(e),n=ln(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=pm(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new zi("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=jo.encode({publicKey:Xe(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:X(this.marshal(),e.marshal())}async validate(e,t){let n=pm(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},pm=(r,e,t)=>{let n=k(r),o=Zt(n.byteLength),s=Zt(e.length),i=Zt(t.length);return new J(o,n,s,e,i,t)};var mm="libp2p-peer-record",gm=Uint8Array.from([3,1]);var Go;(function(r){let e;(function(i){let a;i.codec=()=>(a==null&&(a=Be((f,d,h={})=>{h.lengthDelimited!==!1&&d.fork(),f.multiaddr!=null&&f.multiaddr.byteLength>0&&(d.uint32(10),d.bytes(f.multiaddr)),h.lengthDelimited!==!1&&d.ldelim()},(f,d,h={})=>{let p={multiaddr:ie(0)},g=d==null?f.len:f.pos+d;for(;f.pos<g;){let m=f.uint32();m>>>3===1?p.multiaddr=f.bytes():f.skipType(m&7)}return p},function*(f,d,h,p={}){let g=d==null?f.len:f.pos+d;for(;f.pos<g;){let m=f.uint32();m>>>3===1?yield{field:`${h}.multiaddr`,value:f.bytes()}:f.skipType(m&7)}})),a);function c(f){return Me(f,i.codec())}i.encode=c;function l(f,d){return Ne(f,i.codec(),d)}i.decode=l;function u(f,d){return Fe(f,i.codec(),d)}i.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Be((i,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),i.peerId!=null&&i.peerId.byteLength>0&&(a.uint32(10),a.bytes(i.peerId)),i.seq!=null&&i.seq!==0n&&(a.uint32(16),a.uint64(i.seq)),i.addresses!=null&&i.addresses.length>0)for(let l of i.addresses)a.uint32(26),r.AddressInfo.codec().encode(l,a);c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={peerId:ie(0),seq:0n,addresses:[]},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.peerId=i.bytes();break}case 2:{l.seq=i.uint64();break}case 3:{if(c.limits?.addresses!=null&&l.addresses.length===c.limits.addresses)throw new Ze('Decode error - repeated field "addresses" had too many elements');l.addresses.push(r.AddressInfo.codec().decode(i,i.uint32(),{limits:c.limits?.addresses$}));break}default:{i.skipType(f&7);break}}}return l},function*(i,a,c,l={}){let u={addresses:0},f=a==null?i.len:i.pos+a;for(;i.pos<f;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${c}.peerId`,value:i.bytes()};break}case 2:{yield{field:`${c}.seq`,value:i.uint64()};break}case 3:{if(l.limits?.addresses!=null&&u.addresses===l.limits.addresses)throw new Ze('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(i,i.uint32(),`${c}.addresses[]`,{limits:l.limits?.addresses$}))yield{...h,index:u.addresses};u.addresses++;break}default:{i.skipType(d&7);break}}}})),t);function n(i){return Me(i,r.codec())}r.encode=n;function o(i,a){return Ne(i,r.codec(),a)}r.decode=o;function s(i,a){return Fe(i,r.codec(),a)}r.stream=s})(Go||(Go={}));function ym(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Rr=class r{static createFromProtobuf=e=>{let t=Go.decode(e),n=un(At(t.peerId)),o=(t.addresses??[]).map(i=>Q(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=mm;static CODEC=gm;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Go.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!ym(this.multiaddrs,e.multiaddrs))}};function ix(r){return r[Symbol.asyncIterator]!=null}function ax(r){if(ix(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Yo=ax;var We=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function $i(r,e,t,n){let o=new We(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){ef(t,"abort",f),ef(r,e,l),ef(r,s,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};Ju(t,"abort",f),Ju(r,e,l),Ju(r,s,u)})}function Ju(r,e,t){r!=null&&(bm(r)?r.addEventListener(e,t):r.addListener(e,t))}function ef(r,e,t){r!=null&&(bm(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function bm(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Vi=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Hi=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new We)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function cx(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Wi=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=cx(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new We),this.cleanup())}async join(e={}){let t=new Hi(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await He(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function tf(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Xo=class extends Re{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=tf(this.emitEmpty.bind(this),1),this.emitIdle=tf(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Vi;let n=new Wi(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new We)}),this.clear()}async onEmpty(e){this.size!==0&&await $i(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await $i(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await $i(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Cn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new We("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var ji="lock:worker:request-read",Gi="lock:worker:abort-read-request",Yi="lock:worker:release-read",Xi="lock:master:grant-read",Zi="lock:master:error-read",Qi="lock:worker:request-write",Ji="lock:worker:abort-write-request",ea="lock:worker:release-write",ta="lock:master:grant-write",ra="lock:master:error-write",na="lock:worker:finalize",oa="mortice",wm={singleProcess:!1};var rf=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.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===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===na&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var xm=(r=10)=>Math.random().toString().substring(2,r+2);var sa=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(oa)}readLock(e){return this.sendRequest(ji,Gi,Xi,Zi,Yi,e)}writeLock(e){return this.sendRequest(Qi,Ji,ta,ra,ea,e)}finalize(){this.channel.postMessage({type:na,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=xm();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var Em=r=>{if(r=Object.assign({},wm,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(oa),n=new Re;return t.addEventListener("message",rf(n,t,"requestReadLock","abortReadLockRequest",ji,Gi,Zi,Yi,Xi)),t.addEventListener("message",rf(n,t,"requestWriteLock","abortWriteLockRequest",Qi,Ji,ra,ea,ta)),n}return new sa(r.name)};var Or=new Map,Zo;function vm(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function lx(r){if(Zo==null&&(Zo=Em(r),!vm(Zo))){let e=Zo;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Or.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=Or.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=Or.get(n);o?.finalize()})}return Zo}async function nf(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new We)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var Sm=(r,e)=>{let t=Or.get(r);if(t!=null)return t;let n=lx(e);if(vm(n))return t=n,Or.set(r,t),t;let o=new Xo({concurrency:1}),s;return t={async readLock(i){if(s!=null)return nf(s,i);s=new Xo({concurrency:e.concurrency,autoStart:!1});let a=s,c=nf(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,nf(o,i)},finalize:()=>{Or.delete(r)},queue:o},Or.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var ux={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function of(r){let e=Object.assign({},ux,r);return Sm(e.name,e)}var Nt;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=Be((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&d.value.byteLength>0&&(h.uint32(18),h.bytes(d.value)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let g={key:"",value:ie(0)},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=d.bytes();break}default:{d.skipType(y&7);break}}}return g},function*(d,h,p,g={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield{field:`${p}.value`,value:d.bytes()};break}default:{d.skipType(y&7);break}}}})),c);function l(d){return Me(d,a.codec())}a.encode=l;function u(d,h){return Ne(d,a.codec(),h)}a.decode=u;function f(d,h){return Fe(d,a.codec(),h)}a.stream=f})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=Be((d,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),d.key!=null&&d.key!==""&&(h.uint32(10),h.string(d.key)),d.value!=null&&(h.uint32(18),Jo.codec().encode(d.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(d,h,p={})=>{let g={key:""},m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{g.key=d.string();break}case 2:{g.value=Jo.codec().decode(d,d.uint32(),{limits:p.limits?.value});break}default:{d.skipType(y&7);break}}}return g},function*(d,h,p,g={}){let m=h==null?d.len:d.pos+h;for(;d.pos<m;){let y=d.uint32();switch(y>>>3){case 1:{yield{field:`${p}.key`,value:d.string()};break}case 2:{yield*Jo.codec().stream(d,d.uint32(),`${p}.value`,{limits:g.limits?.value});break}default:{d.skipType(y&7);break}}}})),c);function l(d){return Me(d,a.codec())}a.encode=l;function u(d,h){return Ne(d,a.codec(),h)}a.decode=u;function f(d,h){return Fe(d,a.codec(),h)}a.stream=f})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Be((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let u of a.addresses)c.uint32(10),Qo.codec().encode(u,c);if(a.protocols!=null&&a.protocols.length>0)for(let u of a.protocols)c.uint32(18),c.string(u);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[u,f]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:f},c);if(a.tags!=null&&a.tags.size>0)for(let[u,f]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:f},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={addresses:[],protocols:[],metadata:new Map,tags:new Map},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let d=a.uint32();switch(d>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new Ze('Decode error - repeated field "addresses" had too many elements');u.addresses.push(Qo.codec().decode(a,a.uint32(),{limits:l.limits?.addresses$}));break}case 2:{if(l.limits?.protocols!=null&&u.protocols.length===l.limits.protocols)throw new Ze('Decode error - repeated field "protocols" had too many elements');u.protocols.push(a.string());break}case 4:{u.publicKey=a.bytes();break}case 5:{u.peerRecordEnvelope=a.bytes();break}case 6:{if(l.limits?.metadata!=null&&u.metadata.size===l.limits.metadata)throw new _o('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.metadata$value}});u.metadata.set(h.key,h.value);break}case 7:{if(l.limits?.tags!=null&&u.tags.size===l.limits.tags)throw new _o('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.tags$value}});u.tags.set(h.key,h.value);break}case 8:{u.updated=a.uint64Number();break}default:{a.skipType(d&7);break}}}return u},function*(a,c,l,u={}){let f={addresses:0,protocols:0,metadata:0,tags:0},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&f.addresses===u.limits.addresses)throw new Ze('Streaming decode error - repeated field "addresses" had too many elements');for(let p of Qo.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...p,index:f.addresses};f.addresses++;break}case 2:{if(u.limits?.protocols!=null&&f.protocols===u.limits.protocols)throw new Ze('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:f.protocols,value:a.string()},f.protocols++;break}case 4:{yield{field:`${l}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${l}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(u.limits?.metadata!=null&&f.metadata===u.limits.metadata)throw new Ze('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${l}.metadata{}`,{limits:{value:u.limits?.metadata$value}}),f.metadata++;break}case 7:{if(u.limits?.tags!=null&&f.tags===u.limits.tags)throw new Ze('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${l}.tags{}`,{limits:{value:u.limits?.tags$value}}),f.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return Me(a,r.codec())}r.encode=o;function s(a,c){return Ne(a,r.codec(),c)}r.decode=s;function i(a,c){return Fe(a,r.codec(),c)}r.stream=i})(Nt||(Nt={}));var Qo;(function(r){let e;r.codec=()=>(e==null&&(e=Be((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),s.isCertified!=null&&(i.uint32(16),i.bool(s.isCertified)),s.observed!=null&&(i.uint32(24),i.uint64Number(s.observed)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ie(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}case 2:{c.isCertified=s.bool();break}case 3:{c.observed=s.uint64Number();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:s.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:s.bool()};break}case 3:{yield{field:`${a}.observed`,value:s.uint64Number()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Me(s,r.codec())}r.encode=t;function n(s,i){return Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Qo||(Qo={}));var Jo;(function(r){let e;r.codec=()=>(e==null&&(e=Be((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.value!=null&&s.value!==0&&(i.uint32(8),i.uint32(s.value)),s.expiry!=null&&(i.uint32(16),i.uint64(s.expiry)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={value:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.value=s.uint32();break}case 2:{c.expiry=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:s.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return Me(s,r.codec())}r.encode=t;function n(s,i){return Ne(s,r.codec(),i)}r.decode=n;function o(s,i){return Fe(s,r.codec(),i)}r.stream=o})(Jo||(Jo={}));function fx(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=ln(e.publicKey,t);return jl(n)}function Am(r,e,t){let n=Nt.decode(e);return kn(r,n,t)}function kn(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:fx(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:Q(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function _m(r,e){return dx(r.addresses,e.addresses)&&hx(r.protocols,e.protocols)&&px(r.publicKey,e.publicKey)&&mx(r.peerRecordEnvelope,e.peerRecordEnvelope)&&gx(r.metadata,e.metadata)&&yx(r.tags,e.tags)}function dx(r,e){return Im(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!X(t.multiaddr,n.multiaddr)))}function hx(r,e){return Im(r,e,(t,n)=>t===n)}function px(r,e){return Cm(r,e)}function mx(r,e){return Cm(r,e)}function gx(r,e){return Tm(r,e,(t,n)=>X(t,n))}function yx(r,e){return Tm(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Cm(r,e){return r==null&&e==null?!0:r!=null&&e!=null?X(r,e):!1}function Im(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function Tm(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Mt="/",Lm=new TextEncoder().encode(Mt),ia=Lm[0],Nr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=k(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ia)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Mt))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Lm),this._buf[0]!==ia){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ia,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ia;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Mt).slice(1)}type(){return bx(this.baseNamespace())}name(){return wx(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Mt)||(e+=Mt),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Mt):new r(e.slice(0,-1).join(Mt))}child(e){return this.toString()===Mt?e:e.toString()===Mt?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...xx(e.map(t=>t.namespaces()))])}};function bx(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function wx(r){let e=r.split(":");return e[e.length-1]}function xx(r){return[].concat(...r)}var sf="/peers/";function es(r){if(!Kt(r)||r.type==null)throw new R("Invalid PeerId");let e=r.toCID().toString();return new Nr(`${sf}${e}`)}async function Pm(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=Q(i.multiaddr)),!rr(i.multiaddr))throw new R("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(Q(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function ca(r,e,t,n){if(e==null)throw new R("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new R("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new R("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=aa(d,{validate:Dm})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=aa(d,{validate:km,map:Rm})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=aa([...a.entries()],{validate:Dm})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,g]of d)g==null?h.delete(p):h.set(p,g);c=aa([...h.entries()],{validate:km,map:Rm})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Xe(o.id.publicKey):e.publicKey!=null?u=Xe(e.publicKey):r.publicKey!=null&&(u=Xe(r.publicKey));let f={addresses:await Pm(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:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>X(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function aa(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Dm(r,e){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function km(r,e){if(typeof r!="string")throw new R("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new R("Tag value must be an integer");if(e.value<0||e.value>100)throw new R("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new R("Tag ttl must be an integer");if(e.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function Rm(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function Om(r){let e=r.toString().split("/")[2],t=de.parse(e,Ge);return Oo(t)}function af(r,e,t){let n=Om(r);return Am(n,e,t)}function Ex(r,e){return{prefix:sf,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(af(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(af(n.key,n.value,e),af(o.key,o.value,e)))}}var la=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=Qu({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:of({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(es(e),t)}async load(e,t){let n=es(e),o=await this.datastore.get(n,t),s=Nt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new ir;return kn(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await ca(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await ca(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await ca(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(Ex(e??{},this.maxAddressAge),e)){let o=Om(t);if(o.equals(this.peerId))continue;let s=Nt.decode(n);if(this.#n(o,s)){await this.datastore.delete(t,e);continue}yield kn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=es(e),o=await this.datastore.get(n,t),s=Nt.decode(o);if(this.#n(e,s))throw await this.datastore.delete(n,t),new ir;return{peerPB:s,peer:kn(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=Nt.encode(t);return await this.datastore.put(es(e),s,o),{peer:kn(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!_m(t,n.peerPB)}}#n(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var cf=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new la(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return Yo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Kt(t)?t:Kt(t?.expectedPeer)?t.expectedPeer:void 0,s=Kt(t)||t===void 0?n:t,i=await Dn.openAndCertify(e,Rr.DOMAIN,s),a=Oo(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=Rr.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=Dn.createFromProtobuf(l.peerRecordEnvelope),f=Rr.createFromProtobuf(u.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:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Nm(r,e={}){return new cf(r,e)}var ua=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};function vx(r){return r[Symbol.asyncIterator]!=null}function Sx(r){if(vx(r))return(async()=>{for await(let e of r);})();for(let e of r);}var lf=Sx;function Ax(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Mm=Ax;function _x(r){return r[Symbol.asyncIterator]!=null}function Cx(r,e){let t=0;if(_x(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Mm(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Mr=Cx;function Ix(r){return r[Symbol.asyncIterator]!=null}function Tx(r,e){return Ix(r)?(async function*(){yield*(await Yo(r)).sort(e)})():(function*(){yield*Yo(r).sort(e)})()}var uf=Tx;function Lx(r){return r[Symbol.asyncIterator]!=null}function Px(r,e){return Lx(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var ff=Px;var fa=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await lf(this.putMany(e,n)),e=[],await lf(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Mr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Mr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>uf(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Mr(n,()=>o++>=s)}return e.limit!=null&&(n=ff(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Mr(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Mr(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>uf(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Mr(n,()=>s++>=o)}return e.limit!=null&&(n=ff(n,e.limit)),n}};var da=class extends fa{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new ua;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new Nr(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Nr(n),t?.signal?.throwIfAborted()}};var Fm=864e13;var ha=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=De({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=W(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=yn(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?Fm-Date.now():0,lastVerified:o?Fm-Date.now():void 0})})}remove(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!Ce(o))continue;let s=W(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),Q(n)}confirm(e,t){let n=W(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=W(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var pa=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=De({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:ut(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=W(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!Ce(n))continue;let o=W(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,Q(i)):e}confirm(e,t){if(!Ce(e))return!1;let n=W(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!Ce(e))return!1;let n=W(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var Dx={maxObservedAddresses:10},ma=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=De({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??Dx.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Dt(e)||Op(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:Q(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var kx={maxObservedAddresses:10},ga=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=De({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??kx.maxObservedAddresses}get(e,t){if(Dt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!Ce(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!Ce(e))return e.toString();let t=W(e);return`${t.host}-${t.port}-${t.protocol}`}};var Bm=6e4,Um={maxObservedAddresses:10,addressVerificationTTL:Bm*10,addressVerificationRetry:Bm*5},Rx=r=>r;function df(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&yt(t).equals(e)&&(r=r.decapsulate(Q(`/p2p/${e.toString()}`))),r}var ya=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new ma(e,t),this.dnsMappings=new ha(e,t),this.ipMappings=new pa(e,t),this.transportAddresses=new ga(e,t),this.announceFilter=t.announceFilter??Rx,this.observedAddressFilter=Fo(1024),this.addressVerificationTTL=t.addressVerificationTTL??Um.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Um.addressVerificationRetry,this._updatePeerStoreAddresses=Ho(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>Q(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Q(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Q(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=W(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=df(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=df(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=df(e,this.components.peerId);let n=!0;this.observed.has(e)&&this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n||this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=Q(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Q(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${ut(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(Q(`/ip${ut(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Ce(e))return!1;let t=W(e);if(t.type!=="ip4"||yn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Lr.exactMatch(s)||$o.exactMatch(s),s=>zo.exactMatch(s),s=>rm.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>W(u).type==="ip4"&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!Uo(l)).pop();if(a==null)continue;let c=W(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var Km;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Km||(Km={}));var ba=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},wa=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Rn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},ts=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},xa=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Ea=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},va=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},rs=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Sa=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},Aa=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},_a=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Ca=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Ia=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},nr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Fr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Ta=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},La=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var hf=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=oi())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>As(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Ox=["metrics","connectionProtector","dns"],Nx=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function qm(r={}){let e=new hf(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!Nx.includes(o)){let i=e.components[o];if(i==null&&!Ox.includes(o))throw new ba(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function zm(r){let e={};for(let t of Object.values(r.components))for(let n of Mx(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Fx(t))if(e[n]!==!0)throw new wa(`Service "${Bx(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Mx(r){return Array.isArray(r?.[Yn])?r[Yn]:[]}function Fx(r){return Array.isArray(r?.[ac])?r[ac]:[]}function Bx(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function $m(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>Lr.matches(e)?!0:Dt(e)),r}var ee=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function Pa(r){if(Kt(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:yt(n),e.forEach(o=>{if(!rr(o))throw new Bt("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let i=yt(s);if(t?.equals(i)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Jp.exactMatch(n)),{peerId:t,multiaddrs:e}}var Ux=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Vm(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??Ux;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function ns(r){let e=W(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new R(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new R(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new hn(e.host,t)}function pf(r){return!Pr.exactMatch(r)}function Da(r,e,t){if(r==null||e==null)return;let n=e.filter(s=>s.status==="open").sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>pf(s)))return n}var ka=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>ns(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Qe;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(Ce(c.remoteAddr)){let f=W(c.remoteAddr);return u.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Vm(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Hm="last-dial-failure",Wm="last-dial-success";var jm=100,Ra=50;function Kx(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Gm(r){return r.sort((e,t)=>cm(e.multiaddr,t.multiaddr)||lm(e.multiaddr,t.multiaddr)||um(e.multiaddr,t.multiaddr)||Kx(e,t)||am(e.multiaddr,t.multiaddr))}var Oa=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var gf=rc(Xm(),1);function yf(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var $x=100,On=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:o}=t??{},{size:s}=this,i={priority:n,id:o,run:e};if(s===0){this.#e.length=0,this.#t=0,this.#e.push(i);return}if(this.#e.at(-1).priority>=n){this.#e.push(i);return}this.#n();let a=yf(this.#e,i,(c,l)=>l.priority-c.priority);this.#e.splice(a,0,i)}setPriority(e,t){let n=this.#e.findIndex((s,i)=>i>=this.#t&&s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((n,o)=>o<this.#t?!1:typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>$x&&this.#t>this.#e.length/2&&this.#n(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let o=this.#e[n];o.priority===e.priority&&t.push(o.run)}return t}get size(){return this.#e.length-this.#t}#n(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}};var ss=class extends gf.default{#e;#t;#n=0;#h;#m=!1;#w=!1;#c;#I=0;#x=0;#l;#u;#a;#i=[];#s=0;#r;#T;#o=0;#g;#f;#R=1n;#y=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:On,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#h=e.intervalCap,this.#c=e.interval,this.#a=e.strict,this.#r=new e.queueClass,this.#T=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#f=e.autoStart===!1,this.#q()}#v(e){for(;this.#s<this.#i.length;){let n=this.#i[this.#s];if(n!==void 0&&e-n>=this.#c)this.#s++;else break}(this.#s>100&&this.#s>this.#i.length/2||this.#s===this.#i.length)&&(this.#i=this.#i.slice(this.#s),this.#s=0)}#O(e){this.#a?this.#i.push(e):this.#n++}#N(){this.#a?this.#i.length>this.#s&&this.#i.pop():this.#n>0&&this.#n--}#S(){return this.#i.length-this.#s}get#M(){return this.#t?!0:this.#a?this.#S()<this.#h:this.#n<this.#h}get#F(){return this.#o<this.#g}#B(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#U(){this.#u=void 0,this.#D(),this.#P()}#K(e){if(this.#a){if(this.#v(e),this.#S()>=this.#h){let n=this.#i[this.#s],o=this.#c-(e-n);return this.#A(o),!0}return!1}if(this.#l===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#c)return this.#A(this.#c-n),!0}this.#n=this.#e?this.#o:0}else return this.#A(t),!0}return!1}#A(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#U()},e))}#_(){this.#l&&(clearInterval(this.#l),this.#l=void 0)}#L(){this.#u&&(clearTimeout(this.#u),this.#u=void 0)}#b(){if(this.#r.size===0){if(this.#_(),this.emit("empty"),this.#o===0){if(this.#L(),this.#a&&this.#s>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#f){let t=Date.now(),n=!this.#K(t);if(this.#M&&this.#F){let o=this.#r.dequeue();this.#t||(this.#O(t),this.#p()),this.emit("active"),o(),n&&this.#P(),e=!0}}return e}#P(){this.#t||this.#l!==void 0||this.#a||(this.#l=setInterval(()=>{this.#D()},this.#c),this.#I=Date.now()+this.#c)}#D(){this.#a||(this.#n===0&&this.#o===0&&this.#l&&this.#_(),this.#n=this.#e?this.#o:0),this.#C(),this.#p()}#C(){for(;this.#b(););}get concurrency(){return this.#g}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#g=e,this.#C()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#r.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#R++).toString()},new Promise((n,o)=>{let s=Symbol(`task-${t.id}`),i=()=>{},a=async()=>{i(),this.#o++,this.#y.set(s,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(d){throw this.#z(),this.#y.delete(s),d}this.#x=Date.now();let u=e({signal:t.signal});if(t.timeout&&(u=Vo(Promise.resolve(u),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#r.size} waiting)`})),t.signal){let{signal:d}=t;u=Promise.race([u,new Promise((h,p)=>{l=()=>{p(d.reason)},d.addEventListener("abort",l,{once:!0})})])}let f=await u;n(f),this.emit("completed",f)}catch(u){o(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#y.delete(s),queueMicrotask(()=>{this.#B()})}};this.#r.enqueue(a,t);let c=()=>{if(this.#r instanceof On){this.#r.remove(a);return}this.#r.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{i(),c(),o(l.reason),this.#b(),this.emit("next")};if(i=()=>{l.removeEventListener("abort",u),this.#E.delete(i)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#E.add(i)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#f?(this.#f=!1,this.#C(),this):this}pause(){this.#f=!0}clear(){for(let e of this.#E)e();this.#r=new this.#T,this.#_(),this.#k(),this.emit("empty"),this.#o===0&&(this.#L(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#d("next",()=>this.#r.size<e)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#d("idle")}async onPendingZero(){this.#o!==0&&await this.#d("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#d("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#d("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#d(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#f}#q(){this.#t||(this.on("add",()=>{this.#r.size>0&&this.#p()}),this.on("next",()=>{this.#p()}))}#p(){this.#t||this.#w||(this.#w=!0,queueMicrotask(()=>{this.#w=!1,this.#k()}))}#z(){this.#t||(this.#N(),this.#p())}#k(){let e=this.#m;if(this.#t||this.#r.size===0){e&&(this.#m=!1,this.emit("rateLimitCleared"));return}let t;if(this.#a){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#n;let n=t>=this.#h;n!==e&&(this.#m=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#m}get isSaturated(){return this.#o===this.#g&&this.#r.size>0||this.isRateLimited&&this.#r.size>0}get runningTasks(){return[...this.#y.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}};function Ma(r){let e=[je.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var vf={};te(vf,{base10:()=>Xx});var V3=new Uint8Array(0);function Zm(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Ft(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 Qm(r){return new TextEncoder().encode(r)}function Jm(r){return new TextDecoder().decode(r)}function Vx(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=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,y=0,w=p.length;y!==w&&p[y]===0;)y++,g++;for(var v=(w-y)*u+1>>>0,T=new Uint8Array(v);y!==w;){for(var I=p[y],M=0,L=v-1;(I!==0||M<m)&&L!==-1;L--,M++)I+=256*T[L]>>>0,T[L]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");m=M,y++}for(var _=v-m;_!==v&&T[_]===0;)_++;for(var B=c.repeat(g);_<v;++_)B+=r.charAt(T[_]);return B}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,y=0;p[g]===c;)m++,g++;for(var w=(p.length-g)*l+1>>>0,v=new Uint8Array(w);p[g];){var T=t[p.charCodeAt(g)];if(T===255)return;for(var I=0,M=w-1;(T!==0||I<y)&&M!==-1;M--,I++)T+=a*v[M]>>>0,v[M]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");y=I,g++}if(p[g]!==" "){for(var L=w-y;L!==w&&v[L]===0;)L++;for(var _=new Uint8Array(m+(w-L)),B=m;L!==w;)_[B++]=v[L++];return _}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Hx=Vx,Wx=Hx,tg=Wx;var bf=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},wf=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return rg(this,e)}},xf=class{decoders;constructor(e){this.decoders=e}or(e){return rg(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function rg(r,e){return new xf({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ef=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new bf(e,t,n),this.decoder=new wf(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Nn({name:r,prefix:e,encode:t,decode:n}){return new Ef(r,e,t,n)}function or({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=tg(t,r);return Nn({prefix:e,name:r,encode:n,decode:s=>Ft(o(s))})}function jx(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Gx(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Yx(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ue({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Yx(n);return Nn({prefix:e,name:r,encode(s){return Gx(s,n,t)},decode(s){return jx(s,o,t,r)}})}var Xx=or({prefix:"9",name:"base10",alphabet:"0123456789"});var Sf={};te(Sf,{base16:()=>Zx,base16upper:()=>Qx});var Zx=ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Qx=ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Af={};te(Af,{base2:()=>Jx});var Jx=ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _f={};te(_f,{base256emoji:()=>oE});var ng=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}"),eE=ng.reduce((r,e,t)=>(r[t]=e,r),[]),tE=ng.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function rE(r){return r.reduce((e,t)=>(e+=eE[t],e),"")}function nE(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=tE[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var oE=Nn({prefix:"\u{1F680}",name:"base256emoji",encode:rE,decode:nE});var Cf={};te(Cf,{base32:()=>Mn,base32hex:()=>cE,base32hexpad:()=>uE,base32hexpadupper:()=>fE,base32hexupper:()=>lE,base32pad:()=>iE,base32padupper:()=>aE,base32upper:()=>sE,base32z:()=>dE});var Mn=ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),sE=ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),iE=ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),aE=ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),cE=ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),lE=ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),uE=ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fE=ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),dE=ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var If={};te(If,{base36:()=>is,base36upper:()=>hE});var is=or({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hE=or({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Tf={};te(Tf,{base58btc:()=>xt,base58flickr:()=>pE});var xt=or({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pE=or({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Lf={};te(Lf,{base64:()=>mE,base64pad:()=>gE,base64url:()=>yE,base64urlpad:()=>bE});var mE=ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),gE=ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),yE=ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),bE=ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Pf={};te(Pf,{base8:()=>wE});var wE=ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Df={};te(Df,{identity:()=>xE});var xE=Nn({prefix:"\0",name:"identity",encode:r=>Jm(r),decode:r=>Qm(r)});var iP=new TextEncoder,aP=new TextDecoder;var Rf={};te(Rf,{identity:()=>$E});var SE=ig,og=128,AE=127,_E=~AE,CE=Math.pow(2,31);function ig(r,e,t){e=e||[],t=t||0;for(var n=t;r>=CE;)e[t++]=r&255|og,r/=128;for(;r&_E;)e[t++]=r&255|og,r>>>=7;return e[t]=r|0,ig.bytes=t-n+1,e}var IE=kf,TE=128,sg=127;function kf(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw kf.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&sg)<<o:(i&sg)*Math.pow(2,o),o+=7}while(i>=TE);return kf.bytes=s-n,t}var LE=Math.pow(2,7),PE=Math.pow(2,14),DE=Math.pow(2,21),kE=Math.pow(2,28),RE=Math.pow(2,35),OE=Math.pow(2,42),NE=Math.pow(2,49),ME=Math.pow(2,56),FE=Math.pow(2,63),BE=function(r){return r<LE?1:r<PE?2:r<DE?3:r<kE?4:r<RE?5:r<OE?6:r<NE?7:r<ME?8:r<FE?9:10},UE={encode:SE,decode:IE,encodingLength:BE},KE=UE,as=KE;function cs(r,e=0){return[as.decode(r,e),as.decode.bytes]}function Fn(r,e,t=0){return as.encode(r,e,t),e}function Bn(r){return as.encodingLength(r)}function Kn(r,e){let t=e.byteLength,n=Bn(r),o=n+Bn(t),s=new Uint8Array(o+t);return Fn(r,s,0),Fn(t,s,n),s.set(e,o),new Un(r,t,e,s)}function ag(r){let e=Ft(r),[t,n]=cs(e),[o,s]=cs(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Un(t,o,i,e)}function cg(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Zm(r.bytes,t.bytes)}}var Un=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var lg=0,qE="identity",ug=Ft;function zE(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Kn(lg,ug(r))}var $E={code:lg,name:qE,encode:ug,digest:zE};var Mf={};te(Mf,{sha256:()=>HE,sha512:()=>WE});var VE=20;function Nf({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Of(r,e,t,n,o)}var Of=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??VE,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?fg(n,this.code,t?.truncate):n.then(o=>fg(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function fg(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Kn(e,r)}function hg(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var HE=Nf({name:"sha2-256",code:18,encode:hg("SHA-256")}),WE=Nf({name:"sha2-512",code:19,encode:hg("SHA-512")});function pg(r,e){let{bytes:t,version:n}=r;return n===0?GE(t,Ff(r),e??xt.encoder):YE(t,Ff(r),e??Mn.encoder)}var mg=new WeakMap;function Ff(r){let e=mg.get(r);if(e==null){let t=new Map;return mg.set(r,t),t}return e}var Ba=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==us)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==XE)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Kn(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&cg(e.multihash,n.multihash)}toString(e){return pg(this,e)}toJSON(){return{"/":pg(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??gg(n,o,s.bytes))}else if(t[ZE]===!0){let{version:n,multihash:o,code:s}=t,i=ag(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==us)throw new Error(`Version 0 CID must use dag-pb (code: ${us}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=gg(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,us,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Ft(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Un(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=cs(e.subarray(t));return t+=d,f},o=n(),s=us;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=jE(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ff(s).set(n,e),s}};function jE(r,e){switch(r[0]){case"Q":{let t=e??xt;return[xt.prefix,t.decode(`${xt.prefix}${r}`)]}case xt.prefix:{let t=e??xt;return[xt.prefix,t.decode(r)]}case Mn.prefix:{let t=e??Mn;return[Mn.prefix,t.decode(r)]}case is.prefix:{let t=e??is;return[is.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function GE(r,e,t){let{prefix:n}=t;if(n!==xt.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function YE(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var us=112,XE=18;function gg(r,e,t){let n=Bn(r),o=n+Bn(e),s=new Uint8Array(o+t.byteLength);return Fn(r,s,0),Fn(e,s,n),s.set(t,o),s}var ZE=Symbol.for("@ipld/js-cid/CID");var Bf={...Df,...Af,...Pf,...vf,...Sf,...Cf,...If,...Tf,...Lf,..._f},LP={...Mf,...Rf};function yg(r=0){return new Uint8Array(r)}function wg(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var bg=wg("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Uf=wg("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=yg(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),QE={utf8:bg,"utf-8":bg,hex:Bf.base16,latin1:Uf,ascii:Uf,binary:Uf,...Bf},xg=QE;function Eg(r,e="utf8"){let t=xg[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Kf=60;function Ua(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:je[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:je[e.type],TTL:e.TTL??e.ttl??Kf,data:e.data instanceof Uint8Array?Eg(e.data):e.data}))}}var JE=4;function qf(r,e={}){let t=new ss({concurrency:e.queryConcurrency??JE});return async(n,o={})=>{let s=o?.logger?.forComponent("dns:dns-json-over-https"),i=new URLSearchParams;i.set("name",n),Ma(o.types).forEach(c=>{i.append("type",je[c])}),o.onProgress?.(new ee("dns:query",n)),s?.("GET %s",`${r}?${i}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(s?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=Ua(await c.json());return o.onProgress?.(new ee("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function vg(){return[qf("https://cloudflare-dns.com/dns-query"),qf("https://dns.google/resolve")]}var _g=rc(Ag(),1);var zf=class{lru;constructor(e){this.lru=(0,_g.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return Ua({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:je[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Kf)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Cg(r){return new zf(r)}var ev=1e3,Ka=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=Cg(e.cacheSize??ev),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=vg())}async query(e,t={}){let n=Ma(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new ee("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new ee("dns:error",l))}}throw new Oa(a,`DNS lookup of ${e} ${n} failed`)}};var je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(je||(je={}));function Ig(r={}){return new Ka(r)}var $f=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[je.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(Q(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Ig()),this.dns)}},Br=new $f;async function Vf(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new La("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await Vf(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var qn={maxParallelDials:Ra,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,addressDialTimeout:6e3,resolvers:{dnsaddr:Br}},qa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;addressDialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??qn.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??qn.maxDialQueueLength,this.dialTimeout=t.dialTimeout??qn.dialTimeout,this.addressDialTimeout=t.addressDialTimeout??qn.addressDialTimeout,this.connections=t.connections??new Qe,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??qn.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Ki({concurrency:t.maxParallelDials??qn.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Je.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Pa(e);if(n!=null&&t.force!==!0){let i=Da(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new ee("dial-queue:already-connected",i)),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new ee("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new zr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new ee("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new ee("dial-queue:start-dial"));let a=wt([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Yf,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new ee("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new zr("Peer had more than maxPeerAddrsToDial");a++;let p=wt([t,AbortSignal.timeout(this.addressDialTimeout)]);try{let g=await this.components.transportManager.dial(h.multiaddr,{...e,signal:p});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[Wm]:k(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}return g}catch(g){if(this.log.error("dial failed to %a - %e",h.multiaddr,g),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Hm]:k(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p - %e",n,m)}if(t.aborted)throw new ws(g.message);l.push(g)}finally{p.clear()}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:Q(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new zr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new rs("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,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",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await Vf(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(e!=null){let f=`/p2p/${e.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.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.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 _a(`The dial request has no valid addresses for peer: ${e?.toString()??"unknown peer"}`);let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?Gm(l):l.sort(this.addressSorter);if(u.length===0)throw new rs(`The connection gater denied all addresses in the dial request for peer: ${e?.toString()??"unknown peer"}`);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!Pr.matches(o.multiaddr))!=null:!0}catch{}return!1}};var tv=Object.prototype.toString,rv=r=>tv.call(r)==="[object Error]",nv=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Xf(r){if(!(r&&rv(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"||t.startsWith("Load failed (")&&t.endsWith(")")?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:nv.has(t)}function ov(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function za(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}function Zf(r,e){if(e!==void 0&&typeof e!="function")throw new TypeError(`Expected \`${r}\` to be a function.`)}var Qf=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function sv(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function $a(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function iv(r,e){r<=0||await new Promise((t,n)=>{let o=()=>{clearTimeout(s),e.signal?.removeEventListener("abort",o),n(e.signal.reason)},s=setTimeout(()=>{e.signal?.removeEventListener("abort",o),t()},r);e.unref&&s.unref?.(),e.signal?.addEventListener("abort",o,{once:!0})})}async function av({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(s instanceof Qf)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=sv(t,o);if($a(n,a)<=0){let y=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:0});throw await o.onFailedAttempt(y),s}let u=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:i>0?c:0}),f=await o.shouldConsumeRetry(u),d=f&&i>0?c:0,h=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t,retryDelay:d});if(await o.onFailedAttempt(h),$a(n,a)<=0||$a(n,a)<=0||i<=0||s instanceof TypeError&&!Xf(s)||!await o.shouldRetry(h))throw s;let g=$a(n,a);if(g<=0)throw s;if(!f)return o.signal?.throwIfAborted(),!1;let m=Math.min(d,g);return o.signal?.throwIfAborted(),await iv(m,o),o.signal?.throwIfAborted(),!0}async function Jf(r,e={}){if(e={...e},ov(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,Zf("onFailedAttempt",e.onFailedAttempt),Zf("shouldRetry",e.shouldRetry),Zf("shouldConsumeRetry",e.shouldConsumeRetry),za("factor",e.factor,{min:0,allowInfinity:!1}),za("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),za("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),za("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await av({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Va=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Ui({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);Tg(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Jf(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(ic)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>Tg(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function Tg(r){for(let e of r.tags.keys())if(e.startsWith(ic))return!0;return!1}var Yf=50,ed={maxConnections:jm,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Ha=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??ed.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new Qe,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>ns(Q(n))),this.deny=(t.deny??[]).map(n=>ns(Q(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??ed.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new qi({points:t.inboundConnectionThreshold??ed.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ka({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>Q(n))}),this.dialQueue=new qa(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Ra,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,addressDialTimeout:t.addressDialTimeout??6e3,resolvers:t.resolvers??{dnsaddr:Br},connections:this.connections}),this.reconnectQueue=new Va({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await ud(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 fd(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([ft(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new R("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new vt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new ee("connection:open",e));let{peerId:n,multiaddrs:o}=Pa(e);if(this.peerId.equals(n))throw new qr("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=Da(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new ee("dial-queue:already-connected")),t.onProgress?.(new ee("connection:opened",c)),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Yf});if(s.status!=="open")throw new sr("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Bt("Duplicate multiaddr connection")),c;return a||i.push(s),t.onProgress?.(new ee("connection:opened",s)),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([ft(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Ce(e.remoteAddr)){let s=W(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(Ce(e.remoteAddr)){let s=W(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(Ce(e.remoteAddr)){let o=W(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>Q(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var uv=1e4,fv="1.0.0",dv="ping",hv="ipfs",Lg=32,pv=!0,Wa=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??hv}/${dv}/${fv}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??uv,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??pv,this.timeout=new Pi({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Yn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o;try{o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0});let s=Wu(o);t=Date.now(),await Promise.all([s.write(crypto.getRandomValues(new Uint8Array(Lg)),{signal:n}),s.read({bytes:Lg,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(s){if(o?.abort(s),s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var ja=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:K(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:K(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Rn("No content routers available");let n=this,o=new Er;for await(let s of Ln(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new Rn("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Rn("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new vt;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new vt;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Ga=globalThis.CustomEvent??Event;async function*td(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=ve(),a=ve(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=ve(),await i.promise),u)break;let g={done:!1};s.push(g),p().then(m=>{g.done=!0,g.ok=!0,g.value=m,o.dispatchEvent(new Ga("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new Ga("task-complete"))})}c=!0,o.dispatchEvent(new Ga("task-complete"))}catch(p){l=p,o.dispatchEvent(new Ga("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 u=!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 u=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=ve(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var Ya=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:K(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new ts("No peer routers available");if(e.toString()===this.peerId.toString())throw new xa("Should not try to find self");let n=this,o=Ln(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new ir}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new ts("No peer routers available");let n=this,o=Fo(1024);for await(let s of td((async function*(){let i=Ln(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var Xa=class extends Re{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=wt([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ve(),yield(await ft(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=wt([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=crypto.getRandomValues(new Uint8Array(32)),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await He(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var rd=32,nd=64,Za=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=De({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Ea(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new va(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:rd,maxOutboundStreams:nd,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var Qa=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=De({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=De({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Gn.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new R("Transport must have a valid tag");if(this.transports.has(t))throw new R(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Ta(`No transport available for address ${String(e)}`);return t?.onProgress?.(new ee("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new vt("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new Sa)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),ku.matches(c)?t.ipv4.attempts++:Ru.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),ku.matches(c)&&t.ipv4.success++,Ru.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.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(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Gn.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Aa(`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:
13
13
  ${[...t.errors.entries()].map(([s,i])=>`
14
- ${s}: ${`${v_(i)}`.split(`
14
+ ${s}: ${`${mv(i)}`.split(`
15
15
  `).join(`
16
16
  `)}
17
- `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function v_(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var _t="/multistream/1.0.0";var S_=M(`
18
- `);async function Hs(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==S_[0])throw new Qs("Missing newline");return z(n).trimEnd()}async function ho(r,e,t={}){if(e=Array.isArray(e)?[...e]:[e],e.length===0)throw new Error("At least one protocol must be specified");let n=r.log.newScope("mss:select"),o=ya(r,{...t,maxDataLength:1024});for(let s=0;s<e.length;s++){let i=e[s],a;if(s===0){n.trace('write ["%s", "%s"]',_t,i);let c=M(`${_t}
19
- `),u=M(`${i}
20
- `);if(await o.writeV([c,u],t),n.trace("reading multistream-select header"),a=await Hs(o,t),n.trace('read "%s"',a),a!==_t){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(M(`${i}
21
- `),t);if(n.trace("reading protocol response"),a=await Hs(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new Zs(`Protocol selection failed - could not negotiate ${e}`)}async function po(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=ya(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await Hs(o,t);if(n.trace('read "%s"',s),s===_t){n.trace('respond with "%s" for "%s"',_t,s),await o.write(M(`${_t}
22
- `),t),n.trace('responded with "%s" for "%s"',_t,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(M(`${s}
23
- `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new ee(...e.map(a=>Sa.single(M(`${a}
24
- `))),M(`
25
- `));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(M(`na
26
- `),t),n('responded with "na" for "%s"',s)}}var Hh=class extends Re{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=eh(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new ri(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Xh]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new hr("Connection is not multiplexed");if(this.muxer.status!=="open")throw new mr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new mr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new bo("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new te("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await ho(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=C_(n.protocol,this.components.registrar,t),s=gb(n.protocol,"outbound",this);if(s>o){let c=new ti(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new te("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let u=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",u),t.protocol=await po(t,u,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=__(t.protocol,this.components.registrar);if(gb(t.protocol,"inbound",this)>o)throw new ei(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new bo("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(u,l,f)=>{await i(u,l),f(u,l)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(u,l)=>{e=u,t=l,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function yb(r,e){return new Hh(r,e)}function __(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return qh}function C_(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??$h}function gb(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var zc=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=Pe({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Pe({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new pc(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=vt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new mc("Connection denied");await We(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=xt(n),await We(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,u=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${u}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(I_(n)){if(n.remotePeer==null)throw new jt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;f!=null&&(d=xt(f)),n?.onProgress?.(new te(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new Qr("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new te(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let l=this._createConnection({id:u,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return l.log("successfully upgraded connection"),l}_createConnection(e){let t=yb(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await po(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Wr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Wr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await ho(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Wr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Wr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await ho(e,o,n),i=t.get(s);if(i==null)throw new hr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new hr(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await po(e,o,n),i=t.get(s);if(i==null)throw new hr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function I_(r){return r.skipEncryption===!0}var qc="3.3.3-a34745c01",$c="js-libp2p";function wb(r,e){return`${r??$c}/${e??qc} browser/${globalThis.navigator.userAgent}`}var js=class extends Re{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Re,n=t.dispatchEvent.bind(t);t.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||f},this.peerId=e.peerId,this.logger=e.logger??$i(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??$c,s=e.nodeInfo?.version??qc,i=this.components=Ay({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??wb(o,s)},logger:this.logger,events:t,datastore:e.datastore??new ec,connectionGater:Cy(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",by(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.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})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new zc(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(e.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Kc(this.components,e.transportManager)),this.configureComponent("connectionManager",new Rc(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Oc(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Uc(this.components)),this.configureComponent("addressManager",new sc(this.components,e.addresses));let a=(e.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Fc(this.components,{routers:a}));let c=(e.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Nc(this.components,{routers:c})),this.configureComponent("randomWalk",new Bc(this.components)),(e.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),e.services!=null)for(let u of Object.keys(e.services)){let l=e.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[Hc]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Hc])),f[Gc]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[Gc])),f[jc]!=null&&(this.log("registering service %s for peer discovery",u),f[jc].addEventListener?.("peer",d=>{this.#e(d)}))}_y(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new kr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new R("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new R("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){fr(e)&&(e=xt(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Mt([M("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=Cn(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function T_(r={}){r.privateKey??=await _g("Ed25519");let e=new js({...await Dg(r),peerId:Lg(r.privateKey)});return r.start!==!1&&await e.start(),e}var L_=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function D_(r){return r==null?!1:r instanceof js?!0:L_.every(e=>typeof r[e]=="function")}return _b(P_);})();
17
+ `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function mv(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var Et="/multistream/1.0.0";var gv=k(`
18
+ `);async function fs(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==gv[0])throw new bs("Missing newline");return K(n).trimEnd()}async function zn(r,e,t={}){if(e=Array.isArray(e)?[...e]:[e],e.length===0)throw new Error("At least one protocol must be specified");let n=r.log.newScope("mss:select"),o=ki(r,{...t,maxDataLength:1024});for(let s=0;s<e.length;s++){let i=e[s],a;if(s===0){n.trace('write ["%s", "%s"]',Et,i);let c=k(`${Et}
19
+ `),l=k(`${i}
20
+ `);if(await o.writeV([c,l],t),n.trace("reading multistream-select header"),a=await fs(o,t),n.trace('read "%s"',a),a!==Et){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(k(`${i}
21
+ `),t);if(n.trace("reading protocol response"),a=await fs(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new ys(`Protocol selection failed - could not negotiate ${e}`)}async function $n(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=ki(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await fs(o,t);if(n.trace('read "%s"',s),s===Et){n.trace('respond with "%s" for "%s"',Et,s),await o.write(k(`${Et}
22
+ `),t),n.trace('responded with "%s" for "%s"',Et,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(k(`${s}
23
+ `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new J(...e.map(a=>Bi.single(k(`${a}
24
+ `))),k(`
25
+ `));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(k(`na
26
+ `),t),n('responded with "na" for "%s"',s)}}var sd=class extends Re{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=pf(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new vs(n.local,n.error))})}[Symbol.toStringTag]="Connection";[ld]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new nr("Connection is not multiplexed");if(this.muxer.status!=="open")throw new sr(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new sr(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new jn("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new ee("connection:open-stream",{connection:this,protocols:e})),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await zn(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=wv(n.protocol,this.components.registrar,t),s=Rg(n.protocol,"outbound",this);if(s>o){let c=new Es(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,i);return t.onProgress?.(new ee("connection:opened-stream",{connection:this,stream:a})),a}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await $n(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=bv(t.protocol,this.components.registrar);if(Rg(t.protocol,"inbound",this)>o)throw new xs(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new jn("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,f)=>{await i(l,u),f(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function Og(r,e){return new sd(r,e)}function bv(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return rd}function wv(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??nd}function Rg(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Ja=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=De({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=De({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Ca(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=wt([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Ia("Connection denied");await He(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=yt(n),await He(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(xv(n)){if(n.remotePeer==null)throw new Bt(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;f!=null&&(d=yt(f)),n?.onProgress?.(new ee(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new qr("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new ee(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=Og(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await $n(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Fr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Fr(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await zn(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Fr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Fr(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await zn(e,o,n),i=t.get(s);if(i==null)throw new nr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new nr(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await $n(e,o,n),i=t.get(s);if(i==null)throw new nr(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function xv(r){return r.skipEncryption===!0}var ec="3.3.4",tc="js-libp2p";function Mg(r,e){return`${r??tc}/${e??ec} browser/${globalThis.navigator.userAgent}`}var ds=class extends Re{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Re,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??oi(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??tc,s=e.nodeInfo?.version??ec,i=this.components=qm({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??Mg(o,s)},logger:this.logger,events:t,datastore:e.datastore??new da,connectionGater:$m(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",Nm(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Ja(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new Qa(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ha(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Wa(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Za(this.components)),this.configureComponent("addressManager",new ya(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Ya(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new ja(this.components,{routers:c})),this.configureComponent("randomWalk",new Xa(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[nc]!=null&&(this.log("registering service %s for content routing",l),c.push(f[nc])),f[sc]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[sc])),f[oc]!=null&&(this.log("registering service %s for peer discovery",l),f[oc].addEventListener?.("peer",d=>{this.#e(d)}))}zm(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Er;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new R("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new R("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){rr(e)&&(e=yt(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ye([k("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=ln(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function Ev(r={}){r.privateKey??=await pp("Ed25519");let e=new ds({...await wp(r),peerId:bp(r.privateKey)});return r.start!==!1&&await e.start(),e}var vv=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Sv(r){return r==null?!1:r instanceof ds?!0:vv.every(e=>typeof r[e]=="function")}return zg(Av);})();
27
27
  /*! Bundled license information:
28
28
 
29
29
  @noble/curves/utils.js: