libp2p 2.9.0-cb1c14e62 → 2.9.0-cf9aab5c8

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,23 +1,23 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2P=(()=>{var lm=Object.create;var ts=Object.defineProperty;var um=Object.getOwnPropertyDescriptor;var fm=Object.getOwnPropertyNames;var dm=Object.getPrototypeOf,hm=Object.prototype.hasOwnProperty;var zr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),kt=(r,t)=>{for(var e in t)ts(r,e,{get:t[e],enumerable:!0})},rf=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fm(t))!hm.call(r,o)&&o!==e&&ts(r,o,{get:()=>t[o],enumerable:!(n=um(t,o))||n.enumerable});return r};var es=(r,t,e)=>(e=r!=null?lm(dm(r)):{},rf(t||!r||!r.__esModule?ts(e,"default",{value:r,enumerable:!0}):e,r)),pm=r=>rf(ts({},"__esModule",{value:!0}),r);var gh=zr((g_,El)=>{"use strict";var ay=Object.prototype.hasOwnProperty,Ot="~";function _o(){}Object.create&&(_o.prototype=Object.create(null),new _o().__proto__||(Ot=!1));function cy(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function mh(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new cy(e,n||r,o),i=Ot?Ot+t:t;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Fs(r,t){--r._eventsCount===0?r._events=new _o:delete r._events[t]}function At(){this._events=new _o,this._eventsCount=0}At.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)ay.call(e,n)&&t.push(Ot?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};At.prototype.listeners=function(t){var e=Ot?Ot+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};At.prototype.listenerCount=function(t){var e=Ot?Ot+t:t,n=this._events[e];return n?n.fn?1:n.length:0};At.prototype.emit=function(t,e,n,o,s,i){var a=Ot?Ot+t:t;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,n,o,s,i),!0}for(f=1,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(t,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,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!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};At.prototype.on=function(t,e,n){return mh(this,t,e,n,!1)};At.prototype.once=function(t,e,n){return mh(this,t,e,n,!0)};At.prototype.removeListener=function(t,e,n,o){var s=Ot?Ot+t:t;if(!this._events[s])return this;if(!e)return Fs(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&Fs(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Fs(this,s)}return this};At.prototype.removeAllListeners=function(t){var e;return t?(e=Ot?Ot+t:t,this._events[e]&&Fs(this,e)):(this._events=new _o,this._eventsCount=0),this};At.prototype.off=At.prototype.removeListener;At.prototype.addListener=At.prototype.on;At.prefixed=Ot;At.EventEmitter=At;typeof El<"u"&&(El.exports=At)});var Eh=zr((U_,xh)=>{xh.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var xp=zr(qo=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},i=function(c){var l,u,f,d,h,p;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),h=p[0],u=p[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(e(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+e(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,h,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(g){throw f=g,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=i(this.first),f=i(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),qo.ip2long=i,qo.long2ip=a,qo.Netmask=r}).call(qo)});var Gp=zr((PP,Wp)=>{function Qt(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Wp.exports=Qt;Qt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Qt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Qt.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Qt.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Qt.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Qt.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Qt.prototype.start=Qt.prototype.try;Qt.prototype.errors=function(){return this._errors};Qt.prototype.attempts=function(){return this._attempts};Qt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var jp=zr(Ur=>{var xw=Gp();Ur.operation=function(r){var t=Ur.timeouts(r);return new xw(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Ur.timeouts=function(r){if(r instanceof Array)return[].concat(r);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var e in r)t[e]=r[e];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(s,i){return s-i}),n};Ur.createTimeout=function(r,t){var e=t.randomize?Math.random()+1:1,n=Math.round(e*Math.max(t.minTimeout,1)*Math.pow(t.factor,r));return n=Math.min(n,t.maxTimeout),n};Ur.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var l=Ur.operation(t),u=Array.prototype.slice.call(arguments,1),f=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),f.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[s].options=t}}});var Zp=zr((LP,Xp)=>{Xp.exports=jp()});var Qw={};kt(Qw,{createLibp2p:()=>Xw,dnsaddrResolver:()=>ke,isLibp2p:()=>Yw});var nf=Symbol.for("@libp2p/connection");var Fa=Symbol.for("@libp2p/content-routing");var Ua=Symbol.for("@libp2p/peer-discovery");var rs=Symbol.for("@libp2p/peer-id");function Ue(r){return!!r?.[rs]}var Ka=Symbol.for("@libp2p/peer-routing");var qa="keep-alive";var ix=Symbol.for("@libp2p/transport");var nr;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(nr||(nr={}));var Jt=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var R=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Vr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},Un=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var ns=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Hr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var or=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},$r=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Ke=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},os=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},ss=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},Kn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},is=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var as=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},ye=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Wr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var qn=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},cs=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},ls=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},qe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var qt=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function us(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function of(...r){let t=[];for(let e of r)us(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function sf(...r){let t=[];for(let e of r)us(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var zn=Symbol.for("@libp2p/service-capabilities"),za=Symbol.for("@libp2p/service-dependencies");var Ga={};kt(Ga,{base58btc:()=>Y,base58flickr:()=>Em});var Rx=new Uint8Array(0);function af(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function be(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function cf(r){return new TextEncoder().encode(r)}function lf(r){return new TextDecoder().decode(r)}function mm(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),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,E=0,v=p.length;E!==v&&p[E]===0;)E++,g++;for(var _=(v-E)*u+1>>>0,A=new Uint8Array(_);E!==v;){for(var O=p[E],C=0,F=_-1;(O!==0||C<m)&&F!==-1;F--,C++)O+=256*A[F]>>>0,A[F]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");m=C,E++}for(var U=_-m;U!==_&&A[U]===0;)U++;for(var L=c.repeat(g);U<_;++U)L+=r.charAt(A[U]);return L}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,E=0;p[g]===c;)m++,g++;for(var v=(p.length-g)*l+1>>>0,_=new Uint8Array(v);p[g];){var A=e[p.charCodeAt(g)];if(A===255)return;for(var O=0,C=v-1;(A!==0||O<E)&&C!==-1;C--,O++)A+=a*_[C]>>>0,_[C]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");E=O,g++}if(p[g]!==" "){for(var F=v-E;F!==v&&_[F]===0;)F++;for(var U=new Uint8Array(m+(v-F)),L=m;F!==v;)U[L++]=_[F++];return U}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var gm=mm,ym=gm,ff=ym;var Va=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ha=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return df(this,t)}},$a=class{decoders;constructor(t){this.decoders=t}or(t){return df(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function df(r,t){return new $a({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Wa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Va(t,e,n),this.decoder=new Ha(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Gr({name:r,prefix:t,encode:e,decode:n}){return new Wa(r,t,e,n)}function ze({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ff(e,r);return Gr({prefix:t,name:r,encode:n,decode:s=>be(o(s))})}function bm(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function wm(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function xm(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function st({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=xm(n);return Gr({prefix:t,name:r,encode(s){return wm(s,n,e)},decode(s){return bm(s,o,e,r)}})}var Y=ze({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Em=ze({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ja={};kt(ja,{base32:()=>Gt,base32hex:()=>Am,base32hexpad:()=>Im,base32hexpadupper:()=>Tm,base32hexupper:()=>Cm,base32pad:()=>_m,base32padupper:()=>Sm,base32upper:()=>vm,base32z:()=>Pm});var Gt=st({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),vm=st({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_m=st({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Sm=st({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Am=st({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Cm=st({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Im=st({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Tm=st({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Pm=st({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xa={};kt(Xa,{base36:()=>Vn,base36upper:()=>Dm});var Vn=ze({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Dm=ze({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Lm=mf,hf=128,Rm=127,Om=~Rm,km=Math.pow(2,31);function mf(r,t,e){t=t||[],e=e||0;for(var n=e;r>=km;)t[e++]=r&255|hf,r/=128;for(;r&Om;)t[e++]=r&255|hf,r>>>=7;return t[e]=r|0,mf.bytes=e-n+1,t}var Mm=Za,Nm=128,pf=127;function Za(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Za.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&pf)<<o:(i&pf)*Math.pow(2,o),o+=7}while(i>=Nm);return Za.bytes=s-n,e}var Bm=Math.pow(2,7),Fm=Math.pow(2,14),Um=Math.pow(2,21),Km=Math.pow(2,28),qm=Math.pow(2,35),zm=Math.pow(2,42),Vm=Math.pow(2,49),Hm=Math.pow(2,56),$m=Math.pow(2,63),Wm=function(r){return r<Bm?1:r<Fm?2:r<Um?3:r<Km?4:r<qm?5:r<zm?6:r<Vm?7:r<Hm?8:r<$m?9:10},Gm={encode:Lm,decode:Mm,encodingLength:Wm},jm=Gm,Hn=jm;function $n(r,t=0){return[Hn.decode(r,t),Hn.decode.bytes]}function jr(r,t,e=0){return Hn.encode(r,t,e),t}function Xr(r){return Hn.encodingLength(r)}function te(r,t){let e=t.byteLength,n=Xr(r),o=n+Xr(e),s=new Uint8Array(o+e);return jr(r,s,0),jr(e,s,n),s.set(t,o),new Zr(r,e,t,s)}function we(r){let t=be(r),[e,n]=$n(t),[o,s]=$n(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Zr(e,o,i,t)}function gf(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&af(r.bytes,e.bytes)}}var Zr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function yf(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Zm(e,Ya(r),t??Y.encoder);default:return Ym(e,Ya(r),t??Gt.encoder)}}var bf=new WeakMap;function Ya(r){let t=bf.get(r);if(t==null){let e=new Map;return bf.set(r,e),e}return t}var ot=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Wn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Qm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=te(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&gf(t.multihash,n.multihash)}toString(t){return yf(this,t)}toJSON(){return{"/":yf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??wf(n,o,s.bytes))}else if(e[Jm]===!0){let{version:n,multihash:o,code:s}=e,i=we(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Wn)throw new Error(`Version 0 CID must use dag-pb (code: ${Wn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=wf(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Wn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=be(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Zr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=$n(t.subarray(e));return e+=d,f},o=n(),s=Wn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Xm(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ya(s).set(n,t),s}};function Xm(r,t){switch(r[0]){case"Q":{let e=t??Y;return[Y.prefix,e.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let e=t??Y;return[Y.prefix,e.decode(r)]}case Gt.prefix:{let e=t??Gt;return[Gt.prefix,e.decode(r)]}case Vn.prefix:{let e=t??Vn;return[Vn.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Zm(r,t,e){let{prefix:n}=e;if(n!==Y.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Ym(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Wn=112,Qm=18;function wf(r,t,e){let n=Xr(r),o=n+Xr(t),s=new Uint8Array(o+e.byteLength);return jr(r,s,0),jr(t,s,n),s.set(e,o),s}var Jm=Symbol.for("@ipld/js-cid/CID");var Qa={};kt(Qa,{identity:()=>ee});var xf=0,tg="identity",Ef=be;function eg(r){return te(xf,Ef(r))}var ee={code:xf,name:tg,encode:Ef,digest:eg};function X(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function it(r=0){return new Uint8Array(r)}function Et(r=0){return new Uint8Array(r)}function re(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=Et(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var _f=Symbol.for("@achingbrain/uint8arraylist");function vf(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function ds(r){return!!r?.[_f]}var $=class r{bufs;length;[_f]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(ds(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(ds(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=vf(this.bufs,t);return e.buf[e.index]}set(t,e){let n=vf(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(ds(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return re(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:re(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!ds(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;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(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Et(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=it(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=it(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=it(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Et(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=it(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=it(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=it(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=it(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=it(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!X(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var Ja={};kt(Ja,{base10:()=>rg});var rg=ze({prefix:"9",name:"base10",alphabet:"0123456789"});var tc={};kt(tc,{base16:()=>ng,base16upper:()=>og});var ng=st({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),og=st({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ec={};kt(ec,{base2:()=>sg});var sg=st({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var rc={};kt(rc,{base256emoji:()=>ug});var Sf=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}"),ig=Sf.reduce((r,t,e)=>(r[e]=t,r),[]),ag=Sf.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function cg(r){return r.reduce((t,e)=>(t+=ig[e],t),"")}function lg(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=ag[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var ug=Gr({prefix:"\u{1F680}",name:"base256emoji",encode:cg,decode:lg});var sc={};kt(sc,{base64:()=>nc,base64pad:()=>fg,base64url:()=>oc,base64urlpad:()=>dg});var nc=st({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fg=st({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oc=st({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),dg=st({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ic={};kt(ic,{base8:()=>hg});var hg=st({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ac={};kt(ac,{identity:()=>pg});var pg=Gr({prefix:"\0",name:"identity",encode:r=>lf(r),decode:r=>cf(r)});var mE=new TextEncoder,gE=new TextDecoder;var uc={};kt(uc,{sha256:()=>Yr,sha512:()=>yg});function lc({name:r,code:t,encode:e}){return new cc(r,t,e)}var cc=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?te(this.code,e):e.then(n=>te(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Cf(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Yr=lc({name:"sha2-256",code:18,encode:Cf("SHA-256")}),yg=lc({name:"sha2-512",code:19,encode:Cf("SHA-512")});var Gn={...ac,...ec,...ic,...Ja,...tc,...ja,...Xa,...Ga,...sc,...rc},TE={...uc,...Qa};function Tf(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var If=Tf("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),fc=Tf("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Et(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),bg={utf8:If,"utf-8":If,hex:Gn.base16,latin1:fc,ascii:fc,binary:fc,...Gn},hs=bg;function P(r,t="utf8"){let e=hs[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function N(r,t="utf8"){let e=hs[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var wg=parseInt("11111",2),dc=parseInt("10000000",2),xg=parseInt("01111111",2),Pf={0:jn,1:jn,2:Eg,3:Sg,4:Ag,5:_g,6:vg,16:jn,22:jn,48:jn};function xe(r,t={offset:0}){let e=r[t.offset]&wg;if(t.offset++,Pf[e]!=null)return Pf[e](r,t);throw new Error("No decoder for tag "+e)}function Xn(r,t){let e=0;if((r[t.offset]&dc)===dc){let n=r[t.offset]&xg,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function jn(r,t){Xn(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=xe(r,t);if(n===null)break;e.push(n)}return e}function Eg(r,t){let e=Xn(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function vg(r,t){let e=Xn(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.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 _g(r,t){return t.offset++,null}function Sg(r,t){let e=Xn(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Ag(r,t){let e=Xn(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Cg(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new $;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function ps(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Cg(r.byteLength);return new $(Uint8Array.from([t.byteLength|dc]),t)}function Tt(r){let t=new $,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new $(Uint8Array.from([2]),ps(t),t)}function Zn(r){let t=Uint8Array.from([0]),e=new $(t,r);return new $(Uint8Array.from([3]),ps(e),e)}function Df(r){return new $(Uint8Array.from([4]),ps(r),r)}function ne(r,t=48){let e=new $;for(let n of r)e.append(n);return new $(Uint8Array.from([t]),ps(e),e)}async function Lf(r="P-256"){let t=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",t.publicKey),privateKey:await crypto.subtle.exportKey("jwk",t.privateKey)}}async function Rf(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);e?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Of(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var Ig=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Tg=Uint8Array.from([6,5,43,129,4,0,34]),Pg=Uint8Array.from([6,5,43,129,4,0,35]),Dg={ext:!0,kty:"EC",crv:"P-256"},Lg={ext:!0,kty:"EC",crv:"P-384"},Rg={ext:!0,kty:"EC",crv:"P-521"},hc=32,pc=48,mc=66;function gc(r){let t=xe(r);return kf(t)}function kf(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===hc*2+1)return n=N(t.subarray(e,e+hc),"base64url"),o=N(t.subarray(e+hc),"base64url"),new sr({...Dg,key_ops:["verify"],x:n,y:o});if(t.byteLength===pc*2+1)return n=N(t.subarray(e,e+pc),"base64url"),o=N(t.subarray(e+pc),"base64url"),new sr({...Lg,key_ops:["verify"],x:n,y:o});if(t.byteLength===mc*2+1)return n=N(t.subarray(e,e+mc),"base64url"),o=N(t.subarray(e+mc),"base64url"),new sr({...Rg,key_ops:["verify"],x:n,y:o});throw new R(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Mf(r){return ne([Tt(Uint8Array.from([1])),Df(P(r.d??"","base64url")),ne([Bf(r.crv)],160),ne([Zn(new $(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function Nf(r){return ne([Tt(Uint8Array.from([1])),ne([Bf(r.crv)],160),ne([Zn(new $(Uint8Array.from([4]),P(r.x??"","base64url"),P(r.y??"","base64url")))],161)]).subarray()}function Bf(r){if(r==="P-256")return Ig;if(r==="P-384")return Tg;if(r==="P-521")return Pg;throw new R(`Invalid curve ${r}`)}async function Ff(r="P-256"){let t=await Lf(r);return new ms(t.privateKey)}var sr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Nf(this.jwk)),this._raw}toMultihash(){return ee.digest(jt(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:X(this.raw,t.raw)}async verify(t,e,n){return Of(this.jwk,e,t,n)}},ms=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new sr({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=Mf(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:X(this.raw,t.raw)}async sign(t,e){return Rf(this.jwk,t,e)}};var ir=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ar(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Yn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function at(r,...t){if(!ar(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function gs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Yn(r.outputLen),Yn(r.blockLen)}function Jr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Kf(r,t){at(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function ve(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function ys(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function oe(r,t){return r<<32-t|r>>>t}var qf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Og=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Xt(r){if(at(r),qf)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Og[r[e]];return t}var Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function Uf(r){if(r>=Ee._0&&r<=Ee._9)return r-Ee._0;if(r>=Ee.A&&r<=Ee.F)return r-(Ee.A-10);if(r>=Ee.a&&r<=Ee.f)return r-(Ee.a-10)}function cr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(qf)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=Uf(r.charCodeAt(s)),a=Uf(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function yc(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Qn(r){return typeof r=="string"&&(r=yc(r)),at(r),r}function Mt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];at(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Qr=class{};function bc(r){let t=n=>r().update(Qn(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function lr(r=32){if(ir&&typeof ir.getRandomValues=="function")return ir.getRandomValues(new Uint8Array(r));if(ir&&typeof ir.randomBytes=="function")return Uint8Array.from(ir.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function kg(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function zf(r,t,e){return r&t^~r&e}function Vf(r,t,e){return r&t^r&e^t&e}var Jn=class extends Qr{constructor(t,e,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=ys(this.buffer)}update(t){Jr(this),t=Qn(t),at(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=ys(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Jr(this),Kf(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,ve(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;kg(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=ys(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should 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:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},_e=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var yt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var bs=BigInt(4294967295),Hf=BigInt(32);function Mg(r,t=!1){return t?{h:Number(r&bs),l:Number(r>>Hf&bs)}:{h:Number(r>>Hf&bs)|0,l:Number(r&bs)|0}}function $f(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=Mg(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var wc=(r,t,e)=>r>>>e,xc=(r,t,e)=>r<<32-e|t>>>e,ur=(r,t,e)=>r>>>e|t<<32-e,fr=(r,t,e)=>r<<32-e|t>>>e,to=(r,t,e)=>r<<64-e|t>>>e-32,eo=(r,t,e)=>r>>>e-32|t<<64-e;function ue(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Wf=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Gf=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,jf=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Xf=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Zf=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Yf=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Bg=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]),He=new Uint32Array(64),ws=class extends Jn{constructor(t=32){super(64,t,8,!1),this.A=_e[0]|0,this.B=_e[1]|0,this.C=_e[2]|0,this.D=_e[3]|0,this.E=_e[4]|0,this.F=_e[5]|0,this.G=_e[6]|0,this.H=_e[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)He[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=He[f-15],h=He[f-2],p=oe(d,7)^oe(d,18)^d>>>3,g=oe(h,17)^oe(h,19)^h>>>10;He[f]=g+He[f-7]+p+He[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=oe(a,6)^oe(a,11)^oe(a,25),h=u+d+zf(a,c,l)+Bg[f]+He[f]|0,g=(oe(n,2)^oe(n,13)^oe(n,22))+Vf(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(){ve(He)}destroy(){this.set(0,0,0,0,0,0,0,0),ve(this.buffer)}};var Qf=$f(["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))),Fg=Qf[0],Ug=Qf[1],$e=new Uint32Array(80),We=new Uint32Array(80),Ec=class extends Jn{constructor(t=64){super(128,t,16,!1),this.Ah=yt[0]|0,this.Al=yt[1]|0,this.Bh=yt[2]|0,this.Bl=yt[3]|0,this.Ch=yt[4]|0,this.Cl=yt[5]|0,this.Dh=yt[6]|0,this.Dl=yt[7]|0,this.Eh=yt[8]|0,this.El=yt[9]|0,this.Fh=yt[10]|0,this.Fl=yt[11]|0,this.Gh=yt[12]|0,this.Gl=yt[13]|0,this.Hh=yt[14]|0,this.Hl=yt[15]|0}get(){let{Ah:t,Al:e,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[t,e,n,o,s,i,a,c,l,u,f,d,h,p,g,m]}set(t,e,n,o,s,i,a,c,l,u,f,d,h,p,g,m){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=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(t,e){for(let _=0;_<16;_++,e+=4)$e[_]=t.getUint32(e),We[_]=t.getUint32(e+=4);for(let _=16;_<80;_++){let A=$e[_-15]|0,O=We[_-15]|0,C=ur(A,O,1)^ur(A,O,8)^wc(A,O,7),F=fr(A,O,1)^fr(A,O,8)^xc(A,O,7),U=$e[_-2]|0,L=We[_-2]|0,b=ur(U,L,19)^to(U,L,61)^wc(U,L,6),y=fr(U,L,19)^eo(U,L,61)^xc(U,L,6),S=jf(F,y,We[_-7],We[_-16]),I=Xf(S,C,b,$e[_-7],$e[_-16]);$e[_]=I|0,We[_]=S|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:E,Hl:v}=this;for(let _=0;_<80;_++){let A=ur(f,d,14)^ur(f,d,18)^to(f,d,41),O=fr(f,d,14)^fr(f,d,18)^eo(f,d,41),C=f&h^~f&g,F=d&p^~d&m,U=Zf(v,O,F,Ug[_],We[_]),L=Yf(U,E,A,C,Fg[_],$e[_]),b=U|0,y=ur(n,o,28)^to(n,o,34)^to(n,o,39),S=fr(n,o,28)^eo(n,o,34)^eo(n,o,39),I=n&s^n&a^s&a,k=o&i^o&c^i&c;E=g|0,v=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=ue(l|0,u|0,L|0,b|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let B=Wf(b,S,k);n=Gf(B,L,y,I),o=B|0}({h:n,l:o}=ue(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ue(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ue(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ue(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ue(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ue(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=ue(this.Gh|0,this.Gl|0,g|0,m|0),{h:E,l:v}=ue(this.Hh|0,this.Hl|0,E|0,v|0),this.set(n,o,s,i,a,c,l,u,f,d,h,p,g,m,E,v)}roundClean(){ve($e,We)}destroy(){ve(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var xs=bc(()=>new ws);var Jf=bc(()=>new Ec);var Sc=BigInt(0),_c=BigInt(1);function Se(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}function ro(r){let t=r.toString(16);return t.length&1?"0"+t:t}function td(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Sc:BigInt("0x"+r)}function tn(r){return td(Xt(r))}function Ae(r){return at(r),td(Xt(Uint8Array.from(r).reverse()))}function Es(r,t){return cr(r.toString(16).padStart(t*2,"0"))}function Ce(r,t){return Es(r,t).reverse()}function Q(r,t,e){let n;if(typeof t=="string")try{n=cr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(ar(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function ed(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var vc=r=>typeof r=="bigint"&&Sc<=r;function rd(r,t,e){return vc(r)&&vc(t)&&vc(e)&&t<=r&&r<e}function Ge(r,t,e,n){if(!rd(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function vs(r){let t;for(t=0;r>Sc;r>>=_c,t+=1);return t}var je=r=>(_c<<BigInt(r))-_c;function nd(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>e(i,s,...h),u=(h=n(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,p=[];for(;h<t;){s=l();let g=s.slice();p.push(g),h+=s.length}return Mt(...p)};return(h,p)=>{c(),u(h);let g;for(;!(g=p(f()));)u();return c(),g}}function Xe(r,t,e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(e).forEach(([o,s])=>n(o,s,!0))}function en(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var Pt=BigInt(0),pt=BigInt(1),dr=BigInt(2),id=BigInt(3),ad=BigInt(4),cd=BigInt(5),Kg=BigInt(7),ld=BigInt(8),qg=BigInt(9),ud=BigInt(16);function ct(r,t){let e=r%t;return e>=Pt?e:t+e}function rt(r,t,e){let n=r;for(;t-- >Pt;)n*=n,n%=e;return n}function od(r,t){if(r===Pt)throw new Error("invert: expected non-zero number");if(t<=Pt)throw new Error("invert: expected positive modulus, got "+t);let e=ct(r,t),n=t,o=Pt,s=pt,i=pt,a=Pt;for(;e!==Pt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==pt)throw new Error("invert: does not exist");return ct(o,t)}function Ac(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function fd(r,t){let e=(r.ORDER+pt)/ad,n=r.pow(t,e);return Ac(r,n,t),n}function zg(r,t){let e=(r.ORDER-cd)/ld,n=r.mul(t,dr),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,dr),o),a=r.mul(s,r.sub(i,r.ONE));return Ac(r,a,t),a}function Vg(r){let t=zt(r),e=dd(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+Kg)/ud;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(u),c),p=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,p);let g=a.eql(a.sqr(u),c),m=a.cmov(l,u,g);return Ac(a,m,c),m}}function dd(r){if(r<id)throw new Error("sqrt is not defined for small field");let t=r-pt,e=0;for(;t%dr===Pt;)t/=dr,e++;let n=dr,o=zt(r);for(;sd(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return fd;let s=o.pow(n,t),i=(t+pt)/dr;return function(c,l){if(c.is0(l))return l;if(sd(c,l)!==1)throw new Error("Cannot find square root");let u=e,f=c.mul(c.ONE,s),d=c.pow(l,t),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===u)throw new Error("Cannot find square root");let m=pt<<BigInt(u-p-1),E=c.pow(f,m);u=p,f=c.sqr(E),d=c.mul(d,f),h=c.mul(h,E)}return h}}function Hg(r){return r%ad===id?fd:r%ld===cd?zg:r%ud===qg?Vg(r):dd(r)}var Ie=(r,t)=>(ct(r,t)&pt)===pt,$g=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Cc(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=$g.reduce((n,o)=>(n[o]="function",n),t);return Xe(r,e),r}function Wg(r,t,e){if(e<Pt)throw new Error("invalid exponent, negatives unsupported");if(e===Pt)return r.ONE;if(e===pt)return t;let n=r.ONE,o=t;for(;e>Pt;)e&pt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=pt;return n}function no(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function sd(r,t){let e=(r.ORDER-pt)/dr,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function hd(r,t){t!==void 0&&Yn(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function zt(r,t,e=!1,n={}){if(r<=Pt)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||e)throw new Error("cannot specify opts in two arguments");let d=t;d.BITS&&(o=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(e=d.isLE),typeof d.modOnDecode=="boolean"&&(i=d.modOnDecode),a=d.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:l}=hd(r,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,f=Object.freeze({ORDER:r,isLE:e,BITS:c,BYTES:l,MASK:je(c),ZERO:Pt,ONE:pt,allowedLengths:a,create:d=>ct(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Pt<=d&&d<r},is0:d=>d===Pt,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&pt)===pt,neg:d=>ct(-d,r),eql:(d,h)=>d===h,sqr:d=>ct(d*d,r),add:(d,h)=>ct(d+h,r),sub:(d,h)=>ct(d-h,r),mul:(d,h)=>ct(d*h,r),pow:(d,h)=>Wg(f,d,h),div:(d,h)=>ct(d*od(h,r),r),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>od(d,r),sqrt:s||(d=>(u||(u=Hg(r)),u(f,d))),toBytes:d=>e?Ce(d,l):Es(d,l),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let g=new Uint8Array(l);g.set(d,e?0:g.length-d.length),d=g}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let p=e?Ae(d):tn(d);if(i&&(p=ct(p,r)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>no(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function pd(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Ic(r){let t=pd(r);return t+Math.ceil(t/2)}function Tc(r,t,e=!1){let n=r.length,o=pd(t),s=Ic(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Ae(r):tn(r),a=ct(i,t-pt)+pt;return e?Ce(a,o):Es(a,o)}var rn=BigInt(0),hr=BigInt(1);function oo(r,t){let e=t.negate();return r?e:t}function Te(r,t){let e=no(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function bd(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Pc(r,t){bd(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=je(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function md(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=hr);let l=t*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}function Gg(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function jg(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Dc=new WeakMap,wd=new WeakMap;function Lc(r){return wd.get(r)||1}function gd(r){if(r!==rn)throw new Error("invalid wNAF")}var nn=class{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>rn;)e&hr&&(n=n.add(o)),o=o.double(),e>>=hr;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=Pc(e,this.bits),s=[],i=t,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(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Pc(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=md(n,a,i);n=c,u?s=s.add(oo(d,e[h])):o=o.add(oo(f,e[l]))}return gd(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=Pc(t,this.bits);for(let i=0;i<s.windows&&n!==rn;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=md(n,i,s);if(n=a,!l){let f=e[c];o=o.add(u?f.negate():f)}}return gd(n),o}getPrecomputes(t,e,n){let o=Dc.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),Dc.set(e,o))),o}cached(t,e,n){let o=Lc(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=Lc(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){bd(e,this.bits),wd.set(t,e),Dc.delete(t)}hasCache(t){return Lc(t)!==1}};function xd(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>rn||n>rn;)e&hr&&(s=s.add(o)),n&hr&&(i=i.add(o)),o=o.double(),e>>=hr,n>>=hr;return{p1:s,p2:i}}function on(r,t,e,n){Gg(e,r),jg(n,t);let o=e.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=vs(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=je(c),u=new Array(Number(l)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,d=i;for(let h=f;h>=0;h-=c){u.fill(i);for(let g=0;g<s;g++){let m=n[g],E=Number(m>>BigInt(h)&l);u[E]=u[E].add(e[g])}let p=i;for(let g=u.length-1,m=i;g>0;g--)m=m.add(u[g]),p=p.add(m);if(d=d.add(p),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function yd(r,t){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Cc(t),t}else return zt(r)}function _s(r,t,e={}){if(!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let a of["p","n","h"]){let c=t[a];if(!(typeof c=="bigint"&&c>rn))throw new Error(`CURVE.${a} must be positive bigint`)}let n=yd(t.p,e.Fp),o=yd(t.n,e.Fn),i=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let a of i)if(!n.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:o}}var fe=BigInt(0),ht=BigInt(1),Rc=BigInt(2),Xg=BigInt(8);function Zg(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function Yg(r,t={}){let{Fp:e,Fn:n}=_s("edwards",r,t),{h:o,n:s}=r;Xe(t,{},{uvRatio:"function"});let i=Rc<<BigInt(n.BYTES*8)-ht,a=g=>e.create(g),c=t.uvRatio||((g,m)=>{try{return{isValid:!0,value:e.sqrt(e.div(g,m))}}catch{return{isValid:!1,value:fe}}});if(!Zg(e,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");function l(g,m,E=!1){let v=E?ht:fe;return Ge("coordinate "+g,m,v,i),m}function u(g){if(!(g instanceof h))throw new Error("ExtendedPoint expected")}let f=en((g,m)=>{let{X:E,Y:v,Z:_}=g,A=g.is0();m==null&&(m=A?Xg:e.inv(_));let O=a(E*m),C=a(v*m),F=e.mul(_,m);if(A)return{x:fe,y:ht};if(F!==ht)throw new Error("invZ was invalid");return{x:O,y:C}}),d=en(g=>{let{a:m,d:E}=r;if(g.is0())throw new Error("bad point: ZERO");let{X:v,Y:_,Z:A,T:O}=g,C=a(v*v),F=a(_*_),U=a(A*A),L=a(U*U),b=a(C*m),y=a(U*a(b+F)),S=a(L+a(E*a(C*F)));if(y!==S)throw new Error("bad point: equation left != right (1)");let I=a(v*_),k=a(A*O);if(I!==k)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(m,E,v,_){this.X=l("x",m),this.Y=l("y",E),this.Z=l("z",v,!0),this.T=l("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(m){return Te(h,m)}static msm(m,E){return on(h,n,m,E)}_setWindowSize(m){this.precompute(m)}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:E,y:v}=m||{};return l("x",E),l("y",v),new h(E,v,ht,a(E*v))}precompute(m=8,E=!0){return p.createCache(this,m),E||this.multiply(Rc),this}assertValidity(){d(this)}equals(m){u(m);let{X:E,Y:v,Z:_}=this,{X:A,Y:O,Z:C}=m,F=a(E*C),U=a(A*_),L=a(v*C),b=a(O*_);return F===U&&L===b}is0(){return this.equals(h.ZERO)}negate(){return new h(a(-this.X),this.Y,this.Z,a(-this.T))}double(){let{a:m}=r,{X:E,Y:v,Z:_}=this,A=a(E*E),O=a(v*v),C=a(Rc*a(_*_)),F=a(m*A),U=E+v,L=a(a(U*U)-A-O),b=F+O,y=b-C,S=F-O,I=a(L*y),k=a(b*S),B=a(L*S),x=a(y*b);return new h(I,k,x,B)}add(m){u(m);let{a:E,d:v}=r,{X:_,Y:A,Z:O,T:C}=this,{X:F,Y:U,Z:L,T:b}=m,y=a(_*F),S=a(A*U),I=a(C*v*b),k=a(O*L),B=a((_+A)*(F+U)-y-S),x=k-I,w=k+I,T=a(S-E*y),D=a(B*x),K=a(w*T),q=a(B*T),z=a(x*w);return new h(D,K,z,q)}subtract(m){return this.add(m.negate())}multiply(m){let E=m;Ge("scalar",E,ht,s);let{p:v,f:_}=p.cached(this,E,A=>Te(h,A));return Te(h,[v,_])[0]}multiplyUnsafe(m,E=h.ZERO){let v=m;return Ge("scalar",v,fe,s),v===fe?h.ZERO:this.is0()||v===ht?this:p.unsafe(this,v,_=>Te(h,_),E)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return p.unsafe(this,s).is0()}toAffine(m){return f(this,m)}clearCofactor(){return o===ht?this:this.multiplyUnsafe(o)}static fromBytes(m,E=!1){return at(m),h.fromHex(m,E)}static fromHex(m,E=!1){let{d:v,a:_}=r,A=e.BYTES;m=Q("pointHex",m,A),Se("zip215",E);let O=m.slice(),C=m[A-1];O[A-1]=C&-129;let F=Ae(O),U=E?i:e.ORDER;Ge("pointHex.y",F,fe,U);let L=a(F*F),b=a(L-ht),y=a(v*L-_),{isValid:S,value:I}=c(b,y);if(!S)throw new Error("Point.fromHex: invalid y coordinate");let k=(I&ht)===ht,B=(C&128)!==0;if(!E&&I===fe&&B)throw new Error("Point.fromHex: x=0 and x_0=1");return B!==k&&(I=a(-I)),h.fromAffine({x:I,y:F})}toBytes(){let{x:m,y:E}=this.toAffine(),v=Ce(E,e.BYTES);return v[v.length-1]|=m&ht?128:0,v}toRawBytes(){return this.toBytes()}toHex(){return Xt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}h.BASE=new h(r.Gx,r.Gy,ht,a(r.Gx*r.Gy)),h.ZERO=new h(fe,ht,ht,fe),h.Fp=e,h.Fn=n;let p=new nn(h,n.BYTES*8);return h}var Ss=class{constructor(t){this.ep=t}static fromBytes(t){throw new Error("fromBytes must be implemented by subclass")}static fromHex(t){throw new Error("fromHex must be implemented by subclass")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toRawBytes(){return this.toBytes()}toHex(){return Xt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}};function Qg(r,t,e){if(typeof t!="function")throw new Error('"hash" function param is required');Xe(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:s,Fn:i}=r,a=i.ORDER,c=e.randomBytes||lr,l=e.adjustScalarBytes||(y=>y),u=e.domain||((y,S,I)=>{if(Se("phflag",I),S.length||I)throw new Error("Contexts/pre-hash are not supported");return y});function f(y){return i.create(y)}function d(y){return f(Ae(y))}function h(y){let S=s.BYTES;y=Q("private key",y,S);let I=Q("hashed private key",t(y),2*S),k=l(I.slice(0,S)),B=I.slice(S,2*S),x=d(k);return{head:k,prefix:B,scalar:x}}function p(y){let{head:S,prefix:I,scalar:k}=h(y),B=o.multiply(k),x=B.toBytes();return{head:S,prefix:I,scalar:k,point:B,pointBytes:x}}function g(y){return p(y).pointBytes}function m(y=Uint8Array.of(),...S){let I=Mt(...S);return d(t(u(I,Q("context",y),!!n)))}function E(y,S,I={}){y=Q("message",y),n&&(y=n(y));let{prefix:k,scalar:B,pointBytes:x}=p(S),w=m(I.context,k,y),T=o.multiply(w).toBytes(),D=m(I.context,T,x,y),K=f(w+D*B);Ge("signature.s",K,fe,a);let q=s.BYTES,z=Mt(T,Ce(K,q));return Q("result",z,q*2)}let v={zip215:!0};function _(y,S,I,k=v){let{context:B,zip215:x}=k,w=s.BYTES;y=Q("signature",y,2*w),S=Q("message",S),I=Q("publicKey",I,w),x!==void 0&&Se("zip215",x),n&&(S=n(S));let T=Ae(y.slice(w,2*w)),D,K,q;try{D=r.fromHex(I,x),K=r.fromHex(y.slice(0,w),x),q=o.multiplyUnsafe(T)}catch{return!1}if(!x&&D.isSmallOrder())return!1;let z=m(B,K.toBytes(),D.toBytes(),S);return K.add(D.multiplyUnsafe(z)).subtract(q).clearCofactor().is0()}o.precompute(8);let A=s.BYTES,O={secret:A,public:A,signature:2*A,seed:A};function C(y=c(O.seed)){return y}let F={getExtendedPublicKey:p,randomSecretKey:C,isValidSecretKey:L,isValidPublicKey:b,randomPrivateKey:C,toMontgomery(y){let{y:S}=r.fromBytes(y),I=A===32;if(!I&&A!==57)throw new Error("only defined for 25519 and 448");let k=I?s.div(ht+S,ht-S):s.div(S-ht,S+ht);return s.toBytes(k)},toMontgomeryPriv(y){at(y,A);let S=t(y.subarray(0,A));return l(S).subarray(0,A)},precompute(y=8,S=r.BASE){return S.precompute(y,!1)}};function U(y){let S=F.randomSecretKey(y);return{secretKey:S,publicKey:g(S)}}function L(y){try{return!!i.fromBytes(y,!1)}catch{return!1}}function b(y,S){try{return!!r.fromBytes(y,S)}catch{return!1}}return Object.freeze({keygen:U,getPublicKey:g,sign:E,verify:_,utils:F,Point:r,info:{type:"edwards",lengths:O}})}function Jg(r){let t={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=zt(t.n,r.nBitLength,!0),o={Fp:e,Fn:n,uvRatio:r.uvRatio},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:t,curveOpts:o,hash:r.hash,eddsaOpts:s}}function t0(r,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:r})}function Ed(r){let{CURVE:t,curveOpts:e,hash:n,eddsaOpts:o}=Jg(r),s=Yg(t,e),i=Qg(s,n,o);return t0(r,i)}var e0=BigInt(0),Pe=BigInt(1),vd=BigInt(2),O1=BigInt(3),r0=BigInt(5),n0=BigInt(8),so={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:n0,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function o0(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=so.p,a=r*r%s*r%s,c=rt(a,vd,s)*a%s,l=rt(c,Pe,s)*r%s,u=rt(l,r0,s)*l%s,f=rt(u,t,s)*u%s,d=rt(f,e,s)*f%s,h=rt(d,n,s)*d%s,p=rt(h,o,s)*h%s,g=rt(p,o,s)*h%s,m=rt(g,t,s)*u%s;return{pow_p_5_8:rt(m,vd,s)*r%s,b2:a}}function s0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Oc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Nc(r,t){let e=so.p,n=ct(t*t*t,e),o=ct(n*n*t,e),s=o0(r*o).pow_p_5_8,i=ct(r*n*s,e),a=ct(t*i*i,e),c=i,l=ct(i*Oc,e),u=a===r,f=a===ct(-r,e),d=a===ct(-r*Oc,e);return u&&(i=c),(f||d)&&(i=l),Ie(i,e)&&(i=ct(-i,e)),{isValid:u||f,value:i}}var pr=zt(so.p,{isLE:!0}),i0=zt(so.n,{isLE:!0}),a0={...so,Fp:pr,hash:Jf,adjustScalarBytes:s0,uvRatio:Nc},vt=Ed(a0);var kc=Oc,c0=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),l0=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),u0=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),f0=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),_d=r=>Nc(Pe,r),d0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Mc=r=>vt.CURVE.Fp.create(Ae(r)&d0);function Sd(r){let{d:t}=vt.CURVE,e=vt.CURVE.Fp.ORDER,n=vt.CURVE.Fp.create,o=n(kc*r*r),s=n((o+Pe)*u0),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:l}=Nc(s,a),u=n(l*r);Ie(u,e)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-Pe)*f0-a),d=l*l,h=n((l+l)*a),p=n(f*c0),g=n(Pe-d),m=n(Pe+d);return new vt.Point(n(h*m),n(g*p),n(p*m),n(h*g))}function h0(r){at(r,64);let t=Mc(r.subarray(0,32)),e=Sd(t),n=Mc(r.subarray(32,64)),o=Sd(n);return new De(e.add(o))}var De=class r extends Ss{constructor(t){super(t)}static fromAffine(t){return new r(vt.Point.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static hashToCurve(t){return h0(Q("ristrettoHash",t,64))}static fromBytes(t){at(t,32);let{a:e,d:n}=vt.CURVE,o=pr.ORDER,s=pr.create,i=Mc(t);if(!ed(Ce(i,32),t)||Ie(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Pe+e*a),l=s(Pe-e*a),u=s(c*c),f=s(l*l),d=s(e*n*u-f),{isValid:h,value:p}=_d(s(d*f)),g=s(p*l),m=s(p*g*d),E=s((i+i)*g);Ie(E,o)&&(E=s(-E));let v=s(c*m),_=s(E*v);if(!h||Ie(_,o)||v===e0)throw new Error("invalid ristretto255 encoding 2");return new r(new vt.Point(E,v,Pe,_))}static fromHex(t){return r.fromBytes(Q("ristrettoHex",t,32))}static msm(t,e){return on(r,vt.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=pr.ORDER,i=pr.create,a=i(i(n+e)*i(n-e)),c=i(t*e),l=i(c*c),{value:u}=_d(i(a*l)),f=i(u*a),d=i(u*c),h=i(f*d*o),p;if(Ie(o*h,s)){let m=i(e*kc),E=i(t*kc);t=m,e=E,p=i(f*l0)}else p=d;Ie(t*h,s)&&(e=i(-e));let g=i((n-e)*p);return Ie(g,s)&&(g=i(-g)),Ce(g,32)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=pr.create,a=i(e*s)===i(n*o),c=i(n*s)===i(e*o);return a||c}is0(){return this.equals(r.ZERO)}};De.BASE=new De(vt.Point.BASE);De.ZERO=new De(vt.Point.ZERO);De.Fp=pr;De.Fn=i0;var io=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},ao=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},As=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Ad={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new As("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Nt=Ad;var Cs=32,co=64,Bc=32;var sn,Cd=(async()=>{try{return await Nt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Id(){let r=vt.utils.randomPrivateKey(),t=vt.getPublicKey(r);return{privateKey:b0(r,t),publicKey:t}}async function p0(r,t){let e;r.length===co?e=r.subarray(0,32):e=r;let n={crv:"Ed25519",kty:"OKP",x:N(r.subarray(32),"base64url"),d:N(e,"base64url"),ext:!0,key_ops:["sign"]},o=await Nt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Nt.get().subtle.sign({name:"Ed25519"},o,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(s,0,s.byteLength)}function m0(r,t){let e=r.subarray(0,Bc);return vt.sign(t instanceof Uint8Array?t:t.subarray(),e)}async function Td(r,t){return sn==null&&(sn=await Cd),sn?p0(r,t):m0(r,t)}async function g0(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Nt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Nt.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function y0(r,t,e){return vt.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Pd(r,t,e){return sn==null&&(sn=await Cd),sn?g0(r,t,e):y0(r,t,e)}function b0(r,t){let e=new Uint8Array(co);for(let n=0;n<Bc;n++)e[n]=r[n],e[Bc+n]=t[n];return e}function an(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var lo=class{type="Ed25519";raw;constructor(t){this.raw=Ts(t,Cs)}toMultihash(){return ee.digest(jt(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:X(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Pd(this.raw,e,t);return an(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},Is=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=Ts(t,co),this.publicKey=new lo(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:X(this.raw,t.raw)}sign(t,e){e?.signal?.throwIfAborted();let n=Td(this.raw,t);return an(n)?n.then(o=>(e?.signal?.throwIfAborted(),o)):(e?.signal?.throwIfAborted(),n)}};function Fc(r){return r=Ts(r,Cs),new lo(r)}async function Ld(){let{privateKey:r,publicKey:t}=Id();return new Is(r,t)}function Ts(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new R(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var w0=Math.pow(2,7),x0=Math.pow(2,14),E0=Math.pow(2,21),Uc=Math.pow(2,28),Kc=Math.pow(2,35),qc=Math.pow(2,42),zc=Math.pow(2,49),G=128,_t=127;function mt(r){if(r<w0)return 1;if(r<x0)return 2;if(r<E0)return 3;if(r<Uc)return 4;if(r<Kc)return 5;if(r<qc)return 6;if(r<zc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function cn(r,t,e=0){switch(mt(r)){case 8:t[e++]=r&255|G,r/=128;case 7:t[e++]=r&255|G,r/=128;case 6:t[e++]=r&255|G,r/=128;case 5:t[e++]=r&255|G,r/=128;case 4:t[e++]=r&255|G,r>>>=7;case 3:t[e++]=r&255|G,r>>>=7;case 2:t[e++]=r&255|G,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function v0(r,t,e=0){switch(mt(r)){case 8:t.set(e++,r&255|G),r/=128;case 7:t.set(e++,r&255|G),r/=128;case 6:t.set(e++,r&255|G),r/=128;case 5:t.set(e++,r&255|G),r/=128;case 4:t.set(e++,r&255|G),r>>>=7;case 3:t.set(e++,r&255|G),r>>>=7;case 2:t.set(e++,r&255|G),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Vc(r,t){let e=r[t],n=0;if(n+=e&_t,e<G||(e=r[t+1],n+=(e&_t)<<7,e<G)||(e=r[t+2],n+=(e&_t)<<14,e<G)||(e=r[t+3],n+=(e&_t)<<21,e<G)||(e=r[t+4],n+=(e&_t)*Uc,e<G)||(e=r[t+5],n+=(e&_t)*Kc,e<G)||(e=r[t+6],n+=(e&_t)*qc,e<G)||(e=r[t+7],n+=(e&_t)*zc,e<G))return n;throw new RangeError("Could not decode varint")}function _0(r,t){let e=r.get(t),n=0;if(n+=e&_t,e<G||(e=r.get(t+1),n+=(e&_t)<<7,e<G)||(e=r.get(t+2),n+=(e&_t)<<14,e<G)||(e=r.get(t+3),n+=(e&_t)<<21,e<G)||(e=r.get(t+4),n+=(e&_t)*Uc,e<G)||(e=r.get(t+5),n+=(e&_t)*Kc,e<G)||(e=r.get(t+6),n+=(e&_t)*qc,e<G)||(e=r.get(t+7),n+=(e&_t)*zc,e<G))return n;throw new RangeError("Could not decode varint")}function de(r,t,e=0){return t==null&&(t=Et(mt(r))),t instanceof Uint8Array?cn(r,t,e):v0(r,t,e)}function mr(r,t=0){return r instanceof Uint8Array?Vc(r,t):_0(r,t)}var Hc=new Float32Array([-0]),Ze=new Uint8Array(Hc.buffer);function Rd(r,t,e){Hc[0]=r,t[e]=Ze[0],t[e+1]=Ze[1],t[e+2]=Ze[2],t[e+3]=Ze[3]}function Od(r,t){return Ze[0]=r[t],Ze[1]=r[t+1],Ze[2]=r[t+2],Ze[3]=r[t+3],Hc[0]}var $c=new Float64Array([-0]),St=new Uint8Array($c.buffer);function kd(r,t,e){$c[0]=r,t[e]=St[0],t[e+1]=St[1],t[e+2]=St[2],t[e+3]=St[3],t[e+4]=St[4],t[e+5]=St[5],t[e+6]=St[6],t[e+7]=St[7]}function Md(r,t){return St[0]=r[t],St[1]=r[t+1],St[2]=r[t+2],St[3]=r[t+3],St[4]=r[t+4],St[5]=r[t+5],St[6]=r[t+6],St[7]=r[t+7],$c[0]}var S0=BigInt(Number.MAX_SAFE_INTEGER),A0=BigInt(Number.MIN_SAFE_INTEGER),Vt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return gr;if(t<S0&&t>A0)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Nd&&(o=0n,++n>Nd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return gr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):gr}},gr=new Vt(0,0);gr.toBigInt=function(){return 0n};gr.zzEncode=gr.zzDecode=function(){return this};gr.length=function(){return 1};var Nd=4294967296n;function Bd(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Fd(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Wc(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function se(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Ps(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Gc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,se(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw se(this,4);return Ps(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw se(this,4);return Ps(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw se(this,4);let t=Od(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw se(this,4);let t=Md(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw se(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Fd(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw se(this,t);this.pos+=t}else do if(this.pos>=this.len)throw se(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Vt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw se(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw se(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw se(this,8);let t=Ps(this.buf,this.pos+=4),e=Ps(this.buf,this.pos+=4);return new Vt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Vc(this.buf,this.pos);return this.pos+=mt(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function jc(r){return new Gc(r instanceof Uint8Array?r:r.subarray())}function Dt(r,t,e){let n=jc(r);return t.decode(n,void 0,e)}function Xc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return Et(i);o+i>t&&(n=Et(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var yr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Zc(){}var Qc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},C0=Xc();function I0(r){return globalThis.Buffer!=null?Et(r):C0(r)}var fo=class{len;head;tail;states;constructor(){this.len=0,this.head=new yr(Zc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new yr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Jc((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Ds,10,Vt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Vt.fromBigInt(t);return this._push(Ds,e.length(),e)}uint64Number(t){return this._push(cn,mt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Vt.fromBigInt(t).zzEncode();return this._push(Ds,e.length(),e)}sint64Number(t){let e=Vt.fromNumber(t).zzEncode();return this._push(Ds,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Yc,1,t?1:0)}fixed32(t){return this._push(uo,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Vt.fromBigInt(t);return this._push(uo,4,e.lo)._push(uo,4,e.hi)}fixed64Number(t){let e=Vt.fromNumber(t);return this._push(uo,4,e.lo)._push(uo,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Rd,4,t)}double(t){return this._push(kd,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Yc,1,0):this.uint32(e)._push(P0,e,t)}string(t){let e=Bd(t);return e!==0?this.uint32(e)._push(Wc,e,t):this._push(Yc,1,0)}fork(){return this.states=new Qc(this),this.head=this.tail=new yr(Zc,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 yr(Zc,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=I0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Yc(r,t,e){t[e]=r&255}function T0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Jc=class extends yr{next;constructor(t,e){super(T0,t,e),this.next=void 0}};function Ds(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function uo(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function P0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(fo.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(D0,t,r),this},fo.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(L0,t,r),this});function D0(r,t,e){t.set(r,e)}function L0(r,t,e){r.length<40?Wc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(P(r),e)}function tl(){return new fo}function Lt(r,t){let e=tl();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var un;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(un||(un={}));function Ls(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function el(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Ls("enum",un.VARINT,e,n)}function Rt(r,t){return Ls("message",un.LENGTH_DELIMITED,r,t)}var br=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},ho=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ut;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ut||(ut={}));var rl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(rl||(rl={}));(function(r){r.codec=()=>el(rl)})(ut||(ut={}));var he;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ut.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Lt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(he||(he={}));var nl;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ut.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Lt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(nl||(nl={}));function fn(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return lr(r)}var mo={};kt(mo,{MAX_RSA_KEY_SIZE:()=>ol,generateRSAKeyPair:()=>hl,jwkToJWKKeyPair:()=>Hd,jwkToPkcs1:()=>M0,jwkToPkix:()=>cl,jwkToRSAPrivateKey:()=>dl,pkcs1MessageToJwk:()=>il,pkcs1MessageToRSAPrivateKey:()=>ll,pkcs1ToJwk:()=>k0,pkcs1ToRSAPrivateKey:()=>Vd,pkixMessageToJwk:()=>al,pkixMessageToRSAPublicKey:()=>fl,pkixToJwk:()=>N0,pkixToRSAPublicKey:()=>ul});var Rs=xs;var dn=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=mo.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ot.createV1(114,this._multihash)}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:X(this.raw,t.raw)}verify(t,e,n){return zd(this.jwk,e,t,n)}},po=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=mo.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:X(this.raw,t.raw)}sign(t,e){return qd(this.jwk,t,e)}};var ol=8192,sl=18,R0=1062,O0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function k0(r){let t=xe(r);return il(t)}function il(r){return{n:N(r[1],"base64url"),e:N(r[2],"base64url"),d:N(r[3],"base64url"),p:N(r[4],"base64url"),q:N(r[5],"base64url"),dp:N(r[6],"base64url"),dq:N(r[7],"base64url"),qi:N(r[8],"base64url"),kty:"RSA"}}function M0(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 ne([Tt(Uint8Array.from([0])),Tt(P(r.n,"base64url")),Tt(P(r.e,"base64url")),Tt(P(r.d,"base64url")),Tt(P(r.p,"base64url")),Tt(P(r.q,"base64url")),Tt(P(r.dp,"base64url")),Tt(P(r.dq,"base64url")),Tt(P(r.qi,"base64url"))]).subarray()}function N0(r){let t=xe(r,{offset:0});return al(t)}function al(r){let t=xe(r[1],{offset:0});return{kty:"RSA",n:N(t[0],"base64url"),e:N(t[1],"base64url")}}function cl(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return ne([O0,Zn(ne([Tt(P(r.n,"base64url")),Tt(P(r.e,"base64url"))]))]).subarray()}function Vd(r){let t=xe(r);return ll(t)}function ll(r){let t=il(r);return dl(t)}function ul(r,t){if(r.byteLength>=R0)throw new Vr("Key size is too large");let e=xe(r,{offset:0});return fl(e,r,t)}function fl(r,t,e){let n=al(r);if(e==null){let o=Rs(he.encode({Type:ut.RSA,Data:t}));e=te(sl,o)}return new dn(n,e)}function dl(r){if(Wd(r)>ol)throw new R("Key size is too large");let t=Hd(r),e=Rs(he.encode({Type:ut.RSA,Data:cl(t.publicKey)})),n=te(sl,e);return new po(t.privateKey,new dn(t.publicKey,n))}async function hl(r){if(r>ol)throw new R("Key size is too large");let t=await $d(r),e=Rs(he.encode({Type:ut.RSA,Data:cl(t.publicKey)})),n=te(sl,e);return new po(t.privateKey,new dn(t.publicKey,n))}function Hd(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 $d(r,t){let e=await Nt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await B0(e,t);return{privateKey:n[0],publicKey:n[1]}}async function qd(r,t,e){let n=await Nt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await Nt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function zd(r,t,e,n){let o=await Nt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Nt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),s}async function B0(r,t){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");let e=await Promise.all([Nt.get().subtle.exportKey("jwk",r.privateKey),Nt.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function Wd(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return P(r.n,"base64url").length*8}var Os=class extends Qr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,gs(t);let n=Qn(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),ve(s)}update(t){return Jr(this),this.iHash.update(t),this}digestInto(t){Jr(this),at(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},pl=(r,t,e)=>new Os(r,t).update(e).digest();pl.create=(r,t)=>new Os(r,t);var Gd=(r,t)=>(r+(r>=0?t:-t)/Xd)/t;function F0(r,t,e){let[[n,o],[s,i]]=t,a=Gd(i*r,e),c=Gd(-o*r,e),l=r-a*n-c*s,u=-a*o-c*i,f=l<Re,d=u<Re;f&&(l=-l),d&&(u=-u);let h=je(Math.ceil(vs(e)/2))+pn;if(l<Re||l>=h||u<Re||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}function jd(r){r.lowS!==void 0&&Se("lowS",r.lowS),r.prehash!==void 0&&Se("prehash",r.prehash)}var ml=class extends Error{constructor(t=""){super(t)}},Le={Err:ml,_tlv:{encode:(r,t)=>{let{Err:e}=Le;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=ro(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?ro(o.length/2|128):"";return ro(r)+s+o+t},decode(r,t){let{Err:e}=Le,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Le;if(r<Re)throw new t("integer: negative integers are not allowed");let e=ro(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=Le;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return tn(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Le,o=Q("signature",r),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Le,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Re=BigInt(0),pn=BigInt(1),Xd=BigInt(2),ks=BigInt(3),U0=BigInt(4);function K0(r,t,e){function n(o){let s=r.sqr(o),i=r.mul(s,o);return r.add(r.add(i,r.mul(o,t)),e)}return n}function hn(r,t){let{BYTES:e}=r,n;if(typeof t=="bigint")n=t;else{let o=Q("private key",t);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${e}, got ${typeof t}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function q0(r,t={}){let{Fp:e,Fn:n}=_s("weierstrass",r,t),{h:o,n:s}=r;Xe(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:i}=t;if(i&&(!e.is0(r.a)||typeof i.beta!="bigint"||!Array.isArray(i.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');function a(){if(!e.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(L,b,y){let{x:S,y:I}=b.toAffine(),k=e.toBytes(S);if(Se("isCompressed",y),y){a();let B=!e.isOdd(I);return Mt(Zd(B),k)}else return Mt(Uint8Array.of(4),k,e.toBytes(I))}function l(L){at(L);let b=e.BYTES,y=b+1,S=2*b+1,I=L.length,k=L[0],B=L.subarray(1);if(I===y&&(k===2||k===3)){let x=e.fromBytes(B);if(!e.isValid(x))throw new Error("bad point: is not on curve, wrong x");let w=d(x),T;try{T=e.sqrt(w)}catch(q){let z=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}a();let D=e.isOdd(T);return(k&1)===1!==D&&(T=e.neg(T)),{x,y:T}}else if(I===S&&k===4){let x=e.fromBytes(B.subarray(b*0,b*1)),w=e.fromBytes(B.subarray(b*1,b*2));if(!h(x,w))throw new Error("bad point: is not on curve");return{x,y:w}}else throw new Error(`bad point: got length ${I}, expected compressed=${y} or uncompressed=${S}`)}let u=t.toBytes||c,f=t.fromBytes||l,d=K0(e,r.a,r.b);function h(L,b){let y=e.sqr(b),S=d(L);return e.eql(y,S)}if(!h(r.Gx,r.Gy))throw new Error("bad curve params: generator point");let p=e.mul(e.pow(r.a,ks),U0),g=e.mul(e.sqr(r.b),BigInt(27));if(e.is0(e.add(p,g)))throw new Error("bad curve params: a or b");function m(L,b,y=!1){if(!e.isValid(b)||y&&e.is0(b))throw new Error(`bad point coordinate ${L}`);return b}function E(L){if(!(L instanceof C))throw new Error("ProjectivePoint expected")}function v(L){if(!i||!i.basises)throw new Error("no endo");return F0(L,i.basises,n.ORDER)}let _=en((L,b)=>{let{X:y,Y:S,Z:I}=L;if(e.eql(I,e.ONE))return{x:y,y:S};let k=L.is0();b==null&&(b=k?e.ONE:e.inv(I));let B=e.mul(y,b),x=e.mul(S,b),w=e.mul(I,b);if(k)return{x:e.ZERO,y:e.ZERO};if(!e.eql(w,e.ONE))throw new Error("invZ was invalid");return{x:B,y:x}}),A=en(L=>{if(L.is0()){if(t.allowInfinityPoint&&!e.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:b,y}=L.toAffine();if(!e.isValid(b)||!e.isValid(y))throw new Error("bad point: x or y not field elements");if(!h(b,y))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function O(L,b,y,S,I){return y=new C(e.mul(y.X,L),y.Y,y.Z),b=oo(S,b),y=oo(I,y),b.add(y)}class C{constructor(b,y,S){this.X=m("x",b),this.Y=m("y",y,!0),this.Z=m("z",S),Object.freeze(this)}static fromAffine(b){let{x:y,y:S}=b||{};if(!b||!e.isValid(y)||!e.isValid(S))throw new Error("invalid affine point");if(b instanceof C)throw new Error("projective point not allowed");return e.is0(y)&&e.is0(S)?C.ZERO:new C(y,S,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}static normalizeZ(b){return Te(C,b)}static fromBytes(b){return at(b),C.fromHex(b)}static fromHex(b){let y=C.fromAffine(f(Q("pointHex",b)));return y.assertValidity(),y}static fromPrivateKey(b){return C.BASE.multiply(hn(n,b))}static msm(b,y){return on(C,n,b,y)}_setWindowSize(b){this.precompute(b)}precompute(b=8,y=!0){return U.createCache(this,b),y||this.multiply(ks),this}assertValidity(){A(this)}hasEvenY(){let{y:b}=this.toAffine();if(!e.isOdd)throw new Error("Field doesn't support isOdd");return!e.isOdd(b)}equals(b){E(b);let{X:y,Y:S,Z:I}=this,{X:k,Y:B,Z:x}=b,w=e.eql(e.mul(y,x),e.mul(k,I)),T=e.eql(e.mul(S,x),e.mul(B,I));return w&&T}negate(){return new C(this.X,e.neg(this.Y),this.Z)}double(){let{a:b,b:y}=r,S=e.mul(y,ks),{X:I,Y:k,Z:B}=this,x=e.ZERO,w=e.ZERO,T=e.ZERO,D=e.mul(I,I),K=e.mul(k,k),q=e.mul(B,B),z=e.mul(I,k);return z=e.add(z,z),T=e.mul(I,B),T=e.add(T,T),x=e.mul(b,T),w=e.mul(S,q),w=e.add(x,w),x=e.sub(K,w),w=e.add(K,w),w=e.mul(x,w),x=e.mul(z,x),T=e.mul(S,T),q=e.mul(b,q),z=e.sub(D,q),z=e.mul(b,z),z=e.add(z,T),T=e.add(D,D),D=e.add(T,D),D=e.add(D,q),D=e.mul(D,z),w=e.add(w,D),q=e.mul(k,B),q=e.add(q,q),D=e.mul(q,z),x=e.sub(x,D),T=e.mul(q,K),T=e.add(T,T),T=e.add(T,T),new C(x,w,T)}add(b){E(b);let{X:y,Y:S,Z:I}=this,{X:k,Y:B,Z:x}=b,w=e.ZERO,T=e.ZERO,D=e.ZERO,K=r.a,q=e.mul(r.b,ks),z=e.mul(y,k),tt=e.mul(S,B),J=e.mul(I,x),Ut=e.add(y,S),Z=e.add(k,B);Ut=e.mul(Ut,Z),Z=e.add(z,tt),Ut=e.sub(Ut,Z),Z=e.add(y,I);let dt=e.add(k,x);return Z=e.mul(Z,dt),dt=e.add(z,J),Z=e.sub(Z,dt),dt=e.add(S,I),w=e.add(B,x),dt=e.mul(dt,w),w=e.add(tt,J),dt=e.sub(dt,w),D=e.mul(K,Z),w=e.mul(q,J),D=e.add(w,D),w=e.sub(tt,D),D=e.add(tt,D),T=e.mul(w,D),tt=e.add(z,z),tt=e.add(tt,z),J=e.mul(K,J),Z=e.mul(q,Z),tt=e.add(tt,J),J=e.sub(z,J),J=e.mul(K,J),Z=e.add(Z,J),z=e.mul(tt,Z),T=e.add(T,z),z=e.mul(dt,Z),w=e.mul(Ut,w),w=e.sub(w,z),z=e.mul(Ut,tt),D=e.mul(dt,D),D=e.add(D,z),new C(w,T,D)}subtract(b){return this.add(b.negate())}is0(){return this.equals(C.ZERO)}multiply(b){let{endo:y}=t;if(!n.isValidNot0(b))throw new Error("invalid scalar: out of range");let S,I,k=B=>U.cached(this,B,x=>Te(C,x));if(y){let{k1neg:B,k1:x,k2neg:w,k2:T}=v(b),{p:D,f:K}=k(x),{p:q,f:z}=k(T);I=K.add(z),S=O(y.beta,D,q,B,w)}else{let{p:B,f:x}=k(b);S=B,I=x}return Te(C,[S,I])[0]}multiplyUnsafe(b){let{endo:y}=t,S=this;if(!n.isValid(b))throw new Error("invalid scalar: out of range");if(b===Re||S.is0())return C.ZERO;if(b===pn)return S;if(U.hasCache(this))return this.multiply(b);if(y){let{k1neg:I,k1:k,k2neg:B,k2:x}=v(b),{p1:w,p2:T}=xd(C,S,k,x);return O(y.beta,w,T,I,B)}else return U.unsafe(S,b)}multiplyAndAddUnsafe(b,y,S){let I=this.multiplyUnsafe(y).add(b.multiplyUnsafe(S));return I.is0()?void 0:I}toAffine(b){return _(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return o===pn?!0:b?b(C,this):U.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:b}=t;return o===pn?this:b?b(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(b=!0){return Se("isCompressed",b),this.assertValidity(),u(C,this,b)}toRawBytes(b=!0){return this.toBytes(b)}toHex(b=!0){return Xt(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}C.BASE=new C(r.Gx,r.Gy,e.ONE),C.ZERO=new C(e.ZERO,e.ONE,e.ZERO),C.Fp=e,C.Fn=n;let F=n.BITS,U=new nn(C,t.endo?Math.ceil(F/2):F);return C}function Zd(r){return Uint8Array.of(r?2:3)}function z0(r,t,e={}){gs(t),Xe(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=e.randomBytes||lr,o=e.hmac||((x,...w)=>pl(t,x,Mt(...w))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,l=Ic(a),u={secret:i.BYTES,public:1+s.BYTES,publicUncompressed:1+2*s.BYTES,signature:2*i.BYTES,seed:l};function f(x){let w=a>>pn;return x>w}function d(x){return f(x)?i.neg(x):x}function h(x,w){if(!i.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..CURVE.n`)}class p{constructor(w,T,D){h("r",w),h("s",T),this.r=w,this.s=T,D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(w,T="compact"){if(T==="compact"){let D=i.BYTES;at(w,D*2);let K=w.subarray(0,D),q=w.subarray(D,D*2);return new p(i.fromBytes(K),i.fromBytes(q))}if(T==="der"){at(w);let{r:D,s:K}=Le.toSig(w);return new p(D,K)}throw new Error("invalid format")}static fromHex(w,T){return this.fromBytes(cr(w),T)}addRecoveryBit(w){return new p(this.r,this.s,w)}recoverPublicKey(w){let T=s.ORDER,{r:D,s:K,recovery:q}=this;if(q==null||![0,1,2,3].includes(q))throw new Error("recovery id invalid");if(a*Xd<T&&q>1)throw new Error("recovery id is ambiguous for h>1 curve");let tt=q===2||q===3?D+a:D;if(!s.isValid(tt))throw new Error("recovery id 2 or 3 invalid");let J=s.toBytes(tt),Ut=r.fromHex(Mt(Zd((q&1)===0),J)),Z=i.inv(tt),dt=F(Q("msgHash",w)),Kt=i.create(-dt*Z),Fe=i.create(K*Z),er=r.BASE.multiplyUnsafe(Kt).add(Ut.multiplyUnsafe(Fe));if(er.is0())throw new Error("point at infinify");return er.assertValidity(),er}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,i.neg(this.s),this.recovery):this}toBytes(w="compact"){if(w==="compact")return Mt(i.toBytes(this.r),i.toBytes(this.s));if(w==="der")return cr(Le.hexFromSig(this));throw new Error("invalid format")}toHex(w){return Xt(this.toBytes(w))}assertValidity(){}static fromCompact(w){return p.fromBytes(Q("sig",w),"compact")}static fromDER(w){return p.fromBytes(Q("sig",w),"der")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Xt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Xt(this.toBytes("compact"))}}function g(x){try{return!!hn(i,x)}catch{return!1}}function m(x,w){try{let T=x.length;return w===!0&&T!==u.public||w===!1&&T!==u.publicUncompressed?!1:!!r.fromBytes(x)}catch{return!1}}function E(x=n(l)){return Tc(x,a)}let v={isValidSecretKey:g,isValidPublicKey:m,randomSecretKey:E,isValidPrivateKey:g,randomPrivateKey:E,normPrivateKeyToScalar:x=>hn(i,x),precompute(x=8,w=r.BASE){return w.precompute(x,!1)}};function _(x,w=!0){return r.BASE.multiply(hn(i,x)).toBytes(w)}function A(x){if(typeof x=="bigint")return!1;if(x instanceof r)return!0;if(i.allowedLengths||u.secret===u.public)return;let w=Q("key",x).length;return w===u.public||w===u.publicUncompressed}function O(x,w,T=!0){if(A(x)===!0)throw new Error("first arg must be private key");if(A(w)===!1)throw new Error("second arg must be public key");let D=hn(i,x);return r.fromHex(w).multiply(D).toBytes(T)}let C=e.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let w=tn(x),T=x.length*8-c;return T>0?w>>BigInt(T):w},F=e.bits2int_modN||function(x){return i.create(C(x))},U=je(c);function L(x){return Ge("num < 2^"+c,x,Re,U),i.toBytes(x)}function b(x,w,T=y){if(["recovered","canonical"].some(Kt=>Kt in T))throw new Error("sign() legacy options not supported");let{lowS:D,prehash:K,extraEntropy:q}=T;D==null&&(D=!0),x=Q("msgHash",x),jd(T),K&&(x=Q("prehashed msgHash",t(x)));let z=F(x),tt=hn(i,w),J=[L(tt),L(z)];if(q!=null&&q!==!1){let Kt=q===!0?n(u.secret):q;J.push(Q("extraEntropy",Kt))}let Ut=Mt(...J),Z=z;function dt(Kt){let Fe=C(Kt);if(!i.isValidNot0(Fe))return;let er=i.inv(Fe),Bn=r.BASE.multiply(Fe).toAffine(),rr=i.create(Bn.x);if(rr===Re)return;let Fn=i.create(er*i.create(Z+rr*tt));if(Fn===Re)return;let tf=(Bn.x===rr?0:2)|Number(Bn.y&pn),ef=Fn;return D&&f(Fn)&&(ef=d(Fn),tf^=1),new p(rr,ef,tf)}return{seed:Ut,k2sig:dt}}let y={lowS:e.lowS,prehash:!1},S={lowS:e.lowS,prehash:!1};function I(x,w,T=y){let{seed:D,k2sig:K}=b(x,w,T);return nd(t.outputLen,i.BYTES,o)(D,K)}r.BASE.precompute(8);function k(x,w,T,D=S){let K=x;w=Q("msgHash",w),T=Q("publicKey",T),jd(D);let{lowS:q,prehash:z,format:tt}=D;if("strict"in D)throw new Error("options.strict was renamed to lowS");let J,Ut;if(tt===void 0){let Z=typeof K=="string"||ar(K),dt=!Z&&K!==null&&typeof K=="object"&&typeof K.r=="bigint"&&typeof K.s=="bigint";if(!Z&&!dt)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(dt)J=new p(K.r,K.s);else if(Z){try{J=p.fromDER(K)}catch(Kt){if(!(Kt instanceof Le.Err))throw Kt}if(!J)try{J=p.fromCompact(K)}catch{return!1}}}else if(tt==="compact"||tt==="der"){if(typeof K!="string"&&!ar(K))throw new Error('"der" / "compact" format expects Uint8Array signature');J=p.fromBytes(Q("sig",K),tt)}else if(tt==="js"){if(!(K instanceof p))throw new Error('"js" format expects Signature instance');J=K}else throw new Error('format must be "compact", "der" or "js"');if(!J)return!1;try{if(Ut=r.fromHex(T),q&&J.hasHighS())return!1;z&&(w=t(w));let{r:Z,s:dt}=J,Kt=F(w),Fe=i.inv(dt),er=i.create(Kt*Fe),Bn=i.create(Z*Fe),rr=r.BASE.multiplyUnsafe(er).add(Ut.multiplyUnsafe(Bn));return rr.is0()?!1:i.create(rr.x)===Z}catch{return!1}}function B(x){let w=v.randomSecretKey(x);return{secretKey:w,publicKey:_(w)}}return Object.freeze({keygen:B,getPublicKey:_,sign:I,verify:k,getSharedSecret:O,utils:v,Point:r,Signature:p,info:{type:"weierstrass",lengths:u,publicKeyHasPrefix:!0}})}function V0(r){let t={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=zt(t.n,{BITS:r.nBitLength,allowedLengths:n,modOnDecode:r.wrapPrivateKey}),s={Fp:e,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:t,curveOpts:s}}function H0(r){let{CURVE:t,curveOpts:e}=V0(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:t,curveOpts:e,hash:r.hash,ecdsaOpts:n}}function $0(r,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:r})}function Yd(r){let{CURVE:t,curveOpts:e,hash:n,ecdsaOpts:o}=H0(r),s=q0(t,e),i=z0(s,n,o);return $0(r,i)}function Qd(r,t){let e=n=>Yd({...r,hash:n});return{...e(t),create:e}}var yl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},W0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Jd=BigInt(2);function G0(r){let t=yl.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=rt(u,e,t)*u%t,d=rt(f,e,t)*u%t,h=rt(d,Jd,t)*l%t,p=rt(h,o,t)*h%t,g=rt(p,s,t)*p%t,m=rt(g,a,t)*g%t,E=rt(m,c,t)*m%t,v=rt(E,a,t)*g%t,_=rt(v,e,t)*u%t,A=rt(_,i,t)*p%t,O=rt(A,n,t)*l%t,C=rt(O,Jd,t);if(!gl.eql(gl.sqr(C),r))throw new Error("Cannot find square root");return C}var gl=zt(yl.p,void 0,void 0,{sqrt:G0}),ie=Qd({...yl,Fp:gl,lowS:!0,endo:W0},xs);function th(r,t,e){let n=Yr.digest(t instanceof Uint8Array?t:t.subarray());if(an(n))return n.then(({digest:o})=>(e?.signal?.throwIfAborted(),ie.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new io(String(o))});try{return ie.sign(n.digest,r).toDERRawBytes()}catch(o){throw new io(String(o))}}function eh(r,t,e,n){let o=Yr.digest(e instanceof Uint8Array?e:e.subarray());if(an(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),ie.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new ao(String(s))});try{return n?.signal?.throwIfAborted(),ie.verify(t,o.digest,r)}catch(s){throw new ao(String(s))}}var go=class{type="secp256k1";raw;_key;constructor(t){this._key=oh(t),this.raw=rh(this._key)}toMultihash(){return ee.digest(jt(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:X(this.raw,t.raw)}verify(t,e,n){return eh(this._key,e,t,n)}},Ms=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=nh(t),this.publicKey=new go(e??sh(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:X(this.raw,t.raw)}sign(t,e){return th(this.raw,t,e)}};function bl(r){return new go(r)}async function ih(){let r=j0();return new Ms(r)}function rh(r){return ie.ProjectivePoint.fromHex(r).toRawBytes(!0)}function nh(r){try{return ie.getPublicKey(r,!0),r}catch(t){throw new Un(String(t))}}function oh(r){try{return ie.ProjectivePoint.fromHex(r),r}catch(t){throw new Vr(String(t))}}function sh(r){try{return ie.getPublicKey(r,!0)}catch(t){throw new Un(String(t))}}function j0(){return ie.utils.randomPrivateKey()}async function ah(r,t){if(r==="Ed25519")return Ld();if(r==="secp256k1")return ih();if(r==="RSA")return hl(X0(t));if(r==="ECDSA")return Ff(Z0(t));throw new qe}function mn(r,t){let{Type:e,Data:n}=he.decode(r),o=n??new Uint8Array;switch(e){case ut.RSA:return ul(o,t);case ut.Ed25519:return Fc(o);case ut.secp256k1:return bl(o);case ut.ECDSA:return gc(o);default:throw new qe}}function ch(r){let{Type:t,Data:e}=he.decode(r.digest),n=e??new Uint8Array;switch(t){case ut.Ed25519:return Fc(n);case ut.secp256k1:return bl(n);case ut.ECDSA:return gc(n);default:throw new qe}}function jt(r){return he.encode({Type:ut[r.type],Data:r.raw})}function X0(r){return r==null?2048:parseInt(r,10)}function Z0(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 lh=Symbol.for("nodejs.util.inspect.custom"),Y0=114,yo=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[rs]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ot.createV1(Y0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return X(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return X(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[lh](){return`PeerId(${this.toString()})`}},bo=class extends yo{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},wo=class extends yo{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},xo=class extends yo{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Q0=2336,Eo=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=ee.digest(P(this.url))}[lh](){return`PeerId(${this.url})`}[rs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ot.createV1(Q0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=N(t)),t.toString()===this.toString())}};var J0=114,uh=2336;function pe(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=we(Y.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return vo(ot.parse(r));if(t==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=we(t.decode(r))}return gn(e)}function wl(r){if(r.type==="Ed25519")return new wo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new xo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new bo({multihash:r.toCID().multihash,publicKey:r});throw new qe}function fh(r){return wl(r.publicKey)}function gn(r){if(ey(r))return new bo({multihash:r});if(ty(r))try{let t=ch(r);if(t.type==="Ed25519")return new wo({multihash:r,publicKey:t});if(t.type==="secp256k1")return new xo({multihash:r,publicKey:t})}catch{let e=N(r.digest);return new Eo(new URL(e))}throw new ss("Supplied PeerID Multihash is invalid")}function vo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==J0&&r.code!==uh)throw new os("Supplied PeerID CID is invalid");if(r.code===uh){let t=N(r.multihash.digest);return new Eo(new URL(t))}return gn(r.multihash)}function ty(r){return r.code===ee.code}function ey(r){return r.code===Yr.code}function yn(r){if(typeof r!="object"||r===null)return!1;let t=Object.getPrototypeOf(r);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:hh}=Object.prototype,{propertyIsEnumerable:ry}=Object,bn=(r,t,e)=>{Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0})},ny=void 0,dh={concatArrays:!1,ignoreUndefined:!1},Ns=r=>{let t=[];for(let e in r)hh.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)ry.call(r,n)&&t.push(n)}return t};function wn(r){return Array.isArray(r)?oy(r):yn(r)?sy(r):r}function oy(r){let t=r.slice(0,0);return Ns(r).forEach(e=>{bn(t,e,wn(r[e]))}),t}function sy(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return Ns(r).forEach(e=>{bn(t,e,wn(r[e]))}),t}var ph=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?bn(r,o,xl(r[o],t[o],n)):bn(r,o,wn(t[o])))}),r),iy=(r,t,e)=>{let n=r.slice(0,0),o=0;return[r,t].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)hh.call(s,a)&&(i.push(String(a)),s===r?bn(n,o++,s[a]):bn(n,o++,wn(s[a])));n=ph(n,s,Ns(s).filter(a=>!i.includes(a)),e)}),n};function xl(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?iy(r,t,e):!yn(t)||!yn(r)?wn(t):ph(r,t,Ns(t),e)}function Bs(...r){let t=xl(wn(dh),this!==ny&&this||{},dh),e={_:{}};for(let n of r)if(n!==void 0){if(!yn(n))throw new TypeError("`"+n+"` is not an Option Object");e=xl(e,{_:n},t)}return e._}var ft=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var vl=es(gh(),1);var So=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},_l=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},yh=r=>globalThis.DOMException===void 0?new _l(r):new DOMException(r),bh=r=>{let t=r.reason===void 0?yh("This operation was aborted."):r.reason;return t instanceof Error?t:yh(t)};function Sl(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,l=new Promise((u,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:h}=t;h.aborted&&f(bh(h)),a=()=>{f(bh(h))},h.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new So;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}function Al(r,t,e){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;e(r[i],t)<=0?(n=++i,o-=s+1):o=s}return n}var Ao=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,id:e.id,run:t};if(this.size===0||this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=Al(this.#t,n,(s,i)=>i.priority-s.priority);this.#t.splice(o,0,n)}setPriority(t,e){let n=this.#t.findIndex(s=>s.id===t);if(n===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[o]=this.#t.splice(n,1);this.enqueue(o.run,{priority:e,id:t})}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var Co=class extends vl.default{#t;#n;#e=0;#h;#a;#p=0;#o;#c;#r;#m;#s=0;#l;#i;#g;#w=1n;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ao,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#n=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#h=t.intervalCap,this.#a=t.interval,this.#r=new t.queueClass,this.#m=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#g=t.throwOnTimeout===!0,this.#i=t.autoStart===!1}get#x(){return this.#n||this.#e<this.#h}get#E(){return this.#s<this.#l}#v(){this.#s--,this.#u(),this.emit("next")}#_(){this.#b(),this.#y(),this.#c=void 0}get#S(){let t=Date.now();if(this.#o===void 0){let e=this.#p-t;if(e<0)this.#e=this.#t?this.#s:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#_()},e)),!0}return!1}#u(){if(this.#r.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let t=!this.#S;if(this.#x&&this.#E){let e=this.#r.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#n||this.#o!==void 0||(this.#o=setInterval(()=>{this.#b()},this.#a),this.#p=Date.now()+this.#a)}#b(){this.#e===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#e=this.#t?this.#s:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#l=t,this.#f()}async#A(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}setPriority(t,e){this.#r.setPriority(t,e)}async add(t,e={}){return e.id??=(this.#w++).toString(),e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#s++,this.#e++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=Sl(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#A(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof So&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},e),this.emit("add"),this.#u()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(t){this.#r.size<t||await this.#d("next",()=>this.#r.size<t)}async onIdle(){this.#s===0&&this.#r.size===0||await this.#d("idle")}async#d(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#r.size}sizeBy(t){return this.#r.filter(t).length}get pending(){return this.#s}get isPaused(){return this.#i}};function Us(r){let t=[Ht.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Cl=60;function Ks(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(t=>({name:t.name,type:Ht[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Ht[t.type],TTL:t.TTL??t.ttl??Cl,data:t.data instanceof Uint8Array?N(t.data):t.data}))}}var ly=4;function Il(r,t={}){let e=new Co({concurrency:t.queryConcurrency??ly});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Us(o.types).forEach(a=>{s.append("type",Ht[a])}),o.onProgress?.(new ft("dns:query",{detail:n}));let i=await e.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Ks(await a.json());return o.onProgress?.(new ft("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function wh(){return[Il("https://cloudflare-dns.com/dns-query"),Il("https://dns.google/resolve")]}var vh=es(Eh(),1);var Tl=class{lru;constructor(t){this.lru=(0,vh.default)(t)}get(t,e){let n=!0,o=[];for(let s of e){let i=this.getAnswers(t,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return Ks({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Ht[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Cl)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function _h(r){return new Tl(r)}var uy=1e3,qs=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=_h(t.cacheSize??uy),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=wh())}async query(t,e={}){let n=Us(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new ft("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let l=await c(t,{...e,types:n});for(let u of l.Answer)this.cache.add(t,u);return l}catch(l){a.push(l),e.onProgress?.(new ft("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Ht;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Ht||(Ht={}));function Sh(r={}){return new qs(r)}var bt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Oe=class extends Error{static name="ValidationError";name="ValidationError"},Io=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},zs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Vs=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ah=45,fy=15,xn=new Vs;function Hs(r){if(!(r.length>fy))return xn.new(r).parseWith(()=>xn.readIPv4Addr())}function $s(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ah))return xn.new(r).parseWith(()=>xn.readIPv6Addr())}function En(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Ah)return;let e=xn.new(r).parseWith(()=>xn.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function ae(r){return!!Hs(r)}function Ws(r){return!!$s(r)}function Dl(r){return t=>N(t,r)}function Ll(r){return t=>P(t,r)}function vn(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function wr(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Ch(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=P(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=wr(n);return re([e,o],e.length+o.length)}function Ih(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Gt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=wr(n);return re([e,o],e.length+o.length)}function Rl(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=N(t,"base32"),o=vn(e);return`${n}:${o}`}var Ol=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new bt("Invalid byte value in IP address");t[n]=o}),t},Th=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=ae(e[n]),i;s&&(i=Ol(e[n]),e[n]=N(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,N(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new bt("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Ph=function(r){if(r.byteLength!==4)throw new bt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Dh=function(r){if(r.byteLength!==16)throw new bt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new bt(`Invalid IPv6 address "${e}"`)}};function Lh(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new bt(`Invalid IPv6 address "${r}"`)}}var Pl=Object.values(Gn).map(r=>r.decoder),dy=function(){let r=Pl[0].or(Pl[1]);return Pl.slice(2).forEach(t=>r=r.or(t)),r}();function Rh(r){return dy.decode(r)}function Oh(r){return t=>r.encoder.encode(t)}function hy(r){if(parseInt(r).toString()!==r)throw new Oe("Value must be an integer")}function py(r){if(r<0)throw new Oe("Value must be a positive integer, or zero")}function my(r){return t=>{if(t>r)throw new Oe(`Value must be smaller than or equal to ${r}`)}}function gy(...r){return t=>{for(let e of r)e(t)}}var To=gy(hy,py,my(65535));var gt=-1,kl=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new zs(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Bt=new kl,Ly=[{code:4,name:"ip4",size:32,valueToBytes:Ol,bytesToValue:Ph,validate:r=>{if(!ae(r))throw new Oe(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:wr,bytesToValue:vn,validate:To},{code:273,name:"udp",size:16,valueToBytes:wr,bytesToValue:vn,validate:To},{code:33,name:"dccp",size:16,valueToBytes:wr,bytesToValue:vn,validate:To},{code:41,name:"ip6",size:128,valueToBytes:Th,bytesToValue:Dh,stringToValue:Lh,validate:r=>{if(!Ws(r))throw new Oe(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:gt},{code:43,name:"ipcidr",size:8,bytesToValue:Dl("base10"),valueToBytes:Ll("base10")},{code:53,name:"dns",size:gt,resolvable:!0},{code:54,name:"dns4",size:gt,resolvable:!0},{code:55,name:"dns6",size:gt,resolvable:!0},{code:56,name:"dnsaddr",size:gt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:wr,bytesToValue:vn,validate:To},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:gt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:gt,bytesToValue:Dl("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Ll("base58btc")(r):ot.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Rl,valueToBytes:Ch},{code:445,name:"onion3",size:296,bytesToValue:Rl,valueToBytes:Ih},{code:446,name:"garlic64",size:gt},{code:447,name:"garlic32",size:gt},{code:448,name:"tls"},{code:449,name:"sni",size:gt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:gt,bytesToValue:Oh(oc),valueToBytes:Rh},{code:480,name:"http"},{code:481,name:"http-path",size:gt,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:gt}];Ly.forEach(r=>{Bt.addProtocol(r)});function kh(r){let t=[],e=0;for(;e<r.length;){let n=mr(r,e),o=Bt.getProtocol(n),s=mt(n),i=Ry(o,r,e+s),a=0;i>0&&o.size===gt&&(a=mt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??N(f)}t.push(l),e+=c}return t}function Mh(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Bt.getProtocol(n.code),s=mt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??P(n.value),a=i.byteLength,o.size===gt&&(c=mt(a)));let l=new Uint8Array(s+c+a),u=0;cn(n.code,l,u),u+=s,i!=null&&(o.size===gt&&(cn(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return re(e,t)}function Nh(r){if(r.charAt(0)!=="/")throw new bt('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Bt.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new bt(`Component ${o} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new bt(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new bt("Incomplete multiaddr");return t}function Bh(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Bt.getProtocol(t.code);if(e==null)throw new bt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function Ry(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:mr(t,e)}var Oy=Symbol.for("nodejs.util.inspect.custom"),Hl=Symbol.for("@multiformats/multiaddr"),ky=[53,54,55,56],Vl=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function My(r){if(r==null&&(r="/"),Qe(r))return r.getComponents();if(r instanceof Uint8Array)return kh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Nh(r);if(Array.isArray(r))return r;throw new bt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Zs=class r{[Hl]=!0;#t;#n;#e;constructor(t="/",e={}){this.#t=My(t),e.validate!==!1&&Ny(this)}get bytes(){return this.#e==null&&(this.#e=Mh(this.#t)),this.#e}toString(){return this.#n==null&&(this.#n=Bh(this.#t)),this.#n}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="";for(let{code:a,name:c,value:l}of this.#t)a===42&&(s=`%${l??""}`),ky.includes(a)&&(e="tcp",o=443,n=`${l??""}${s}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",o=parseInt(l??"")),(a===4||a===41)&&(e="tcp",n=`${l??""}${s}`,t=a===41?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=Bt.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=Bt.getProtocol(t),o=[t];return e!=null&&o.push(n.valueToBytes?.(e)??P(e)),o})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Io(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:o})=>{n===421&&t.push([n,o]),n===290&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?N(Y.decode(`z${n}`),"base58btc"):N(ot.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(Bt.getProtocol(t.code).path)return t.value??null;return null}equals(t){return X(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Fh.get(e.name);if(n==null)throw new Vl(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>V(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[Oy](){return`Multiaddr(${this.toString()})`}};function Ny(r){r.getComponents().forEach(t=>{let e=Bt.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function Uh(r,t,e){let n=0;for(let o of r)if(!(n<t)){if(n>e)break;if(o!==255)return!1;n++}return!0}function Kh(r,t,e,n){let o=0;for(let s of r)if(!(o<e)){if(o>n)break;if(s!==t[o])return!1;o++}return!0}function $l(r){switch(r.length){case Sr:return r.join(".");case Ar:{let t=[];for(let e=0;e<r.length;e++)e%2===0&&t.push(r[e].toString(16).padStart(2,"0")+r[e+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}function qh(r){let t=0;for(let[e,n]of r.entries()){if(n===255){t+=8;continue}for(;(n&128)!=0;)t++,n=n<<1;if((n&128)!=0)return-1;for(let o=e+1;o<r.length;o++)if(r[o]!=0)return-1;break}return t}function zh(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var Sr=4,Ar=16,zS=parseInt("0xFFFF",16),By=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Do(r,t){t.length===Ar&&r.length===Sr&&Uh(t,0,11)&&(t=t.slice(12)),t.length===Sr&&r.length===Ar&&Kh(r,By,0,11)&&(r=r.slice(12));let e=r.length;if(e!=t.length)throw new Error("Failed to mask ip");let n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=r[o]&t[o];return n}function Vh(r,t){if(typeof t=="string"&&(t=En(t)),t==null)throw new Error("Invalid ip");if(t.length!==r.network.length)return!1;for(let e=0;e<t.length;e++)if((r.network[e]&r.mask[e])!==(t[e]&r.mask[e]))return!1;return!0}function Wl(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=Sr,o=Hs(t);if(o==null&&(n=Ar,o=$s(t),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(e,10);if(Number.isNaN(s)||String(s).length!==e.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Gl(s,8*n);return{network:Do(o,i),mask:i}}function Gl(r,t){if(t!==8*Sr&&t!==8*Ar)throw new Error("Invalid CIDR mask");if(r<0||r>t)throw new Error("Invalid CIDR mask");let e=t/8,n=new Uint8Array(e);for(let o=0;o<e;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var In=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=Wl(t));else{let n=En(t);if(n==null)throw new Error("Failed to parse network");e=String(e);let o=parseInt(e,10);if(Number.isNaN(o)||String(o).length!==e.length||o<0||o>n.length*8){let s=En(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Gl(o,8*n.length);this.network=Do(n,this.mask)}}contains(t){return Vh({network:this.network,mask:this.mask},t)}toString(){let t=qh(this.mask),e=t!==-1?String(t):zh(this.mask);return $l(this.network)+"/"+e}};function jl(r){let t,e;if(r.getComponents().forEach(n=>{(n.name==="ip4"||n.name==="ip6")&&(e=n.value),n.name==="ipcidr"&&(t=n.value)}),t==null||e==null)throw new Error("Invalid multiaddr");return new In(e,t)}var Fh=new Map;function Qe(r){return!!r?.[Hl]}function V(r){return new Zs(r)}function Ys(r){let t=Bt.getProtocol(r);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}var Xl=class{dns;canResolve(t){return t.getComponents().some(({name:e})=>e==="dnsaddr")}async resolve(t,e){let n=t.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[t];let s=await this.getDNS(e).query(`_dnsaddr.${n}`,{signal:e?.signal,types:[Ht.TXT]}),i=t.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(V(l)))}return a}getDNS(t){return t.dns!=null?t.dns:(this.dns==null&&(this.dns=Sh()),this.dns)}},ke=new Xl;var Fy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:ke}},transportManager:{faultTolerance:nr.FATAL_ALL}};async function Hh(r){let t=Bs(Fy,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new R("Private network is enforced, but no protector was provided");return t}function Uy(r,t){try{if(typeof r=="string"&&r.length>0)return Ky(r);if(typeof r=="number"&&isFinite(r))return t?.long?zy(r):qy(r);throw new Error("Value is not a string or number.")}catch(e){let n=Vy(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function Ky(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Js=Uy;function qy(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function zy(r){let t=Math.abs(r);return t>=864e5?Qs(r,t,864e5,"day"):t>=36e5?Qs(r,t,36e5,"hour"):t>=6e4?Qs(r,t,6e4,"minute"):t>=1e3?Qs(r,t,1e3,"second"):`${r} ms`}function Qs(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function Vy(r){return typeof r=="object"&&r!==null&&"message"in r}function Zl(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=Js,e.destroy=l,Object.keys(r).forEach(u=>{e[u]=r[u]}),e.names=[],e.skips=[],e.formatters={};function t(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(u){let f,d=null,h,p;function g(...m){if(!g.enabled)return;let E=g,v=Number(new Date),_=v-(f||v);E.diff=_,E.prev=f,E.curr=v,f=v,m[0]=e.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let A=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(C,F)=>{if(C==="%%")return"%";A++;let U=e.formatters[F];if(typeof U=="function"){let L=m[A];C=U.call(E,L),m.splice(A,1),A--}return C}),e.formatArgs.call(E,m),(E.log||e.log).apply(E,m)}return g.namespace=u,g.useColors=e.useColors(),g.color=e.selectColor(u),g.extend=n,g.destroy=e.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,p=e.enabled(u)),p),set:m=>{d=m}}),typeof e.init=="function"&&e.init(g),g}function n(u,f){let d=e(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){e.save(u),e.namespaces=u,e.names=[],e.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]==="-"?e.skips.push(new RegExp("^"+u.substr(1)+"$")):e.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(u))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.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 e.setupFormatters(e.formatters),e.enable(e.load()),e}var ti=Zy(),Hy=["#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 $y(){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 Wy(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Js(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var Gy=console.debug??console.log??(()=>{});function jy(r){try{r?ti?.setItem("debug",r):ti?.removeItem("debug")}catch{}}function Xy(){let r;try{r=ti?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Zy(){try{return localStorage}catch{}}function Yy(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var $h=Zl({formatArgs:Wy,save:jy,load:Xy,useColors:$y,setupFormatters:Yy,colors:Hy,storage:ti,log:Gy});var Ft=$h;Ft.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);Ft.formatters.t=r=>r==null?"undefined":Gt.baseEncode(r);Ft.formatters.m=r=>r==null?"undefined":nc.baseEncode(r);Ft.formatters.p=r=>r==null?"undefined":r.toString();Ft.formatters.c=r=>r==null?"undefined":r.toString();Ft.formatters.k=r=>r==null?"undefined":r.toString();Ft.formatters.a=r=>r==null?"undefined":r.toString();Ft.formatters.e=r=>r==null?"undefined":Wh(r.stack)??Wh(r.message)??r.toString();function Qy(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function ei(){return{forComponent(r){return Gh(r)}}}function Gh(r){let t=Qy(`${r}:trace`);return Ft.enabled(`${r}:trace`)&&Ft.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=Ft(`${r}:trace`)),Object.assign(Ft(r),{error:Ft(`${r}:error`),trace:t,newScope:e=>Gh(`${r}:${e}`)})}function Wh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Cr(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function ri(r){let t=we(Y.decode(`z${r}`));return gn(t)}var Yt=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Cr(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Cr(this.map.values(),t=>t.key)}values(){return Cr(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ir=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return Cr(this.set.entries(),t=>{let e=ri(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=ri(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return Cr(this.set.values(),t=>ri(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var Yl={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},jh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Xh=new globalThis.TextEncoder;function Jy(r,t){let e=Yl[t],n=jh[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function tb(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Yl[t],o=jh[t],s=r;for(;s.length>0;){let i=Xh.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Ql(r,{size:t=32,utf8Buffer:e}={}){if(!Yl[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return tb(r,t,e);r=Xh.encode(r)}return Jy(r,t)}var Lo={hash:r=>Number(Ql(r,{size:32})),hashV:(r,t)=>eb(Lo.hash(r,t))};function eb(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),P(t,"base16")}var Jl=64,le=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Jl)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=it(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?X(this.fp,t.fp):!1}};function Tr(r,t){return Math.floor(Math.random()*(t-r))+r}var Pr=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");let e=Tr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof le))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var rb=500,Ro=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Lo,this.seed=t.seed??Tr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=P(t));let e=new le(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Pr(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Pr(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Tr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Pr(this.bucketSize));for(let a=0;a<rb;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Pr(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=P(t));let e=new le(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=P(t));let e=new le(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},nb={1:.5,2:.84,4:.95,8:.98};function ob(r=.001){return r>.002?2:r>1e-5?4:8}function Zh(r,t=.001){let e=ob(t),n=nb[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Jl);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var ni=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Lo,this.seed=t.seed??Tr(0,Math.pow(2,10)),this.filterSeries=[new Ro({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=P(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new Ro({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=P(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Oo(r,t=.001,e){return new ni({...Zh(r,t),...e??{}})}var tu=class extends Yt{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function eu(r){let{name:t,metrics:e}=r,n;return e!=null?n=new tu({name:t,metrics:e}):n=new Yt,n}var ko;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:it(0),payloadType:it(0),payload:it(0),signature:it(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Lt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(ko||(ko={}));var oi=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var Tn=class r{static createFromProtobuf=t=>{let e=ko.decode(t),n=mn(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e,n)=>{if(e==null)throw new Error("Missing private key");let o=t.domain,s=t.codec,i=t.marshal(),a=Yh(o,s,i),c=await e.sign(a.subarray(),n);return new r({publicKey:e.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(t,e,n)=>{let o=r.createFromProtobuf(t);if(!await o.validate(e,n))throw new oi("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=ko.encode({publicKey:jt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:X(this.marshal(),t.marshal())}async validate(t,e){let n=Yh(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},Yh=(r,t,e)=>{let n=P(r),o=de(n.byteLength),s=de(t.length),i=de(e.length);return new $(o,n,s,t,i,e)};function Qh(r,t){let e=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==t.length?!1:(t.sort(e),r.sort(e).every((n,o)=>t[o].equals(n)))}var Jh="libp2p-peer-record",tp=Uint8Array.from([3,1]);var Mo;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=Rt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:it(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}default:{s.skipType(u&7);break}}}return c})),o),n.encode=s=>Lt(s,n.codec()),n.decode=(s,i)=>Dt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=Rt((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:it(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new br('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),e),r.encode=n=>Lt(n,r.codec()),r.decode=(n,o)=>Dt(n,r.codec(),o)})(Mo||(Mo={}));var Dr=class r{static createFromProtobuf=t=>{let e=Mo.decode(t),n=gn(we(e.peerId)),o=(e.addresses??[]).map(i=>V(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Jh;static CODEC=tp;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(t){let{peerId:e,multiaddrs:n,seqNumber:o}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Mo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof r)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!Qh(this.multiaddrs,t.multiaddrs))}};function sb(r){return r[Symbol.asyncIterator]!=null}function ib(r){if(sb(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var No=ib;var Wt=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};function lt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var si=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Pn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new si(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new si(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var ru=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function ii(r={}){return ab(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function ab(r,t){t=t??{};let e=t.onEnd,n=new Pn,o,s,i,a=lt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,E)=>{s=v=>{s=null,n.push(v);try{m(r(n))}catch(_){E(_)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=lt()})}},l=m=>s!=null?s(m):(n.push(m),o),u=m=>(n=new Pn,s!=null?s({error:m}):(n.push({error:m}),o)),f=m=>{if(i)return o;if(t?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?u(m):l({done:!0})),h=()=>(n=new Pn,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 E=m?.signal;if(E?.throwIfAborted(),n.isEmpty())return;let v,_;E!=null&&(v=new Promise((A,O)=>{_=()=>{O(new ru)},E.addEventListener("abort",_)}));try{await Promise.race([a.promise,v])}finally{_!=null&&E!=null&&E?.removeEventListener("abort",_)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(m){return g.throw(m),e!=null&&(e(m),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(m){return g.end(m),e!=null&&(e(m),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:m=>g.onEmpty(m)},o}async function ge(r,t,e,n){let o=new Wt(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){ou(e,"abort",f),ou(r,t,l),ou(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)};nu(e,"abort",f),nu(r,t,l),nu(r,s,u)})}function nu(r,t,e){r!=null&&(ep(r)?r.addEventListener(t,e):r.addListener(t,e))}function ou(r,t,e){r!=null&&(ep(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function ep(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var ai=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ci=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function wt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new ci(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new ci(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var li=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Wt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function cb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ui=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=cb(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Wt),this.cleanup())}async join(t={}){let e=new li(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await wt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};function su(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Bo=class extends qt{concurrency;maxSize;queue;pending;sort;autoStart;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=t.autoStart??!0,this.sort=t.sort,this.queue=[],this.emitEmpty=su(this.emitEmpty.bind(this),1),this.emitIdle=su(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ai;let n=new ui(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Wt)}),this.clear()}async onEmpty(t){this.size!==0&&await ge(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await ge(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ge(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=ii({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Wt("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var fi="lock:worker:request-read",di="lock:worker:abort-read-request",hi="lock:worker:release-read",pi="lock:master:grant-read",mi="lock:master:error-read",gi="lock:worker:request-write",yi="lock:worker:abort-write-request",bi="lock:worker:release-write",wi="lock:master:grant-write",xi="lock:master:error-write",Ei="lock:worker:finalize",vi="mortice",rp={singleProcess:!1};var iu=(r,t,e,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(e,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{t.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&&(t.removeEventListener("message",d),f())};t.addEventListener("message",d)})},onError:f=>{t.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===Ei&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var np=(r=10)=>Math.random().toString().substring(2,r+2);var _i=class{name;channel;constructor(t){this.name=t,this.channel=new BroadcastChannel(vi)}readLock(t){return this.sendRequest(fi,di,pi,mi,hi,t)}writeLock(t){return this.sendRequest(gi,yi,wi,xi,bi,t)}finalize(){this.channel.postMessage({type:Ei,name:this.name}),this.channel.close()}async sendRequest(t,e,n,o,s,i){i?.signal?.throwIfAborted();let a=np();return this.channel.postMessage({type:t,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:e,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 op=r=>{if(r=Object.assign({},rp,r),!!globalThis.document||r.singleProcess){let e=new BroadcastChannel(vi),n=new qt;return e.addEventListener("message",iu(n,e,"requestReadLock","abortReadLockRequest",fi,di,mi,hi,pi)),e.addEventListener("message",iu(n,e,"requestWriteLock","abortWriteLockRequest",gi,yi,xi,bi,wi)),n}return new _i(r.name)};var Lr=new Map,Fo;function sp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function lb(r){if(Fo==null&&(Fo=op(r),!sp(Fo))){let t=Fo;t.addEventListener("requestReadLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=Lr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};t.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await e.detail.handler().finally(()=>{c()})}).catch(c=>{e.detail.onError(c)}).finally(()=>{t.removeEventListener("abortReadLockRequest",a)})}),t.addEventListener("requestWriteLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=Lr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};t.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await e.detail.handler().finally(()=>{c()})}).catch(c=>{e.detail.onError(c)}).finally(()=>{t.removeEventListener("abortWriteLockRequest",a)})}),t.addEventListener("finalizeRequest",e=>{let n=e.detail.name,o=Lr.get(n);o?.finalize()})}return Fo}async function au(r,t){let e,n,o=new Promise((i,a)=>{e=i,n=a}),s=()=>{n(new Wt)};return t?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{e(()=>{t?.signal?.removeEventListener("abort",s),i()})})},{signal:t?.signal}).catch(i=>{n(i)}),o}var ip=(r,t)=>{let e=Lr.get(r);if(e!=null)return e;let n=lb(t);if(sp(n))return e=n,Lr.set(r,e),e;let o=new Bo({concurrency:1}),s;return e={async readLock(i){if(s!=null)return au(s,i);s=new Bo({concurrency:t.concurrency,autoStart:!1});let a=s,c=au(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,au(o,i)},finalize:()=>{Lr.delete(r)},queue:o},Lr.set(r,e),t.autoFinalize===!0&&o.addEventListener("idle",()=>{e.finalize()},{once:!0}),e};var ub={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function cu(r){let t=Object.assign({},ub,r);return ip(t.name,t)}var Me;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=Rt((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:it(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Lt(i,o.codec()),o.decode=(i,a)=>Dt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=Rt((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Ai.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Ai.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Lt(i,o.codec()),o.decode=(i,a)=>Dt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Rt((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Si.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new br('Decode error - map field "addresses" had too many elements');a.addresses.push(Si.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new br('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new ho('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new ho('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Lt(o,r.codec()),r.decode=(o,s)=>Dt(o,r.codec(),s)})(Me||(Me={}));var Si;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),e.observed!=null&&(n.uint32(24),n.uint64Number(e.observed)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:it(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}case 3:{s.observed=e.uint64Number();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Lt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Si||(Si={}));var Ai;(function(r){let t;r.codec=()=>(t==null&&(t=Rt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Lt(e,r.codec()),r.decode=(e,n)=>Dt(e,r.codec(),n)})(Ai||(Ai={}));function fb(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;r.type==="RSA"&&(e=r.toMultihash());let n=mn(t.publicKey,e);return wl(n)}function ap(r,t,e){let n=Me.decode(t);return Dn(r,n,e)}function Dn(r,t,e){let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:fb(r,t),addresses:t.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-e).map(({multiaddr:s,isCertified:i})=>({multiaddr:V(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function cp(r,t){return db(r.addresses,t.addresses)&&hb(r.protocols,t.protocols)&&pb(r.publicKey,t.publicKey)&&mb(r.peerRecordEnvelope,t.peerRecordEnvelope)&&gb(r.metadata,t.metadata)&&yb(r.tags,t.tags)}function db(r,t){return up(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!X(e.multiaddr,n.multiaddr)))}function hb(r,t){return up(r,t,(e,n)=>e===n)}function pb(r,t){return lp(r,t)}function mb(r,t){return lp(r,t)}function gb(r,t){return fp(r,t,(e,n)=>X(e,n))}function yb(r,t){return fp(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function lp(r,t){return r==null&&t==null?!0:r!=null&&t!=null?X(r,t):!1}function up(r,t,e){if(r.length!==t.length)return!1;for(let n=0;n<r.length;n++)if(!e(r[n],t[n]))return!1;return!0}function fp(r,t,e){if(r.size!==t.size)return!1;for(let[n,o]of r.entries()){let s=t.get(n);if(s==null||!e(o,s))return!1}return!0}var Ne="/",dp=new TextEncoder().encode(Ne),Ci=dp[0],Rr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=P(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Ci)throw new Error("Invalid key")}toString(t="utf8"){return N(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Ne))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=dp),this._buf[0]!==Ci){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Ci,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ci;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Ne).slice(1)}type(){return bb(this.baseNamespace())}name(){return wb(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Ne)||(t+=Ne),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Ne):new r(t.slice(0,-1).join(Ne))}child(t){return this.toString()===Ne?t:t.toString()===Ne?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...xb(t.map(e=>e.namespaces()))])}};function bb(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function wb(r){let t=r.split(":");return t[t.length-1]}function xb(r){return[].concat(...r)}var lu="/peers/";function Uo(r){if(!Ue(r)||r.type==null)throw new R("Invalid PeerId");let t=r.toCID().toString();return new Rr(`${lu}${t}`)}async function hp(r,t,e,n,o){let s=new Map;for(let i of e){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=V(i.multiaddr)),!Qe(i.multiaddr))throw new R("Multiaddr was invalid");if(!await t(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.getPeerId();return r.equals(c)&&(a=a.decapsulate(V(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Ti(r,t,e,n){if(t==null)throw new R("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.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(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Ii(d,{validate:pp})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Ii(d,{validate:mp,map:gp})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Ii([...a.entries()],{validate:pp})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),h=new Map(c);for(let[p,g]of d)g==null?h.delete(p):h.set(p,g);c=Ii([...h.entries()],{validate:mp,map:gp})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=jt(o.id.publicKey):t.publicKey!=null?u=jt(t.publicKey):r.publicKey!=null&&(u=jt(r.publicKey));let f={addresses:await hp(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 Ii(r,t){let e=new Map;for(let[n,o]of r)o!=null&&t.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&e.set(n,t.map?.(n,o)??o);return e}function pp(r,t){if(typeof r!="string")throw new R("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new R("Metadata value must be a Uint8Array")}function mp(r,t){if(typeof r!="string")throw new R("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new R("Tag value must be an integer");if(t.value<0||t.value>100)throw new R("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new R("Tag ttl must be an integer");if(t.ttl<0)throw new R("Tag ttl must be between greater than 0")}}function gp(r,t){let e;t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl)));let n={value:t.value??0};return e!=null&&(n.expiry=e),n}function yp(r){let t=r.toString().split("/")[2],e=ot.parse(t,Gt);return vo(e)}function uu(r,t,e){let n=yp(r);return ap(n,t,e)}function Eb(r,t){return{prefix:lu,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(uu(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(uu(n.key,n.value,t),uu(o.key,o.value,t)))}}var Pi=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.locks=eu({name:"libp2p_peer_store_locks",metrics:t.metrics}),this.maxAddressAge=e.maxAddressAge??36e5,this.maxPeerAge=e.maxPeerAge??216e5}getLock(t){let e=this.locks.get(t);return e==null&&(e={refs:0,lock:cu({name:t.toString(),singleProcess:!0})},this.locks.set(t,e)),e.refs++,e}maybeRemoveLock(t,e){e.refs--,e.refs===0&&(e.lock.finalize(),this.locks.delete(t))}async getReadLock(t,e){let n=this.getLock(t);try{let o=await n.lock.readLock(e);return()=>{o(),this.maybeRemoveLock(t,n)}}catch(o){throw this.maybeRemoveLock(t,n),o}}async getWriteLock(t,e){let n=this.getLock(t);try{let o=await n.lock.writeLock(e);return()=>{o(),this.maybeRemoveLock(t,n)}}catch(o){throw this.maybeRemoveLock(t,n),o}}async has(t,e){try{return await this.load(t,e),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(t,e){this.peerId.equals(t)||await this.datastore.delete(Uo(t),e)}async load(t,e){let n=Uo(t),o=await this.datastore.get(n,e),s=Me.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new or;return Dn(t,s,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e,n){let o=await this.#t(t,n),s=await Ti(t,e,"patch",{...n,addressFilter:this.addressFilter});return this.#n(t,s,o)}async patch(t,e,n){let o=await this.#t(t,n),s=await Ti(t,e,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#n(t,s,o)}async merge(t,e,n){let o=await this.#t(t,n),s=await Ti(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#n(t,s,o)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(Eb(t??{},this.maxAddressAge),t)){let o=yp(e);if(o.equals(this.peerId))continue;let s=Me.decode(n);if(this.#e(o,s)){await this.datastore.delete(e,t);continue}yield Dn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t,e){try{let n=Uo(t),o=await this.datastore.get(n,e),s=Me.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new or;return{peerPB:s,peer:Dn(t,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#n(t,e,n,o){e.updated=Date.now();let s=Me.encode(e);return await this.datastore.put(Uo(t),s,o),{peer:Dn(t,e,this.maxAddressAge),previous:n?.peer,updated:n==null||!cp(e,n.peerPB)}}#e(t,e){if(e.updated==null)return!0;if(this.peerId.equals(t))return!1;let n=e.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=e.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var fu=class{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Pi(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){for await(let n of this.store.all(e))t(n)}async all(t){return No(this.store.all(t))}async delete(t,e){let n=await this.store.getReadLock(t,e);try{await this.store.delete(t,e)}finally{n()}}async has(t,e){let n=await this.store.getReadLock(t,e);try{return await this.store.has(t,e)}finally{this.log.trace("has release read lock"),n?.()}}async get(t,e){let n=await this.store.getReadLock(t,e);try{return await this.store.load(t,e)}finally{n?.()}}async getInfo(t,e){let n=await this.get(t,e);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.save(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async patch(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.patch(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async merge(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.merge(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async consumePeerRecord(t,e,n){let o=Ue(e)?e:Ue(e?.expectedPeer)?e.expectedPeer:void 0,s=Ue(e)||e===void 0?n:e,i=await Tn.openAndCertify(t,Dr.DOMAIN,s),a=vo(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=Dr.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=Tn.createFromProtobuf(l.peerRecordEnvelope),f=Dr.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:t,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#t(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}};function bp(r,t={}){return new fu(r,t)}var Di=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};function vb(r){return r[Symbol.asyncIterator]!=null}function _b(r){if(vb(r))return(async()=>{for await(let t of r);})();for(let t of r);}var du=_b;function Sb(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var wp=Sb;function Ab(r){return r[Symbol.asyncIterator]!=null}function Cb(r,t){let e=0;if(Ab(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=wp(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=t(o,e++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){i===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var Or=Cb;function Ib(r){return r[Symbol.asyncIterator]!=null}function Tb(r,t){return Ib(r)?async function*(){yield*(await No(r)).sort(t)}():function*(){yield*No(r).sort(t)}()}var hu=Tb;function Pb(r){return r[Symbol.asyncIterator]!=null}function Db(r,t){return Pb(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var pu=Db;var Li=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await du(this.putMany(t,n)),t=[],await du(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=Or(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Or(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>hu(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=Or(n,()=>o++>=s)}return t.limit!=null&&(n=pu(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=Or(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Or(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>hu(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=Or(n,()=>s++>=o)}return t.limit!=null&&(n=pu(n,t.limit)),n}};var Ri=class extends Li{data;constructor(){super(),this.data=new Map}put(t,e,n){return n?.signal?.throwIfAborted(),this.data.set(t.toString(),e),t}get(t,e){e?.signal?.throwIfAborted();let n=this.data.get(t.toString());if(n==null)throw new Di;return n}has(t,e){return e?.signal?.throwIfAborted(),this.data.has(t.toString())}delete(t,e){e?.signal?.throwIfAborted(),this.data.delete(t.toString())}*_all(t,e){e?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new Rr(n),value:o},e?.signal?.throwIfAborted()}*_allKeys(t,e){e?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Rr(n),e?.signal?.throwIfAborted()}};function Ko(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Ep=es(xp(),1),Lb=["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"],Rb=Lb.map(r=>new Ep.Netmask(r));function mu(r){for(let t of Rb)if(t.contains(r))return!0;return!1}function Ob(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function kb(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return mu(o)}function Mb(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Nb(r){let t=r.split(":"),e=t[t.length-1];return mu(e)}function Bb(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 Je(r){if(ae(r))return mu(r);if(Ob(r))return kb(r);if(Mb(r))return Nb(r);if(Ws(r))return Bb(r)}var nt=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),M=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),H=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),Ct=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),j=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function et(...r){function t(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 e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var Fb=M(421),vp=et(Fb),ki=M(54),Mi=M(55),Ni=M(56),yu=M(53),lT=et(ki,H(M(421))),uT=et(Mi,H(M(421))),fT=et(Ni,H(M(421))),dT=et(Ct(yu,Ni,ki,Mi),H(M(421))),_p=j(M(4),H(M(43))),Sp=j(H(M(42)),M(41),H(M(43))),bu=Ct(_p,Sp),kr=Ct(bu,yu,ki,Mi,Ni),hT=et(Ct(bu,j(Ct(yu,Ni,ki,Mi),H(M(421))))),wu=et(_p),xu=et(Sp),pT=et(bu),Eu=j(kr,M(6)),zo=j(kr,M(273)),Vo=et(j(Eu,H(M(421)))),mT=et(zo),vu=j(zo,nt(460),H(M(421))),Bi=j(zo,nt(461),H(M(421))),Ub=Ct(vu,Bi),gT=et(vu),Ap=et(Bi),gu=Ct(kr,Eu,zo,vu,Bi),Cp=Ct(j(gu,nt(477),H(M(421)))),Mr=et(Cp),Ip=Ct(j(gu,nt(478),H(M(421))),j(gu,nt(448),H(M(449)),nt(477),H(M(421)))),Ho=et(Ip),Tp=j(zo,nt(280),H(M(466)),H(M(466)),H(M(421))),_u=et(Tp),Pp=j(Bi,nt(465),H(M(466)),H(M(466)),H(M(421))),Su=et(Pp),Oi=Ct(Cp,Ip,j(Eu,H(M(421))),j(Ub,H(M(421))),j(kr,H(M(421))),Tp,Pp,M(421)),yT=et(Oi),Kb=j(Oi,nt(290),M(421)),$o=et(Kb),qb=Ct(j(Oi,nt(290),nt(281),H(M(421))),j(Oi,nt(281),H(M(421))),j(nt(281),H(M(421)))),Au=et(qb),zb=Ct(j(kr,M(6),nt(480),H(M(421))),j(kr,nt(480),H(M(421)))),bT=et(zb),Vb=j(kr,Ct(j(M(6,"443"),nt(480)),j(M(6),nt(443)),j(M(6),nt(448),nt(480)),j(nt(448),nt(480)),nt(448),nt(443)),H(M(421))),wT=et(Vb),Hb=Ct(j(M(777),H(M(421)))),xT=et(Hb),$b=Ct(j(M(400),H(M(421)))),ET=et($b);var Cu=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function It(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Cu({name:t,metrics:e}):n=new Map,n}var Dp=864e13;var Wb=448,Iu=449,Gb=53,jb=54,Xb=55,Zb=56,Fi=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=It({name:"libp2p_address_manager_dns_mappings",metrics:t.metrics})}has(t){let e=this.findHost(t);for(let n of this.mappings.values())if(n.domain===e)return!0;return!1}add(t,e){e.forEach(n=>{this.log("add DNS mapping %s to %s",n,t);let o=Je(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?Dp-Date.now():0,lastVerified:o?Dp-Date.now():void 0})})}remove(t){let e=this.findHost(t),n=!1;for(let[o,s]of this.mappings.entries())s.domain===e&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n].multiaddr.stringTuples(),i=s[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(s,c.domain)&&(t.splice(n,1),n--,e.push({multiaddr:V(`/${s.map(u=>[Ys(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return e}maybeAddSNITuple(t,e){for(let n=0;n<t.length;n++)if(t[n][0]===Wb&&t[n+1]?.[0]!==Iu)return t.splice(n+1,0,[Iu,e]),!0;return!1}confirm(t,e){let n=this.findHost(t),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",s,i.domain),o=i.verified,i.verified=!0,i.expires=Date.now()+e,i.lastVerified=Date.now());return o}unconfirm(t,e){let n=this.findHost(t),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",s,i.domain),o=o||i.verified,i.verified=!1,i.expires=Date.now()+e);return o}findHost(t){for(let e of t.stringTuples())if(e[0]===Iu||e[0]===Gb||e[0]===jb||e[0]===Xb||e[0]===Zb)return e[1]}};var Tu=4,Pu=41,Du=6,Yb=273,Ui=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=It({name:"libp2p_address_manager_ip_mappings",metrics:t.metrics})}has(t){let e=t.stringTuples();for(let n of this.mappings.values())for(let o of n)if(o.externalIp===e[0][1])return!0;return!1}add(t,e,n,o=e,s="tcp"){let i=`${t}-${e}-${s}`,a=this.mappings.get(i)??[],c={internalIp:t,internalPort:e,externalIp:n,externalPort:o,externalFamily:ae(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(t){let e=t.stringTuples(),n=e[0][1]??"",o=e[1][0]===Du?"tcp":"udp",s=parseInt(e[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===s&&u.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,s,o),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(t){let e=[];for(let{multiaddr:n}of t){let o=n.stringTuples(),s;if((o[0][0]===Tu||o[0][0]===Pu)&&o[1][0]===Du?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===Tu||o[0][0]===Pu)&&o[1][0]===Yb&&(s=`${o[0][1]}-${o[1][1]}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)o[0][0]=a.externalFamily===4?Tu:Pu,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:V(`/${o.map(c=>[Ys(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return e}confirm(t,e){let o=t.stringTuples()[0][1],s=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===o&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),s=a.verified,a.verified=!0,a.expires=Date.now()+e,a.lastVerified=Date.now());return s}unconfirm(t,e){let n=t.stringTuples(),o=n[0][1]??"",s=n[1][0]===Du?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===o&&u.externalPort===i&&u.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,o,i,s),a=a||u.verified,u.verified=!1,u.expires=Date.now()+e)}return a}};function Lp(r){try{for(let{code:t,value:e}of r.getComponents())if(t!==42&&e!=null){if(t===4)return e.startsWith("169.254.");if(t===41)return e.toLowerCase().startsWith("fe80")}}catch{}return!1}function Ki(r){try{for(let{code:t}of r.getComponents())if(t!==42)return t===4||t===41}catch{}return!1}function Nr(r){try{if(!Ki(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:Je(t)??!1}catch{}return!0}var Qb={maxObservedAddresses:10},qi=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=It({name:"libp2p_address_manager_observed_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??Qb.maxObservedAddresses}has(t){return this.addresses.has(t.toString())}removePrefixed(t){for(let e of this.addresses.keys())e.toString().startsWith(t)&&this.addresses.delete(e)}add(t){this.addresses.size!==this.maxObservedAddresses&&(Nr(t)||Lp(t)||(this.log("adding observed address %a",t),this.addresses.set(t.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([t,e])=>({multiaddr:V(t),verified:e.verified,type:"observed",expires:e.expires,lastVerified:e.lastVerified}))}remove(t){let e=this.addresses.get(t.toString())?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(t.toString()),e}confirm(t,e){let n=t.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+e,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var Jb=[4,41,53,54,55,56];function Lu(r){try{for(let{code:t}of r.getComponents())if(t!==42)return Jb.includes(t)}catch{}return!1}var tw={maxObservedAddresses:10},zi=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=It({name:"libp2p_address_manager_transport_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??tw.maxObservedAddresses}get(t,e){if(Nr(t))return{multiaddr:t,verified:!0,type:"transport",expires:Date.now()+e,lastVerified:Date.now()};let n=this.toKey(t),o=this.addresses.get(n);return o==null&&(o={verified:!Lu(t),expires:0},this.addresses.set(n,o)),{multiaddr:t,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(t){let e=this.toKey(t);return this.addresses.has(e)}remove(t){let e=this.toKey(t),n=this.addresses.get(e)?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(e),n}confirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+e,this.addresses.set(n,o),s}toKey(t){if(Lu(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var Rp=6e4,Op={maxObservedAddresses:10,addressVerificationTTL:Rp*10,addressVerificationRetry:Rp*5},ew=r=>r;function Ru(r,t){let e=r.getPeerId();return e!=null&&pe(e).equals(t)&&(r=r.decapsulate(V(`/p2p/${t.toString()}`))),r}var Vi=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(t,e={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=e;this.components=t,this.log=t.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new qi(t,e),this.dnsMappings=new Fi(t,e),this.ipMappings=new Ui(t,e),this.transportAddresses=new zi(t,e),this.announceFilter=e.announceFilter??ew,this.observedAddressFilter=Oo(1024),this.addressVerificationTTL=e.addressVerificationTTL??Op.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??Op.addressVerificationRetry,this._updatePeerStoreAddresses=Ko(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAddresses().map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>V(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>V(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>V(t))}getObservedAddrs(){return this.observed.getAll().map(t=>t.multiaddr)}addObservedAddr(t){let e=t.stringTuples(),n=`${e[0][1]}:${e[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),t=Ru(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=Ru(t,this.components.peerId);let n=!0;(e?.type==="transport"||this.transportAddresses.has(t))&&!this.transportAddresses.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="dns-mapping"||this.dnsMappings.has(t))&&!this.dnsMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="ip-mapping"||this.ipMappings.has(t))&&!this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="observed"||this.observed.has(t))&&(this.maybeUpgradeToIPMapping(t)?(this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(t,e){t=Ru(t,this.components.peerId);let n=!1;this.observed.has(t)&&!this.observed.remove(t)&&n&&(n=!1),this.transportAddresses.has(t)&&!this.transportAddresses.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(t)&&!this.dnsMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(t)&&!this.ipMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let t=new Set,e=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return t.has(o)?!1:(t.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(e.map(n=>{let o=V(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let t=this.getAnnounceAddrs();if(t.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(t)}),t.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let e=[];e=e.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),e=e.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),e=e.concat(this.observed.getAll()),e=e.concat(this.ipMappings.getAll(e)),e=e.concat(this.dnsMappings.getAll(e)),e}addDNSMapping(t,e){this.dnsMappings.add(t,e)}removeDNSMapping(t){this.dnsMappings.remove(V(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${ae(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(V(`/ip${ae(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(t){if(this.ipMappings.has(t))return!1;let e=t.toOptions();if(e.family===6||e.host==="127.0.0.1"||Je(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Mr.exactMatch(s)||Ho.exactMatch(s),s=>Vo.exactMatch(s),s=>Ap.exactMatch(s)];for(let s of o){if(!s(t))continue;let i=n.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(t),this.ipMappings.add(c.host,c.port,e.host,e.port,e.transport),!0}return!1}};var kp;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(kp||(kp={}));var Hi=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},$i=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},Ln=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},Wo=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Wi=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Gi=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},ji=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},Go=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Xi=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Zi=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},Yi=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Qi=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Ji=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},Br=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},Fr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},ta=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}},ea=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}};var Ou=class{components={};_started=!1;constructor(t={}){this.components={};for(let[e,n]of Object.entries(t))this.components[e]=n;this.components.logger==null&&(this.components.logger=ei())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>us(e)).map(async e=>{await e[t]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},nw=["metrics","connectionProtector","dns"],ow=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Mp(r={}){let t=new Ou(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!ow.includes(o)){let i=t.components[o];if(i==null&&!nw.includes(o))throw new Hi(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?t.components[o]=s:Reflect.set(n,o,s),!0}})}function Np(r){let t={};for(let e of Object.values(r.components))for(let n of sw(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of iw(e))if(t[n]!==!0)throw new $i(`Service "${aw(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function sw(r){return Array.isArray(r?.[zn])?r[zn]:[]}function iw(r){return Array.isArray(r?.[za])?r[za]:[]}function aw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var cw=4,lw=41;function Bp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(Mr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===cw||e[0][0]===lw?!!Je(`${e[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var Fp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},uw=new WeakMap;function fw({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Fp());let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(Fp())},u=()=>{o&&o.removeEventListener("abort",l)},f=new Promise((d,h)=>{i=()=>{u(),d(n)},a=h,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",l,{once:!0}),uw.set(f,()=>{c(s),s=null,i()}),f}}var dw=fw(),Up=dw;var ra=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}},na=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var oa=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new ku}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ra("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await Up(a)}return i}penalty(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},ku=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function sa(r){if(Ue(r))return{peerId:r,multiaddrs:[]};let t=Array.isArray(r)?r:[r],e;if(t.length>0){let n=t[0].getPeerId();e=n==null?void 0:pe(n),t.forEach(o=>{if(!Qe(o))throw new Ke("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(e!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let i=pe(s);if(e?.equals(i)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return t=t.filter(n=>!vp.exactMatch(n)),{peerId:e,multiaddrs:t}}var hw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Kp(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??hw;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}function jo(r){try{let t;typeof r=="string"?t=V(r):t=r;let e=new Set([...t.getComponents().map(n=>n.name)]);if(!e.has("ipcidr")){let o=e.has("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(o)}return jl(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var ia=class{connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.allow=(e.allow??[]).map(n=>jo(n)),this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(t=>{this.log.error("error while pruning connections %e",t)})}async _maybePruneConnections(){let t=this.connectionManager.getConnections(),e=t.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",e,n),e<=n)return;let o=new Yt;for(let c of t){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",u)}}}let s=this.sortConnections(t,o),i=Math.max(e-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Kp(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(t,e){return t.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=e.get(n.remotePeer)??0,i=e.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var qp="last-dial-failure",zp="last-dial-success";var Vp=100,aa=50;var ca=class{deferred;signal;constructor(t){this.signal=t,this.deferred=lt(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function pw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var la=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=pw(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Jt),this.cleanup())}async join(t={}){let e=new ca(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await wt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Rn=class extends qt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Ko(this.emitEmpty.bind(this),1),this.emitIdle=Ko(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new na;let n=new la(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Jt)}),this.clear()}async onEmpty(t){this.size!==0&&await ge(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await ge(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ge(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=ii({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Jt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var ua=class extends Rn{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Be(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function Hp(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Mu(r){if(!Ki(r))return!1;let{address:t}=r.nodeAddress();return Hp(t)}function mw(r,t){let e=Vo.exactMatch(r.multiaddr),n=Vo.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=Ho.exactMatch(r.multiaddr),s=Ho.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Mr.exactMatch(r.multiaddr),a=Mr.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Au.exactMatch(r.multiaddr),l=Au.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=_u.exactMatch(r.multiaddr),f=_u.exactMatch(t.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Su.exactMatch(r.multiaddr),h=Su.exactMatch(t.multiaddr);return d&&!h?-1:!d&&h?1:0}function gw(r,t){let e=Mu(r.multiaddr),n=Mu(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function yw(r,t){let e=Nr(r.multiaddr),n=Nr(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function bw(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function ww(r,t){let e=$o.exactMatch(r.multiaddr),n=$o.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function $p(r){return r.sort(mw).sort(bw).sort(ww).sort(yw).sort(gw)}async function Nu(r,t,e){let n=e.depth??0;if(n>(e.maxRecursiveDepth??32))throw new ea("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(t))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,e);for(let c of a)s.push(...await Nu(c,t,{...e,depth:n+1}))}return o===!1&&s.push(r),s}var Xo={maxParallelDials:aa,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:ke}},fa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??Xo.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??Xo.maxDialQueueLength,this.dialTimeout=e.dialTimeout??Xo.dialTimeout,this.connections=e.connections??new Yt,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.resolvers=e.resolvers??Xo.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new ua({concurrency:e.maxParallelDials??Xo.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Jt.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=sa(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0||a.limits!=null?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new ft("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new ft("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Wr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new ft("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new ft("dial-queue:start-dial"));let c=Be([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??Ku,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async dialPeer(t,e){let n=t.peerId,o=t.multiaddrs,s=new Set,i=t.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(t.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...t,signal:e});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),t?.onProgress?.(new ft("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,t.peerId),new Wr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...t,signal:e});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[zp]:P(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}return p}catch(p){if(this.log.error("dial failed to %a",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[qp]:P(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(e.aborted)throw new as(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(f=>({multiaddr:V(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Wr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new Go("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let f=await this.components.peerStore.get(t);o.push(...f.addresses),this.log("loaded multiaddrs for %p",t,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",t);try{let f=await this.components.peerRouting.findPeer(t,n);this.log("found multiaddrs for %p in the peer routing",t,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",t):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",t,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await Nu(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(t!=null){let f=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new Yi("The dial request has no valid addresses");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?$p(l):l.sort(this.addressSorter);if(u.length===0)throw new Go("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!$o.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var da=class extends Rn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Qp=es(Zp(),1);var Ew=Object.prototype.toString,vw=r=>Ew.call(r)==="[object Error]",_w=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function qu(r){return r&&vw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:_w.has(r.message):!1}var zu=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},Yp=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Vu(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=Qp.default.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof zu)throw c.originalError;if(c instanceof TypeError&&!qu(c))throw c;if(Yp(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){Yp(l,a,t),i(),n(l)}}})})}var ha=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new da({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,this.events=t.events,t.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(t){if(!this.started)return;let e=await this.peerStore.get(t);Jp(e)&&(this.queue.has(t)||this.queue.add(async n=>{await Vu(async o=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",t,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",t,n);let o={};[...e.tags.keys()].forEach(s=>{s.startsWith(qa)&&(o[s]=void 0)}),await this.peerStore.merge(t,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",t,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>Jp(e)]});await Promise.all(t.map(async e=>{await this.connectionManager.openConnection(e.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}};function Jp(r){for(let t of r.tags.keys())if(t.startsWith(qa))return!0;return!1}var Ku=50,Hu={maxConnections:Vp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},pa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(t,e={}){if(this.maxConnections=e.maxConnections??Hu.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new Yt,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(e.allow??[]).map(n=>jo(n)),this.deny=(e.deny??[]).map(n=>jo(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??Hu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new oa({points:e.inboundConnectionThreshold??Hu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ia({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{allow:e.allow?.map(n=>V(n))}),this.dialQueue=new fa(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??aa,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:ke},connections:this.connections}),this.reconnectQueue=new ha({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let e of this.connections.values())for(let n of e)t[n.direction]++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await of(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await sf(this.reconnectQueue,this.dialQueue,this.connectionPruner);let t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(t){if(this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");let e=!1;t<this.maxConnections&&(e=!0),this.maxConnections=t,e&&this.connectionPruner.maybePruneConnections()}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new ye("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=sa(t);if(this.peerId.equals(n))throw new $r("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p as %a",n,a.remoteAddr),e.onProgress?.(new ft("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??Ku});if(o.status!=="open")throw new Hr("Remote closed connection during opening");let s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)if(a.id===o.id&&(i=!0),e.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new Ke("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>V(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var On=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(t){this.timeSpan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timeSpan)}push(t,e=Date.now()){if(this.previousTime!=null){let n=this.alpha(e,this.previousTime),o=t-this.movingAverage,s=n*o;this.movingAverage=n*t+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=t;this.previousTime=e}};var Cw=1.2,Iw=2,Tw=5e3,Pw=6e4,Dw=5e3,ma=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(t={}){let e=t.interval??Dw;this.success=new On(e),this.failure=new On(e),this.next=new On(e),this.failureMultiplier=t.failureMultiplier??Iw,this.timeoutMultiplier=t.timeoutMultiplier??Cw,this.minTimeout=t.minTimeout??Tw,this.maxTimeout=t.maxTimeout??Pw,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier));e<this.minTimeout&&(e=this.minTimeout),e>this.maxTimeout&&(e=this.maxTimeout);let n=AbortSignal.timeout(e),o=Be([t.signal,n]);return o.start=Date.now(),o.timeout=e,o}cleanUp(t){let e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}};var $u=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=lt(),this.haveNext=lt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=lt(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=lt(),await wt(this.readNext.promise,e?.signal,e)}};function ga(){return new $u}var ya=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ba(r,t){let e=ga();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new $;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await wt(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await wt(n.next(),i?.signal);if(l===!0)throw new ya("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Lw=1e4,Rw="1.0.0",Ow="ping",kw="ipfs",tm=32,Mw=!0,wa=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??kw}/${Ow}/${Rw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??Lw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??Mw,this.timeout=new ma({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[zn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=ba(o);e=Date.now(),await Promise.all([s.write(fn(tm),{signal:n}),s.read({bytes:tm,signal:n})]),t.rtt=Date.now()-e,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function Nw(r){return r[Symbol.asyncIterator]!=null}async function Bw(r,t,e){try{await Promise.all(r.map(async n=>{for await(let o of n)await t.push(o,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*Fw(r){let t=new AbortController,e=ga();Bw(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*Uw(r){for(let t of r)yield*t}function Kw(...r){let t=[];for(let e of r)Nw(e)||t.push(e);return t.length===r.length?Uw(t):Fw(r)}var Zo=Kw;var xa=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t,this.findProviders=t.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=t.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=t.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=t.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:N(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:N(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(this.routers.length===0)throw new Ln("No content routers available");let n=this,o=new Ir;for await(let s of Zo(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(t,e))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},e),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new Ln("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(this.routers.length===0)throw new Ln("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new ye;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new ye;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(t,e)))}};var Ea=globalThis.CustomEvent??Event;async function*Wu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=lt(),a=lt(),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===e&&(i=lt(),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 Ea("task-complete"))},m=>{g.done=!0,g.err=m,o.dispatchEvent(new Ea("task-complete"))})}c=!0,o.dispatchEvent(new Ea("task-complete"))}catch(p){l=p,o.dispatchEvent(new Ea("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=lt(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var va=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[],this.findPeer=t.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=t.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:N(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(this.routers.length===0)throw new Wo("No peer routers available");if(t.toString()===this.peerId.toString())throw new Wi("Should not try to find self");let n=this,o=Zo(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>async function*(){try{yield await s.findPeer(t,e)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},e),s;throw new or}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new Wo("No peer routers available");let n=this,o=Oo(1024);for await(let s of Wu(async function*(){let i=Zo(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(t,e)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...e,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},e),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var _a=class extends qt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(t){this.walking||this.startWalk(),this.walkers++;let e=Be([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=lt(),yield(await ge(this,"walk:peer",e,{errorEvent:"walk:error"})).detail}finally{e.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let t=Be([this.walkController.signal,this.shutdownController.signal]);let e=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=fn(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:t}))t.aborted&&this.log("aborting walk"),t.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await wt(this.needNext.promise,t)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-e),this.walking=!1})}};var Gu=32,ju=64,Sa=class{log;topologies;handlers;components;constructor(t){this.components=t,this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,t.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let e={};for(let[n,o]of this.topologies)e[n]=o.size;return e}}),this.handlers=It({name:"libp2p_registrar_protocol_handlers",metrics:t.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){let e=this.handlers.get(t);if(e==null)throw new Gi(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t)&&n?.force!==!0)throw new ji(`Handler already registered for protocol ${t}`);let o=Bs.bind({ignoreUndefined:!0})({maxInboundStreams:Gu,maxOutboundStreams:ju},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]},n)}async unhandle(t,e){(Array.isArray(t)?t:[t]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},e)}async register(t,e){if(e==null)throw new R("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,e),n}unregister(t){for(let[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(e))}_onDisconnect(t){let e=t.detail,n={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(e,n).then(o=>{for(let s of o.protocols){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e)!==!1&&(a.filter?.remove(e),a.onDisconnect?.(e))}}).catch(o=>{o.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,o)})}_onPeerUpdate(t){let{peer:e,previous:n}=t.detail,o=(n?.protocols??[]).filter(s=>!e.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e.id)!==!1&&(a.filter?.remove(e.id),a.onDisconnect?.(e.id))}}_onPeerIdentify(t){let e=t.detail.protocols,n=t.detail.connection,o=t.detail.peerId;for(let s of e){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Aa=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=It({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=It({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??nr.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new R("Transport must have a valid tag");if(this.transports.has(e))throw new R(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new ta(`No transport available for address ${String(t)}`);return e?.onProgress?.(new ft("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new ye("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach(s=>{e.errors.set(s.toString(),new Xi)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(t);for(let c of a){this.log("creating listener for %s on %a",s,c);let 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})}),wu.matches(c)?e.ipv4.attempts++:xu.matches(c)&&e.ipv6.attempts++,n.push(l.listen(c).then(()=>{e.errors.delete(c.toString()),wu.matches(c)&&e.ipv4.success++,xu.matches(c)&&e.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),e.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(e)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===nr.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Zi(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
2
+ "use strict";var Libp2P=(()=>{var hm=Object.create;var Jo=Object.defineProperty;var pm=Object.getOwnPropertyDescriptor;var mm=Object.getOwnPropertyNames;var gm=Object.getPrototypeOf,ym=Object.prototype.hasOwnProperty;var Kr=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Bt=(r,t)=>{for(var e in t)Jo(r,e,{get:t[e],enumerable:!0})},cf=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of mm(t))!ym.call(r,o)&&o!==e&&Jo(r,o,{get:()=>t[o],enumerable:!(n=pm(t,o))||n.enumerable});return r};var ts=(r,t,e)=>(e=r!=null?hm(gm(r)):{},cf(t||!r||!r.__esModule?Jo(e,"default",{value:r,enumerable:!0}):e,r)),bm=r=>cf(Jo({},"__esModule",{value:!0}),r);var xh=Kr((x_,Cl)=>{"use strict";var f0=Object.prototype.hasOwnProperty,Mt="~";function Eo(){}Object.create&&(Eo.prototype=Object.create(null),new Eo().__proto__||(Mt=!1));function d0(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function wh(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new d0(e,n||r,o),i=Mt?Mt+t:t;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Us(r,t){--r._eventsCount===0?r._events=new Eo:delete r._events[t]}function Ct(){this._events=new Eo,this._eventsCount=0}Ct.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)f0.call(e,n)&&t.push(Mt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Ct.prototype.listeners=function(t){var e=Mt?Mt+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Ct.prototype.listenerCount=function(t){var e=Mt?Mt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Ct.prototype.emit=function(t,e,n,o,s,i){var a=Mt?Mt+t:t;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,n,o,s,i),!0}for(f=1,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(t,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,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!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};Ct.prototype.on=function(t,e,n){return wh(this,t,e,n,!1)};Ct.prototype.once=function(t,e,n){return wh(this,t,e,n,!0)};Ct.prototype.removeListener=function(t,e,n,o){var s=Mt?Mt+t:t;if(!this._events[s])return this;if(!e)return Us(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&Us(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Us(this,s)}return this};Ct.prototype.removeAllListeners=function(t){var e;return t?(e=Mt?Mt+t:t,this._events[e]&&Us(this,e)):(this._events=new Eo,this._eventsCount=0),this};Ct.prototype.off=Ct.prototype.removeListener;Ct.prototype.addListener=Ct.prototype.on;Ct.prefixed=Mt;Ct.EventEmitter=Ct;typeof Cl<"u"&&(Cl.exports=Ct)});var Ah=Kr((z_,Sh)=>{Sh.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var Sp=Kr(Fo=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},i=function(c){var l,u,f,d,h,p;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),h=p[0],u=p[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(e(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+e(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,h,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw f=m,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw f=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=i(this.first),f=i(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Fo.ip2long=i,Fo.long2ip=a,Fo.Netmask=r}).call(Fo)});var Yp=Kr((OP,Zp)=>{function ee(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Zp.exports=ee;ee.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};ee.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};ee.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};ee.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};ee.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};ee.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};ee.prototype.start=ee.prototype.try;ee.prototype.errors=function(){return this._errors};ee.prototype.attempts=function(){return this._attempts};ee.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var Qp=Kr(Br=>{var Sw=Yp();Br.operation=function(r){var t=Br.timeouts(r);return new Sw(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Br.timeouts=function(r){if(r instanceof Array)return[].concat(r);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var e in r)t[e]=r[e];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(s,i){return s-i}),n};Br.createTimeout=function(r,t){var e=t.randomize?Math.random()+1:1,n=Math.round(e*Math.max(t.minTimeout,1)*Math.pow(t.factor,r));return n=Math.min(n,t.maxTimeout),n};Br.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var l=Br.operation(t),u=Array.prototype.slice.call(arguments,1),f=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),f.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[s].options=t}}});var tm=Kr((MP,Jp)=>{Jp.exports=Qp()});var rx={};Bt(rx,{createLibp2p:()=>Jw,dnsaddrResolver:()=>Ne,isLibp2p:()=>ex});var lf=Symbol.for("@libp2p/connection");var Ua=Symbol.for("@libp2p/content-routing");var Fa=Symbol.for("@libp2p/peer-discovery");var es=Symbol.for("@libp2p/peer-id");function Ke(r){return!!r?.[es]}var Ka=Symbol.for("@libp2p/peer-routing");var qa="keep-alive";var ux=Symbol.for("@libp2p/transport");var or;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(or||(or={}));var re=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var k=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},qr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},Nn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var rs=class extends Error{static name="ConnectionClosingError";constructor(t="The connection is closing"){super(t),this.name="ConnectionClosingError"}},Vr=class extends Error{static name="ConnectionClosedError";constructor(t="The connection is closed"){super(t),this.name="ConnectionClosedError"}};var sr=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},zr=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},qe=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},ns=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},os=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},Bn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},ss=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var is=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},we=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var $r=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Un=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},as=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},cs=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Ve=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Vt=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function ls(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function uf(...r){let t=[];for(let e of r)ls(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function ff(...r){let t=[];for(let e of r)ls(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}var Fn=Symbol.for("@libp2p/service-capabilities"),Va=Symbol.for("@libp2p/service-dependencies");var Ga={};Bt(Ga,{base58btc:()=>Y,base58flickr:()=>Am});var Nx=new Uint8Array(0);function df(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function xe(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 hf(r){return new TextEncoder().encode(r)}function pf(r){return new TextDecoder().decode(r)}function wm(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),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 m=0,x=0,g=0,_=p.length;g!==_&&p[g]===0;)g++,m++;for(var w=(_-g)*u+1>>>0,A=new Uint8Array(w);g!==_;){for(var R=p[g],K=0,V=w-1;(R!==0||K<x)&&V!==-1;V--,K++)R+=256*A[V]>>>0,A[V]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");x=K,g++}for(var M=w-x;M!==w&&A[M]===0;)M++;for(var v=c.repeat(m);M<w;++M)v+=r.charAt(A[M]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var x=0,g=0;p[m]===c;)x++,m++;for(var _=(p.length-m)*l+1>>>0,w=new Uint8Array(_);p[m];){var A=e[p.charCodeAt(m)];if(A===255)return;for(var R=0,K=_-1;(A!==0||R<g)&&K!==-1;K--,R++)A+=a*w[K]>>>0,w[K]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");g=R,m++}if(p[m]!==" "){for(var V=_-g;V!==_&&w[V]===0;)V++;for(var M=new Uint8Array(x+(_-V)),v=x;V!==_;)M[v++]=w[V++];return M}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var xm=wm,Em=xm,gf=Em;var za=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},$a=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return yf(this,t)}},Ha=class{decoders;constructor(t){this.decoders=t}or(t){return yf(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function yf(r,t){return new Ha({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Wa=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new za(t,e,n),this.decoder=new $a(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Hr({name:r,prefix:t,encode:e,decode:n}){return new Wa(r,t,e,n)}function ze({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=gf(e,r);return Hr({prefix:t,name:r,encode:n,decode:s=>xe(o(s))})}function vm(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=t[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function _m(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function Sm(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function at({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Sm(n);return Hr({prefix:t,name:r,encode(s){return _m(s,n,e)},decode(s){return vm(s,o,e,r)}})}var Y=ze({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Am=ze({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ja={};Bt(ja,{base32:()=>Xt,base32hex:()=>Pm,base32hexpad:()=>Lm,base32hexpadupper:()=>Rm,base32hexupper:()=>Dm,base32pad:()=>Im,base32padupper:()=>Tm,base32upper:()=>Cm,base32z:()=>Om});var Xt=at({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cm=at({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Im=at({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Tm=at({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Pm=at({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Dm=at({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Lm=at({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Rm=at({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Om=at({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xa={};Bt(Xa,{base36:()=>Kn,base36upper:()=>km});var Kn=ze({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),km=ze({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Mm=xf,bf=128,Nm=127,Bm=~Nm,Um=Math.pow(2,31);function xf(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Um;)t[e++]=r&255|bf,r/=128;for(;r&Bm;)t[e++]=r&255|bf,r>>>=7;return t[e]=r|0,xf.bytes=e-n+1,t}var Fm=Za,Km=128,wf=127;function Za(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Za.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&wf)<<o:(i&wf)*Math.pow(2,o),o+=7}while(i>=Km);return Za.bytes=s-n,e}var qm=Math.pow(2,7),Vm=Math.pow(2,14),zm=Math.pow(2,21),$m=Math.pow(2,28),Hm=Math.pow(2,35),Wm=Math.pow(2,42),Gm=Math.pow(2,49),jm=Math.pow(2,56),Xm=Math.pow(2,63),Zm=function(r){return r<qm?1:r<Vm?2:r<zm?3:r<$m?4:r<Hm?5:r<Wm?6:r<Gm?7:r<jm?8:r<Xm?9:10},Ym={encode:Mm,decode:Fm,encodingLength:Zm},Qm=Ym,qn=Qm;function Vn(r,t=0){return[qn.decode(r,t),qn.decode.bytes]}function Wr(r,t,e=0){return qn.encode(r,t,e),t}function Gr(r){return qn.encodingLength(r)}function ne(r,t){let e=t.byteLength,n=Gr(r),o=n+Gr(e),s=new Uint8Array(o+e);return Wr(r,s,0),Wr(e,s,n),s.set(t,o),new jr(r,e,t,s)}function Ee(r){let t=xe(r),[e,n]=Vn(t),[o,s]=Vn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new jr(e,o,i,t)}function Ef(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&df(r.bytes,e.bytes)}}var jr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function vf(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return tg(e,Ya(r),t??Y.encoder);default:return eg(e,Ya(r),t??Xt.encoder)}}var _f=new WeakMap;function Ya(r){let t=_f.get(r);if(t==null){let e=new Map;return _f.set(r,e),e}return t}var nt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==zn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==rg)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=ne(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Ef(t.multihash,n.multihash)}toString(t){return vf(this,t)}toJSON(){return{"/":vf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Sf(n,o,s.bytes))}else if(e[ng]===!0){let{version:n,multihash:o,code:s}=e,i=Ee(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==zn)throw new Error(`Version 0 CID must use dag-pb (code: ${zn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Sf(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,zn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=xe(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new jr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=Vn(t.subarray(e));return e+=d,f},o=n(),s=zn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Jm(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ya(s).set(n,t),s}};function Jm(r,t){switch(r[0]){case"Q":{let e=t??Y;return[Y.prefix,e.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let e=t??Y;return[Y.prefix,e.decode(r)]}case Xt.prefix:{let e=t??Xt;return[Xt.prefix,e.decode(r)]}case Kn.prefix:{let e=t??Kn;return[Kn.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function tg(r,t,e){let{prefix:n}=e;if(n!==Y.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function eg(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var zn=112,rg=18;function Sf(r,t,e){let n=Gr(r),o=n+Gr(t),s=new Uint8Array(o+e.byteLength);return Wr(r,s,0),Wr(t,s,n),s.set(e,o),s}var ng=Symbol.for("@ipld/js-cid/CID");var Qa={};Bt(Qa,{identity:()=>oe});var Af=0,og="identity",Cf=xe;function sg(r){return ne(Af,Cf(r))}var oe={code:Af,name:og,encode:Cf,digest:sg};function Z(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ct(r=0){return new Uint8Array(r)}function _t(r=0){return new Uint8Array(r)}function se(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=_t(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Tf=Symbol.for("@achingbrain/uint8arraylist");function If(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function fs(r){return!!r?.[Tf]}var W=class r{bufs;length;[Tf]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(fs(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(fs(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=If(this.bufs,t);return e.buf[e.index]}set(t,e){let n=If(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(fs(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return se(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:se(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!fs(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;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(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=_t(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=_t(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=ct(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=ct(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=ct(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Z(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var Ja={};Bt(Ja,{base10:()=>ig});var ig=ze({prefix:"9",name:"base10",alphabet:"0123456789"});var tc={};Bt(tc,{base16:()=>ag,base16upper:()=>cg});var ag=at({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),cg=at({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ec={};Bt(ec,{base2:()=>lg});var lg=at({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var rc={};Bt(rc,{base256emoji:()=>pg});var Pf=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}"),ug=Pf.reduce((r,t,e)=>(r[e]=t,r),[]),fg=Pf.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function dg(r){return r.reduce((t,e)=>(t+=ug[e],t),"")}function hg(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=fg[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var pg=Hr({prefix:"\u{1F680}",name:"base256emoji",encode:dg,decode:hg});var sc={};Bt(sc,{base64:()=>nc,base64pad:()=>mg,base64url:()=>oc,base64urlpad:()=>gg});var nc=at({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),mg=at({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),oc=at({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gg=at({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ic={};Bt(ic,{base8:()=>yg});var yg=at({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ac={};Bt(ac,{identity:()=>bg});var bg=Hr({prefix:"\0",name:"identity",encode:r=>pf(r),decode:r=>hf(r)});var wE=new TextEncoder,xE=new TextDecoder;var uc={};Bt(uc,{sha256:()=>Xr,sha512:()=>Eg});function lc({name:r,code:t,encode:e}){return new cc(r,t,e)}var cc=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?ne(this.code,e):e.then(n=>ne(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Lf(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Xr=lc({name:"sha2-256",code:18,encode:Lf("SHA-256")}),Eg=lc({name:"sha2-512",code:19,encode:Lf("SHA-512")});var $n={...ac,...ec,...ic,...Ja,...tc,...ja,...Xa,...Ga,...sc,...rc},RE={...uc,...Qa};function Of(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Rf=Of("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),fc=Of("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=_t(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),vg={utf8:Rf,"utf-8":Rf,hex:$n.base16,latin1:fc,ascii:fc,binary:fc,...$n},ds=vg;function C(r,t="utf8"){let e=ds[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function U(r,t="utf8"){let e=ds[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var _g=parseInt("11111",2),dc=parseInt("10000000",2),Sg=parseInt("01111111",2),kf={0:Hn,1:Hn,2:Ag,3:Tg,4:Pg,5:Ig,6:Cg,16:Hn,22:Hn,48:Hn};function ve(r,t={offset:0}){let e=r[t.offset]&_g;if(t.offset++,kf[e]!=null)return kf[e](r,t);throw new Error("No decoder for tag "+e)}function Wn(r,t){let e=0;if((r[t.offset]&dc)===dc){let n=r[t.offset]&Sg,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function Hn(r,t){Wn(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ve(r,t);if(n===null)break;e.push(n)}return e}function Ag(r,t){let e=Wn(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function Cg(r,t){let e=Wn(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.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 Ig(r,t){return t.offset++,null}function Tg(r,t){let e=Wn(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Pg(r,t){let e=Wn(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Dg(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new W;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function hs(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Dg(r.byteLength);return new W(Uint8Array.from([t.byteLength|dc]),t)}function Pt(r){let t=new W,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new W(Uint8Array.from([2]),hs(t),t)}function Gn(r){let t=Uint8Array.from([0]),e=new W(t,r);return new W(Uint8Array.from([3]),hs(e),e)}function Mf(r){return new W(Uint8Array.from([4]),hs(r),r)}function ie(r,t=48){let e=new W;for(let n of r)e.append(n);return new W(Uint8Array.from([t]),hs(e),e)}async function Nf(r="P-256"){let t=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",t.publicKey),privateKey:await crypto.subtle.exportKey("jwk",t.privateKey)}}async function Bf(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);e?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Uf(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var Lg=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Rg=Uint8Array.from([6,5,43,129,4,0,34]),Og=Uint8Array.from([6,5,43,129,4,0,35]),kg={ext:!0,kty:"EC",crv:"P-256"},Mg={ext:!0,kty:"EC",crv:"P-384"},Ng={ext:!0,kty:"EC",crv:"P-521"},hc=32,pc=48,mc=66;function gc(r){let t=ve(r);return Ff(t)}function Ff(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===hc*2+1)return n=U(t.subarray(e,e+hc),"base64url"),o=U(t.subarray(e+hc),"base64url"),new ir({...kg,key_ops:["verify"],x:n,y:o});if(t.byteLength===pc*2+1)return n=U(t.subarray(e,e+pc),"base64url"),o=U(t.subarray(e+pc),"base64url"),new ir({...Mg,key_ops:["verify"],x:n,y:o});if(t.byteLength===mc*2+1)return n=U(t.subarray(e,e+mc),"base64url"),o=U(t.subarray(e+mc),"base64url"),new ir({...Ng,key_ops:["verify"],x:n,y:o});throw new k(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Kf(r){return ie([Pt(Uint8Array.from([1])),Mf(C(r.d??"","base64url")),ie([Vf(r.crv)],160),ie([Gn(new W(Uint8Array.from([4]),C(r.x??"","base64url"),C(r.y??"","base64url")))],161)]).subarray()}function qf(r){return ie([Pt(Uint8Array.from([1])),ie([Vf(r.crv)],160),ie([Gn(new W(Uint8Array.from([4]),C(r.x??"","base64url"),C(r.y??"","base64url")))],161)]).subarray()}function Vf(r){if(r==="P-256")return Lg;if(r==="P-384")return Rg;if(r==="P-521")return Og;throw new k(`Invalid curve ${r}`)}async function zf(r="P-256"){let t=await Nf(r);return new ps(t.privateKey)}var ir=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=qf(this.jwk)),this._raw}toMultihash(){return oe.digest(Zt(this))}toCID(){return nt.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}async verify(t,e,n){return Uf(this.jwk,e,t,n)}},ps=class{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new ir({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=Kf(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}async sign(t,e){return Bf(this.jwk,t,e)}};var ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Se(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function jn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Ut(r,...t){if(!Se(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function ms(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");jn(r.outputLen),jn(r.blockLen)}function Yr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Hf(r,t){Ut(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function Ae(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function gs(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ae(r,t){return r<<32-t|r>>>t}var Wf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Bg=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Yt(r){if(Ut(r),Wf)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Bg[r[e]];return t}var _e={_0:48,_9:57,A:65,F:70,a:97,f:102};function $f(r){if(r>=_e._0&&r<=_e._9)return r-_e._0;if(r>=_e.A&&r<=_e.F)return r-(_e.A-10);if(r>=_e.a&&r<=_e.f)return r-(_e.a-10)}function cr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Wf)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=$f(r.charCodeAt(s)),a=$f(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function yc(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Xn(r){return typeof r=="string"&&(r=yc(r)),Ut(r),r}function Dt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ut(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Zr=class{};function bc(r){let t=n=>r().update(Xn(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function He(r=32){if(ar&&typeof ar.getRandomValues=="function")return ar.getRandomValues(new Uint8Array(r));if(ar&&typeof ar.randomBytes=="function")return Uint8Array.from(ar.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function Ug(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function Gf(r,t,e){return r&t^~r&e}function jf(r,t,e){return r&t^r&e^t&e}var Zn=class extends Zr{constructor(t,e,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=gs(this.buffer)}update(t){Yr(this),t=Xn(t),Ut(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=gs(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Yr(this),Hf(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Ae(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;Ug(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=gs(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should 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:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var bt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var ys=BigInt(4294967295),Xf=BigInt(32);function Fg(r,t=!1){return t?{h:Number(r&ys),l:Number(r>>Xf&ys)}:{h:Number(r>>Xf&ys)|0,l:Number(r&ys)|0}}function Zf(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=Fg(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var wc=(r,t,e)=>r>>>e,xc=(r,t,e)=>r<<32-e|t>>>e,lr=(r,t,e)=>r>>>e|t<<32-e,ur=(r,t,e)=>r<<32-e|t>>>e,Yn=(r,t,e)=>r<<64-e|t>>>e-32,Qn=(r,t,e)=>r>>>e-32|t<<64-e;function he(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Yf=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Qf=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Jf=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),td=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,ed=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),rd=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var qg=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]),We=new Uint32Array(64),bs=class extends Zn{constructor(t=32){super(64,t,8,!1),this.A=Ce[0]|0,this.B=Ce[1]|0,this.C=Ce[2]|0,this.D=Ce[3]|0,this.E=Ce[4]|0,this.F=Ce[5]|0,this.G=Ce[6]|0,this.H=Ce[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)We[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=We[f-15],h=We[f-2],p=ae(d,7)^ae(d,18)^d>>>3,m=ae(h,17)^ae(h,19)^h>>>10;We[f]=m+We[f-7]+p+We[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=ae(a,6)^ae(a,11)^ae(a,25),h=u+d+Gf(a,c,l)+qg[f]+We[f]|0,m=(ae(n,2)^ae(n,13)^ae(n,22))+jf(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){Ae(We)}destroy(){this.set(0,0,0,0,0,0,0,0),Ae(this.buffer)}};var nd=Zf(["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))),Vg=nd[0],zg=nd[1],Ge=new Uint32Array(80),je=new Uint32Array(80),Ec=class extends Zn{constructor(t=64){super(128,t,16,!1),this.Ah=bt[0]|0,this.Al=bt[1]|0,this.Bh=bt[2]|0,this.Bl=bt[3]|0,this.Ch=bt[4]|0,this.Cl=bt[5]|0,this.Dh=bt[6]|0,this.Dl=bt[7]|0,this.Eh=bt[8]|0,this.El=bt[9]|0,this.Fh=bt[10]|0,this.Fl=bt[11]|0,this.Gh=bt[12]|0,this.Gl=bt[13]|0,this.Hh=bt[14]|0,this.Hl=bt[15]|0}get(){let{Ah:t,Al:e,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:m,Hl:x}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,h,p,m,x]}set(t,e,n,o,s,i,a,c,l,u,f,d,h,p,m,x){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=x|0}process(t,e){for(let w=0;w<16;w++,e+=4)Ge[w]=t.getUint32(e),je[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let A=Ge[w-15]|0,R=je[w-15]|0,K=lr(A,R,1)^lr(A,R,8)^wc(A,R,7),V=ur(A,R,1)^ur(A,R,8)^xc(A,R,7),M=Ge[w-2]|0,v=je[w-2]|0,D=lr(M,v,19)^Yn(M,v,61)^wc(M,v,6),F=ur(M,v,19)^Qn(M,v,61)^xc(M,v,6),L=Jf(V,F,je[w-7],je[w-16]),E=td(L,K,D,Ge[w-7],Ge[w-16]);Ge[w]=E|0,je[w]=L|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:m,Gl:x,Hh:g,Hl:_}=this;for(let w=0;w<80;w++){let A=lr(f,d,14)^lr(f,d,18)^Yn(f,d,41),R=ur(f,d,14)^ur(f,d,18)^Qn(f,d,41),K=f&h^~f&m,V=d&p^~d&x,M=ed(_,R,V,zg[w],je[w]),v=rd(M,g,A,K,Vg[w],Ge[w]),D=M|0,F=lr(n,o,28)^Yn(n,o,34)^Yn(n,o,39),L=ur(n,o,28)^Qn(n,o,34)^Qn(n,o,39),E=n&s^n&a^s&a,y=o&i^o&c^i&c;g=m|0,_=x|0,m=h|0,x=p|0,h=f|0,p=d|0,{h:f,l:d}=he(l|0,u|0,v|0,D|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let b=Yf(D,L,y);n=Qf(b,v,F,E),o=b|0}({h:n,l:o}=he(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=he(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=he(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=he(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=he(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=he(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:x}=he(this.Gh|0,this.Gl|0,m|0,x|0),{h:g,l:_}=he(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,o,s,i,a,c,l,u,f,d,h,p,m,x,g,_)}roundClean(){Ae(Ge,je)}destroy(){Ae(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ws=bc(()=>new bs);var od=bc(()=>new Ec);var Sc=BigInt(0),_c=BigInt(1);function Ie(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}"`;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function zt(r,t,e=""){let n=Se(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Jn(r){let t=r.toString(16);return t.length&1?"0"+t:t}function sd(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Sc:BigInt("0x"+r)}function Qr(r){return sd(Yt(r))}function Te(r){return Ut(r),sd(Yt(Uint8Array.from(r).reverse()))}function xs(r,t){return cr(r.toString(16).padStart(t*2,"0"))}function Ac(r,t){return xs(r,t).reverse()}function Q(r,t,e){let n;if(typeof t=="string")try{n=cr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Se(t))n=Uint8Array.from(t);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(r+" of length "+e+" expected, got "+o);return n}function id(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Cc(r){return Uint8Array.from(r)}var vc=r=>typeof r=="bigint"&&Sc<=r;function ad(r,t,e){return vc(r)&&vc(t)&&vc(e)&&t<=r&&r<e}function to(r,t,e,n){if(!ad(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Es(r){let t;for(t=0;r>Sc;r>>=_c,t+=1);return t}var Xe=r=>(_c<<BigInt(r))-_c;function cd(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>e(i,s,...h),u=(h=n(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,p=[];for(;h<t;){s=l();let m=s.slice();p.push(m),h+=s.length}return Dt(...p)};return(h,p)=>{c(),u(h);let m;for(;!(m=p(f()));)u();return c(),m}}function Ze(r,t,e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([o,s])=>n(o,s,!1)),Object.entries(e).forEach(([o,s])=>n(o,s,!0))}var Ic=()=>{throw new Error("not implemented")};function Jr(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var Lt=BigInt(0),pt=BigInt(1),fr=BigInt(2),fd=BigInt(3),dd=BigInt(4),hd=BigInt(5),$g=BigInt(7),pd=BigInt(8),Hg=BigInt(9),md=BigInt(16);function lt(r,t){let e=r%t;return e>=Lt?e:t+e}function et(r,t,e){let n=r;for(;t-- >Lt;)n*=n,n%=e;return n}function ld(r,t){if(r===Lt)throw new Error("invert: expected non-zero number");if(t<=Lt)throw new Error("invert: expected positive modulus, got "+t);let e=lt(r,t),n=t,o=Lt,s=pt,i=pt,a=Lt;for(;e!==Lt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==pt)throw new Error("invert: does not exist");return lt(o,t)}function Tc(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function gd(r,t){let e=(r.ORDER+pt)/dd,n=r.pow(t,e);return Tc(r,n,t),n}function Wg(r,t){let e=(r.ORDER-hd)/pd,n=r.mul(t,fr),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,fr),o),a=r.mul(s,r.sub(i,r.ONE));return Tc(r,a,t),a}function Gg(r){let t=$t(r),e=yd(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+$g)/md;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(u),c),p=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,p);let m=a.eql(a.sqr(u),c),x=a.cmov(l,u,m);return Tc(a,x,c),x}}function yd(r){if(r<fd)throw new Error("sqrt is not defined for small field");let t=r-pt,e=0;for(;t%fr===Lt;)t/=fr,e++;let n=fr,o=$t(r);for(;ud(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return gd;let s=o.pow(n,t),i=(t+pt)/fr;return function(c,l){if(c.is0(l))return l;if(ud(c,l)!==1)throw new Error("Cannot find square root");let u=e,f=c.mul(c.ONE,s),d=c.pow(l,t),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===u)throw new Error("Cannot find square root");let x=pt<<BigInt(u-p-1),g=c.pow(f,x);u=p,f=c.sqr(g),d=c.mul(d,f),h=c.mul(h,g)}return h}}function jg(r){return r%dd===fd?gd:r%pd===hd?Wg:r%md===Hg?Gg(r):yd(r)}var Pe=(r,t)=>(lt(r,t)&pt)===pt,Xg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Pc(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},e=Xg.reduce((n,o)=>(n[o]="function",n),t);return Ze(r,e),r}function Zg(r,t,e){if(e<Lt)throw new Error("invalid exponent, negatives unsupported");if(e===Lt)return r.ONE;if(e===pt)return t;let n=r.ONE,o=t;for(;e>Lt;)e&pt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=pt;return n}function eo(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function ud(r,t){let e=(r.ORDER-pt)/fr,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function vs(r,t){t!==void 0&&jn(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function $t(r,t,e=!1,n={}){if(r<=Lt)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||e)throw new Error("cannot specify opts in two arguments");let d=t;d.BITS&&(o=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(e=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:l}=vs(r,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,f=Object.freeze({ORDER:r,isLE:e,BITS:c,BYTES:l,MASK:Xe(c),ZERO:Lt,ONE:pt,allowedLengths:a,create:d=>lt(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Lt<=d&&d<r},is0:d=>d===Lt,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&pt)===pt,neg:d=>lt(-d,r),eql:(d,h)=>d===h,sqr:d=>lt(d*d,r),add:(d,h)=>lt(d+h,r),sub:(d,h)=>lt(d-h,r),mul:(d,h)=>lt(d*h,r),pow:(d,h)=>Zg(f,d,h),div:(d,h)=>lt(d*ld(h,r),r),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>ld(d,r),sqrt:s||(d=>(u||(u=jg(r)),u(f,d))),toBytes:d=>e?Ac(d,l):xs(d,l),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let m=new Uint8Array(l);m.set(d,e?0:m.length-d.length),d=m}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let p=e?Te(d):Qr(d);if(i&&(p=lt(p,r)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>eo(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function bd(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Dc(r){let t=bd(r);return t+Math.ceil(t/2)}function Lc(r,t,e=!1){let n=r.length,o=bd(t),s=Dc(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Te(r):Qr(r),a=lt(i,t-pt)+pt;return e?Ac(a,o):xs(a,o)}var tn=BigInt(0),dr=BigInt(1);function ro(r,t){let e=t.negate();return r?e:t}function De(r,t){let e=eo(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function vd(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Rc(r,t){vd(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=Xe(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function wd(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=dr);let l=t*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}function Yg(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function Qg(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Oc=new WeakMap,_d=new WeakMap;function kc(r){return _d.get(r)||1}function xd(r){if(r!==tn)throw new Error("invalid wNAF")}var en=class{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>tn;)e&dr&&(n=n.add(o)),o=o.double(),e>>=dr;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=Rc(e,this.bits),s=[],i=t,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(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Rc(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=wd(n,a,i);n=c,u?s=s.add(ro(d,e[h])):o=o.add(ro(f,e[l]))}return xd(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=Rc(t,this.bits);for(let i=0;i<s.windows&&n!==tn;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=wd(n,i,s);if(n=a,!l){let f=e[c];o=o.add(u?f.negate():f)}}return xd(n),o}getPrecomputes(t,e,n){let o=Oc.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),Oc.set(e,o))),o}cached(t,e,n){let o=kc(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=kc(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){vd(e,this.bits),_d.set(t,e),Oc.delete(t)}hasCache(t){return kc(t)!==1}};function Sd(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>tn||n>tn;)e&dr&&(s=s.add(o)),n&dr&&(i=i.add(o)),o=o.double(),e>>=dr,n>>=dr;return{p1:s,p2:i}}function rn(r,t,e,n){Yg(e,r),Qg(n,t);let o=e.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=Es(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Xe(c),u=new Array(Number(l)+1).fill(i),f=Math.floor((t.BITS-1)/c)*c,d=i;for(let h=f;h>=0;h-=c){u.fill(i);for(let m=0;m<s;m++){let x=n[m],g=Number(x>>BigInt(h)&l);u[g]=u[g].add(e[m])}let p=i;for(let m=u.length-1,x=i;m>0;m--)x=x.add(u[m]),p=p.add(x);if(d=d.add(p),h!==0)for(let m=0;m<c;m++)d=d.double()}return d}function Ed(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Pc(t),t}else return $t(r,{isLE:e})}function _s(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>tn))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ed(t.p,e.Fp,n),s=Ed(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}var Ye=BigInt(0),mt=BigInt(1),Mc=BigInt(2),Jg=BigInt(8);function ty(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function ey(r,t={}){let e=_s("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;Ze(t,{},{uvRatio:"function"});let a=Mc<<BigInt(o.BYTES*8)-mt,c=x=>n.create(x),l=t.uvRatio||((x,g)=>{try{return{isValid:!0,value:n.sqrt(n.div(x,g))}}catch{return{isValid:!1,value:Ye}}});if(!ty(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(x,g,_=!1){let w=_?mt:Ye;return to("coordinate "+x,g,w,a),g}function f(x){if(!(x instanceof p))throw new Error("ExtendedPoint expected")}let d=Jr((x,g)=>{let{X:_,Y:w,Z:A}=x,R=x.is0();g==null&&(g=R?Jg:n.inv(A));let K=c(_*g),V=c(w*g),M=n.mul(A,g);if(R)return{x:Ye,y:mt};if(M!==mt)throw new Error("invZ was invalid");return{x:K,y:V}}),h=Jr(x=>{let{a:g,d:_}=s;if(x.is0())throw new Error("bad point: ZERO");let{X:w,Y:A,Z:R,T:K}=x,V=c(w*w),M=c(A*A),v=c(R*R),D=c(v*v),F=c(V*g),L=c(v*c(F+M)),E=c(D+c(_*c(V*M)));if(L!==E)throw new Error("bad point: equation left != right (1)");let y=c(w*A),b=c(R*K);if(y!==b)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(g,_,w,A){this.X=u("x",g),this.Y=u("y",_),this.Z=u("z",w,!0),this.T=u("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof p)throw new Error("extended point not allowed");let{x:_,y:w}=g||{};return u("x",_),u("y",w),new p(_,w,mt,c(_*w))}static fromBytes(g,_=!1){let w=n.BYTES,{a:A,d:R}=s;g=Cc(zt(g,w,"point")),Ie(_,"zip215");let K=Cc(g),V=g[w-1];K[w-1]=V&-129;let M=Te(K),v=_?a:n.ORDER;to("point.y",M,Ye,v);let D=c(M*M),F=c(D-mt),L=c(R*D-A),{isValid:E,value:y}=l(F,L);if(!E)throw new Error("bad point: invalid y coordinate");let b=(y&mt)===mt,S=(V&128)!==0;if(!_&&y===Ye&&S)throw new Error("bad point: x=0 and x_0=1");return S!==b&&(y=c(-y)),p.fromAffine({x:y,y:M})}static fromHex(g,_=!1){return p.fromBytes(Q("point",g),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,_=!0){return m.createCache(this,g),_||this.multiply(Mc),this}assertValidity(){h(this)}equals(g){f(g);let{X:_,Y:w,Z:A}=this,{X:R,Y:K,Z:V}=g,M=c(_*V),v=c(R*A),D=c(w*V),F=c(K*A);return M===v&&D===F}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:g}=s,{X:_,Y:w,Z:A}=this,R=c(_*_),K=c(w*w),V=c(Mc*c(A*A)),M=c(g*R),v=_+w,D=c(c(v*v)-R-K),F=M+K,L=F-V,E=M-K,y=c(D*L),b=c(F*E),S=c(D*E),I=c(L*F);return new p(y,b,I,S)}add(g){f(g);let{a:_,d:w}=s,{X:A,Y:R,Z:K,T:V}=this,{X:M,Y:v,Z:D,T:F}=g,L=c(A*M),E=c(R*v),y=c(V*w*F),b=c(K*D),S=c((A+R)*(M+v)-L-E),I=b-y,O=b+y,T=c(E-_*L),P=c(S*I),B=c(O*T),q=c(S*T),ot=c(I*O);return new p(P,B,ot,q)}subtract(g){return this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:w}=m.cached(this,g,A=>De(p,A));return De(p,[_,w])[0]}multiplyUnsafe(g,_=p.ZERO){if(!o.isValid(g))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return g===Ye?p.ZERO:this.is0()||g===mt?this:m.unsafe(this,g,w=>De(p,w),_)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(g){return d(this,g)}clearCofactor(){return i===mt?this:this.multiplyUnsafe(i)}toBytes(){let{x:g,y:_}=this.toAffine(),w=n.toBytes(_);return w[w.length-1]|=g&mt?128:0,w}toHex(){return Yt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(g){return De(p,g)}static msm(g,_){return rn(p,o,g,_)}_setWindowSize(g){this.precompute(g)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,mt,c(s.Gx*s.Gy)),p.ZERO=new p(Ye,mt,mt,Ye),p.Fp=n,p.Fn=o;let m=new en(p,o.BITS);return p.BASE.precompute(8),p}var Ss=class{constructor(t){this.ep=t}static fromBytes(t){Ic()}static fromHex(t){Ic()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return Yt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}};function ry(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');Ze(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:s,Fn:i}=r,a=e.randomBytes||He,c=e.adjustScalarBytes||(v=>v),l=e.domain||((v,D,F)=>{if(Ie(F,"phflag"),D.length||F)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(Te(v))}function f(v){let D=w.secretKey;v=Q("private key",v,D);let F=Q("hashed private key",t(v),2*D),L=c(F.slice(0,D)),E=F.slice(D,2*D),y=u(L);return{head:L,prefix:E,scalar:y}}function d(v){let{head:D,prefix:F,scalar:L}=f(v),E=o.multiply(L),y=E.toBytes();return{head:D,prefix:F,scalar:L,point:E,pointBytes:y}}function h(v){return d(v).pointBytes}function p(v=Uint8Array.of(),...D){let F=Dt(...D);return u(t(l(F,Q("context",v),!!n)))}function m(v,D,F={}){v=Q("message",v),n&&(v=n(v));let{prefix:L,scalar:E,pointBytes:y}=d(D),b=p(F.context,L,v),S=o.multiply(b).toBytes(),I=p(F.context,S,y,v),O=i.create(b+I*E);if(!i.isValid(O))throw new Error("sign failed: invalid s");let T=Dt(S,i.toBytes(O));return zt(T,w.signature,"result")}let x={zip215:!0};function g(v,D,F,L=x){let{context:E,zip215:y}=L,b=w.signature;v=Q("signature",v,b),D=Q("message",D),F=Q("publicKey",F,w.publicKey),y!==void 0&&Ie(y,"zip215"),n&&(D=n(D));let S=b/2,I=v.subarray(0,S),O=Te(v.subarray(S,b)),T,P,B;try{T=r.fromBytes(F,y),P=r.fromBytes(I,y),B=o.multiplyUnsafe(O)}catch{return!1}if(!y&&T.isSmallOrder())return!1;let q=p(E,P.toBytes(),T.toBytes(),D);return P.add(T.multiplyUnsafe(q)).subtract(B).clearCofactor().is0()}let _=s.BYTES,w={secretKey:_,publicKey:_,signature:2*_,seed:_};function A(v=a(w.seed)){return zt(v,w.seed,"seed")}function R(v){let D=M.randomSecretKey(v);return{secretKey:D,publicKey:h(D)}}function K(v){return Se(v)&&v.length===i.BYTES}function V(v,D){try{return!!r.fromBytes(v,D)}catch{return!1}}let M={getExtendedPublicKey:d,randomSecretKey:A,isValidSecretKey:K,isValidPublicKey:V,toMontgomery(v){let{y:D}=r.fromBytes(v),F=w.publicKey,L=F===32;if(!L&&F!==57)throw new Error("only defined for 25519 and 448");let E=L?s.div(mt+D,mt-D):s.div(D-mt,D+mt);return s.toBytes(E)},toMontgomeryPriv(v){let D=w.secretKey;zt(v,D);let F=t(v.subarray(0,D));return c(F).subarray(0,D)},randomPrivateKey:A,precompute(v=8,D=r.BASE){return D.precompute(v,!1)}};return Object.freeze({keygen:R,getPublicKey:h,sign:m,verify:g,utils:M,Point:r,lengths:w})}function ny(r){let t={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=$t(t.n,r.nBitLength,!0),o={Fp:e,Fn:n,uvRatio:r.uvRatio},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:t,curveOpts:o,hash:r.hash,eddsaOpts:s}}function oy(r,t){let e=t.Point;return Object.assign({},t,{ExtendedPoint:e,CURVE:r,nBitLength:e.Fn.BITS,nByteLength:e.Fn.BYTES})}function Ad(r){let{CURVE:t,curveOpts:e,hash:n,eddsaOpts:o}=ny(r),s=ey(t,e),i=ry(s,n,o);return oy(r,i)}var sy=BigInt(0),Le=BigInt(1),Cd=BigInt(2),B1=BigInt(3),iy=BigInt(5),ay=BigInt(8),nn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),no={p:nn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ay,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function cy(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=nn,a=r*r%s*r%s,c=et(a,Cd,s)*a%s,l=et(c,Le,s)*r%s,u=et(l,iy,s)*l%s,f=et(u,t,s)*u%s,d=et(f,e,s)*f%s,h=et(d,n,s)*d%s,p=et(h,o,s)*h%s,m=et(p,o,s)*h%s,x=et(m,t,s)*u%s;return{pow_p_5_8:et(x,Cd,s)*r%s,b2:a}}function ly(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Nc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Fc(r,t){let e=nn,n=lt(t*t*t,e),o=lt(n*n*t,e),s=cy(r*o).pow_p_5_8,i=lt(r*n*s,e),a=lt(t*i*i,e),c=i,l=lt(i*Nc,e),u=a===r,f=a===lt(-r,e),d=a===lt(-r*Nc,e);return u&&(i=c),(f||d)&&(i=l),Pe(i,e)&&(i=lt(-i,e)),{isValid:u||f,value:i}}var Qe=$t(no.p,{isLE:!0}),uy=$t(no.n,{isLE:!0}),fy={...no,Fp:Qe,hash:od,adjustScalarBytes:ly,uvRatio:Fc},Qt=Ad(fy);var Bc=Nc,dy=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),hy=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),py=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),my=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Id=r=>Fc(Le,r),gy=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Uc=r=>Qt.Point.Fp.create(Te(r)&gy);function Td(r){let{d:t}=no,e=nn,n=g=>Qe.create(g),o=n(Bc*r*r),s=n((o+Le)*py),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:l}=Fc(s,a),u=n(l*r);Pe(u,e)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-Le)*my-a),d=l*l,h=n((l+l)*a),p=n(f*dy),m=n(Le-d),x=n(Le+d);return new Qt.Point(n(h*x),n(m*p),n(p*x),n(h*m))}function yy(r){Ut(r,64);let t=Uc(r.subarray(0,32)),e=Td(t),n=Uc(r.subarray(32,64)),o=Td(n);return new Re(e.add(o))}var Re=class r extends Ss{constructor(t){super(t)}static fromAffine(t){return new r(Qt.Point.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static hashToCurve(t){return yy(Q("ristrettoHash",t,64))}static fromBytes(t){Ut(t,32);let{a:e,d:n}=no,o=nn,s=A=>Qe.create(A),i=Uc(t);if(!id(Qe.toBytes(i),t)||Pe(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Le+e*a),l=s(Le-e*a),u=s(c*c),f=s(l*l),d=s(e*n*u-f),{isValid:h,value:p}=Id(s(d*f)),m=s(p*l),x=s(p*m*d),g=s((i+i)*m);Pe(g,o)&&(g=s(-g));let _=s(c*x),w=s(g*_);if(!h||Pe(w,o)||_===sy)throw new Error("invalid ristretto255 encoding 2");return new r(new Qt.Point(g,_,Le,w))}static fromHex(t){return r.fromBytes(Q("ristrettoHex",t,32))}static msm(t,e){return rn(r,Qt.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=nn,i=x=>Qe.create(x),a=i(i(n+e)*i(n-e)),c=i(t*e),l=i(c*c),{value:u}=Id(i(a*l)),f=i(u*a),d=i(u*c),h=i(f*d*o),p;if(Pe(o*h,s)){let x=i(e*Bc),g=i(t*Bc);t=x,e=g,p=i(f*hy)}else p=d;Pe(t*h,s)&&(e=i(-e));let m=i((n-e)*p);return Pe(m,s)&&(m=i(-m)),Qe.toBytes(m)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=l=>Qe.create(l),a=i(e*s)===i(n*o),c=i(n*s)===i(e*o);return a||c}is0(){return this.equals(r.ZERO)}};Re.BASE=new Re(Qt.Point.BASE);Re.ZERO=new Re(Qt.Point.ZERO);Re.Fp=Qe;Re.Fn=uy;var oo=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},so=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},As=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Pd={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new As("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Ft=Pd;var Cs=32,io=64,Kc=32;var on,Dd=(async()=>{try{return await Ft.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Ld(){let r=Qt.utils.randomPrivateKey(),t=Qt.getPublicKey(r);return{privateKey:vy(r,t),publicKey:t}}async function by(r,t){let e;r.length===io?e=r.subarray(0,32):e=r;let n={crv:"Ed25519",kty:"OKP",x:U(r.subarray(32),"base64url"),d:U(e,"base64url"),ext:!0,key_ops:["sign"]},o=await Ft.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Ft.get().subtle.sign({name:"Ed25519"},o,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(s,0,s.byteLength)}function wy(r,t){let e=r.subarray(0,Kc);return Qt.sign(t instanceof Uint8Array?t:t.subarray(),e)}async function Rd(r,t){return on==null&&(on=await Dd),on?by(r,t):wy(r,t)}async function xy(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Ft.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ft.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Ey(r,t,e){return Qt.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Od(r,t,e){return on==null&&(on=await Dd),on?xy(r,t,e):Ey(r,t,e)}function vy(r,t){let e=new Uint8Array(io);for(let n=0;n<Kc;n++)e[n]=r[n],e[Kc+n]=t[n];return e}function sn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var ao=class{type="Ed25519";raw;constructor(t){this.raw=Ts(t,Cs)}toMultihash(){return oe.digest(Zt(this))}toCID(){return nt.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Od(this.raw,e,t);return sn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},Is=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=Ts(t,io),this.publicKey=new ao(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}sign(t,e){e?.signal?.throwIfAborted();let n=Rd(this.raw,t);return sn(n)?n.then(o=>(e?.signal?.throwIfAborted(),o)):(e?.signal?.throwIfAborted(),n)}};function qc(r){return r=Ts(r,Cs),new ao(r)}async function Md(){let{privateKey:r,publicKey:t}=Ld();return new Is(r,t)}function Ts(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new k(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var _y=Math.pow(2,7),Sy=Math.pow(2,14),Ay=Math.pow(2,21),Vc=Math.pow(2,28),zc=Math.pow(2,35),$c=Math.pow(2,42),Hc=Math.pow(2,49),j=128,St=127;function gt(r){if(r<_y)return 1;if(r<Sy)return 2;if(r<Ay)return 3;if(r<Vc)return 4;if(r<zc)return 5;if(r<$c)return 6;if(r<Hc)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,t,e=0){switch(gt(r)){case 8:t[e++]=r&255|j,r/=128;case 7:t[e++]=r&255|j,r/=128;case 6:t[e++]=r&255|j,r/=128;case 5:t[e++]=r&255|j,r/=128;case 4:t[e++]=r&255|j,r>>>=7;case 3:t[e++]=r&255|j,r>>>=7;case 2:t[e++]=r&255|j,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Cy(r,t,e=0){switch(gt(r)){case 8:t.set(e++,r&255|j),r/=128;case 7:t.set(e++,r&255|j),r/=128;case 6:t.set(e++,r&255|j),r/=128;case 5:t.set(e++,r&255|j),r/=128;case 4:t.set(e++,r&255|j),r>>>=7;case 3:t.set(e++,r&255|j),r>>>=7;case 2:t.set(e++,r&255|j),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Wc(r,t){let e=r[t],n=0;if(n+=e&St,e<j||(e=r[t+1],n+=(e&St)<<7,e<j)||(e=r[t+2],n+=(e&St)<<14,e<j)||(e=r[t+3],n+=(e&St)<<21,e<j)||(e=r[t+4],n+=(e&St)*Vc,e<j)||(e=r[t+5],n+=(e&St)*zc,e<j)||(e=r[t+6],n+=(e&St)*$c,e<j)||(e=r[t+7],n+=(e&St)*Hc,e<j))return n;throw new RangeError("Could not decode varint")}function Iy(r,t){let e=r.get(t),n=0;if(n+=e&St,e<j||(e=r.get(t+1),n+=(e&St)<<7,e<j)||(e=r.get(t+2),n+=(e&St)<<14,e<j)||(e=r.get(t+3),n+=(e&St)<<21,e<j)||(e=r.get(t+4),n+=(e&St)*Vc,e<j)||(e=r.get(t+5),n+=(e&St)*zc,e<j)||(e=r.get(t+6),n+=(e&St)*$c,e<j)||(e=r.get(t+7),n+=(e&St)*Hc,e<j))return n;throw new RangeError("Could not decode varint")}function pe(r,t,e=0){return t==null&&(t=_t(gt(r))),t instanceof Uint8Array?an(r,t,e):Cy(r,t,e)}function hr(r,t=0){return r instanceof Uint8Array?Wc(r,t):Iy(r,t)}var Gc=new Float32Array([-0]),Je=new Uint8Array(Gc.buffer);function Nd(r,t,e){Gc[0]=r,t[e]=Je[0],t[e+1]=Je[1],t[e+2]=Je[2],t[e+3]=Je[3]}function Bd(r,t){return Je[0]=r[t],Je[1]=r[t+1],Je[2]=r[t+2],Je[3]=r[t+3],Gc[0]}var jc=new Float64Array([-0]),At=new Uint8Array(jc.buffer);function Ud(r,t,e){jc[0]=r,t[e]=At[0],t[e+1]=At[1],t[e+2]=At[2],t[e+3]=At[3],t[e+4]=At[4],t[e+5]=At[5],t[e+6]=At[6],t[e+7]=At[7]}function Fd(r,t){return At[0]=r[t],At[1]=r[t+1],At[2]=r[t+2],At[3]=r[t+3],At[4]=r[t+4],At[5]=r[t+5],At[6]=r[t+6],At[7]=r[t+7],jc[0]}var Ty=BigInt(Number.MAX_SAFE_INTEGER),Py=BigInt(Number.MIN_SAFE_INTEGER),Ht=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return pr;if(t<Ty&&t>Py)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Kd&&(o=0n,++n>Kd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return pr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):pr}},pr=new Ht(0,0);pr.toBigInt=function(){return 0n};pr.zzEncode=pr.zzDecode=function(){return this};pr.length=function(){return 1};var Kd=4294967296n;function qd(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Vd(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Xc(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function ce(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Ps(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Zc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,ce(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ce(this,4);return Ps(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ce(this,4);return Ps(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ce(this,4);let t=Bd(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ce(this,4);let t=Fd(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw ce(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Vd(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ce(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ce(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Ht(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ce(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw ce(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ce(this,8);let t=Ps(this.buf,this.pos+=4),e=Ps(this.buf,this.pos+=4);return new Ht(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Wc(this.buf,this.pos);return this.pos+=gt(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Yc(r){return new Zc(r instanceof Uint8Array?r:r.subarray())}function Rt(r,t,e){let n=Yc(r);return t.decode(n,void 0,e)}function Qc(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return _t(i);o+i>t&&(n=_t(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var mr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Jc(){}var el=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Dy=Qc();function Ly(r){return globalThis.Buffer!=null?_t(r):Dy(r)}var lo=class{len;head;tail;states;constructor(){this.len=0,this.head=new mr(Jc,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new mr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new rl((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Ds,10,Ht.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Ht.fromBigInt(t);return this._push(Ds,e.length(),e)}uint64Number(t){return this._push(an,gt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Ht.fromBigInt(t).zzEncode();return this._push(Ds,e.length(),e)}sint64Number(t){let e=Ht.fromNumber(t).zzEncode();return this._push(Ds,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(tl,1,t?1:0)}fixed32(t){return this._push(co,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Ht.fromBigInt(t);return this._push(co,4,e.lo)._push(co,4,e.hi)}fixed64Number(t){let e=Ht.fromNumber(t);return this._push(co,4,e.lo)._push(co,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Nd,4,t)}double(t){return this._push(Ud,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(tl,1,0):this.uint32(e)._push(Oy,e,t)}string(t){let e=qd(t);return e!==0?this.uint32(e)._push(Xc,e,t):this._push(tl,1,0)}fork(){return this.states=new el(this),this.head=this.tail=new mr(Jc,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 mr(Jc,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Ly(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function tl(r,t,e){t[e]=r&255}function Ry(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var rl=class extends mr{next;constructor(t,e){super(Ry,t,e),this.next=void 0}};function Ds(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function co(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Oy(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(lo.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(ky,t,r),this},lo.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(My,t,r),this});function ky(r,t,e){t.set(r,e)}function My(r,t,e){r.length<40?Xc(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(C(r),e)}function nl(){return new lo}function Ot(r,t){let e=nl();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var ln;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(ln||(ln={}));function Ls(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function ol(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Ls("enum",ln.VARINT,e,n)}function kt(r,t){return Ls("message",ln.LENGTH_DELIMITED,r,t)}var gr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},uo=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ft;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ft||(ft={}));var sl;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(sl||(sl={}));(function(r){r.codec=()=>ol(sl)})(ft||(ft={}));var me;(function(r){let t;r.codec=()=>(t==null&&(t=kt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ft.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ot(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(me||(me={}));var il;(function(r){let t;r.codec=()=>(t==null&&(t=kt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ft.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ot(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(il||(il={}));function un(r){if(isNaN(r)||r<=0)throw new k("random bytes length must be a Number bigger than 0");return He(r)}var ho={};Bt(ho,{MAX_RSA_KEY_SIZE:()=>al,generateRSAKeyPair:()=>gl,jwkToJWKKeyPair:()=>jd,jwkToPkcs1:()=>Fy,jwkToPkix:()=>fl,jwkToRSAPrivateKey:()=>ml,pkcs1MessageToJwk:()=>ll,pkcs1MessageToRSAPrivateKey:()=>dl,pkcs1ToJwk:()=>Uy,pkcs1ToRSAPrivateKey:()=>Gd,pkixMessageToJwk:()=>ul,pkixMessageToRSAPublicKey:()=>pl,pkixToJwk:()=>Ky,pkixToRSAPublicKey:()=>hl});var Rs=ws;var fn=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=ho.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return nt.createV1(114,this._multihash)}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}verify(t,e,n){return Wd(this.jwk,e,t,n)}},fo=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=ho.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}sign(t,e){return Hd(this.jwk,t,e)}};var al=8192,cl=18,Ny=1062,By=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Uy(r){let t=ve(r);return ll(t)}function ll(r){return{n:U(r[1],"base64url"),e:U(r[2],"base64url"),d:U(r[3],"base64url"),p:U(r[4],"base64url"),q:U(r[5],"base64url"),dp:U(r[6],"base64url"),dq:U(r[7],"base64url"),qi:U(r[8],"base64url"),kty:"RSA"}}function Fy(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new k("JWK was missing components");return ie([Pt(Uint8Array.from([0])),Pt(C(r.n,"base64url")),Pt(C(r.e,"base64url")),Pt(C(r.d,"base64url")),Pt(C(r.p,"base64url")),Pt(C(r.q,"base64url")),Pt(C(r.dp,"base64url")),Pt(C(r.dq,"base64url")),Pt(C(r.qi,"base64url"))]).subarray()}function Ky(r){let t=ve(r,{offset:0});return ul(t)}function ul(r){let t=ve(r[1],{offset:0});return{kty:"RSA",n:U(t[0],"base64url"),e:U(t[1],"base64url")}}function fl(r){if(r.n==null||r.e==null)throw new k("JWK was missing components");return ie([By,Gn(ie([Pt(C(r.n,"base64url")),Pt(C(r.e,"base64url"))]))]).subarray()}function Gd(r){let t=ve(r);return dl(t)}function dl(r){let t=ll(r);return ml(t)}function hl(r,t){if(r.byteLength>=Ny)throw new qr("Key size is too large");let e=ve(r,{offset:0});return pl(e,r,t)}function pl(r,t,e){let n=ul(r);if(e==null){let o=Rs(me.encode({Type:ft.RSA,Data:t}));e=ne(cl,o)}return new fn(n,e)}function ml(r){if(Zd(r)>al)throw new k("Key size is too large");let t=jd(r),e=Rs(me.encode({Type:ft.RSA,Data:fl(t.publicKey)})),n=ne(cl,e);return new fo(t.privateKey,new fn(t.publicKey,n))}async function gl(r){if(r>al)throw new k("Key size is too large");let t=await Xd(r),e=Rs(me.encode({Type:ft.RSA,Data:fl(t.publicKey)})),n=ne(cl,e);return new fo(t.privateKey,new fn(t.publicKey,n))}function jd(r){if(r==null)throw new k("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Xd(r,t){let e=await Ft.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await qy(e,t);return{privateKey:n[0],publicKey:n[1]}}async function Hd(r,t,e){let n=await Ft.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await Ft.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Wd(r,t,e,n){let o=await Ft.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ft.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),s}async function qy(r,t){if(r.privateKey==null||r.publicKey==null)throw new k("Private and public key are required");let e=await Promise.all([Ft.get().subtle.exportKey("jwk",r.privateKey),Ft.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function Zd(r){if(r.kty!=="RSA")throw new k("invalid key type");if(r.n==null)throw new k("invalid key modulus");return C(r.n,"base64url").length*8}var Os=class extends Zr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,ms(t);let n=Xn(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),Ae(s)}update(t){return Yr(this),this.iHash.update(t),this}digestInto(t){Yr(this),Ut(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},yl=(r,t,e)=>new Os(r,t).update(e).digest();yl.create=(r,t)=>new Os(r,t);var Yd=(r,t)=>(r+(r>=0?t:-t)/Qd)/t;function Vy(r,t,e){let[[n,o],[s,i]]=t,a=Yd(i*r,e),c=Yd(-o*r,e),l=r-a*n-c*s,u=-a*o-c*i,f=l<ke,d=u<ke;f&&(l=-l),d&&(u=-u);let h=Xe(Math.ceil(Es(e)/2))+hn;if(l<ke||l>=h||u<ke||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}function wl(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function bl(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Ie(e.lowS,"lowS"),Ie(e.prehash,"prehash"),e.format!==void 0&&wl(e.format),e}var xl=class extends Error{constructor(t=""){super(t)}},Oe={Err:xl,_tlv:{encode:(r,t)=>{let{Err:e}=Oe;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Jn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Jn(o.length/2|128):"";return Jn(r)+s+o+t},decode(r,t){let{Err:e}=Oe,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Oe;if(r<ke)throw new t("integer: negative integers are not allowed");let e=Jn(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=Oe;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Qr(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Oe,o=Q("signature",r),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Oe,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},ke=BigInt(0),hn=BigInt(1),Qd=BigInt(2),ks=BigInt(3),zy=BigInt(4);function dn(r,t){let{BYTES:e}=r,n;if(typeof t=="bigint")n=t;else{let o=Q("private key",t);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${e}, got ${typeof t}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function $y(r,t={}){let e=_s("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;Ze(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;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=th(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(L,E,y){let{x:b,y:S}=E.toAffine(),I=n.toBytes(b);if(Ie(y,"isCompressed"),y){u();let O=!n.isOdd(S);return Dt(Jd(O),I)}else return Dt(Uint8Array.of(4),I,n.toBytes(S))}function d(L){zt(L,void 0,"Point");let{publicKey:E,publicKeyUncompressed:y}=l,b=L.length,S=L[0],I=L.subarray(1);if(b===E&&(S===2||S===3)){let O=n.fromBytes(I);if(!n.isValid(O))throw new Error("bad point: is not on curve, wrong x");let T=m(O),P;try{P=n.sqrt(T)}catch(ot){let J=ot instanceof Error?": "+ot.message:"";throw new Error("bad point: is not on curve, sqrt error"+J)}u();let B=n.isOdd(P);return(S&1)===1!==B&&(P=n.neg(P)),{x:O,y:P}}else if(b===y&&S===4){let O=n.BYTES,T=n.fromBytes(I.subarray(0,O)),P=n.fromBytes(I.subarray(O,O*2));if(!x(T,P))throw new Error("bad point: is not on curve");return{x:T,y:P}}else throw new Error(`bad point: got length ${b}, expected compressed=${E} or uncompressed=${y}`)}let h=t.toBytes||f,p=t.fromBytes||d;function m(L){let E=n.sqr(L),y=n.mul(E,L);return n.add(n.add(y,n.mul(L,s.a)),s.b)}function x(L,E){let y=n.sqr(E),b=m(L);return n.eql(y,b)}if(!x(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let g=n.mul(n.pow(s.a,ks),zy),_=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(g,_)))throw new Error("bad curve params: a or b");function w(L,E,y=!1){if(!n.isValid(E)||y&&n.is0(E))throw new Error(`bad point coordinate ${L}`);return E}function A(L){if(!(L instanceof v))throw new Error("ProjectivePoint expected")}function R(L){if(!c||!c.basises)throw new Error("no endo");return Vy(L,c.basises,o.ORDER)}let K=Jr((L,E)=>{let{X:y,Y:b,Z:S}=L;if(n.eql(S,n.ONE))return{x:y,y:b};let I=L.is0();E==null&&(E=I?n.ONE:n.inv(S));let O=n.mul(y,E),T=n.mul(b,E),P=n.mul(S,E);if(I)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:O,y:T}}),V=Jr(L=>{if(L.is0()){if(t.allowInfinityPoint&&!n.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:E,y}=L.toAffine();if(!n.isValid(E)||!n.isValid(y))throw new Error("bad point: x or y not field elements");if(!x(E,y))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(L,E,y,b,S){return y=new v(n.mul(y.X,L),y.Y,y.Z),E=ro(b,E),y=ro(S,y),E.add(y)}class v{constructor(E,y,b){this.X=w("x",E),this.Y=w("y",y,!0),this.Z=w("z",b),Object.freeze(this)}static CURVE(){return s}static fromAffine(E){let{x:y,y:b}=E||{};if(!E||!n.isValid(y)||!n.isValid(b))throw new Error("invalid affine point");if(E instanceof v)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(b)?v.ZERO:new v(y,b,n.ONE)}static fromBytes(E){let y=v.fromAffine(p(zt(E,void 0,"point")));return y.assertValidity(),y}static fromHex(E){return v.fromBytes(Q("pointHex",E))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=8,y=!0){return F.createCache(this,E),y||this.multiply(ks),this}assertValidity(){V(this)}hasEvenY(){let{y:E}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(E)}equals(E){A(E);let{X:y,Y:b,Z:S}=this,{X:I,Y:O,Z:T}=E,P=n.eql(n.mul(y,T),n.mul(I,S)),B=n.eql(n.mul(b,T),n.mul(O,S));return P&&B}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:E,b:y}=s,b=n.mul(y,ks),{X:S,Y:I,Z:O}=this,T=n.ZERO,P=n.ZERO,B=n.ZERO,q=n.mul(S,S),ot=n.mul(I,I),J=n.mul(O,O),H=n.mul(S,I);return H=n.add(H,H),B=n.mul(S,O),B=n.add(B,B),T=n.mul(E,B),P=n.mul(b,J),P=n.add(T,P),T=n.sub(ot,P),P=n.add(ot,P),P=n.mul(T,P),T=n.mul(H,T),B=n.mul(b,B),J=n.mul(E,J),H=n.sub(q,J),H=n.mul(E,H),H=n.add(H,B),B=n.add(q,q),q=n.add(B,q),q=n.add(q,J),q=n.mul(q,H),P=n.add(P,q),J=n.mul(I,O),J=n.add(J,J),q=n.mul(J,H),T=n.sub(T,q),B=n.mul(J,ot),B=n.add(B,B),B=n.add(B,B),new v(T,P,B)}add(E){A(E);let{X:y,Y:b,Z:S}=this,{X:I,Y:O,Z:T}=E,P=n.ZERO,B=n.ZERO,q=n.ZERO,ot=s.a,J=n.mul(s.b,ks),H=n.mul(y,I),st=n.mul(b,O),ht=n.mul(S,T),Nt=n.add(y,b),it=n.add(I,O);Nt=n.mul(Nt,it),it=n.add(H,st),Nt=n.sub(Nt,it),it=n.add(y,S);let vt=n.add(I,T);return it=n.mul(it,vt),vt=n.add(H,ht),it=n.sub(it,vt),vt=n.add(b,S),P=n.add(O,T),vt=n.mul(vt,P),P=n.add(st,ht),vt=n.sub(vt,P),q=n.mul(ot,it),P=n.mul(J,ht),q=n.add(P,q),P=n.sub(st,q),q=n.add(st,q),B=n.mul(P,q),st=n.add(H,H),st=n.add(st,H),ht=n.mul(ot,ht),it=n.mul(J,it),st=n.add(st,ht),ht=n.sub(H,ht),ht=n.mul(ot,ht),it=n.add(it,ht),H=n.mul(st,it),B=n.add(B,H),H=n.mul(vt,it),P=n.mul(Nt,P),P=n.sub(P,H),H=n.mul(Nt,st),q=n.mul(vt,q),q=n.add(q,H),new v(P,B,q)}subtract(E){return this.add(E.negate())}is0(){return this.equals(v.ZERO)}multiply(E){let{endo:y}=t;if(!o.isValidNot0(E))throw new Error("invalid scalar: out of range");let b,S,I=O=>F.cached(this,O,T=>De(v,T));if(y){let{k1neg:O,k1:T,k2neg:P,k2:B}=R(E),{p:q,f:ot}=I(T),{p:J,f:H}=I(B);S=ot.add(H),b=M(y.beta,q,J,O,P)}else{let{p:O,f:T}=I(E);b=O,S=T}return De(v,[b,S])[0]}multiplyUnsafe(E){let{endo:y}=t,b=this;if(!o.isValid(E))throw new Error("invalid scalar: out of range");if(E===ke||b.is0())return v.ZERO;if(E===hn)return b;if(F.hasCache(this))return this.multiply(E);if(y){let{k1neg:S,k1:I,k2neg:O,k2:T}=R(E),{p1:P,p2:B}=Sd(v,b,I,T);return M(y.beta,P,B,S,O)}else return F.unsafe(b,E)}multiplyAndAddUnsafe(E,y,b){let S=this.multiplyUnsafe(y).add(E.multiplyUnsafe(b));return S.is0()?void 0:S}toAffine(E){return K(this,E)}isTorsionFree(){let{isTorsionFree:E}=t;return i===hn?!0:E?E(v,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:E}=t;return i===hn?this:E?E(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(E=!0){return Ie(E,"isCompressed"),this.assertValidity(),h(v,this,E)}toHex(E=!0){return Yt(this.toBytes(E))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(E=!0){return this.toBytes(E)}_setWindowSize(E){this.precompute(E)}static normalizeZ(E){return De(v,E)}static msm(E,y){return rn(v,o,E,y)}static fromPrivateKey(E){return v.BASE.multiply(dn(o,E))}}v.BASE=new v(s.Gx,s.Gy,n.ONE),v.ZERO=new v(n.ZERO,n.ONE,n.ZERO),v.Fp=n,v.Fn=o;let D=o.BITS,F=new en(v,t.endo?Math.ceil(D/2):D);return v.BASE.precompute(8),v}function Jd(r){return Uint8Array.of(r?2:3)}function th(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Hy(r,t={}){let{Fn:e}=r,n=t.randomBytes||He,o=Object.assign(th(r.Fp,e),{seed:Dc(e.ORDER)});function s(h){try{return!!dn(e,h)}catch{return!1}}function i(h,p){let{publicKey:m,publicKeyUncompressed:x}=o;try{let g=h.length;return p===!0&&g!==m||p===!1&&g!==x?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return Lc(zt(h,o.seed,"seed"),e.ORDER)}function c(h,p=!0){return r.BASE.multiply(dn(e,h)).toBytes(p)}function l(h){let p=a(h);return{secretKey:p,publicKey:c(p)}}function u(h){if(typeof h=="bigint")return!1;if(h instanceof r)return!0;let{secretKey:p,publicKey:m,publicKeyUncompressed:x}=o;if(e.allowedLengths||p===m)return;let g=Q("key",h).length;return g===m||g===x}function f(h,p,m=!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 x=dn(e,h);return r.fromHex(p).multiply(x).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:l,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>dn(e,h),precompute(h=8,p=r.BASE){return p.precompute(h,!1)}},lengths:o})}function Wy(r,t,e={}){ms(t),Ze(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=e.randomBytes||He,o=e.hmac||((y,...b)=>yl(t,y,Dt(...b))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h}=Hy(r,e),p={prehash:!1,lowS:typeof e.lowS=="boolean"?e.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function x(y){let b=a>>hn;return y>b}function g(y,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return b}function _(y,b){wl(b);let S=h.signature,I=b==="compact"?S:b==="recovered"?S+1:void 0;return zt(y,I,`${b} signature`)}class w{constructor(b,S,I){this.r=g("r",b),this.s=g("s",S),I!=null&&(this.recovery=I),Object.freeze(this)}static fromBytes(b,S=m){_(b,S);let I;if(S==="der"){let{r:B,s:q}=Oe.toSig(zt(b));return new w(B,q)}S==="recovered"&&(I=b[0],S="compact",b=b.subarray(1));let O=i.BYTES,T=b.subarray(0,O),P=b.subarray(O,O*2);return new w(i.fromBytes(T),i.fromBytes(P),I)}static fromHex(b,S){return this.fromBytes(cr(b),S)}addRecoveryBit(b){return new w(this.r,this.s,b)}recoverPublicKey(b){let S=s.ORDER,{r:I,s:O,recovery:T}=this;if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");if(a*Qd<S&&T>1)throw new Error("recovery id is ambiguous for h>1 curve");let B=T===2||T===3?I+a:I;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");let q=s.toBytes(B),ot=r.fromBytes(Dt(Jd((T&1)===0),q)),J=i.inv(B),H=R(Q("msgHash",b)),st=i.create(-H*J),ht=i.create(O*J),Nt=r.BASE.multiplyUnsafe(st).add(ot.multiplyUnsafe(ht));if(Nt.is0())throw new Error("point at infinify");return Nt.assertValidity(),Nt}hasHighS(){return x(this.s)}toBytes(b=m){if(wl(b),b==="der")return cr(Oe.hexFromSig(this));let S=i.toBytes(this.r),I=i.toBytes(this.s);if(b==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Dt(Uint8Array.of(this.recovery),S,I)}return Dt(S,I)}toHex(b){return Yt(this.toBytes(b))}assertValidity(){}static fromCompact(b){return w.fromBytes(Q("sig",b),"compact")}static fromDER(b){return w.fromBytes(Q("sig",b),"der")}normalizeS(){return this.hasHighS()?new w(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Yt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Yt(this.toBytes("compact"))}}let A=e.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let S=Qr(b),I=b.length*8-c;return I>0?S>>BigInt(I):S},R=e.bits2int_modN||function(b){return i.create(A(b))},K=Xe(c);function V(y){return to("num < 2^"+c,y,ke,K),i.toBytes(y)}function M(y,b){return zt(y,void 0,"message"),b?zt(t(y),void 0,"prehashed message"):y}function v(y,b,S){if(["recovered","canonical"].some(st=>st in S))throw new Error("sign() legacy options not supported");let{lowS:I,prehash:O,extraEntropy:T}=bl(S,p);y=M(y,O);let P=R(y),B=dn(i,b),q=[V(B),V(P)];if(T!=null&&T!==!1){let st=T===!0?n(h.secretKey):T;q.push(Q("extraEntropy",st))}let ot=Dt(...q),J=P;function H(st){let ht=A(st);if(!i.isValidNot0(ht))return;let Nt=i.inv(ht),it=r.BASE.multiply(ht).toAffine(),vt=i.create(it.x);if(vt===ke)return;let Qo=i.create(Nt*i.create(J+vt*B));if(Qo===ke)return;let sf=(it.x===vt?0:2)|Number(it.y&hn),af=Qo;return I&&x(Qo)&&(af=i.neg(Qo),sf^=1),new w(vt,af,sf)}return{seed:ot,k2sig:H}}function D(y,b,S={}){y=Q("message",y);let{seed:I,k2sig:O}=v(y,b,S);return cd(t.outputLen,i.BYTES,o)(I,O)}function F(y){let b,S=typeof y=="string"||Se(y),I=!S&&y!==null&&typeof y=="object"&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!S&&!I)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(I)b=new w(y.r,y.s);else if(S){try{b=w.fromBytes(Q("sig",y),"der")}catch(O){if(!(O instanceof Oe.Err))throw O}if(!b)try{b=w.fromBytes(Q("sig",y),"compact")}catch{return!1}}return b||!1}function L(y,b,S,I={}){let{lowS:O,prehash:T,format:P}=bl(I,p);if(S=Q("publicKey",S),b=M(Q("message",b),T),"strict"in I)throw new Error("options.strict was renamed to lowS");let B=P===void 0?F(y):w.fromBytes(Q("sig",y),P);if(B===!1)return!1;try{let q=r.fromBytes(S);if(O&&B.hasHighS())return!1;let{r:ot,s:J}=B,H=R(b),st=i.inv(J),ht=i.create(H*st),Nt=i.create(ot*st),it=r.BASE.multiplyUnsafe(ht).add(q.multiplyUnsafe(Nt));return it.is0()?!1:i.create(it.x)===ot}catch{return!1}}function E(y,b,S={}){let{prehash:I}=bl(S,p);return b=M(b,I),w.fromBytes(y,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h,Point:r,sign:D,verify:L,recoverPublicKey:E,Signature:w,hash:t})}function Gy(r){let t={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},e=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=$t(t.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),s={Fp:e,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:t,curveOpts:s}}function jy(r){let{CURVE:t,curveOpts:e}=Gy(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:t,curveOpts:e,hash:r.hash,ecdsaOpts:n}}function Xy(r,t){let e=t.Point;return Object.assign({},t,{ProjectivePoint:e,CURVE:Object.assign({},r,vs(e.Fn.ORDER,e.Fn.BITS))})}function eh(r){let{CURVE:t,curveOpts:e,hash:n,ecdsaOpts:o}=jy(r),s=$y(t,e),i=Wy(s,n,o);return Xy(r,i)}function rh(r,t){let e=n=>eh({...r,hash:n});return{...e(t),create:e}}var vl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Zy={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var nh=BigInt(2);function Yy(r){let t=vl.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=et(u,e,t)*u%t,d=et(f,e,t)*u%t,h=et(d,nh,t)*l%t,p=et(h,o,t)*h%t,m=et(p,s,t)*p%t,x=et(m,a,t)*m%t,g=et(x,c,t)*x%t,_=et(g,a,t)*m%t,w=et(_,e,t)*u%t,A=et(w,i,t)*p%t,R=et(A,n,t)*l%t,K=et(R,nh,t);if(!El.eql(El.sqr(K),r))throw new Error("Cannot find square root");return K}var El=$t(vl.p,{sqrt:Yy}),le=rh({...vl,Fp:El,lowS:!0,endo:Zy},ws);function oh(r,t,e){let n=Xr.digest(t instanceof Uint8Array?t:t.subarray());if(sn(n))return n.then(({digest:o})=>(e?.signal?.throwIfAborted(),le.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new oo(String(o))});try{return le.sign(n.digest,r).toDERRawBytes()}catch(o){throw new oo(String(o))}}function sh(r,t,e,n){let o=Xr.digest(e instanceof Uint8Array?e:e.subarray());if(sn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),le.verify(t,s,r))).catch(s=>{throw s.name==="AbortError"?s:new so(String(s))});try{return n?.signal?.throwIfAborted(),le.verify(t,o.digest,r)}catch(s){throw new so(String(s))}}var po=class{type="secp256k1";raw;_key;constructor(t){this._key=ch(t),this.raw=ih(this._key)}toMultihash(){return oe.digest(Zt(this))}toCID(){return nt.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}verify(t,e,n){return sh(this._key,e,t,n)}},Ms=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=ah(t),this.publicKey=new po(e??lh(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}sign(t,e){return oh(this.raw,t,e)}};function _l(r){return new po(r)}async function uh(){let r=Qy();return new Ms(r)}function ih(r){return le.ProjectivePoint.fromHex(r).toRawBytes(!0)}function ah(r){try{return le.getPublicKey(r,!0),r}catch(t){throw new Nn(String(t))}}function ch(r){try{return le.ProjectivePoint.fromHex(r),r}catch(t){throw new qr(String(t))}}function lh(r){try{return le.getPublicKey(r,!0)}catch(t){throw new Nn(String(t))}}function Qy(){return le.utils.randomPrivateKey()}async function fh(r,t){if(r==="Ed25519")return Md();if(r==="secp256k1")return uh();if(r==="RSA")return gl(Jy(t));if(r==="ECDSA")return zf(t0(t));throw new Ve}function pn(r,t){let{Type:e,Data:n}=me.decode(r),o=n??new Uint8Array;switch(e){case ft.RSA:return hl(o,t);case ft.Ed25519:return qc(o);case ft.secp256k1:return _l(o);case ft.ECDSA:return gc(o);default:throw new Ve}}function dh(r){let{Type:t,Data:e}=me.decode(r.digest),n=e??new Uint8Array;switch(t){case ft.Ed25519:return qc(n);case ft.secp256k1:return _l(n);case ft.ECDSA:return gc(n);default:throw new Ve}}function Zt(r){return me.encode({Type:ft[r.type],Data:r.raw})}function Jy(r){return r==null?2048:parseInt(r,10)}function t0(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new k("Unsupported curve, should be P-256, P-384 or P-521")}var hh=Symbol.for("nodejs.util.inspect.custom"),e0=114,mo=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[es]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return nt.createV1(e0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Z(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Z(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[hh](){return`PeerId(${this.toString()})`}},go=class extends mo{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},yo=class extends mo{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},bo=class extends mo{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},r0=2336,wo=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=oe.digest(C(this.url))}[hh](){return`PeerId(${this.url})`}[es]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return nt.createV1(r0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=U(t)),t.toString()===this.toString())}};var n0=114,ph=2336;function ge(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Ee(Y.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return xo(nt.parse(r));if(t==null)throw new k('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Ee(t.decode(r))}return mn(e)}function Sl(r){if(r.type==="Ed25519")return new yo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new bo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new go({multihash:r.toCID().multihash,publicKey:r});throw new Ve}function mh(r){return Sl(r.publicKey)}function mn(r){if(s0(r))return new go({multihash:r});if(o0(r))try{let t=dh(r);if(t.type==="Ed25519")return new yo({multihash:r,publicKey:t});if(t.type==="secp256k1")return new bo({multihash:r,publicKey:t})}catch{let e=U(r.digest);return new wo(new URL(e))}throw new os("Supplied PeerID Multihash is invalid")}function xo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==n0&&r.code!==ph)throw new ns("Supplied PeerID CID is invalid");if(r.code===ph){let t=U(r.multihash.digest);return new wo(new URL(t))}return mn(r.multihash)}function o0(r){return r.code===oe.code}function s0(r){return r.code===Xr.code}function gn(r){if(typeof r!="object"||r===null)return!1;let t=Object.getPrototypeOf(r);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:yh}=Object.prototype,{propertyIsEnumerable:i0}=Object,yn=(r,t,e)=>{Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0})},a0=void 0,gh={concatArrays:!1,ignoreUndefined:!1},Ns=r=>{let t=[];for(let e in r)yh.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)i0.call(r,n)&&t.push(n)}return t};function bn(r){return Array.isArray(r)?c0(r):gn(r)?l0(r):r}function c0(r){let t=r.slice(0,0);return Ns(r).forEach(e=>{yn(t,e,bn(r[e]))}),t}function l0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return Ns(r).forEach(e=>{yn(t,e,bn(r[e]))}),t}var bh=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?yn(r,o,Al(r[o],t[o],n)):yn(r,o,bn(t[o])))}),r),u0=(r,t,e)=>{let n=r.slice(0,0),o=0;return[r,t].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)yh.call(s,a)&&(i.push(String(a)),s===r?yn(n,o++,s[a]):yn(n,o++,bn(s[a])));n=bh(n,s,Ns(s).filter(a=>!i.includes(a)),e)}),n};function Al(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?u0(r,t,e):!gn(t)||!gn(r)?bn(t):bh(r,t,Ns(t),e)}function Bs(...r){let t=Al(bn(gh),this!==a0&&this||{},gh),e={_:{}};for(let n of r)if(n!==void 0){if(!gn(n))throw new TypeError("`"+n+"` is not an Option Object");e=Al(e,{_:n},t)}return e._}var dt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Il=ts(xh(),1);var vo=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Tl=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Eh=r=>globalThis.DOMException===void 0?new Tl(r):new DOMException(r),vh=r=>{let t=r.reason===void 0?Eh("This operation was aborted."):r.reason;return t instanceof Error?t:Eh(t)};function Pl(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,l=new Promise((u,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:h}=t;h.aborted&&f(vh(h)),a=()=>{f(vh(h))},h.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new vo;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}function Dl(r,t,e){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;e(r[i],t)<=0?(n=++i,o-=s+1):o=s}return n}var _o=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,id:e.id,run:t};if(this.size===0||this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=Dl(this.#t,n,(s,i)=>i.priority-s.priority);this.#t.splice(o,0,n)}setPriority(t,e){let n=this.#t.findIndex(s=>s.id===t);if(n===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);let[o]=this.#t.splice(n,1);this.enqueue(o.run,{priority:e,id:t})}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var So=class extends Il.default{#t;#n;#e=0;#h;#a;#p=0;#o;#c;#r;#m;#s=0;#l;#i;#g;#w=1n;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:_o,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#n=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#h=t.intervalCap,this.#a=t.interval,this.#r=new t.queueClass,this.#m=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#g=t.throwOnTimeout===!0,this.#i=t.autoStart===!1}get#x(){return this.#n||this.#e<this.#h}get#E(){return this.#s<this.#l}#v(){this.#s--,this.#u(),this.emit("next")}#_(){this.#b(),this.#y(),this.#c=void 0}get#S(){let t=Date.now();if(this.#o===void 0){let e=this.#p-t;if(e<0)this.#e=this.#t?this.#s:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#_()},e)),!0}return!1}#u(){if(this.#r.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let t=!this.#S;if(this.#x&&this.#E){let e=this.#r.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#n||this.#o!==void 0||(this.#o=setInterval(()=>{this.#b()},this.#a),this.#p=Date.now()+this.#a)}#b(){this.#e===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#e=this.#t?this.#s:0,this.#f()}#f(){for(;this.#u(););}get concurrency(){return this.#l}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#l=t,this.#f()}async#A(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}setPriority(t,e){this.#r.setPriority(t,e)}async add(t,e={}){return e.id??=(this.#w++).toString(),e={timeout:this.timeout,throwOnTimeout:this.#g,...e},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#s++,this.#e++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=Pl(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#A(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof vo&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#v()}},e),this.emit("add"),this.#u()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#i?(this.#i=!1,this.#f(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#d("empty")}async onSizeLessThan(t){this.#r.size<t||await this.#d("next",()=>this.#r.size<t)}async onIdle(){this.#s===0&&this.#r.size===0||await this.#d("idle")}async#d(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#r.size}sizeBy(t){return this.#r.filter(t).length}get pending(){return this.#s}get isPaused(){return this.#i}};function Fs(r){let t=[Wt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Ll=60;function Ks(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(t=>({name:t.name,type:Wt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:Wt[t.type],TTL:t.TTL??t.ttl??Ll,data:t.data instanceof Uint8Array?U(t.data):t.data}))}}var h0=4;function Rl(r,t={}){let e=new So({concurrency:t.queryConcurrency??h0});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Fs(o.types).forEach(a=>{s.append("type",Wt[a])}),o.onProgress?.(new dt("dns:query",{detail:n}));let i=await e.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Ks(await a.json());return o.onProgress?.(new dt("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function _h(){return[Rl("https://cloudflare-dns.com/dns-query"),Rl("https://dns.google/resolve")]}var Ch=ts(Ah(),1);var Ol=class{lru;constructor(t){this.lru=(0,Ch.default)(t)}get(t,e){let n=!0,o=[];for(let s of e){let i=this.getAnswers(t,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return Ks({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Wt[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Ll)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Ih(r){return new Ol(r)}var p0=1e3,qs=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Ih(t.cacheSize??p0),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=_h())}async query(t,e={}){let n=Fs(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new dt("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let l=await c(t,{...e,types:n});for(let u of l.Answer)this.cache.add(t,u);return l}catch(l){a.push(l),e.onProgress?.(new dt("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var Wt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Wt||(Wt={}));function Th(r={}){return new qs(r)}var wt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Me=class extends Error{static name="ValidationError";name="ValidationError"},Ao=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Vs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var zs=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ph=45,m0=15,wn=new zs;function $s(r){if(!(r.length>m0))return wn.new(r).parseWith(()=>wn.readIPv4Addr())}function Hs(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ph))return wn.new(r).parseWith(()=>wn.readIPv6Addr())}function xn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Ph)return;let e=wn.new(r).parseWith(()=>wn.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}function ue(r){return!!$s(r)}function Ws(r){return!!Hs(r)}function Ml(r){return t=>U(t,r)}function Nl(r){return t=>C(t,r)}function En(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function yr(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Dh(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=C(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=yr(n);return se([e,o],e.length+o.length)}function Lh(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Xt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=yr(n);return se([e,o],e.length+o.length)}function Bl(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=U(t,"base32"),o=En(e);return`${n}:${o}`}var Ul=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new wt("Invalid byte value in IP address");t[n]=o}),t},Rh=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=ue(e[n]),i;s&&(i=Ul(e[n]),e[n]=U(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,U(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new wt("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Oh=function(r){if(r.byteLength!==4)throw new wt("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},kh=function(r){if(r.byteLength!==16)throw new wt("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new wt(`Invalid IPv6 address "${e}"`)}};function Mh(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new wt(`Invalid IPv6 address "${r}"`)}}var kl=Object.values($n).map(r=>r.decoder),g0=function(){let r=kl[0].or(kl[1]);return kl.slice(2).forEach(t=>r=r.or(t)),r}();function Nh(r){return g0.decode(r)}function Bh(r){return t=>r.encoder.encode(t)}function y0(r){if(parseInt(r).toString()!==r)throw new Me("Value must be an integer")}function b0(r){if(r<0)throw new Me("Value must be a positive integer, or zero")}function w0(r){return t=>{if(t>r)throw new Me(`Value must be smaller than or equal to ${r}`)}}function x0(...r){return t=>{for(let e of r)e(t)}}var Co=x0(y0,b0,w0(65535));var yt=-1,Fl=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new Vs(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Kt=new Fl,M0=[{code:4,name:"ip4",size:32,valueToBytes:Ul,bytesToValue:Oh,validate:r=>{if(!ue(r))throw new Me(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:yr,bytesToValue:En,validate:Co},{code:273,name:"udp",size:16,valueToBytes:yr,bytesToValue:En,validate:Co},{code:33,name:"dccp",size:16,valueToBytes:yr,bytesToValue:En,validate:Co},{code:41,name:"ip6",size:128,valueToBytes:Rh,bytesToValue:kh,stringToValue:Mh,validate:r=>{if(!Ws(r))throw new Me(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:yt},{code:43,name:"ipcidr",size:8,bytesToValue:Ml("base10"),valueToBytes:Nl("base10")},{code:53,name:"dns",size:yt,resolvable:!0},{code:54,name:"dns4",size:yt,resolvable:!0},{code:55,name:"dns6",size:yt,resolvable:!0},{code:56,name:"dnsaddr",size:yt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:yr,bytesToValue:En,validate:Co},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:yt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:yt,bytesToValue:Ml("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Nl("base58btc")(r):nt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Bl,valueToBytes:Dh},{code:445,name:"onion3",size:296,bytesToValue:Bl,valueToBytes:Lh},{code:446,name:"garlic64",size:yt},{code:447,name:"garlic32",size:yt},{code:448,name:"tls"},{code:449,name:"sni",size:yt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:yt,bytesToValue:Bh(oc),valueToBytes:Nh},{code:480,name:"http"},{code:481,name:"http-path",size:yt,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:yt}];M0.forEach(r=>{Kt.addProtocol(r)});function Uh(r){let t=[],e=0;for(;e<r.length;){let n=hr(r,e),o=Kt.getProtocol(n),s=gt(n),i=N0(o,r,e+s),a=0;i>0&&o.size===yt&&(a=gt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let u=e+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??U(f)}t.push(l),e+=c}return t}function Fh(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Kt.getProtocol(n.code),s=gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??C(n.value),a=i.byteLength,o.size===yt&&(c=gt(a)));let l=new Uint8Array(s+c+a),u=0;an(n.code,l,u),u+=s,i!=null&&(o.size===yt&&(an(a,l,u),u+=c),l.set(i,u)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return se(e,t)}function Kh(r){if(r.charAt(0)!=="/")throw new wt('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Kt.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new wt(`Component ${o} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new wt(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new wt("Incomplete multiaddr");return t}function qh(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Kt.getProtocol(t.code);if(e==null)throw new wt(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function N0(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:hr(t,e)}var B0=Symbol.for("nodejs.util.inspect.custom"),Xl=Symbol.for("@multiformats/multiaddr"),U0=[53,54,55,56],jl=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function F0(r){if(r==null&&(r="/"),er(r))return r.getComponents();if(r instanceof Uint8Array)return Uh(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Kh(r);if(Array.isArray(r))return r;throw new wt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Zs=class r{[Xl]=!0;#t;#n;#e;constructor(t="/",e={}){this.#t=F0(t),e.validate!==!1&&K0(this)}get bytes(){return this.#e==null&&(this.#e=Fh(this.#t)),this.#e}toString(){return this.#n==null&&(this.#n=qh(this.#t)),this.#n}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="";for(let{code:a,name:c,value:l}of this.#t)a===42&&(s=`%${l??""}`),U0.includes(a)&&(e="tcp",o=443,n=`${l??""}${s}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",o=parseInt(l??"")),(a===4||a===41)&&(e="tcp",n=`${l??""}${s}`,t=a===41?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=Kt.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=Kt.getProtocol(t),o=[t];return e!=null&&o.push(n.valueToBytes?.(e)??C(e)),o})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Ao(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:o})=>{n===421&&t.push([n,o]),n===290&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?U(Y.decode(`z${n}`),"base58btc"):U(nt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(Kt.getProtocol(t.code).path)return t.value??null;return null}equals(t){return Z(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Vh.get(e.name);if(n==null)throw new jl(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>z(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[B0](){return`Multiaddr(${this.toString()})`}};function K0(r){r.getComponents().forEach(t=>{let e=Kt.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function zh(r,t,e){let n=0;for(let o of r)if(!(n<t)){if(n>e)break;if(o!==255)return!1;n++}return!0}function $h(r,t,e,n){let o=0;for(let s of r)if(!(o<e)){if(o>n)break;if(s!==t[o])return!1;o++}return!0}function Zl(r){switch(r.length){case vr:return r.join(".");case _r:{let t=[];for(let e=0;e<r.length;e++)e%2===0&&t.push(r[e].toString(16).padStart(2,"0")+r[e+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}function Hh(r){let t=0;for(let[e,n]of r.entries()){if(n===255){t+=8;continue}for(;(n&128)!=0;)t++,n=n<<1;if((n&128)!=0)return-1;for(let o=e+1;o<r.length;o++)if(r[o]!=0)return-1;break}return t}function Wh(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var vr=4,_r=16,WS=parseInt("0xFFFF",16),q0=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function To(r,t){t.length===_r&&r.length===vr&&zh(t,0,11)&&(t=t.slice(12)),t.length===vr&&r.length===_r&&$h(r,q0,0,11)&&(r=r.slice(12));let e=r.length;if(e!=t.length)throw new Error("Failed to mask ip");let n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=r[o]&t[o];return n}function Gh(r,t){if(typeof t=="string"&&(t=xn(t)),t==null)throw new Error("Invalid ip");if(t.length!==r.network.length)return!1;for(let e=0;e<t.length;e++)if((r.network[e]&r.mask[e])!==(t[e]&r.mask[e]))return!1;return!0}function Yl(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=vr,o=$s(t);if(o==null&&(n=_r,o=Hs(t),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(e,10);if(Number.isNaN(s)||String(s).length!==e.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=Ql(s,8*n);return{network:To(o,i),mask:i}}function Ql(r,t){if(t!==8*vr&&t!==8*_r)throw new Error("Invalid CIDR mask");if(r<0||r>t)throw new Error("Invalid CIDR mask");let e=t/8,n=new Uint8Array(e);for(let o=0;o<e;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Cn=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=Yl(t));else{let n=xn(t);if(n==null)throw new Error("Failed to parse network");e=String(e);let o=parseInt(e,10);if(Number.isNaN(o)||String(o).length!==e.length||o<0||o>n.length*8){let s=xn(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Ql(o,8*n.length);this.network=To(n,this.mask)}}contains(t){return Gh({network:this.network,mask:this.mask},t)}toString(){let t=Hh(this.mask),e=t!==-1?String(t):Wh(this.mask);return Zl(this.network)+"/"+e}};function Jl(r){let t,e;if(r.getComponents().forEach(n=>{(n.name==="ip4"||n.name==="ip6")&&(e=n.value),n.name==="ipcidr"&&(t=n.value)}),t==null||e==null)throw new Error("Invalid multiaddr");return new Cn(e,t)}var Vh=new Map;function er(r){return!!r?.[Xl]}function z(r){return new Zs(r)}function Ys(r){let t=Kt.getProtocol(r);return{code:t.code,size:t.size??0,name:t.name,resolvable:!!t.resolvable,path:!!t.path}}var tu=class{dns;canResolve(t){return t.getComponents().some(({name:e})=>e==="dnsaddr")}async resolve(t,e){let n=t.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[t];let s=await this.getDNS(e).query(`_dnsaddr.${n}`,{signal:e?.signal,types:[Wt.TXT]}),i=t.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(z(l)))}return a}getDNS(t){return t.dns!=null?t.dns:(this.dns==null&&(this.dns=Th()),this.dns)}},Ne=new tu;var V0={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ne}},transportManager:{faultTolerance:or.FATAL_ALL}};async function jh(r){let t=Bs(V0,r);if(t.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new k("Private network is enforced, but no protector was provided");return t}function z0(r,t){try{if(typeof r=="string"&&r.length>0)return $0(r);if(typeof r=="number"&&isFinite(r))return t?.long?W0(r):H0(r);throw new Error("Value is not a string or number.")}catch(e){let n=G0(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function $0(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Js=z0;function H0(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function W0(r){let t=Math.abs(r);return t>=864e5?Qs(r,t,864e5,"day"):t>=36e5?Qs(r,t,36e5,"hour"):t>=6e4?Qs(r,t,6e4,"minute"):t>=1e3?Qs(r,t,1e3,"second"):`${r} ms`}function Qs(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function G0(r){return typeof r=="object"&&r!==null&&"message"in r}function eu(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=Js,e.destroy=l,Object.keys(r).forEach(u=>{e[u]=r[u]}),e.names=[],e.skips=[],e.formatters={};function t(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(u){let f,d=null,h,p;function m(...x){if(!m.enabled)return;let g=m,_=Number(new Date),w=_-(f||_);g.diff=w,g.prev=f,g.curr=_,f=_,x[0]=e.coerce(x[0]),typeof x[0]!="string"&&x.unshift("%O");let A=0;x[0]=x[0].replace(/%([a-zA-Z%])/g,(K,V)=>{if(K==="%%")return"%";A++;let M=e.formatters[V];if(typeof M=="function"){let v=x[A];K=M.call(g,v),x.splice(A,1),A--}return K}),e.formatArgs.call(g,x),(g.log||e.log).apply(g,x)}return m.namespace=u,m.useColors=e.useColors(),m.color=e.selectColor(u),m.extend=n,m.destroy=e.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,p=e.enabled(u)),p),set:x=>{d=x}}),typeof e.init=="function"&&e.init(m),m}function n(u,f){let d=e(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){e.save(u),e.namespaces=u,e.names=[],e.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]==="-"?e.skips.push(new RegExp("^"+u.substr(1)+"$")):e.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(u))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.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 e.setupFormatters(e.formatters),e.enable(e.load()),e}var ti=tb(),j0=["#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 X0(){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 Z0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Js(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var Y0=console.debug??console.log??(()=>{});function Q0(r){try{r?ti?.setItem("debug",r):ti?.removeItem("debug")}catch{}}function J0(){let r;try{r=ti?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function tb(){try{return localStorage}catch{}}function eb(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Xh=eu({formatArgs:Z0,save:Q0,load:J0,useColors:X0,setupFormatters:eb,colors:j0,storage:ti,log:Y0});var qt=Xh;qt.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);qt.formatters.t=r=>r==null?"undefined":Xt.baseEncode(r);qt.formatters.m=r=>r==null?"undefined":nc.baseEncode(r);qt.formatters.p=r=>r==null?"undefined":r.toString();qt.formatters.c=r=>r==null?"undefined":r.toString();qt.formatters.k=r=>r==null?"undefined":r.toString();qt.formatters.a=r=>r==null?"undefined":r.toString();qt.formatters.e=r=>r==null?"undefined":Zh(r.stack)??Zh(r.message)??r.toString();function rb(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function ei(){return{forComponent(r){return Yh(r)}}}function Yh(r){let t=rb(`${r}:trace`);return qt.enabled(`${r}:trace`)&&qt.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=qt(`${r}:trace`)),Object.assign(qt(r),{error:qt(`${r}:error`),trace:t,newScope:e=>Yh(`${r}:${e}`)})}function Zh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Sr(r,t){let e={[Symbol.iterator]:()=>e,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:t(o)}}};return e}function ri(r){let t=Ee(Y.decode(`z${r}`));return mn(t)}var te=class{map;constructor(t){if(this.map=new Map,t!=null)for(let[e,n]of t.entries())this.map.set(e.toString(),{key:e,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(t){return this.map.delete(t.toString())}entries(){return Sr(this.map.entries(),t=>[t[1].key,t[1].value])}forEach(t){this.map.forEach((e,n)=>{t(e.value,e.key,this)})}get(t){return this.map.get(t.toString())?.value}has(t){return this.map.has(t.toString())}set(t,e){this.map.set(t.toString(),{key:t,value:e})}keys(){return Sr(this.map.values(),t=>t.key)}values(){return Sr(this.map.values(),t=>t.value)}get size(){return this.map.size}};var Ar=class r{set;constructor(t){if(this.set=new Set,t!=null)for(let e of t)this.set.add(e.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(t){this.set.add(t.toString())}clear(){this.set.clear()}delete(t){this.set.delete(t.toString())}entries(){return Sr(this.set.entries(),t=>{let e=ri(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=ri(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return Sr(this.set.values(),t=>ri(t))}intersection(t){let e=new r;for(let n of t)this.has(n)&&e.add(n);return e}difference(t){let e=new r;for(let n of this)t.has(n)||e.add(n);return e}union(t){let e=new r;for(let n of t)e.add(n);for(let n of this)e.add(n);return e}};var ru={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Qh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Jh=new globalThis.TextEncoder;function nb(r,t){let e=ru[t],n=Qh[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function ob(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=ru[t],o=Qh[t],s=r;for(;s.length>0;){let i=Jh.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function nu(r,{size:t=32,utf8Buffer:e}={}){if(!ru[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return ob(r,t,e);r=Jh.encode(r)}return nb(r,t)}var Po={hash:r=>Number(nu(r,{size:32})),hashV:(r,t)=>sb(Po.hash(r,t))};function sb(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),C(t,"base16")}var ou=64,de=class{fp;h;seed;constructor(t,e,n,o=2){if(o>ou)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=ct(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?Z(this.fp,t.fp):!1}};function Cr(r,t){return Math.floor(Math.random()*(t-r))+r}var Ir=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof de))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof de))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof de))throw new TypeError("Invalid Fingerprint");let e=Cr(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof de))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var ib=500,Do=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Po,this.seed=t.seed??Cr(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=C(t));let e=new de(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ir(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ir(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[Cr(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize));for(let a=0;a<ib;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=C(t));let e=new de(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=C(t));let e=new de(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},ab={1:.5,2:.84,4:.95,8:.98};function cb(r=.001){return r>.002?2:r>1e-5?4:8}function tp(r,t=.001){let e=cb(t),n=ab[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),ou);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var ni=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Po,this.seed=t.seed??Cr(0,Math.pow(2,10)),this.filterSeries=[new Do({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=C(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new Do({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=C(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=C(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Lo(r,t=.001,e){return new ni({...tp(r,t),...e??{}})}var su=class extends te{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function iu(r){let{name:t,metrics:e}=r,n;return e!=null?n=new su({name:t,metrics:e}):n=new te,n}var Ro;(function(r){let t;r.codec=()=>(t==null&&(t=kt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.publicKey!=null&&e.publicKey.byteLength>0&&(n.uint32(10),n.bytes(e.publicKey)),e.payloadType!=null&&e.payloadType.byteLength>0&&(n.uint32(18),n.bytes(e.payloadType)),e.payload!=null&&e.payload.byteLength>0&&(n.uint32(26),n.bytes(e.payload)),e.signature!=null&&e.signature.byteLength>0&&(n.uint32(42),n.bytes(e.signature)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={publicKey:ct(0),payloadType:ct(0),payload:ct(0),signature:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.publicKey=e.bytes();break}case 2:{s.payloadType=e.bytes();break}case 3:{s.payload=e.bytes();break}case 5:{s.signature=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ot(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Ro||(Ro={}));var oi=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var In=class r{static createFromProtobuf=t=>{let e=Ro.decode(t),n=pn(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e,n)=>{if(e==null)throw new Error("Missing private key");let o=t.domain,s=t.codec,i=t.marshal(),a=ep(o,s,i),c=await e.sign(a.subarray(),n);return new r({publicKey:e.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(t,e,n)=>{let o=r.createFromProtobuf(t);if(!await o.validate(e,n))throw new oi("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(t){let{publicKey:e,payloadType:n,payload:o,signature:s}=t;this.publicKey=e,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=Ro.encode({publicKey:Zt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return t==null?!1:Z(this.marshal(),t.marshal())}async validate(t,e){let n=ep(t,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,e)}},ep=(r,t,e)=>{let n=C(r),o=pe(n.byteLength),s=pe(t.length),i=pe(e.length);return new W(o,n,s,t,i,e)};function rp(r,t){let e=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==t.length?!1:(t.sort(e),r.sort(e).every((n,o)=>t[o].equals(n)))}var np="libp2p-peer-record",op=Uint8Array.from([3,1]);var Oo;(function(r){let t;(function(n){let o;n.codec=()=>(o==null&&(o=kt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:ct(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}default:{s.skipType(u&7);break}}}return c})),o),n.encode=s=>Ot(s,n.codec()),n.decode=(s,i)=>Rt(s,n.codec(),i)})(t=r.AddressInfo||(r.AddressInfo={}));let e;r.codec=()=>(e==null&&(e=kt((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:ct(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new gr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),e),r.encode=n=>Ot(n,r.codec()),r.decode=(n,o)=>Rt(n,r.codec(),o)})(Oo||(Oo={}));var Tr=class r{static createFromProtobuf=t=>{let e=Oo.decode(t),n=mn(Ee(e.peerId)),o=(e.addresses??[]).map(i=>z(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=np;static CODEC=op;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(t){let{peerId:e,multiaddrs:n,seqNumber:o}=t;this.peerId=e,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Oo.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(t=>({multiaddr:t.bytes}))})),this.marshaled}equals(t){return!(!(t instanceof r)||!this.peerId.equals(t.peerId)||this.seqNumber!==t.seqNumber||!rp(this.multiaddrs,t.multiaddrs))}};function lb(r){return r[Symbol.asyncIterator]!=null}function ub(r){if(lb(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var ko=ub;var jt=class extends Error{static name="AbortError";name="AbortError";constructor(t="The operation was aborted",...e){super(t,...e)}};function ut(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var si=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Tn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new si(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new si(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var au=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function ii(r={}){return fb(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function fb(r,t){t=t??{};let e=t.onEnd,n=new Tn,o,s,i,a=ut(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((x,g)=>{s=_=>{s=null,n.push(_);try{x(r(n))}catch(w){g(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ut()})}},l=x=>s!=null?s(x):(n.push(x),o),u=x=>(n=new Tn,s!=null?s({error:x}):(n.push({error:x}),o)),f=x=>{if(i)return o;if(t?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:x})},d=x=>i?o:(i=!0,x!=null?u(x):l({done:!0})),h=()=>(n=new Tn,d(),{done:!0}),p=x=>(d(x),{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 x=>{let g=x?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let _,w;g!=null&&(_=new Promise((A,R)=>{w=()=>{R(new au)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,_])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(x){return m.throw(x),e!=null&&(e(x),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(x){return m.end(x),e!=null&&(e(x),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:x=>m.onEmpty(x)},o}async function be(r,t,e,n){let o=new jt(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return e?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){lu(e,"abort",f),lu(r,t,l),lu(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)};cu(e,"abort",f),cu(r,t,l),cu(r,s,u)})}function cu(r,t,e){r!=null&&(sp(r)?r.addEventListener(t,e):r.addListener(t,e))}function lu(r,t,e){r!=null&&(sp(r)?r.removeEventListener(t,e):r.removeListener(t,e))}function sp(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var ai=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var ci=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function xt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new ci(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new ci(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var li=class{deferred;signal;constructor(t){this.signal=t,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function db(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ui=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=db(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new jt),this.cleanup())}async join(t={}){let e=new li(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await xt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};function uu(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Mo=class extends Vt{concurrency;maxSize;queue;pending;sort;autoStart;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=t.autoStart??!0,this.sort=t.sort,this.queue=[],this.emitEmpty=uu(this.emitEmpty.bind(this),1),this.emitIdle=uu(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ai;let n=new ui(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new jt)}),this.clear()}async onEmpty(t){this.size!==0&&await be(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await be(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await be(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=ii({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new jt("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var fi="lock:worker:request-read",di="lock:worker:abort-read-request",hi="lock:worker:release-read",pi="lock:master:grant-read",mi="lock:master:error-read",gi="lock:worker:request-write",yi="lock:worker:abort-write-request",bi="lock:worker:release-write",wi="lock:master:grant-write",xi="lock:master:error-write",Ei="lock:worker:finalize",vi="mortice",ip={singleProcess:!1};var fu=(r,t,e,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(e,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{t.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&&(t.removeEventListener("message",d),f())};t.addEventListener("message",d)})},onError:f=>{t.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===Ei&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var ap=(r=10)=>Math.random().toString().substring(2,r+2);var _i=class{name;channel;constructor(t){this.name=t,this.channel=new BroadcastChannel(vi)}readLock(t){return this.sendRequest(fi,di,pi,mi,hi,t)}writeLock(t){return this.sendRequest(gi,yi,wi,xi,bi,t)}finalize(){this.channel.postMessage({type:Ei,name:this.name}),this.channel.close()}async sendRequest(t,e,n,o,s,i){i?.signal?.throwIfAborted();let a=ap();return this.channel.postMessage({type:t,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:e,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 cp=r=>{if(r=Object.assign({},ip,r),!!globalThis.document||r.singleProcess){let e=new BroadcastChannel(vi),n=new Vt;return e.addEventListener("message",fu(n,e,"requestReadLock","abortReadLockRequest",fi,di,mi,hi,pi)),e.addEventListener("message",fu(n,e,"requestWriteLock","abortWriteLockRequest",gi,yi,xi,bi,wi)),n}return new _i(r.name)};var Pr=new Map,No;function lp(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function hb(r){if(No==null&&(No=cp(r),!lp(No))){let t=No;t.addEventListener("requestReadLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=Pr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};t.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await e.detail.handler().finally(()=>{c()})}).catch(c=>{e.detail.onError(c)}).finally(()=>{t.removeEventListener("abortReadLockRequest",a)})}),t.addEventListener("requestWriteLock",e=>{let n=e.detail.name,o=e.detail.identifier,s=Pr.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};t.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await e.detail.handler().finally(()=>{c()})}).catch(c=>{e.detail.onError(c)}).finally(()=>{t.removeEventListener("abortWriteLockRequest",a)})}),t.addEventListener("finalizeRequest",e=>{let n=e.detail.name,o=Pr.get(n);o?.finalize()})}return No}async function du(r,t){let e,n,o=new Promise((i,a)=>{e=i,n=a}),s=()=>{n(new jt)};return t?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{e(()=>{t?.signal?.removeEventListener("abort",s),i()})})},{signal:t?.signal}).catch(i=>{n(i)}),o}var up=(r,t)=>{let e=Pr.get(r);if(e!=null)return e;let n=hb(t);if(lp(n))return e=n,Pr.set(r,e),e;let o=new Mo({concurrency:1}),s;return e={async readLock(i){if(s!=null)return du(s,i);s=new Mo({concurrency:t.concurrency,autoStart:!1});let a=s,c=du(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,du(o,i)},finalize:()=>{Pr.delete(r)},queue:o},Pr.set(r,e),t.autoFinalize===!0&&o.addEventListener("idle",()=>{e.finalize()},{once:!0}),e};var pb={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function hu(r){let t=Object.assign({},pb,r);return up(t.name,t)}var Be;(function(r){let t;(function(o){let s;o.codec=()=>(s==null&&(s=kt((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ct(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Ot(i,o.codec()),o.decode=(i,a)=>Rt(i,o.codec(),a)})(t=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let e;(function(o){let s;o.codec=()=>(s==null&&(s=kt((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Ai.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Ai.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Ot(i,o.codec()),o.decode=(i,a)=>Rt(i,o.codec(),a)})(e=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=kt((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Si.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new gr('Decode error - map field "addresses" had too many elements');a.addresses.push(Si.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new gr('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new uo('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new uo('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Ot(o,r.codec()),r.decode=(o,s)=>Rt(o,r.codec(),s)})(Be||(Be={}));var Si;(function(r){let t;r.codec=()=>(t==null&&(t=kt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.multiaddr!=null&&e.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(e.multiaddr)),e.isCertified!=null&&(n.uint32(16),n.bool(e.isCertified)),e.observed!=null&&(n.uint32(24),n.uint64Number(e.observed)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={multiaddr:ct(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.multiaddr=e.bytes();break}case 2:{s.isCertified=e.bool();break}case 3:{s.observed=e.uint64Number();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ot(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Si||(Si={}));var Ai;(function(r){let t;r.codec=()=>(t==null&&(t=kt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.value!=null&&e.value!==0&&(n.uint32(8),n.uint32(e.value)),e.expiry!=null&&(n.uint32(16),n.uint64(e.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={value:0},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.value=e.uint32();break}case 2:{s.expiry=e.uint64();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Ot(e,r.codec()),r.decode=(e,n)=>Rt(e,r.codec(),n)})(Ai||(Ai={}));function mb(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;r.type==="RSA"&&(e=r.toMultihash());let n=pn(t.publicKey,e);return Sl(n)}function fp(r,t,e){let n=Be.decode(t);return Pn(r,n,e)}function Pn(r,t,e){let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:mb(r,t),addresses:t.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-e).map(({multiaddr:s,isCertified:i})=>({multiaddr:z(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function dp(r,t){return gb(r.addresses,t.addresses)&&yb(r.protocols,t.protocols)&&bb(r.publicKey,t.publicKey)&&wb(r.peerRecordEnvelope,t.peerRecordEnvelope)&&xb(r.metadata,t.metadata)&&Eb(r.tags,t.tags)}function gb(r,t){return pp(r,t,(e,n)=>!(e.isCertified!==n.isCertified||!Z(e.multiaddr,n.multiaddr)))}function yb(r,t){return pp(r,t,(e,n)=>e===n)}function bb(r,t){return hp(r,t)}function wb(r,t){return hp(r,t)}function xb(r,t){return mp(r,t,(e,n)=>Z(e,n))}function Eb(r,t){return mp(r,t,(e,n)=>e.value===n.value&&e.expiry===n.expiry)}function hp(r,t){return r==null&&t==null?!0:r!=null&&t!=null?Z(r,t):!1}function pp(r,t,e){if(r.length!==t.length)return!1;for(let n=0;n<r.length;n++)if(!e(r[n],t[n]))return!1;return!0}function mp(r,t,e){if(r.size!==t.size)return!1;for(let[n,o]of r.entries()){let s=t.get(n);if(s==null||!e(o,s))return!1}return!0}var Ue="/",gp=new TextEncoder().encode(Ue),Ci=gp[0],Dr=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=C(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Ci)throw new Error("Invalid key")}toString(t="utf8"){return U(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Ue))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=gp),this._buf[0]!==Ci){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Ci,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ci;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Ue).slice(1)}type(){return vb(this.baseNamespace())}name(){return _b(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Ue)||(t+=Ue),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Ue):new r(t.slice(0,-1).join(Ue))}child(t){return this.toString()===Ue?t:t.toString()===Ue?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...Sb(t.map(e=>e.namespaces()))])}};function vb(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function _b(r){let t=r.split(":");return t[t.length-1]}function Sb(r){return[].concat(...r)}var pu="/peers/";function Bo(r){if(!Ke(r)||r.type==null)throw new k("Invalid PeerId");let t=r.toCID().toString();return new Dr(`${pu}${t}`)}async function yp(r,t,e,n,o){let s=new Map;for(let i of e){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=z(i.multiaddr)),!er(i.multiaddr))throw new k("Multiaddr was invalid");if(!await t(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),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.getPeerId();return r.equals(c)&&(a=a.decapsulate(z(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Ti(r,t,e,n){if(t==null)throw new k("Invalid PeerData");if(t.publicKey!=null&&r.publicKey!=null&&!t.publicKey.equals(r.publicKey))throw new k("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new k("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(e==="patch"){if((t.multiaddrs!=null||t.addresses!=null)&&(s=[],t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses)),t.protocols!=null&&(i=new Set(t.protocols)),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);a=Ii(d,{validate:bp})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=Ii(d,{validate:wp,map:xp})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Ii([...a.entries()],{validate:bp})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Ii([...h.entries()],{validate:wp,map:xp})}t.peerRecordEnvelope!=null&&(l=t.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Zt(o.id.publicKey):t.publicKey!=null?u=Zt(t.publicKey):r.publicKey!=null&&(u=Zt(r.publicKey));let f={addresses:await yp(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=>Z(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Ii(r,t){let e=new Map;for(let[n,o]of r)o!=null&&t.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&e.set(n,t.map?.(n,o)??o);return e}function bp(r,t){if(typeof r!="string")throw new k("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new k("Metadata value must be a Uint8Array")}function wp(r,t){if(typeof r!="string")throw new k("Tag name must be a string");if(t.value!=null){if(parseInt(`${t.value}`,10)!==t.value)throw new k("Tag value must be an integer");if(t.value<0||t.value>100)throw new k("Tag value must be between 0-100")}if(t.ttl!=null){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new k("Tag ttl must be an integer");if(t.ttl<0)throw new k("Tag ttl must be between greater than 0")}}function xp(r,t){let e;t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl)));let n={value:t.value??0};return e!=null&&(n.expiry=e),n}function Ep(r){let t=r.toString().split("/")[2],e=nt.parse(t,Xt);return xo(e)}function mu(r,t,e){let n=Ep(r);return fp(n,t,e)}function Ab(r,t){return{prefix:pu,filters:(r.filters??[]).map(e=>({key:n,value:o})=>e(mu(n,o,t))),orders:(r.orders??[]).map(e=>(n,o)=>e(mu(n.key,n.value,t),mu(o.key,o.value,t)))}}var Pi=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.locks=iu({name:"libp2p_peer_store_locks",metrics:t.metrics}),this.maxAddressAge=e.maxAddressAge??36e5,this.maxPeerAge=e.maxPeerAge??216e5}getLock(t){let e=this.locks.get(t);return e==null&&(e={refs:0,lock:hu({name:t.toString(),singleProcess:!0})},this.locks.set(t,e)),e.refs++,e}maybeRemoveLock(t,e){e.refs--,e.refs===0&&(e.lock.finalize(),this.locks.delete(t))}async getReadLock(t,e){let n=this.getLock(t);try{let o=await n.lock.readLock(e);return()=>{o(),this.maybeRemoveLock(t,n)}}catch(o){throw this.maybeRemoveLock(t,n),o}}async getWriteLock(t,e){let n=this.getLock(t);try{let o=await n.lock.writeLock(e);return()=>{o(),this.maybeRemoveLock(t,n)}}catch(o){throw this.maybeRemoveLock(t,n),o}}async has(t,e){try{return await this.load(t,e),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(t,e){this.peerId.equals(t)||await this.datastore.delete(Bo(t),e)}async load(t,e){let n=Bo(t),o=await this.datastore.get(n,e),s=Be.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new sr;return Pn(t,s,this.peerId.equals(t)?1/0:this.maxAddressAge)}async save(t,e,n){let o=await this.#t(t,n),s=await Ti(t,e,"patch",{...n,addressFilter:this.addressFilter});return this.#n(t,s,o)}async patch(t,e,n){let o=await this.#t(t,n),s=await Ti(t,e,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#n(t,s,o)}async merge(t,e,n){let o=await this.#t(t,n),s=await Ti(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#n(t,s,o)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(Ab(t??{},this.maxAddressAge),t)){let o=Ep(e);if(o.equals(this.peerId))continue;let s=Be.decode(n);if(this.#e(o,s)){await this.datastore.delete(e,t);continue}yield Pn(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#t(t,e){try{let n=Bo(t),o=await this.datastore.get(n,e),s=Be.decode(o);if(this.#e(t,s))throw await this.datastore.delete(n,e),new sr;return{peerPB:s,peer:Pn(t,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#n(t,e,n,o){e.updated=Date.now();let s=Be.encode(e);return await this.datastore.put(Bo(t),s,o),{peer:Pn(t,e,this.maxAddressAge),previous:n?.peer,updated:n==null||!dp(e,n.peerPB)}}#e(t,e){if(e.updated==null)return!0;if(this.peerId.equals(t))return!1;let n=e.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=e.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var gu=class{store;events;peerId;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Pi(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){for await(let n of this.store.all(e))t(n)}async all(t){return ko(this.store.all(t))}async delete(t,e){let n=await this.store.getReadLock(t,e);try{await this.store.delete(t,e)}finally{n()}}async has(t,e){let n=await this.store.getReadLock(t,e);try{return await this.store.has(t,e)}finally{this.log.trace("has release read lock"),n?.()}}async get(t,e){let n=await this.store.getReadLock(t,e);try{return await this.store.load(t,e)}finally{n?.()}}async getInfo(t,e){let n=await this.get(t,e);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.save(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async patch(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.patch(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async merge(t,e,n){let o=await this.store.getWriteLock(t,n);try{let s=await this.store.merge(t,e,n);return this.#t(t,s),s.peer}finally{o?.()}}async consumePeerRecord(t,e,n){let o=Ke(e)?e:Ke(e?.expectedPeer)?e.expectedPeer:void 0,s=Ke(e)||e===void 0?n:e,i=await In.openAndCertify(t,Tr.DOMAIN,s),a=xo(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=Tr.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=In.createFromProtobuf(l.peerRecordEnvelope),f=Tr.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:t,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#t(t,e){e.updated&&(this.peerId.equals(t)?this.events.safeDispatchEvent("self:peer:update",{detail:e}):this.events.safeDispatchEvent("peer:update",{detail:e}))}};function vp(r,t={}){return new gu(r,t)}var Di=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};function Cb(r){return r[Symbol.asyncIterator]!=null}function Ib(r){if(Cb(r))return(async()=>{for await(let t of r);})();for(let t of r);}var yu=Ib;function Tb(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var _p=Tb;function Pb(r){return r[Symbol.asyncIterator]!=null}function Db(r,t){let e=0;if(Pb(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=_p(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=t(o,e++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){i===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var Lr=Db;function Lb(r){return r[Symbol.asyncIterator]!=null}function Rb(r,t){return Lb(r)?async function*(){yield*(await ko(r)).sort(t)}():function*(){yield*ko(r).sort(t)}()}var bu=Rb;function Ob(r){return r[Symbol.asyncIterator]!=null}function kb(r,t){return Ob(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var wu=kb;var Li=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await yu(this.putMany(t,n)),t=[],await yu(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=Lr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>bu(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=Lr(n,()=>o++>=s)}return t.limit!=null&&(n=wu(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=Lr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>Lr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>bu(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=Lr(n,()=>s++>=o)}return t.limit!=null&&(n=wu(n,t.limit)),n}};var Ri=class extends Li{data;constructor(){super(),this.data=new Map}put(t,e,n){return n?.signal?.throwIfAborted(),this.data.set(t.toString(),e),t}get(t,e){e?.signal?.throwIfAborted();let n=this.data.get(t.toString());if(n==null)throw new Di;return n}has(t,e){return e?.signal?.throwIfAborted(),this.data.has(t.toString())}delete(t,e){e?.signal?.throwIfAborted(),this.data.delete(t.toString())}*_all(t,e){e?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new Dr(n),value:o},e?.signal?.throwIfAborted()}*_allKeys(t,e){e?.signal?.throwIfAborted();for(let n of this.data.keys())yield new Dr(n),e?.signal?.throwIfAborted()}};function Uo(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Ap=ts(Sp(),1),Mb=["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"],Nb=Mb.map(r=>new Ap.Netmask(r));function xu(r){for(let t of Nb)if(t.contains(r))return!0;return!1}function Bb(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ub(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return xu(o)}function Fb(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Kb(r){let t=r.split(":"),e=t[t.length-1];return xu(e)}function qb(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 rr(r){if(ue(r))return xu(r);if(Bb(r))return Ub(r);if(Fb(r))return Kb(r);if(Ws(r))return qb(r)}var rt=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),N=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),$=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),It=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),X=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function tt(...r){function t(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 e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var Vb=N(421),Cp=tt(Vb),ki=N(54),Mi=N(55),Ni=N(56),vu=N(53),hT=tt(ki,$(N(421))),pT=tt(Mi,$(N(421))),mT=tt(Ni,$(N(421))),gT=tt(It(vu,Ni,ki,Mi),$(N(421))),Ip=X(N(4),$(N(43))),Tp=X($(N(42)),N(41),$(N(43))),_u=It(Ip,Tp),Rr=It(_u,vu,ki,Mi,Ni),yT=tt(It(_u,X(It(vu,Ni,ki,Mi),$(N(421))))),Su=tt(Ip),Au=tt(Tp),bT=tt(_u),Cu=X(Rr,N(6)),Ko=X(Rr,N(273)),qo=tt(X(Cu,$(N(421)))),wT=tt(Ko),Iu=X(Ko,rt(460),$(N(421))),Bi=X(Ko,rt(461),$(N(421))),zb=It(Iu,Bi),xT=tt(Iu),Pp=tt(Bi),Eu=It(Rr,Cu,Ko,Iu,Bi),Dp=It(X(Eu,rt(477),$(N(421)))),Or=tt(Dp),Lp=It(X(Eu,rt(478),$(N(421))),X(Eu,rt(448),$(N(449)),rt(477),$(N(421)))),Vo=tt(Lp),Rp=X(Ko,rt(280),$(N(466)),$(N(466)),$(N(421))),Tu=tt(Rp),Op=X(Bi,rt(465),$(N(466)),$(N(466)),$(N(421))),Pu=tt(Op),Oi=It(Dp,Lp,X(Cu,$(N(421))),X(zb,$(N(421))),X(Rr,$(N(421))),Rp,Op,N(421)),ET=tt(Oi),$b=X(Oi,rt(290),N(421)),zo=tt($b),Hb=It(X(Oi,rt(290),rt(281),$(N(421))),X(Oi,rt(281),$(N(421))),X(rt(281),$(N(421)))),Du=tt(Hb),Wb=It(X(Rr,N(6),rt(480),$(N(421))),X(Rr,rt(480),$(N(421)))),vT=tt(Wb),Gb=X(Rr,It(X(N(6,"443"),rt(480)),X(N(6),rt(443)),X(N(6),rt(448),rt(480)),X(rt(448),rt(480)),rt(448),rt(443)),$(N(421))),_T=tt(Gb),jb=It(X(N(777),$(N(421)))),ST=tt(jb),Xb=It(X(N(400),$(N(421)))),AT=tt(Xb);var Lu=class extends Map{metric;constructor(t){super();let{name:e,metrics:n}=t;this.metric=n.registerMetric(e),this.updateComponentMetric()}set(t,e){return super.set(t,e),this.updateComponentMetric(),this}delete(t){let e=super.delete(t);return this.updateComponentMetric(),e}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Tt(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Lu({name:t,metrics:e}):n=new Map,n}var kp=864e13;var Zb=448,Ru=449,Yb=53,Qb=54,Jb=55,tw=56,Ui=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Tt({name:"libp2p_address_manager_dns_mappings",metrics:t.metrics})}has(t){let e=this.findHost(t);for(let n of this.mappings.values())if(n.domain===e)return!0;return!1}add(t,e){e.forEach(n=>{this.log("add DNS mapping %s to %s",n,t);let o=rr(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?kp-Date.now():0,lastVerified:o?kp-Date.now():void 0})})}remove(t){let e=this.findHost(t),n=!1;for(let[o,s]of this.mappings.entries())s.domain===e&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n].multiaddr.stringTuples(),i=s[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(s,c.domain)&&(t.splice(n,1),n--,e.push({multiaddr:z(`/${s.map(u=>[Ys(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return e}maybeAddSNITuple(t,e){for(let n=0;n<t.length;n++)if(t[n][0]===Zb&&t[n+1]?.[0]!==Ru)return t.splice(n+1,0,[Ru,e]),!0;return!1}confirm(t,e){let n=this.findHost(t),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",s,i.domain),o=i.verified,i.verified=!0,i.expires=Date.now()+e,i.lastVerified=Date.now());return o}unconfirm(t,e){let n=this.findHost(t),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",s,i.domain),o=o||i.verified,i.verified=!1,i.expires=Date.now()+e);return o}findHost(t){for(let e of t.stringTuples())if(e[0]===Ru||e[0]===Yb||e[0]===Qb||e[0]===Jb||e[0]===tw)return e[1]}};var Ou=4,ku=41,Mu=6,ew=273,Fi=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Tt({name:"libp2p_address_manager_ip_mappings",metrics:t.metrics})}has(t){let e=t.stringTuples();for(let n of this.mappings.values())for(let o of n)if(o.externalIp===e[0][1])return!0;return!1}add(t,e,n,o=e,s="tcp"){let i=`${t}-${e}-${s}`,a=this.mappings.get(i)??[],c={internalIp:t,internalPort:e,externalIp:n,externalPort:o,externalFamily:ue(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(t){let e=t.stringTuples(),n=e[0][1]??"",o=e[1][0]===Mu?"tcp":"udp",s=parseInt(e[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===s&&u.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,s,o),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(t){let e=[];for(let{multiaddr:n}of t){let o=n.stringTuples(),s;if((o[0][0]===Ou||o[0][0]===ku)&&o[1][0]===Mu?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===Ou||o[0][0]===ku)&&o[1][0]===ew&&(s=`${o[0][1]}-${o[1][1]}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)o[0][0]=a.externalFamily===4?Ou:ku,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:z(`/${o.map(c=>[Ys(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return e}confirm(t,e){let o=t.stringTuples()[0][1],s=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===o&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),s=a.verified,a.verified=!0,a.expires=Date.now()+e,a.lastVerified=Date.now());return s}unconfirm(t,e){let n=t.stringTuples(),o=n[0][1]??"",s=n[1][0]===Mu?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===o&&u.externalPort===i&&u.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,o,i,s),a=a||u.verified,u.verified=!1,u.expires=Date.now()+e)}return a}};function Mp(r){try{for(let{code:t,value:e}of r.getComponents())if(t!==42&&e!=null){if(t===4)return e.startsWith("169.254.");if(t===41)return e.toLowerCase().startsWith("fe80")}}catch{}return!1}function Ki(r){try{for(let{code:t}of r.getComponents())if(t!==42)return t===4||t===41}catch{}return!1}function kr(r){try{if(!Ki(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:rr(t)??!1}catch{}return!0}var rw={maxObservedAddresses:10},qi=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Tt({name:"libp2p_address_manager_observed_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??rw.maxObservedAddresses}has(t){return this.addresses.has(t.toString())}removePrefixed(t){for(let e of this.addresses.keys())e.toString().startsWith(t)&&this.addresses.delete(e)}add(t){this.addresses.size!==this.maxObservedAddresses&&(kr(t)||Mp(t)||(this.log("adding observed address %a",t),this.addresses.set(t.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([t,e])=>({multiaddr:z(t),verified:e.verified,type:"observed",expires:e.expires,lastVerified:e.lastVerified}))}remove(t){let e=this.addresses.get(t.toString())?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(t.toString()),e}confirm(t,e){let n=t.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+e,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var nw=[4,41,53,54,55,56];function Nu(r){try{for(let{code:t}of r.getComponents())if(t!==42)return nw.includes(t)}catch{}return!1}var ow={maxObservedAddresses:10},Vi=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Tt({name:"libp2p_address_manager_transport_addresses",metrics:t.metrics}),this.maxObservedAddresses=e.maxObservedAddresses??ow.maxObservedAddresses}get(t,e){if(kr(t))return{multiaddr:t,verified:!0,type:"transport",expires:Date.now()+e,lastVerified:Date.now()};let n=this.toKey(t),o=this.addresses.get(n);return o==null&&(o={verified:!Nu(t),expires:0},this.addresses.set(n,o)),{multiaddr:t,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(t){let e=this.toKey(t);return this.addresses.has(e)}remove(t){let e=this.toKey(t),n=this.addresses.get(e)?.verified??!1;return this.log("removing observed address %a",t),this.addresses.delete(e),n}confirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+e,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(t,e){let n=this.toKey(t),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+e,this.addresses.set(n,o),s}toKey(t){if(Nu(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var Np=6e4,Bp={maxObservedAddresses:10,addressVerificationTTL:Np*10,addressVerificationRetry:Np*5},sw=r=>r;function Bu(r,t){let e=r.getPeerId();return e!=null&&ge(e).equals(t)&&(r=r.decapsulate(z(`/p2p/${t.toString()}`))),r}var zi=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(t,e={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=e;this.components=t,this.log=t.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new qi(t,e),this.dnsMappings=new Ui(t,e),this.ipMappings=new Fi(t,e),this.transportAddresses=new Vi(t,e),this.announceFilter=e.announceFilter??sw,this.observedAddressFilter=Lo(1024),this.addressVerificationTTL=e.addressVerificationTTL??Bp.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??Bp.addressVerificationRetry,this._updatePeerStoreAddresses=Uo(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),t.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let t=this.getAddresses().map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:t}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(t=>z(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>z(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>z(t))}getObservedAddrs(){return this.observed.getAll().map(t=>t.multiaddr)}addObservedAddr(t){let e=t.stringTuples(),n=`${e[0][1]}:${e[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),t=Bu(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=Bu(t,this.components.peerId);let n=!0;(e?.type==="transport"||this.transportAddresses.has(t))&&!this.transportAddresses.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="dns-mapping"||this.dnsMappings.has(t))&&!this.dnsMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="ip-mapping"||this.ipMappings.has(t))&&!this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(e?.type==="observed"||this.observed.has(t))&&(this.maybeUpgradeToIPMapping(t)?(this.ipMappings.confirm(t,e?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(t,e?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(t,e){t=Bu(t,this.components.peerId);let n=!1;this.observed.has(t)&&!this.observed.remove(t)&&n&&(n=!1),this.transportAddresses.has(t)&&!this.transportAddresses.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(t)&&!this.dnsMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(t)&&!this.ipMappings.unconfirm(t,e?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let t=new Set,e=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return t.has(o)?!1:(t.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(e.map(n=>{let o=z(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let t=this.getAnnounceAddrs();if(t.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(t)}),t.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let e=[];e=e.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),e=e.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),e=e.concat(this.observed.getAll()),e=e.concat(this.ipMappings.getAll(e)),e=e.concat(this.dnsMappings.getAll(e)),e}addDNSMapping(t,e){this.dnsMappings.add(t,e)}removeDNSMapping(t){this.dnsMappings.remove(z(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${ue(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(z(`/ip${ue(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(t){if(this.ipMappings.has(t))return!1;let e=t.toOptions();if(e.family===6||e.host==="127.0.0.1"||rr(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>Or.exactMatch(s)||Vo.exactMatch(s),s=>qo.exactMatch(s),s=>Pp.exactMatch(s)];for(let s of o){if(!s(t))continue;let i=n.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(t),this.ipMappings.add(c.host,c.port,e.host,e.port,e.transport),!0}return!1}};var Up;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Up||(Up={}));var $i=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Hi=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},Dn=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},$o=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},Wi=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},Gi=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},ji=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},Ho=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},Xi=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Zi=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},Yi=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Qi=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Ji=class extends Error{constructor(t="Connection denied"){super(t),this.name="ConnectionDeniedError"}},Mr=class extends Error{constructor(t="Stream is not multiplexed"){super(t),this.name="MuxerUnavailableError"}},Nr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},ta=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}},ea=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}};var Uu=class{components={};_started=!1;constructor(t={}){this.components={};for(let[e,n]of Object.entries(t))this.components[e]=n;this.components.logger==null&&(this.components.logger=ei())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>ls(e)).map(async e=>{await e[t]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},aw=["metrics","connectionProtector","dns"],cw=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Fp(r={}){let t=new Uu(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!cw.includes(o)){let i=t.components[o];if(i==null&&!aw.includes(o))throw new $i(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?t.components[o]=s:Reflect.set(n,o,s),!0}})}function Kp(r){let t={};for(let e of Object.values(r.components))for(let n of lw(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of uw(e))if(t[n]!==!0)throw new Hi(`Service "${fw(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function lw(r){return Array.isArray(r?.[Fn])?r[Fn]:[]}function uw(r){return Array.isArray(r?.[Va])?r[Va]:[]}function fw(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var dw=4,hw=41;function qp(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(Or.matches(t))return!1;let e=t.stringTuples();return e[0][0]===dw||e[0][0]===hw?!!rr(`${e[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var Vp=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},pw=new WeakMap;function mw({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Vp());let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(Vp())},u=()=>{o&&o.removeEventListener("abort",l)},f=new Promise((d,h)=>{i=()=>{u(),d(n)},a=h,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",l,{once:!0}),pw.set(f,()=>{c(s),s=null,i()}),f}}var gw=mw(),zp=gw;var ra=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(t="Rate limit exceeded",e){super(t),this.name="RateLimitError",this.remainingPoints=e.remainingPoints,this.msBeforeNext=e.msBeforeNext,this.consumedPoints=e.consumedPoints,this.isFirstInDuration=e.isFirstInDuration}},na=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var oa=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(t={}){this.points=t.points??4,this.duration=t.duration??1,this.blockDuration=t.blockDuration??0,this.execEvenly=t.execEvenly??!1,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=t.keyPrefix??"rlflx",this.memoryStorage=new Fu}async consume(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+e&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ra("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await zp(a)}return i}penalty(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(t,e=1,n={}){let o=this.getKey(t),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-e,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(t,e){let n=e*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(t),o,e),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(t,e,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(t),e,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:e,isFirstInDuration:!1}}get(t){let e=this.memoryStorage.get(this.getKey(t));return e!=null&&(e.remainingPoints=Math.max(this.points-e.consumedPoints,0)),e}delete(t){this.memoryStorage.delete(this.getKey(t))}_getKeySecDuration(t){return t?.customDuration!=null&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return t.substring(this.keyPrefix.length)}},Fu=class{storage;constructor(){this.storage=new Map}incrby(t,e,n){let o=this.storage.get(t);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=e,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(t,e,n)}return this.set(t,e,n)}set(t,e,n){let o=n*1e3,s=this.storage.get(t);s!=null&&clearTimeout(s.timeoutId);let i={value:e,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(t)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(t){let e=this.storage.get(t);if(e!=null)return{remainingPoints:0,msBeforeNext:e.expiresAt!=null?e.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:e.value,isFirstInDuration:!1}}delete(t){let e=this.storage.get(t);return e!=null?(e.timeoutId!=null&&clearTimeout(e.timeoutId),this.storage.delete(t),!0):!1}};function sa(r){if(Ke(r))return{peerId:r,multiaddrs:[]};let t=Array.isArray(r)?r:[r],e;if(t.length>0){let n=t[0].getPeerId();e=n==null?void 0:ge(n),t.forEach(o=>{if(!er(o))throw new qe("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(e!=null)throw new k("Multiaddrs must all have the same peer id or have no peer id")}else{let i=ge(s);if(e?.equals(i)!==!0)throw new k("Multiaddrs must all have the same peer id or have no peer id")}})}return t=t.filter(n=>!Cp.exactMatch(n)),{peerId:e,multiaddrs:t}}var yw=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function $p(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??yw;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}function Wo(r){try{let t;typeof r=="string"?t=z(r):t=r;let e=new Set([...t.getComponents().map(n=>n.name)]);if(!e.has("ipcidr")){let o=e.has("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(o)}return Jl(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var ia=class{connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.allow=(e.allow??[]).map(n=>Wo(n)),this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(t=>{this.log.error("error while pruning connections %e",t)})}async _maybePruneConnections(){let t=this.connectionManager.getConnections(),e=t.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",e,n),e<=n)return;let o=new te;for(let c of t){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",u)}}}let s=this.sortConnections(t,o),i=Math.max(e-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await $p(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(t,e){return t.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=e.get(n.remotePeer)??0,i=e.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Hp="last-dial-failure",Wp="last-dial-success";var Gp=100,aa=50;var ca=class{deferred;signal;constructor(t){this.signal=t,this.deferred=ut(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new re)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function bw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var la=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=bw(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new re),this.cleanup())}async join(t={}){let e=new ca(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await xt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Ln=class extends Vt{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Uo(this.emitEmpty.bind(this),1),this.emitIdle=Uo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new na;let n=new la(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new re)}),this.clear()}async onEmpty(t){this.size!==0&&await be(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await be(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await be(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=ii({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new re("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var ua=class extends Ln{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function Fe(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function jp(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Ku(r){if(!Ki(r))return!1;let{address:t}=r.nodeAddress();return jp(t)}function ww(r,t){let e=qo.exactMatch(r.multiaddr),n=qo.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=Vo.exactMatch(r.multiaddr),s=Vo.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=Or.exactMatch(r.multiaddr),a=Or.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Du.exactMatch(r.multiaddr),l=Du.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Tu.exactMatch(r.multiaddr),f=Tu.exactMatch(t.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Pu.exactMatch(r.multiaddr),h=Pu.exactMatch(t.multiaddr);return d&&!h?-1:!d&&h?1:0}function xw(r,t){let e=Ku(r.multiaddr),n=Ku(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Ew(r,t){let e=kr(r.multiaddr),n=kr(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function vw(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function _w(r,t){let e=zo.exactMatch(r.multiaddr),n=zo.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Xp(r){return r.sort(ww).sort(vw).sort(_w).sort(Ew).sort(xw)}async function qu(r,t,e){let n=e.depth??0;if(n>(e.maxRecursiveDepth??32))throw new ea("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(t))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,e);for(let c of a)s.push(...await qu(c,t,{...e,depth:n+1}))}return o===!1&&s.push(r),s}var Go={maxParallelDials:aa,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Ne}},fa=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??Go.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??Go.maxDialQueueLength,this.dialTimeout=e.dialTimeout??Go.dialTimeout,this.connections=e.connections??new te,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.resolvers=e.resolvers??Go.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new ua({concurrency:e.maxParallelDials??Go.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==re.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=sa(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0||a.limits!=null?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new dt("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new dt("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new $r("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new dt("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new dt("dial-queue:start-dial"));let c=Fe([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??Hu,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async dialPeer(t,e){let n=t.peerId,o=t.multiaddrs,s=new Set,i=t.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(t.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...t,signal:e});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),t?.onProgress?.(new dt("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,t.peerId),new $r("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...t,signal:e});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[Wp]:C(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}return p}catch(p){if(this.log.error("dial failed to %a",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[Hp]:C(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}if(e.aborted)throw new is(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(f=>({multiaddr:z(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new $r("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new Ho("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let f=await this.components.peerStore.get(t);o.push(...f.addresses),this.log("loaded multiaddrs for %p",t,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",t);try{let f=await this.components.peerRouting.findPeer(t,n);this.log("found multiaddrs for %p in the peer routing",t,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",t):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",t,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await qu(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(t!=null){let f=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return t!=null&&d!=null?t.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new Yi("The dial request has no valid addresses");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?Xp(l):l.sort(this.addressSorter);if(u.length===0)throw new Ho("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!zo.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var da=class extends Ln{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var rm=ts(tm(),1);var Aw=Object.prototype.toString,Cw=r=>Aw.call(r)==="[object Error]",Iw=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function Wu(r){return r&&Cw(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Iw.has(r.message):!1}var Gu=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},em=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function ju(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=rm.default.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});let i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),e(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Gu)throw c.originalError;if(c instanceof TypeError&&!Wu(c))throw c;if(em(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){em(l,a,t),i(),n(l)}}})})}var ha=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new da({concurrency:e.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=e.retries??5,this.backoffFactor=e.backoffFactor,this.retryInterval=e.retryInterval,this.events=t.events,t.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(t){if(!this.started)return;let e=await this.peerStore.get(t);nm(e)&&(this.queue.has(t)||this.queue.add(async n=>{await ju(async o=>{if(this.started)try{await this.connectionManager.openConnection(t,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",t,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:t}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",t,n);let o={};[...e.tags.keys()].forEach(s=>{s.startsWith(qa)&&(o[s]=void 0)}),await this.peerStore.merge(t,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",t,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let t=await this.peerStore.all({filters:[e=>nm(e)]});await Promise.all(t.map(async e=>{await this.connectionManager.openConnection(e.id).catch(n=>{this.log.error(n)})}))}).catch(t=>{this.log.error(t)})}stop(){this.started=!1,this.queue.abort()}};function nm(r){for(let t of r.tags.keys())if(t.startsWith(qa))return!0;return!1}var Hu=50,Xu={maxConnections:Gp,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},pa=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(t,e={}){if(this.maxConnections=e.maxConnections??Xu.maxConnections,this.maxConnections<1)throw new k("Connection Manager maxConnections must be greater than 0");this.connections=new te,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(e.allow??[]).map(n=>Wo(n)),this.deny=(e.deny??[]).map(n=>Wo(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??Xu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new oa({points:e.inboundConnectionThreshold??Xu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ia({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{allow:e.allow?.map(n=>z(n))}),this.dialQueue=new fa(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??aa,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:Ne},connections:this.connections}),this.reconnectQueue=new ha({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:e.reconnectRetries,retryInterval:e.reconnectRetryInterval,backoffFactor:e.reconnectBackoffFactor,maxParallelReconnects:e.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let t={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let e of this.connections.values())for(let n of e)t[n.direction]++;return t}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let t={};for(let e of this.connections.values())for(let n of e)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;t[s]=(t[s]??0)+1}return t}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let t={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))t[i]=t[i]??[],t[i].push(a)}let e={};for(let[n,o]of Object.entries(t)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);e[n]=o[s]}return e}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await uf(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 ff(this.reconnectQueue,this.dialQueue,this.connectionPruner);let t=[];for(let e of this.connections.values())for(let n of e)t.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",t.length),await Promise.all(t),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(t){if(this.maxConnections<1)throw new k("Connection Manager maxConnections must be greater than 0");let e=!1;t<this.maxConnections&&(e=!0),this.maxConnections=t,e&&this.connectionPruner.maybePruneConnections()}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new we("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=sa(t);if(this.peerId.equals(n))throw new zr("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p as %a",n,a.remoteAddr),e.onProgress?.(new dt("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??Hu});if(o.status!=="open")throw new Vr("Remote closed connection during opening");let s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)if(a.id===o.id&&(i=!0),e.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new qe("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(t,e={}){let n=this.connections.get(t)??[];await Promise.all(n.map(async o=>{try{await o.close(e)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(t){if(this.deny.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(this.allow.some(o=>o.contains(t.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){let o=t.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let t={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(e=>({id:e.id,status:t[e.status],peerId:e.options.peerId,multiaddrs:[...e.options.multiaddrs].map(n=>z(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var Rn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(t){this.timeSpan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(t,e){return 1-Math.exp(-(t-e)/this.timeSpan)}push(t,e=Date.now()){if(this.previousTime!=null){let n=this.alpha(e,this.previousTime),o=t-this.movingAverage,s=n*o;this.movingAverage=n*t+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=t;this.previousTime=e}};var Dw=1.2,Lw=2,Rw=5e3,Ow=6e4,kw=5e3,ma=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(t={}){let e=t.interval??kw;this.success=new Rn(e),this.failure=new Rn(e),this.next=new Rn(e),this.failureMultiplier=t.failureMultiplier??Lw,this.timeoutMultiplier=t.timeoutMultiplier??Dw,this.minTimeout=t.minTimeout??Rw,this.maxTimeout=t.maxTimeout??Ow,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier));e<this.minTimeout&&(e=this.minTimeout),e>this.maxTimeout&&(e=this.maxTimeout);let n=AbortSignal.timeout(e),o=Fe([t.signal,n]);return o.start=Date.now(),o.timeout=e,o}cleanUp(t){let e=Date.now()-t.start;t.aborted?(this.failure.push(e),this.next.push(e*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:e})):(this.success.push(e),this.next.push(e),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:e}))}};var Zu=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ut(),this.haveNext=ut()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ut(),t}async throw(t){return this.ended=!0,this.error=t,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return this.ended=!0,this.nextResult=t,this.haveNext.resolve(),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ut(),await xt(this.readNext.promise,e?.signal,e)}};function ga(){return new Zu}var ya=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ba(r,t){let e=ga();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new W;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await xt(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await xt(n.next(),i?.signal);if(l===!0)throw new ya("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Mw=1e4,Nw="1.0.0",Bw="ping",Uw="ipfs",om=32,Fw=!0,wa=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??Uw}/${Bw}/${Nw}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??Mw,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??Fw,this.timeout=new ma({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Fn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(t=>{Promise.resolve().then(async()=>{let e=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await t.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=ba(o);e=Date.now(),await Promise.all([s.write(un(om),{signal:n}),s.read({bytes:om,signal:n})]),t.rtt=Date.now()-e,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;t.rtt=(Date.now()-e)/2}}).catch(e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function Kw(r){return r[Symbol.asyncIterator]!=null}async function qw(r,t,e){try{await Promise.all(r.map(async n=>{for await(let o of n)await t.push(o,{signal:e}),e.throwIfAborted()})),await t.end(void 0,{signal:e})}catch(n){await t.end(n,{signal:e}).catch(()=>{})}}async function*Vw(r){let t=new AbortController,e=ga();qw(r,e,t.signal).catch(()=>{});try{yield*e}finally{t.abort()}}function*zw(r){for(let t of r)yield*t}function $w(...r){let t=[];for(let e of r)Kw(e)||t.push(e);return t.length===r.length?zw(t):Vw(r)}var jo=$w;var xa=class{routers;started;components;constructor(t,e){this.routers=e.routers??[],this.started=!1,this.components=t,this.findProviders=t.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=t.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=t.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=t.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:U(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:U(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(t,e={}){if(this.routers.length===0)throw new Dn("No content routers available");let n=this,o=new Ar;for await(let s of jo(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(t,e))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},e),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new Dn("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(this.routers.length===0)throw new Dn("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new we;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new we;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(t,e)))}};var Ea=globalThis.CustomEvent??Event;async function*Yu(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered??!1,o=new EventTarget,s=[],i=ut(),a=ut(),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===e&&(i=ut(),await i.promise),u)break;let m={done:!1};s.push(m),p().then(x=>{m.done=!0,m.ok=!0,m.value=x,o.dispatchEvent(new Ea("task-complete"))},x=>{m.done=!0,m.err=x,o.dispatchEvent(new Ea("task-complete"))})}c=!0,o.dispatchEvent(new Ea("task-complete"))}catch(p){l=p,o.dispatchEvent(new Ea("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 m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(f()||(a=ut(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var va=class{log;peerId;peerStore;routers;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=e.routers??[],this.findPeer=t.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=t.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:U(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(t,e){if(this.routers.length===0)throw new $o("No peer routers available");if(t.toString()===this.peerId.toString())throw new Wi("Should not try to find self");let n=this,o=jo(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>async function*(){try{yield await s.findPeer(t,e)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},e),s;throw new sr}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new $o("No peer routers available");let n=this,o=Lo(1024);for await(let s of Yu(async function*(){let i=jo(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(t,e)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...e,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},e),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var _a=class extends Vt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(t){super(),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(t){this.walking||this.startWalk(),this.walkers++;let e=Fe([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ut(),yield(await be(this,"walk:peer",e,{errorEvent:"walk:error"})).detail}finally{e.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let t=Fe([this.walkController.signal,this.shutdownController.signal]);let e=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=un(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:t}))t.aborted&&this.log("aborting walk"),t.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await xt(this.needNext.promise,t)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-e),this.walking=!1})}};var Qu=32,Ju=64,Sa=class{log;topologies;handlers;components;constructor(t){this.components=t,this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,t.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let e={};for(let[n,o]of this.topologies)e[n]=o.size;return e}}),this.handlers=Tt({name:"libp2p_registrar_protocol_handlers",metrics:t.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(t){let e=this.handlers.get(t);if(e==null)throw new Gi(`No handler registered for protocol ${t}`);return e}getTopologies(t){let e=this.topologies.get(t);return e==null?[]:[...e.values()]}async handle(t,e,n){if(this.handlers.has(t)&&n?.force!==!0)throw new ji(`Handler already registered for protocol ${t}`);let o=Bs.bind({ignoreUndefined:!0})({maxInboundStreams:Qu,maxOutboundStreams:Ju},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]},n)}async unhandle(t,e){(Array.isArray(t)?t:[t]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},e)}async register(t,e){if(e==null)throw new k("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(t);return o==null&&(o=new Map,this.topologies.set(t,o)),o.set(n,e),n}unregister(t){for(let[e,n]of this.topologies.entries())n.has(t)&&(n.delete(t),n.size===0&&this.topologies.delete(e))}_onDisconnect(t){let e=t.detail,n={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(e,n).then(o=>{for(let s of o.protocols){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e)!==!1&&(a.filter?.remove(e),a.onDisconnect?.(e))}}).catch(o=>{o.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,o)})}_onPeerUpdate(t){let{peer:e,previous:n}=t.detail,o=(n?.protocols??[]).filter(s=>!e.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(e.id)!==!1&&(a.filter?.remove(e.id),a.onDisconnect?.(e.id))}}_onPeerIdentify(t){let e=t.detail.protocols,n=t.detail.connection,o=t.detail.peerId;for(let s of e){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Aa=class{log;components;transports;listeners;faultTolerance;started;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=Tt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Tt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??or.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(t){let e=t[Symbol.toStringTag];if(e==null)throw new k("Transport must have a valid tag");if(this.transports.has(e))throw new k(`There is already a transport with the tag ${e}`);this.log("adding transport %s",e),this.transports.set(e,t),this.listeners.has(e)||this.listeners.set(e,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let t=this.components.addressManager.getListenAddrs();await this.listen(t)}async stop(){let t=[];for(let[e,n]of this.listeners)for(this.log("closing listeners for %s",e);n.length>0;){let o=n.pop();o!=null&&t.push(o.close())}await Promise.all(t),this.log("all listeners closed");for(let e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(t,e){let n=this.dialTransportForMultiaddr(t);if(n==null)throw new ta(`No transport available for address ${String(t)}`);return e?.onProgress?.(new dt("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(t,{...e,upgrader:this.components.upgrader})}getAddrs(){let t=[];for(let e of this.listeners.values())for(let n of e)t=[...t,...n.getAddrs()];return t}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(t){for(let e of this.transports.values())if(e.dialFilter([t]).length>0)return e}listenTransportForMultiaddr(t){for(let e of this.transports.values())if(e.listenFilter([t]).length>0)return e}async listen(t){if(!this.isStarted())throw new we("Not started");if(t==null||t.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach(s=>{e.errors.set(s.toString(),new Xi)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(t);for(let c of a){this.log("creating listener for %s on %a",s,c);let 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})}),Su.matches(c)?e.ipv4.attempts++:Au.matches(c)&&e.ipv6.attempts++,n.push(l.listen(c).then(()=>{e.errors.delete(c.toString()),Su.matches(c)&&e.ipv4.success++,Au.matches(c)&&e.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),e.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(e)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===or.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Zi(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
3
3
  ${[...e.errors.entries()].map(([s,i])=>`
4
4
  ${s}: ${`${i.stack??i}`.split(`
5
5
  `).join(`
6
6
  `)}
7
- `).join("")}`)}}ipv6Unsupported(t){if(t.ipv4.attempts===0||t.ipv6.attempts===0)return!1;let e=t.ipv4.attempts===t.ipv4.success,n=t.ipv6.success===0;return e&&n}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var xt="/multistream/1.0.0";var Ca=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ia=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ta=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Yo(r,t={}){let e=ba(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=mt(t.maxDataLength));let n=t?.lengthDecoder??mr,o=t?.lengthEncoder??de;return{read:async i=>{let a=-1,c=new $;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Ca("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ta("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ia("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new $(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new $(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var zw=P(`
8
- `);async function Kr(r,t,e){await r.write(t,e)}async function em(r,t,e){await r.writeV(t,e)}async function Vw(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==zw[0])throw t.log.error("Invalid mss message - missing newline",e),new is("Missing newline");return e.sublist(0,-1)}async function tr(r,t){let e=await Vw(r,t);return N(e.subarray())}async function kn(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return Hw(r,t[0],e);let n=Yo(r,{...e,maxDataLength:1024}),o=t.shift();if(o==null)throw new Error("At least one protocol must be specified");e.log.trace('select: write ["%s", "%s"]',xt,o);let s=P(`${xt}
9
- `),i=P(`${o}
10
- `);await em(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await tr(n,e);if(e.log.trace('select: read "%s"',a),a===xt&&(e.log.trace("select: reading protocol response"),a=await tr(n,e),e.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of t){e.log.trace('select: write "%s"',c),await Kr(n,P(`${c}
11
- `),e),e.log.trace("select: reading protocol response");let l=await tr(n,e);if(e.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:n.unwrap(),protocol:c}}throw new Kn("protocol selection failed")}function Hw(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=lt(),c=!1,l=!1,u=lt(),f=!1,d=!1,h=lt(),p=Yo({sink:n,source:o},{...e,maxDataLength:1024});r.sink=async v=>{let{sink:_}=p.unwrap();await _(async function*(){let A=!1;for await(let O of v){if(l&&await u.promise,c)yield O;else{l=!0,e.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',xt,t,O.byteLength);let C=`${t}
12
- `;yield new $(Uint8Array.from([19]),P(`${xt}
13
- `),de(C.length),P(C),O).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',xt,t,O.byteLength),c=!0,l=!1,u.resolve(),g().catch(F=>{e.log.error("could not finish optimistic protocol negotiation of %s",t,F)})}A=!0}A||await g()}())};async function g(){if(i){e.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}i=!0;try{c||(e.log.trace("optimistic: doing send protocol for %s stream",t),await m()),f||(e.log.trace("optimistic: doing read protocol for %s stream",t),await E())}finally{i=!1,s=!0,a.resolve()}}async function m(){if(l){await u.promise;return}l=!0;try{e.log.trace('optimistic: write ["%s", "%s", data] in source',xt,t),await p.writeV([P(`${xt}
14
- `),P(`${t}
15
- `)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',xt,t)}finally{c=!0,l=!1,u.resolve()}}async function E(){if(d){await h.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let v=await tr(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',v),v===xt&&(v=await tr(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',v,t),v!==t)throw new Kn("protocol selection failed")}finally{f=!0,d=!1,h.resolve()}}if(r.source=async function*(){await g(),e.log.trace('optimistic: reading data from "%s" stream',t),yield*p.unwrap().source}(),r.closeRead!=null){let v=r.closeRead.bind(r);r.closeRead=async _=>{s||await g().catch(A=>{e.log.error("could not negotiate protocol before close read",A)}),await v(_)}}if(r.closeWrite!=null){let v=r.closeWrite.bind(r);r.closeWrite=async _=>{s||await g().catch(A=>{e.log.error("could not negotiate protocol before close write",A)}),await v(_)}}if(r.close!=null){let v=r.close.bind(r);r.close=async _=>{let A=[];l&&A.push(u.promise),d&&A.push(h.promise),A.length>0?await wt(Promise.all(A),_?.signal):(s=!0,i=!1,a.resolve()),await v(_)}}return{stream:r,protocol:t}}var Pa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Mn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Da=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Qo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function La(r){return r[Symbol.asyncIterator]!=null}function nm(r,t){if(r.byteLength>t)throw new Mn("Message length too long")}var Oa=r=>{let t=mt(r),e=Et(t);return de(r,e),Oa.bytes=t,e};Oa.bytes=0;function ka(r,t){t=t??{};let e=t.lengthEncoder??Oa,n=t?.maxDataLength??4194304;function*o(s){nm(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return La(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}ka.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Oa,n=t?.maxDataLength??4194304;return nm(r,n),new $(e(r.byteLength),r)};var qr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(qr||(qr={}));var Yu=r=>{let t=mr(r);return Yu.bytes=mt(t),t};Yu.bytes=0;function Zu(r,t){let e=new $,n=qr.LENGTH,o=-1,s=t?.lengthDecoder??Yu,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===qr.LENGTH)try{if(o=s(e),o<0)throw new Pa("Invalid message length");if(o>a)throw new Mn("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=qr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Da("Message length length too long");break}throw l}if(n===qr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=qr.LENGTH}}}return La(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Qo("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Qo("Unexpected end of input")}()}Zu.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return Zu(n,{...t??{},onLength:s=>{e=s}})};async function Nn(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=Yo(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await tr(n,e);if(e.log.trace('handle: read "%s"',o),o===xt){e.log.trace('handle: respond with "%s" for "%s"',xt,o),await Kr(n,P(`${xt}
16
- `),e),e.log.trace('handle: responded with "%s" for "%s"',xt,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await Kr(n,P(`${o}
17
- `),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new $(...t.map(i=>ka.single(P(`${i}
18
- `))),P(`
19
- `));e.log.trace('handle: respond with "%s" for %s',t,o),await Kr(n,s,e),e.log.trace('handle: responded with "%s" for %s',t,o);continue}e.log.trace('handle: respond with "na" for "%s"',o),await Kr(n,P(`na
20
- `),e),e.log('handle: responded with "na" for "%s"',o)}}var Ww=500,Ju=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;constructor(t,e){this.components=t,this.id=e.id,this.remoteAddr=e.maConn.remoteAddr,this.remotePeer=e.remotePeer,this.direction=e.direction??"outbound",this.status="open",this.timeline=e.maConn.timeline,this.encryption=e.encryption,this.limits=e.limits,this.maConn=e.maConn,this.log=e.maConn.log,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this.tags=[],e.muxerFactory!=null&&(this.multiplexer=e.muxerFactory.protocol,this.muxer=e.muxerFactory.createStreamMuxer({direction:this.direction,log:this.log,onIncomingStream:n=>{this.onIncomingStream(n)}}),Promise.all([this.muxer.sink(this.maConn.source),this.maConn.sink(this.muxer.source)]).catch(n=>{this.log.error("error piping data through muxer - %e",n)}))}[Symbol.toStringTag]="Connection";[nf]=!0;get streams(){return this.muxer?.streams??[]}newStream=async(t,e={})=>{if(this.status==="closing")throw new ns("the connection is being closed");if(this.status==="closed")throw new Hr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new qn("Cannot open protocol stream on limited connection");if(this.muxer==null)throw new Br("Connection is not multiplexed");this.log.trace("starting new stream for protocols %s",t);let n=await this.muxer.newStream();this.log.trace("started new stream %s for protocols %s",n.id,t);try{if(e.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);e={...e,signal:c}}n.log.trace("selecting protocol from protocols %s",t);let{stream:o,protocol:s}=await kn(n,t,{...e,log:n.log,yieldBytes:!0});n.log("selected protocol %s",s);let i=jw(s,this.components.registrar,e),a=sm(s,"outbound",this);if(a>=i){let c=new ls(`Too many outbound protocol streams for protocol "${s}" - ${a}/${i}`);throw n.abort(c),c}return await this.components.peerStore.merge(this.remotePeer,{protocols:[s]}),n.source=o.source,n.sink=o.sink,n.protocol=s,o.closeWrite!=null&&(n.closeWrite=o.closeWrite),o.closeRead!=null&&(n.closeRead=o.closeRead),o.close!=null&&(n.close=o.close),this.components.metrics?.trackProtocolStream(n,this),n.direction="outbound",n}catch(o){throw this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,t,o),n.timeline.close==null&&n.abort(o),o}};onIncomingStream(t){let e=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{let n=this.components.registrar.getProtocols(),{stream:o,protocol:s}=await Nn(t,n,{signal:e,log:t.log,yieldBytes:!1});this.log("incoming %s stream opened",s);let i=Gw(s,this.components.registrar);if(sm(s,"inbound",this)===i){let u=new cs(`Too many inbound protocol streams for protocol "${s}" - limit ${i}`);throw t.abort(u),u}t.source=o.source,t.sink=o.sink,t.protocol=s,o.closeWrite!=null&&(t.closeWrite=o.closeWrite),o.closeRead!=null&&(t.closeRead=o.closeRead),o.close!=null&&(t.close=o.close),await this.components.peerStore.merge(this.remotePeer,{protocols:[s]},{signal:e}),this.components.metrics?.trackProtocolStream(t,this);let{handler:c,options:l}=this.components.registrar.getHandler(s);if(this.limits!=null&&l.runOnLimitedConnection!==!0)throw new qn("Cannot open protocol stream on limited connection");await c({connection:this,stream:t})}).catch(async n=>{this.log.error("error handling incoming stream id %s - %e",t.id,n),t.abort(n)})}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(Ww);t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this.muxer?.close(t),await this.maConn.close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.muxer?.abort(t),this.maConn.abort(t),this.status="closed",this.timeline.close=Date.now())}};function im(r,t){return new Ju(r,t)}function Gw(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Gu}function jw(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??ju}function sm(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Ma=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=It({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=It({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new Qi(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Be([AbortSignal.timeout(this.inboundUpgradeTimeout),t]);return e}async upgradeInbound(t,e){let n=!1,o=this.createInboundAbortSignal(e.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await wt(this.components.connectionManager.acceptIncomingConnection(t),o),!n)throw new Ji("Connection denied");await wt(this.shouldBlockConnection("denyInboundConnection",t),o),await this._performUpgrade(t,"inbound",{...e,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=pe(n),await wt(this.shouldBlockConnection("denyOutboundConnection",o,t),e.signal));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;t.log=t.log.newScope(`${e}:${l}`),this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let u=t;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the %s connection",e),u=await d.protect(t,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new ft(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(u,n):this._encryptOutbound(u,n));let d={...u,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new Ke(`${e} connection that skipped encryption must have a peer id`);let h=pe(d);c="native",s=h}if(s.equals(this.components.peerId)){let d=new $r("Can not dial self");throw t.abort(d),d}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new ft(`upgrader:multiplex-${e}-connection`));let d=await(e==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,d),d}await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t);let f=this._createConnection({id:l,cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits});return f.log("successfully upgraded %s connection",e),f}_createConnection(t){let{id:e,cryptoProtocol:n,direction:o,maConn:s,upgradedConn:i,remotePeer:a,muxerFactory:c,limits:l}=t,u,f=s.timeline;return s.timeline=new Proxy(f,{set:(...d)=>(d[1]==="close"&&d[2]!=null&&f.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(h){u.log.error("error closing connection after timeline close %e",h)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(h=>{u.log.error("error thrown while dispatching connection:close event %e",h)}),Reflect.set(...d))}),s.timeline.upgraded=Date.now(),u=im(this.components,{id:e,maConn:i,remotePeer:a,direction:o,muxerFactory:c,encryption:n,limits:l,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout}),this.events.safeDispatchEvent("connection:open",{detail:u}),u}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await Nn(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Fr(`no crypto module found for ${s}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,o),new Fr(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await kn(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Fr(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,s),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,o),new Fr(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await kn(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new Br(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await Nn(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new Br(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var Na="2.9.0-cb1c14e62",Ba="js-libp2p";function cm(r,t){return`${r??Ba}/${t??Na} browser/${globalThis.navigator.userAgent}`}var Jo=class extends qt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new qt,n=e.dispatchEvent.bind(e);e.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=t.peerId,this.logger=t.logger??ei(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Ba,s=t.nodeInfo?.version??Na,i=this.components=Mp({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??cm(o,s)},logger:this.logger,events:e,datastore:t.datastore??new Ri,connectionGater:Bp(t.connectionGater),dns:t.dns});t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",bp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.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})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new Ma(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(t.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Aa(this.components,t.transportManager)),this.configureComponent("connectionManager",new pa(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new wa(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Sa(this.components)),this.configureComponent("addressManager",new Vi(this.components,t.addresses));let a=(t.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new va(this.components,{routers:a}));let c=(t.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new xa(this.components,{routers:c})),this.configureComponent("randomWalk",new _a(this.components)),(t.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),t.services!=null)for(let l of Object.keys(t.services)){let u=t.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[Fa]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Fa])),f[Ka]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Ka])),f[Ua]!=null&&(this.log("registering service %s for peer discovery",l),f[Ua].addEventListener?.("peer",d=>{this.#t(d)}))}Np(i)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new Ir;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new R("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new R("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){Qe(t)&&(t=pe(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t,e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=re([P("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=mn(o);return await this.peerStore.patch(t,{publicKey:s},e),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t,e){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async n=>{await this.components.registrar.unhandle(n,e)}))}async register(t,e,n){return this.components.registrar.register(t,e,n)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Xw(r={}){r.privateKey??=await ah("Ed25519");let t=new Jo({...await Hh(r),peerId:fh(r.privateKey)});return r.start!==!1&&await t.start(),t}var Zw=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Yw(r){return r==null?!1:r instanceof Jo?!0:Zw.every(t=>typeof r[t]=="function")}return pm(Qw);})();
7
+ `).join("")}`)}}ipv6Unsupported(t){if(t.ipv4.attempts===0||t.ipv6.attempts===0)return!1;let e=t.ipv4.attempts===t.ipv4.success,n=t.ipv6.success===0;return e&&n}async remove(t){let e=this.listeners.get(t)??[];this.log.trace("removing transport %s",t);let n=[];for(this.log.trace("closing listeners for %s",t);e.length>0;){let o=e.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(t),this.listeners.delete(t)}async removeAll(){let t=[];for(let e of this.transports.keys())t.push(this.remove(e));await Promise.all(t)}};var Et="/multistream/1.0.0";var Ca=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ia=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ta=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Xo(r,t={}){let e=ba(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=gt(t.maxDataLength));let n=t?.lengthDecoder??hr,o=t?.lengthEncoder??pe;return{read:async i=>{let a=-1,c=new W;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Ca("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ta("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ia("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new W(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new W(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var Ww=C(`
8
+ `);async function Ur(r,t,e){await r.write(t,e)}async function sm(r,t,e){await r.writeV(t,e)}async function Gw(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==Ww[0])throw t.log.error("Invalid mss message - missing newline",e),new ss("Missing newline");return e.sublist(0,-1)}async function nr(r,t){let e=await Gw(r,t);return U(e.subarray())}async function On(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return jw(r,t[0],e);let n=Xo(r,{...e,maxDataLength:1024}),o=t.shift();if(o==null)throw new Error("At least one protocol must be specified");e.log.trace('select: write ["%s", "%s"]',Et,o);let s=C(`${Et}
9
+ `),i=C(`${o}
10
+ `);await sm(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await nr(n,e);if(e.log.trace('select: read "%s"',a),a===Et&&(e.log.trace("select: reading protocol response"),a=await nr(n,e),e.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of t){e.log.trace('select: write "%s"',c),await Ur(n,C(`${c}
11
+ `),e),e.log.trace("select: reading protocol response");let l=await nr(n,e);if(e.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:n.unwrap(),protocol:c}}throw new Bn("protocol selection failed")}function jw(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=ut(),c=!1,l=!1,u=ut(),f=!1,d=!1,h=ut(),p=Xo({sink:n,source:o},{...e,maxDataLength:1024});r.sink=async _=>{let{sink:w}=p.unwrap();await w(async function*(){let A=!1;for await(let R of _){if(l&&await u.promise,c)yield R;else{l=!0,e.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Et,t,R.byteLength);let K=`${t}
12
+ `;yield new W(Uint8Array.from([19]),C(`${Et}
13
+ `),pe(K.length),C(K),R).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Et,t,R.byteLength),c=!0,l=!1,u.resolve(),m().catch(V=>{e.log.error("could not finish optimistic protocol negotiation of %s",t,V)})}A=!0}A||await m()}())};async function m(){if(i){e.log.trace("optimistic: already negotiating %s stream",t),await a.promise;return}i=!0;try{c||(e.log.trace("optimistic: doing send protocol for %s stream",t),await x()),f||(e.log.trace("optimistic: doing read protocol for %s stream",t),await g())}finally{i=!1,s=!0,a.resolve()}}async function x(){if(l){await u.promise;return}l=!0;try{e.log.trace('optimistic: write ["%s", "%s", data] in source',Et,t),await p.writeV([C(`${Et}
14
+ `),C(`${t}
15
+ `)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',Et,t)}finally{c=!0,l=!1,u.resolve()}}async function g(){if(d){await h.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let _=await nr(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',_),_===Et&&(_=await nr(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',_,t),_!==t)throw new Bn("protocol selection failed")}finally{f=!0,d=!1,h.resolve()}}if(r.source=async function*(){await m(),e.log.trace('optimistic: reading data from "%s" stream',t),yield*p.unwrap().source}(),r.closeRead!=null){let _=r.closeRead.bind(r);r.closeRead=async w=>{s||await m().catch(A=>{e.log.error("could not negotiate protocol before close read",A)}),await _(w)}}if(r.closeWrite!=null){let _=r.closeWrite.bind(r);r.closeWrite=async w=>{s||await m().catch(A=>{e.log.error("could not negotiate protocol before close write",A)}),await _(w)}}if(r.close!=null){let _=r.close.bind(r);r.close=async w=>{let A=[];l&&A.push(u.promise),d&&A.push(h.promise),A.length>0?await xt(Promise.all(A),w?.signal):(s=!0,i=!1,a.resolve()),await _(w)}}return{stream:r,protocol:t}}var Pa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},kn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Da=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Zo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function La(r){return r[Symbol.asyncIterator]!=null}function am(r,t){if(r.byteLength>t)throw new kn("Message length too long")}var Oa=r=>{let t=gt(r),e=_t(t);return pe(r,e),Oa.bytes=t,e};Oa.bytes=0;function ka(r,t){t=t??{};let e=t.lengthEncoder??Oa,n=t?.maxDataLength??4194304;function*o(s){am(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return La(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}ka.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Oa,n=t?.maxDataLength??4194304;return am(r,n),new W(e(r.byteLength),r)};var Fr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Fr||(Fr={}));var rf=r=>{let t=hr(r);return rf.bytes=gt(t),t};rf.bytes=0;function ef(r,t){let e=new W,n=Fr.LENGTH,o=-1,s=t?.lengthDecoder??rf,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Fr.LENGTH)try{if(o=s(e),o<0)throw new Pa("Invalid message length");if(o>a)throw new kn("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=Fr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Da("Message length length too long");break}throw l}if(n===Fr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=Fr.LENGTH}}}return La(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Zo("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Zo("Unexpected end of input")}()}ef.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return ef(n,{...t??{},onLength:s=>{e=s}})};async function Mn(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=Xo(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await nr(n,e);if(e.log.trace('handle: read "%s"',o),o===Et){e.log.trace('handle: respond with "%s" for "%s"',Et,o),await Ur(n,C(`${Et}
16
+ `),e),e.log.trace('handle: responded with "%s" for "%s"',Et,o);continue}if(t.includes(o))return e.log.trace('handle: respond with "%s" for "%s"',o,o),await Ur(n,C(`${o}
17
+ `),e),e.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new W(...t.map(i=>ka.single(C(`${i}
18
+ `))),C(`
19
+ `));e.log.trace('handle: respond with "%s" for %s',t,o),await Ur(n,s,e),e.log.trace('handle: responded with "%s" for %s',t,o);continue}e.log.trace('handle: respond with "na" for "%s"',o),await Ur(n,C(`na
20
+ `),e),e.log('handle: responded with "na" for "%s"',o)}}var Zw=500,of=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;constructor(t,e){this.components=t,this.id=e.id,this.remoteAddr=e.maConn.remoteAddr,this.remotePeer=e.remotePeer,this.direction=e.direction??"outbound",this.status="open",this.timeline=e.maConn.timeline,this.encryption=e.encryption,this.limits=e.limits,this.maConn=e.maConn,this.log=e.maConn.log,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this.tags=[],e.muxerFactory!=null&&(this.multiplexer=e.muxerFactory.protocol,this.muxer=e.muxerFactory.createStreamMuxer({direction:this.direction,log:this.log,onIncomingStream:n=>{this.onIncomingStream(n)}}),Promise.all([this.muxer.sink(this.maConn.source),this.maConn.sink(this.muxer.source)]).catch(n=>{this.log.error("error piping data through muxer - %e",n)}))}[Symbol.toStringTag]="Connection";[lf]=!0;get streams(){return this.muxer?.streams??[]}newStream=async(t,e={})=>{if(this.status==="closing")throw new rs("the connection is being closed");if(this.status==="closed")throw new Vr("the connection is closed");if(Array.isArray(t)||(t=[t]),this.limits!=null&&e?.runOnLimitedConnection!==!0)throw new Un("Cannot open protocol stream on limited connection");if(this.muxer==null)throw new Mr("Connection is not multiplexed");this.log.trace("starting new stream for protocols %s",t);let n=await this.muxer.newStream();this.log.trace("started new stream %s for protocols %s",n.id,t);try{if(e.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);e={...e,signal:c}}n.log.trace("selecting protocol from protocols %s",t);let{stream:o,protocol:s}=await On(n,t,{...e,log:n.log,yieldBytes:!0});n.log("selected protocol %s",s);let i=Qw(s,this.components.registrar,e),a=lm(s,"outbound",this);if(a>=i){let c=new cs(`Too many outbound protocol streams for protocol "${s}" - ${a}/${i}`);throw n.abort(c),c}return await this.components.peerStore.merge(this.remotePeer,{protocols:[s]}),n.source=o.source,n.sink=o.sink,n.protocol=s,o.closeWrite!=null&&(n.closeWrite=o.closeWrite),o.closeRead!=null&&(n.closeRead=o.closeRead),o.close!=null&&(n.close=o.close),this.components.metrics?.trackProtocolStream(n,this),n.direction="outbound",n}catch(o){throw this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,t,o),n.timeline.close==null&&n.abort(o),o}};onIncomingStream(t){let e=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{let n=this.components.registrar.getProtocols(),{stream:o,protocol:s}=await Mn(t,n,{signal:e,log:t.log,yieldBytes:!1});this.log("incoming %s stream opened",s);let i=Yw(s,this.components.registrar);if(lm(s,"inbound",this)===i){let u=new as(`Too many inbound protocol streams for protocol "${s}" - limit ${i}`);throw t.abort(u),u}t.source=o.source,t.sink=o.sink,t.protocol=s,o.closeWrite!=null&&(t.closeWrite=o.closeWrite),o.closeRead!=null&&(t.closeRead=o.closeRead),o.close!=null&&(t.close=o.close),await this.components.peerStore.merge(this.remotePeer,{protocols:[s]},{signal:e}),this.components.metrics?.trackProtocolStream(t,this);let{handler:c,options:l}=this.components.registrar.getHandler(s);if(this.limits!=null&&l.runOnLimitedConnection!==!0)throw new Un("Cannot open protocol stream on limited connection");await c({connection:this,stream:t})}).catch(async n=>{this.log.error("error handling incoming stream id %s - %e",t.id,n),t.abort(n)})}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(Zw);t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this.muxer?.close(t),await this.maConn.close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this.muxer?.abort(t),this.maConn.abort(t),this.status="closed",this.timeline.close=Date.now())}};function um(r,t){return new of(r,t)}function Yw(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Qu}function Qw(r,t,e={}){try{let{options:n}=t.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return e.maxOutboundStreams??Ju}function lm(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Ma=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=Tt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Tt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),e.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=e.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=e.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=e.outboundStreamProtocolNegotiationTimeout??1e4,this.events=t.events,this.metrics={dials:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:t.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(t,...e){let n=this.components.connectionGater[t];if(n==null)return;if(await n.apply(this.components.connectionGater,e)===!0)throw new Qi(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=Fe([AbortSignal.timeout(this.inboundUpgradeTimeout),t]);return e}async upgradeInbound(t,e){let n=!1,o=this.createInboundAbortSignal(e.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await xt(this.components.connectionManager.acceptIncomingConnection(t),o),!n)throw new Ji("Connection denied");await xt(this.shouldBlockConnection("denyInboundConnection",t),o),await this._performUpgrade(t,"inbound",{...e,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(t,e){try{this.metrics.dials?.increment({outbound:!0});let n=t.remoteAddr.getPeerId(),o;n!=null&&(o=ge(n),await xt(this.shouldBlockConnection("denyOutboundConnection",o,t),e.signal));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;t.log=t.log.newScope(`${e}:${l}`),this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let u=t;if(n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(t.log("protecting the %s connection",e),u=await d.protect(t,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new dt(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(e==="inbound"?this._encryptInbound(u,n):this._encryptOutbound(u,n));let d={...u,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,d)}else{let d=t.remoteAddr.getPeerId();if(d==null)throw new qe(`${e} connection that skipped encryption must have a peer id`);let h=ge(d);c="native",s=h}if(s.equals(this.components.peerId)){let d=new zr("Can not dial self");throw t.abort(d),d}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new dt(`upgrader:multiplex-${e}-connection`));let d=await(e==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=d.muxerFactory,i=d.stream}}catch(d){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,d),d}await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t);let f=this._createConnection({id:l,cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits});return f.log("successfully upgraded %s connection",e),f}_createConnection(t){let{id:e,cryptoProtocol:n,direction:o,maConn:s,upgradedConn:i,remotePeer:a,muxerFactory:c,limits:l}=t,u,f=s.timeline;return s.timeline=new Proxy(f,{set:(...d)=>(d[1]==="close"&&d[2]!=null&&f.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(h){u.log.error("error closing connection after timeline close %e",h)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(h=>{u.log.error("error thrown while dispatching connection:close event %e",h)}),Reflect.set(...d))}),s.timeline.upgraded=Date.now(),u=um(this.components,{id:e,maConn:i,remotePeer:a,direction:o,muxerFactory:c,encryption:n,limits:l,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout}),this.events.safeDispatchEvent("connection:open",{detail:u}),u}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await Mn(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new Nr(`no crypto module found for ${s}`);return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,s),{...await i.secureInbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,o),new Nr(o.message)}}async _encryptOutbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await On(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new Nr(`no crypto module found for ${s}`);return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,s),{...await i.secureOutbound(o,e),protocol:s}}catch(o){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,o),new Nr(o.message)}}async _multiplexOutbound(t,e,n){let o=Array.from(e.keys());t.log("outbound selecting muxer %s",o);try{t.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await On(t,o,{...n,log:t.log,yieldBytes:!0});t.log("selected %s as muxer protocol",i);let a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing outbound connection",s),new Mr(String(s))}}async _multiplexInbound(t,e,n){let o=Array.from(e.keys());t.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await Mn(t,o,{...n,log:t.log}),a=e.get(i);return{stream:s,muxerFactory:a}}catch(s){throw t.log.error("error multiplexing inbound connection",s),new Mr(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var Na="2.9.0-cf9aab5c8",Ba="js-libp2p";function dm(r,t){return`${r??Ba}/${t??Na} browser/${globalThis.navigator.userAgent}`}var Yo=class extends Vt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new Vt,n=e.dispatchEvent.bind(e);e.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=t.peerId,this.logger=t.logger??ei(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Ba,s=t.nodeInfo?.version??Na,i=this.components=Fp({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??dm(o,s)},logger:this.logger,events:e,datastore:t.datastore??new Ri,connectionGater:qp(t.connectionGater),dns:t.dns});t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",vp(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.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})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new Ma(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(t.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Aa(this.components,t.transportManager)),this.configureComponent("connectionManager",new pa(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new wa(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Sa(this.components)),this.configureComponent("addressManager",new zi(this.components,t.addresses));let a=(t.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new va(this.components,{routers:a}));let c=(t.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new xa(this.components,{routers:c})),this.configureComponent("randomWalk",new _a(this.components)),(t.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),t.services!=null)for(let l of Object.keys(t.services)){let u=t.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[Ua]!=null&&(this.log("registering service %s for content routing",l),c.push(f[Ua])),f[Ka]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Ka])),f[Fa]!=null&&(this.log("registering service %s for peer discovery",l),f[Fa].addEventListener?.("peer",d=>{this.#t(d)}))}Kp(i)}configureComponent(t,e){return e==null&&this.log.error("component %s was null or undefined",t),this.components[t]=e,e}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(t){throw this.log.error("An error occurred starting libp2p",t),this.status="started",await this.stop(),t}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(t){return this.components.connectionManager.getConnections(t)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let t=new Ar;for(let e of this.components.connectionManager.getConnections())t.add(e.remotePeer);return Array.from(t)}async dial(t,e={}){return this.components.connectionManager.openConnection(t,{priority:75,...e})}async dialProtocol(t,e,n={}){if(e==null)throw new k("no protocols were provided to open a stream");if(e=Array.isArray(e)?e:[e],e.length===0)throw new k("no protocols were provided to open a stream");return(await this.dial(t,n)).newStream(e,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(t,e={}){er(t)&&(t=ge(t.getPeerId()??"")),await this.components.connectionManager.closeConnections(t,e)}async getPublicKey(t,e={}){if(this.log("getPublicKey %p",t),t.publicKey!=null)return t.publicKey;try{let i=await this.peerStore.get(t,e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=se([C("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=pn(o);return await this.peerStore.patch(t,{publicKey:s},e),s}async handle(t,e,n){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async o=>{await this.components.registrar.handle(o,e,n)}))}async unhandle(t,e){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async n=>{await this.components.registrar.unhandle(n,e)}))}async register(t,e,n){return this.components.registrar.register(t,e,n)}unregister(t){this.components.registrar.unregister(t)}async isDialable(t,e={}){return this.components.connectionManager.isDialable(t,e)}#t(t){let{detail:e}=t;if(e.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Jw(r={}){r.privateKey??=await fh("Ed25519");let t=new Yo({...await jh(r),peerId:mh(r.privateKey)});return r.start!==!1&&await t.start(),t}var tx=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function ex(r){return r==null?!1:r instanceof Yo?!0:tx.every(t=>typeof r[t]=="function")}return bm(rx);})();
21
21
  /*! Bundled license information:
22
22
 
23
23
  @noble/hashes/esm/utils.js: