libp2p 2.7.4 → 2.7.5

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,55 +1,25 @@
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 Um=Object.create;var $s=Object.defineProperty;var Fm=Object.getOwnPropertyDescriptor;var Vm=Object.getOwnPropertyNames;var Hm=Object.getPrototypeOf,Km=Object.prototype.hasOwnProperty;var wt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),De=(r,e)=>{for(var t in e)$s(r,t,{get:e[t],enumerable:!0})},bf=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vm(e))!Km.call(r,s)&&s!==t&&$s(r,s,{get:()=>e[s],enumerable:!(n=Fm(e,s))||n.enumerable});return r};var Vr=(r,e,t)=>(t=r!=null?Um(Hm(r)):{},bf(e||!r||!r.__esModule?$s(t,"default",{value:r,enumerable:!0}):t,r)),$m=r=>bf($s({},"__esModule",{value:!0}),r);var Sd=wt(on=>{"use strict";var fy="[object ArrayBuffer]",Bt=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===fy}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==s[o])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let s=new Uint8Array(n),o=0;for(let i of t){let a=this.toUint8Array(i);s.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}},wl="string",dy=/^[0-9a-f\s]+$/i,hy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,py=/^[a-zA-Z0-9-_]+$/,Eo=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n.buffer}static toString(e){let t=Bt.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return decodeURIComponent(escape(n))}},Ze=class{static toString(e,t=!1){let n=Bt.toArrayBuffer(e),s=new DataView(n),o="";for(let i=0;i<n.byteLength;i+=2){let a=s.getUint16(i,t);o+=String.fromCharCode(a)}return o}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),s=new DataView(n);for(let o=0;o<e.length;o++)s.setUint16(o*2,e.charCodeAt(o),t);return n}},Ao=class r{static isHex(e){return typeof e===wl&&dy.test(e)}static isBase64(e){return typeof e===wl&&hy.test(e)}static isBase64Url(e){return typeof e===wl&&py.test(e)}static ToString(e,t="utf8"){let n=Bt.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Ze.toString(n,!0);case"utf16":case"utf16be":return Ze.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Ze.fromString(e,!0);case"utf16":case"utf16be":return Ze.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Bt.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Eo.fromString(e);case"utf16":case"utf16be":return Ze.fromString(e);case"utf16le":case"usc2":return Ze.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Eo.toString(e);case"utf16":case"utf16be":return Ze.toString(e);case"utf16le":case"usc2":return Ze.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return n.buffer}static ToBinary(e){let t=Bt.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return n}static ToHex(e){let t=Bt.toUint8Array(e),n="",s=t.length;for(let o=0;o<s;o++){let i=t[o];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let s=0;s<t.length;s=s+2){let o=t.slice(s,s+2);n[s/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,t=!1){return Ze.toString(e,t)}static FromUtf16String(e,t=!1){return Ze.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Ao.DEFAULT_UTF8_ENCODING="utf8";function my(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let s=arguments[n];for(let o in s)t[o]=s[o]}return t}function gy(...r){let e=r.map(s=>s.byteLength).reduce((s,o)=>s+o),t=new Uint8Array(e),n=0;return r.map(s=>new Uint8Array(s)).forEach(s=>{for(let o of s)t[n++]=o}),t.buffer}function yy(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)if(t[s]!==n[s])return!1;return!0}on.BufferSourceConverter=Bt;on.Convert=Ao;on.assign=my;on.combine=gy;on.isEqual=yy});var Vh=wt((fA,Rl)=>{"use strict";var Vy=Object.prototype.hasOwnProperty,Ve="~";function ys(){}Object.create&&(ys.prototype=Object.create(null),new ys().__proto__||(Ve=!1));function Hy(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Fh(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Hy(t,n||r,s),i=Ve?Ve+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],o]:r._events[i].push(o):(r._events[i]=o,r._eventsCount++),r}function gi(r,e){--r._eventsCount===0?r._events=new ys:delete r._events[e]}function Le(){this._events=new ys,this._eventsCount=0}Le.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Vy.call(t,n)&&e.push(Ve?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Le.prototype.listeners=function(e){var t=Ve?Ve+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s<o;s++)i[s]=n[s].fn;return i};Le.prototype.listenerCount=function(e){var t=Ve?Ve+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Le.prototype.emit=function(e,t,n,s,o,i){var a=Ve?Ve+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,s),!0;case 5:return c.fn.call(c.context,t,n,s,o),!0;case 6:return c.fn.call(c.context,t,n,s,o,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,m;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,s);break;default:if(!u)for(m=1,u=new Array(l-1);m<l;m++)u[m-1]=arguments[m];c[f].fn.apply(c[f].context,u)}}return!0};Le.prototype.on=function(e,t,n){return Fh(this,e,t,n,!1)};Le.prototype.once=function(e,t,n){return Fh(this,e,t,n,!0)};Le.prototype.removeListener=function(e,t,n,s){var o=Ve?Ve+e:e;if(!this._events[o])return this;if(!t)return gi(this,o),this;var i=this._events[o];if(i.fn)i.fn===t&&(!s||i.once)&&(!n||i.context===n)&&gi(this,o);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||s&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[o]=c.length===1?c[0]:c:gi(this,o)}return this};Le.prototype.removeAllListeners=function(e){var t;return e?(t=Ve?Ve+e:e,this._events[t]&&gi(this,t)):(this._events=new ys,this._eventsCount=0),this};Le.prototype.off=Le.prototype.removeListener;Le.prototype.addListener=Le.prototype.on;Le.prefixed=Ve;Le.EventEmitter=Le;typeof Rl<"u"&&(Rl.exports=Le)});var zh=wt((DA,qh)=>{qh.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var lp=wt((a_,cp)=>{"use strict";cp.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var mp=wt((hp,pp)=>{"use strict";var Ii=lp(),{hasOwnProperty:fp}=Object.prototype,{propertyIsEnumerable:dw}=Object,xn=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),hw=hp,up={concatArrays:!1,ignoreUndefined:!1},Bi=r=>{let e=[];for(let t in r)fp.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)dw.call(r,n)&&e.push(n)}return e};function vn(r){return Array.isArray(r)?pw(r):Ii(r)?mw(r):r}function pw(r){let e=r.slice(0,0);return Bi(r).forEach(t=>{xn(e,t,vn(r[t]))}),e}function mw(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return Bi(r).forEach(t=>{xn(e,t,vn(r[t]))}),e}var dp=(r,e,t,n)=>(t.forEach(s=>{typeof e[s]>"u"&&n.ignoreUndefined||(s in r&&r[s]!==Object.getPrototypeOf(r)?xn(r,s,ou(r[s],e[s],n)):xn(r,s,vn(e[s])))}),r),gw=(r,e,t)=>{let n=r.slice(0,0),s=0;return[r,e].forEach(o=>{let i=[];for(let a=0;a<o.length;a++)fp.call(o,a)&&(i.push(String(a)),o===r?xn(n,s++,o[a]):xn(n,s++,vn(o[a])));n=dp(n,o,Bi(o).filter(a=>!i.includes(a)),t)}),n};function ou(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?gw(r,e,t):!Ii(e)||!Ii(r)?vn(e):dp(r,e,Bi(e),t)}pp.exports=function(...r){let e=ou(vn(up),this!==hw&&this||{},up),t={_:{}};for(let n of r)if(n!==void 0){if(!Ii(n))throw new TypeError("`"+n+"` is not an Option Object");t=ou(t,{_:n},e)}return t._}});var Hp=wt(Bs=>{(function(){var r,e,t,n,s,o,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,m,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=e(c),m=p[0],u=p[1],c=c.substring(u),l.push(m)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),s=t("A"),e=function(c){var l,u,f,d,m;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")),m=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(t(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+t(c[f])-o)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+t(c[f])-s)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===m)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,m,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=m=32;m>=0;d=--m)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}(),Bs.ip2long=i,Bs.long2ip=a,Bs.Netmask=r}).call(Bs)});var hm=wt((Ak,dm)=>{function Ye(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.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))}dm.exports=Ye;Ye.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ye.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ye.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=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)},t),this._options.unref&&this._timer.unref(),!0};Ye.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Ye.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ye.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ye.prototype.start=Ye.prototype.try;Ye.prototype.errors=function(){return this._errors};Ye.prototype.attempts=function(){return this._attempts};Ye.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var s=this._errors[n],o=s.message,i=(r[o]||0)+1;r[o]=i,i>=t&&(e=s,t=i)}return e}});var pm=wt(Or=>{var Wb=hm();Or.operation=function(r){var e=Or.timeouts(r);return new Wb(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Or.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<e.retries;s++)n.push(this.createTimeout(s,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(s,e)),n.sort(function(o,i){return o-i}),n};Or.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};Or.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var s=0;s<t.length;s++){var o=t[s],i=r[o];r[o]=function(c){var l=Or.operation(e),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[o].options=e}}});var gm=wt((_k,mm)=>{mm.exports=pm()});var bx={};De(bx,{createLibp2p:()=>wx});var xf=Symbol.for("@libp2p/connection");var sc=Symbol.for("@libp2p/content-routing");var oc=Symbol.for("@libp2p/peer-discovery");var qs=Symbol.for("@libp2p/peer-id");function zs(r){return!!r?.[qs]}var ic=Symbol.for("@libp2p/peer-routing");var ac="keep-alive";var Ix=Symbol.for("@libp2p/transport");var cr;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(cr||(cr={}));var Je=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var D=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Hr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Mn=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var Gs=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},Kr=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Ws=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},$r=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Vt=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},js=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Zs=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},On=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Xs=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Ys=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},bt=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var qr=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var zr=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Js=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Qs=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ht=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var xt=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let s=this.#e.get(e);s!=null&&(s=s.filter(({callback:o})=>o!==t),this.#e.set(e,s))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:s})=>!s),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function eo(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function vf(...r){let e=[];for(let t of r)eo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Ef(...r){let e=[];for(let t of r)eo(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Un=Symbol.for("@libp2p/service-capabilities"),cc=Symbol.for("@libp2p/service-dependencies");var hc={};De(hc,{base58btc:()=>X,base58flickr:()=>Zm});var ev=new Uint8Array(0);function Af(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function vt(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 Sf(r){return new TextEncoder().encode(r)}function _f(r){return new TextDecoder().decode(r)}function qm(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}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,h=0,w=0,x=p.length;w!==x&&p[w]===0;)w++,g++;for(var y=(x-w)*u+1>>>0,E=new Uint8Array(y);w!==x;){for(var _=p[w],L=0,I=y-1;(_!==0||L<h)&&I!==-1;I--,L++)_+=256*E[I]>>>0,E[I]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");h=L,w++}for(var T=y-h;T!==y&&E[T]===0;)T++;for(var k=c.repeat(g);T<y;++T)k+=r.charAt(E[T]);return k}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 h=0,w=0;p[g]===c;)h++,g++;for(var x=(p.length-g)*l+1>>>0,y=new Uint8Array(x);p[g];){var E=t[p.charCodeAt(g)];if(E===255)return;for(var _=0,L=x-1;(E!==0||_<w)&&L!==-1;L--,_++)E+=a*y[L]>>>0,y[L]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=_,g++}if(p[g]!==" "){for(var I=x-w;I!==x&&y[I]===0;)I++;for(var T=new Uint8Array(h+(x-I)),k=h;I!==x;)T[k++]=y[I++];return T}}}function m(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var zm=qm,Gm=zm,If=Gm;var lc=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},uc=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Bf(this,e)}},fc=class{decoders;constructor(e){this.decoders=e}or(e){return Bf(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Bf(r,e){return new fc({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var dc=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new lc(e,t,n),this.decoder=new uc(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Gr({name:r,prefix:e,encode:t,decode:n}){return new dc(r,e,t,n)}function Kt({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=If(t,r);return Gr({prefix:e,name:r,encode:n,decode:o=>vt(s(o))})}function Wm(r,e,t,n){let s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),a=0,c=0,l=0;for(let u=0;u<o;++u){let f=s[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=t||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function jm(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Gr({prefix:e,name:r,encode(s){return jm(s,n,t)},decode(s){return Wm(s,n,t,r)}})}var X=Kt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Zm=Kt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var pc={};De(pc,{base32:()=>Ge,base32hex:()=>Qm,base32hexpad:()=>tg,base32hexpadupper:()=>rg,base32hexupper:()=>eg,base32pad:()=>Ym,base32padupper:()=>Jm,base32upper:()=>Xm,base32z:()=>ng});var Ge=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xm=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ym=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Jm=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qm=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),eg=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tg=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rg=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ng=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mc={};De(mc,{base36:()=>Fn,base36upper:()=>sg});var Fn=Kt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sg=Kt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var og=Lf,kf=128,ig=127,ag=~ig,cg=Math.pow(2,31);function Lf(r,e,t){e=e||[],t=t||0;for(var n=t;r>=cg;)e[t++]=r&255|kf,r/=128;for(;r&ag;)e[t++]=r&255|kf,r>>>=7;return e[t]=r|0,Lf.bytes=t-n+1,e}var lg=gc,ug=128,Tf=127;function gc(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw gc.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Tf)<<s:(i&Tf)*Math.pow(2,s),s+=7}while(i>=ug);return gc.bytes=o-n,t}var fg=Math.pow(2,7),dg=Math.pow(2,14),hg=Math.pow(2,21),pg=Math.pow(2,28),mg=Math.pow(2,35),gg=Math.pow(2,42),yg=Math.pow(2,49),wg=Math.pow(2,56),bg=Math.pow(2,63),xg=function(r){return r<fg?1:r<dg?2:r<hg?3:r<pg?4:r<mg?5:r<gg?6:r<yg?7:r<wg?8:r<bg?9:10},vg={encode:og,decode:lg,encodingLength:xg},Eg=vg,Vn=Eg;function Hn(r,e=0){return[Vn.decode(r,e),Vn.decode.bytes]}function Wr(r,e,t=0){return Vn.encode(r,e,t),e}function jr(r){return Vn.encodingLength(r)}function Qe(r,e){let t=e.byteLength,n=jr(r),s=n+jr(t),o=new Uint8Array(s+t);return Wr(r,o,0),Wr(t,o,n),o.set(e,s),new Zr(r,t,e,o)}function et(r){let e=vt(r),[t,n]=Hn(e),[s,o]=Hn(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Zr(t,s,i,e)}function Pf(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Af(r.bytes,t.bytes)}}var Zr=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};function Nf(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Sg(t,yc(r),e??X.encoder);default:return _g(t,yc(r),e??Ge.encoder)}}var Df=new WeakMap;function yc(r){let e=Df.get(r);if(e==null){let t=new Map;return Df.set(r,t),t}return e}var pe=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Kn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Cg)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Qe(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Pf(e.multihash,n.multihash)}toString(e){return Nf(this,e)}toJSON(){return{"/":Nf(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Rf(n,s,o.bytes))}else if(t[Ig]===!0){let{version:n,multihash:s,code:o}=t,i=et(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Kn)throw new Error(`Version 0 CID must use dag-pb (code: ${Kn}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Rf(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Kn,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=vt(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new Zr(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Hn(e.subarray(t));return t+=d,f},s=n(),o=Kn;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=Ag(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return yc(o).set(n,e),o}};function Ag(r,e){switch(r[0]){case"Q":{let t=e??X;return[X.prefix,t.decode(`${X.prefix}${r}`)]}case X.prefix:{let t=e??X;return[X.prefix,t.decode(r)]}case Ge.prefix:{let t=e??Ge;return[Ge.prefix,t.decode(r)]}case Fn.prefix:{let t=e??Fn;return[Fn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Sg(r,e,t){let{prefix:n}=t;if(n!==X.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function _g(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Kn=112,Cg=18;function Rf(r,e,t){let n=jr(r),s=n+jr(e),o=new Uint8Array(s+t.byteLength);return Wr(r,o,0),Wr(e,o,n),o.set(t,s),o}var Ig=Symbol.for("@ipld/js-cid/CID");var wc={};De(wc,{identity:()=>At});var Mf=0,Bg="identity",Of=vt;function kg(r){return Qe(Mf,Of(r))}var At={code:Mf,name:Bg,encode:Of,digest:kg};function ce(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Uf(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Tg(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Xr(r,...e){if(!Tg(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Ff(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Uf(r.outputLen),Uf(r.blockLen)}function Yr(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Vf(r,e){Xr(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var lr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ro(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function tt(r,e){return r<<32-e|r>>>e}function Hf(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function $n(r){return typeof r=="string"&&(r=Hf(r)),Xr(r),r}function bc(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];Xr(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}var Jr=class{clone(){return this._cloneInto()}};function no(r){let e=n=>r().update($n(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Qr(r=32){if(lr&&typeof lr.getRandomValues=="function")return lr.getRandomValues(new Uint8Array(r));if(lr&&typeof lr.randomBytes=="function")return lr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Lg(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let s=BigInt(32),o=BigInt(4294967295),i=Number(t>>s&o),a=Number(t&o),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}function Kf(r,e,t){return r&e^~r&t}function $f(r,e,t){return r&e^r&t^e&t}var en=class extends Jr{constructor(e,t,n,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ro(this.buffer)}update(e){Yr(this);let{view:t,buffer:n,blockLen:s}=this;e=$n(e);let o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let c=ro(e);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Yr(this),Vf(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)t[f]=0;Lg(n,s-8,BigInt(this.length*8),o),this.process(n,0);let a=ro(e),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],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return e.length=s,e.pos=a,e.finished=o,e.destroyed=i,s%t&&e.buffer.set(n),e}};var so=BigInt(4294967295),xc=BigInt(32);function qf(r,e=!1){return e?{h:Number(r&so),l:Number(r>>xc&so)}:{h:Number(r>>xc&so)|0,l:Number(r&so)|0}}function Pg(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let s=0;s<r.length;s++){let{h:o,l:i}=qf(r[s],e);[t[s],n[s]]=[o,i]}return[t,n]}var Ng=(r,e)=>BigInt(r>>>0)<<xc|BigInt(e>>>0),Dg=(r,e,t)=>r>>>t,Rg=(r,e,t)=>r<<32-t|e>>>t,Mg=(r,e,t)=>r>>>t|e<<32-t,Og=(r,e,t)=>r<<32-t|e>>>t,Ug=(r,e,t)=>r<<64-t|e>>>t-32,Fg=(r,e,t)=>r>>>t-32|e<<64-t,Vg=(r,e)=>e,Hg=(r,e)=>r,Kg=(r,e,t)=>r<<t|e>>>32-t,$g=(r,e,t)=>e<<t|r>>>32-t,qg=(r,e,t)=>e<<t-32|r>>>64-t,zg=(r,e,t)=>r<<t-32|e>>>64-t;function Gg(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var Wg=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),jg=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Zg=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Xg=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,Yg=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),Jg=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;var Qg={fromBig:qf,split:Pg,toBig:Ng,shrSH:Dg,shrSL:Rg,rotrSH:Mg,rotrSL:Og,rotrBH:Ug,rotrBL:Fg,rotr32H:Vg,rotr32L:Hg,rotlSH:Kg,rotlSL:$g,rotlBH:qg,rotlBL:zg,add:Gg,add3L:Wg,add3H:jg,add4L:Zg,add4H:Xg,add5H:Jg,add5L:Yg},U=Qg;var[e0,t0]=U.split(["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))),$t=new Uint32Array(80),qt=new Uint32Array(80),vc=class extends en{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:m,Gl:p,Hh:g,Hl:h}=this;return[e,t,n,s,o,i,a,c,l,u,f,d,m,p,g,h]}set(e,t,n,s,o,i,a,c,l,u,f,d,m,p,g,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|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=m|0,this.Gl=p|0,this.Hh=g|0,this.Hl=h|0}process(e,t){for(let y=0;y<16;y++,t+=4)$t[y]=e.getUint32(t),qt[y]=e.getUint32(t+=4);for(let y=16;y<80;y++){let E=$t[y-15]|0,_=qt[y-15]|0,L=U.rotrSH(E,_,1)^U.rotrSH(E,_,8)^U.shrSH(E,_,7),I=U.rotrSL(E,_,1)^U.rotrSL(E,_,8)^U.shrSL(E,_,7),T=$t[y-2]|0,k=qt[y-2]|0,re=U.rotrSH(T,k,19)^U.rotrBH(T,k,61)^U.shrSH(T,k,6),W=U.rotrSL(T,k,19)^U.rotrBL(T,k,61)^U.shrSL(T,k,6),V=U.add4L(I,W,qt[y-7],qt[y-16]),he=U.add4H(V,L,re,$t[y-7],$t[y-16]);$t[y]=he|0,qt[y]=V|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:m,Fl:p,Gh:g,Gl:h,Hh:w,Hl:x}=this;for(let y=0;y<80;y++){let E=U.rotrSH(f,d,14)^U.rotrSH(f,d,18)^U.rotrBH(f,d,41),_=U.rotrSL(f,d,14)^U.rotrSL(f,d,18)^U.rotrBL(f,d,41),L=f&m^~f&g,I=d&p^~d&h,T=U.add5L(x,_,I,t0[y],qt[y]),k=U.add5H(T,w,E,L,e0[y],$t[y]),re=T|0,W=U.rotrSH(n,s,28)^U.rotrBH(n,s,34)^U.rotrBH(n,s,39),V=U.rotrSL(n,s,28)^U.rotrBL(n,s,34)^U.rotrBL(n,s,39),he=n&o^n&a^o&a,S=s&i^s&c^i&c;w=g|0,x=h|0,g=m|0,h=p|0,m=f|0,p=d|0,{h:f,l:d}=U.add(l|0,u|0,k|0,re|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let P=U.add3L(re,V,S);n=U.add3H(P,k,W,he),s=P|0}({h:n,l:s}=U.add(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=U.add(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=U.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=U.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=U.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:p}=U.add(this.Fh|0,this.Fl|0,m|0,p|0),{h:g,l:h}=U.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:x}=U.add(this.Hh|0,this.Hl|0,w|0,x|0),this.set(n,s,o,i,a,c,l,u,f,d,m,p,g,h,w,x)}roundClean(){$t.fill(0),qt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var zf=no(()=>new vc);var ao={};De(ao,{aInRange:()=>Ke,abool:()=>rt,abytes:()=>tn,bitGet:()=>a0,bitLen:()=>_c,bitMask:()=>zn,bitSet:()=>c0,bytesToHex:()=>_t,bytesToNumberBE:()=>Ct,bytesToNumberLE:()=>Gt,concatBytes:()=>It,createHmacDrbg:()=>Cc,ensureBytes:()=>oe,equalBytes:()=>o0,hexToBytes:()=>fr,hexToNumber:()=>Sc,inRange:()=>qn,isBytes:()=>zt,memoized:()=>hr,notImplemented:()=>u0,numberToBytesBE:()=>Wt,numberToBytesLE:()=>dr,numberToHexUnpadded:()=>ur,numberToVarBytesBE:()=>s0,utf8ToBytes:()=>i0,validateObject:()=>ut});var oo=BigInt(0),io=BigInt(1),r0=BigInt(2);function zt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function tn(r){if(!zt(r))throw new Error("Uint8Array expected")}function rt(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}var n0=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function _t(r){tn(r);let e="";for(let t=0;t<r.length;t++)e+=n0[r[t]];return e}function ur(r){let e=r.toString(16);return e.length&1?"0"+e:e}function Sc(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?oo:BigInt("0x"+r)}var St={_0:48,_9:57,A:65,F:70,a:97,f:102};function Gf(r){if(r>=St._0&&r<=St._9)return r-St._0;if(r>=St.A&&r<=St.F)return r-(St.A-10);if(r>=St.a&&r<=St.f)return r-(St.a-10)}function fr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=Gf(r.charCodeAt(o)),a=Gf(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function Ct(r){return Sc(_t(r))}function Gt(r){return tn(r),Sc(_t(Uint8Array.from(r).reverse()))}function Wt(r,e){return fr(r.toString(16).padStart(e*2,"0"))}function dr(r,e){return Wt(r,e).reverse()}function s0(r){return fr(ur(r))}function oe(r,e,t){let n;if(typeof e=="string")try{n=fr(e)}catch(o){throw new Error(r+" must be hex string or Uint8Array, cause: "+o)}else if(zt(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let s=n.length;if(typeof t=="number"&&s!==t)throw new Error(r+" of length "+t+" expected, got "+s);return n}function It(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];tn(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function o0(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function i0(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var Ec=r=>typeof r=="bigint"&&oo<=r;function qn(r,e,t){return Ec(r)&&Ec(e)&&Ec(t)&&e<=r&&r<t}function Ke(r,e,t,n){if(!qn(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function _c(r){let e;for(e=0;r>oo;r>>=io,e+=1);return e}function a0(r,e){return r>>BigInt(e)&io}function c0(r,e,t){return r|(t?io:oo)<<BigInt(e)}var zn=r=>(r0<<BigInt(r-1))-io,Ac=r=>new Uint8Array(r),Wf=r=>Uint8Array.from(r);function Cc(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Ac(r),s=Ac(r),o=0,i=()=>{n.fill(1),s.fill(0),o=0},a=(...f)=>t(s,n,...f),c=(f=Ac())=>{s=a(Wf([0]),f),n=a(),f.length!==0&&(s=a(Wf([1]),f),n=a())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<e;){n=a();let m=n.slice();d.push(m),f+=n.length}return It(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var l0={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||zt(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function ut(r,e,t={}){let n=(s,o,i)=>{let a=l0[o];if(typeof a!="function")throw new Error("invalid validator function");let c=r[s];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(s)+" is invalid. Expected "+o+", got "+c)};for(let[s,o]of Object.entries(e))n(s,o,!1);for(let[s,o]of Object.entries(t))n(s,o,!0);return r}var u0=()=>{throw new Error("not implemented")};function hr(r){let e=new WeakMap;return(t,...n)=>{let s=e.get(t);if(s!==void 0)return s;let o=r(t,...n);return e.set(t,o),o}}var me=BigInt(0),ne=BigInt(1),pr=BigInt(2),f0=BigInt(3),Ic=BigInt(4),jf=BigInt(5),Zf=BigInt(8),d0=BigInt(9),h0=BigInt(16);function Q(r,e){let t=r%e;return t>=me?t:e+t}function p0(r,e,t){if(e<me)throw new Error("invalid exponent, negatives unsupported");if(t<=me)throw new Error("invalid modulus");if(t===ne)return me;let n=ne;for(;e>me;)e&ne&&(n=n*r%t),r=r*r%t,e>>=ne;return n}function se(r,e,t){let n=r;for(;e-- >me;)n*=n,n%=t;return n}function co(r,e){if(r===me)throw new Error("invert: expected non-zero number");if(e<=me)throw new Error("invert: expected positive modulus, got "+e);let t=Q(r,e),n=e,s=me,o=ne,i=ne,a=me;for(;t!==me;){let l=n/t,u=n%t,f=s-i*l,d=o-a*l;n=t,t=u,s=i,o=a,i=f,a=d}if(n!==ne)throw new Error("invert: does not exist");return Q(s,e)}function m0(r){let e=(r-ne)/pr,t,n,s;for(t=r-ne,n=0;t%pr===me;t/=pr,n++);for(s=pr;s<r&&p0(s,e,r)!==r-ne;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+ne)/Ic;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let o=(t+ne)/pr;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,s),t),f=a.pow(c,o),d=a.pow(c,t);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let m=1;for(let g=a.sqr(d);m<l&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let p=a.pow(u,ne<<BigInt(l-m-1));u=a.sqr(p),f=a.mul(f,p),d=a.mul(d,u),l=m}return f}}function g0(r){if(r%Ic===f0){let e=(r+ne)/Ic;return function(n,s){let o=n.pow(s,e);if(!n.eql(n.sqr(o),s))throw new Error("Cannot find square root");return o}}if(r%Zf===jf){let e=(r-jf)/Zf;return function(n,s){let o=n.mul(s,pr),i=n.pow(o,e),a=n.mul(s,i),c=n.mul(n.mul(a,pr),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),s))throw new Error("Cannot find square root");return l}}return r%h0,m0(r)}var Xf=(r,e)=>(Q(r,e)&ne)===ne,y0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Bc(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=y0.reduce((n,s)=>(n[s]="function",n),e);return ut(r,t)}function w0(r,e,t){if(t<me)throw new Error("invalid exponent, negatives unsupported");if(t===me)return r.ONE;if(t===ne)return e;let n=r.ONE,s=e;for(;t>me;)t&ne&&(n=r.mul(n,s)),s=r.sqr(s),t>>=ne;return n}function b0(r,e){let t=new Array(e.length),n=e.reduce((o,i,a)=>r.is0(i)?o:(t[a]=o,r.mul(o,i)),r.ONE),s=r.inv(n);return e.reduceRight((o,i,a)=>r.is0(i)?o:(t[a]=r.mul(o,t[a]),r.mul(o,i)),s),t}function kc(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function jt(r,e,t=!1,n={}){if(r<=me)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:s,nByteLength:o}=kc(r,e);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:t,BITS:s,BYTES:o,MASK:zn(s),ZERO:me,ONE:ne,create:c=>Q(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return me<=c&&c<r},is0:c=>c===me,isOdd:c=>(c&ne)===ne,neg:c=>Q(-c,r),eql:(c,l)=>c===l,sqr:c=>Q(c*c,r),add:(c,l)=>Q(c+l,r),sub:(c,l)=>Q(c-l,r),mul:(c,l)=>Q(c*l,r),pow:(c,l)=>w0(a,c,l),div:(c,l)=>Q(c*co(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>co(c,r),sqrt:n.sqrt||(c=>(i||(i=g0(r)),i(a,c))),invertBatch:c=>b0(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>t?dr(c,o):Wt(c,o),fromBytes:c=>{if(c.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+c.length);return t?Gt(c):Ct(c)}});return Object.freeze(a)}function Yf(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Tc(r){let e=Yf(r);return e+Math.ceil(e/2)}function Jf(r,e,t=!1){let n=r.length,s=Yf(e),o=Tc(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?Gt(r):Ct(r),a=Q(i,e-ne)+ne;return t?dr(a,s):Wt(a,s)}var Qf=BigInt(0),lo=BigInt(1);function Lc(r,e){let t=e.negate();return r?t:e}function ed(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Pc(r,e){ed(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1);return{windows:t,windowSize:n}}function x0(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function v0(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var Nc=new WeakMap,td=new WeakMap;function Dc(r){return td.get(r)||1}function uo(r,e){return{constTimeNegate:Lc,hasPrecomputes(t){return Dc(t)!==1},unsafeLadder(t,n,s=r.ZERO){let o=t;for(;n>Qf;)n&lo&&(s=s.add(o)),o=o.double(),n>>=lo;return s},precomputeWindow(t,n){let{windows:s,windowSize:o}=Pc(n,e),i=[],a=t,c=a;for(let l=0;l<s;l++){c=a,i.push(c);for(let u=1;u<o;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(t,n,s){let{windows:o,windowSize:i}=Pc(t,e),a=r.ZERO,c=r.BASE,l=BigInt(2**t-1),u=2**t,f=BigInt(t);for(let d=0;d<o;d++){let m=d*i,p=Number(s&l);s>>=f,p>i&&(p-=u,s+=lo);let g=m,h=m+Math.abs(p)-1,w=d%2!==0,x=p<0;p===0?c=c.add(Lc(w,n[g])):a=a.add(Lc(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(t,n,s,o=r.ZERO){let{windows:i,windowSize:a}=Pc(t,e),c=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let f=0;f<i;f++){let d=f*a;if(s===Qf)break;let m=Number(s&c);if(s>>=u,m>a&&(m-=l,s+=lo),m===0)continue;let p=n[d+Math.abs(m)-1];m<0&&(p=p.negate()),o=o.add(p)}return o},getPrecomputes(t,n,s){let o=Nc.get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&Nc.set(n,s(o))),o},wNAFCached(t,n,s){let o=Dc(t);return this.wNAF(o,this.getPrecomputes(o,t,s),n)},wNAFCachedUnsafe(t,n,s,o){let i=Dc(t);return i===1?this.unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,s),n,o)},setWindowSize(t,n){ed(n,e),td.set(t,n),Nc.delete(t)}}}function fo(r,e,t,n){if(x0(t,r),v0(n,e),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let s=r.ZERO,o=_c(BigInt(t.length)),i=o>12?o-3:o>4?o-2:o?2:1,a=(1<<i)-1,c=new Array(a+1).fill(s),l=Math.floor((e.BITS-1)/i)*i,u=s;for(let f=l;f>=0;f-=i){c.fill(s);for(let m=0;m<n.length;m++){let p=n[m],g=Number(p>>BigInt(f)&BigInt(a));c[g]=c[g].add(t[m])}let d=s;for(let m=c.length-1,p=s;m>0;m--)p=p.add(c[m]),d=d.add(p);if(u=u.add(d),f!==0)for(let m=0;m<i;m++)u=u.double()}return u}function Gn(r){return Bc(r.Fp),ut(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...kc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var nt=BigInt(0),$e=BigInt(1),ho=BigInt(2),E0=BigInt(8),A0={zip215:!0};function S0(r){let e=Gn(r);return ut(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function rd(r){let e=S0(r),{Fp:t,n,prehash:s,hash:o,randomBytes:i,nByteLength:a,h:c}=e,l=ho<<BigInt(a*8)-$e,u=t.create,f=jt(e.n,e.nBitLength),d=e.uvRatio||((v,b)=>{try{return{isValid:!0,value:t.sqrt(v*t.inv(b))}}catch{return{isValid:!1,value:nt}}}),m=e.adjustScalarBytes||(v=>v),p=e.domain||((v,b,A)=>{if(rt("phflag",A),b.length||A)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,b){Ke("coordinate "+v,b,nt,l)}function h(v){if(!(v instanceof y))throw new Error("ExtendedPoint expected")}let w=hr((v,b)=>{let{ex:A,ey:B,ez:R}=v,M=v.is0();b==null&&(b=M?E0:t.inv(R));let F=u(A*b),K=u(B*b),O=u(R*b);if(M)return{x:nt,y:$e};if(O!==$e)throw new Error("invZ was invalid");return{x:F,y:K}}),x=hr(v=>{let{a:b,d:A}=e;if(v.is0())throw new Error("bad point: ZERO");let{ex:B,ey:R,ez:M,et:F}=v,K=u(B*B),O=u(R*R),J=u(M*M),te=u(J*J),we=u(K*b),be=u(J*u(we+O)),ve=u(te+u(A*u(K*O)));if(be!==ve)throw new Error("bad point: equation left != right (1)");let _e=u(B*R),He=u(M*F);if(_e!==He)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(b,A,B,R){this.ex=b,this.ey=A,this.ez=B,this.et=R,g("x",b),g("y",A),g("z",B),g("t",R),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof y)throw new Error("extended point not allowed");let{x:A,y:B}=b||{};return g("x",A),g("y",B),new y(A,B,$e,u(A*B))}static normalizeZ(b){let A=t.invertBatch(b.map(B=>B.ez));return b.map((B,R)=>B.toAffine(A[R])).map(y.fromAffine)}static msm(b,A){return fo(y,f,b,A)}_setWindowSize(b){L.setWindowSize(this,b)}assertValidity(){x(this)}equals(b){h(b);let{ex:A,ey:B,ez:R}=this,{ex:M,ey:F,ez:K}=b,O=u(A*K),J=u(M*R),te=u(B*K),we=u(F*R);return O===J&&te===we}is0(){return this.equals(y.ZERO)}negate(){return new y(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:b}=e,{ex:A,ey:B,ez:R}=this,M=u(A*A),F=u(B*B),K=u(ho*u(R*R)),O=u(b*M),J=A+B,te=u(u(J*J)-M-F),we=O+F,be=we-K,ve=O-F,_e=u(te*be),He=u(we*ve),Ne=u(te*ve),lt=u(be*we);return new y(_e,He,lt,Ne)}add(b){h(b);let{a:A,d:B}=e,{ex:R,ey:M,ez:F,et:K}=this,{ex:O,ey:J,ez:te,et:we}=b;if(A===BigInt(-1)){let df=u((M-R)*(J+O)),hf=u((M+R)*(J-O)),nc=u(hf-df);if(nc===nt)return this.double();let pf=u(F*ho*we),mf=u(K*ho*te),gf=mf+pf,yf=hf+df,wf=mf-pf,Dm=u(gf*nc),Rm=u(yf*wf),Mm=u(gf*wf),Om=u(nc*yf);return new y(Dm,Rm,Om,Mm)}let be=u(R*O),ve=u(M*J),_e=u(K*B*we),He=u(F*te),Ne=u((R+M)*(O+J)-be-ve),lt=He-_e,yt=He+_e,Rn=u(ve-A*be),Tm=u(Ne*lt),Lm=u(yt*Rn),Pm=u(Ne*Rn),Nm=u(lt*yt);return new y(Tm,Lm,Nm,Pm)}subtract(b){return this.add(b.negate())}wNAF(b){return L.wNAFCached(this,b,y.normalizeZ)}multiply(b){let A=b;Ke("scalar",A,$e,n);let{p:B,f:R}=this.wNAF(A);return y.normalizeZ([B,R])[0]}multiplyUnsafe(b,A=y.ZERO){let B=b;return Ke("scalar",B,nt,n),B===nt?_:this.is0()||B===$e?this:L.wNAFCachedUnsafe(this,B,y.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return L.unsafeLadder(this,n).is0()}toAffine(b){return w(this,b)}clearCofactor(){let{h:b}=e;return b===$e?this:this.multiplyUnsafe(b)}static fromHex(b,A=!1){let{d:B,a:R}=e,M=t.BYTES;b=oe("pointHex",b,M),rt("zip215",A);let F=b.slice(),K=b[M-1];F[M-1]=K&-129;let O=Gt(F),J=A?l:t.ORDER;Ke("pointHex.y",O,nt,J);let te=u(O*O),we=u(te-$e),be=u(B*te-R),{isValid:ve,value:_e}=d(we,be);if(!ve)throw new Error("Point.fromHex: invalid y coordinate");let He=(_e&$e)===$e,Ne=(K&128)!==0;if(!A&&_e===nt&&Ne)throw new Error("Point.fromHex: x=0 and x_0=1");return Ne!==He&&(_e=u(-_e)),y.fromAffine({x:_e,y:O})}static fromPrivateKey(b){return k(b).point}toRawBytes(){let{x:b,y:A}=this.toAffine(),B=dr(A,t.BYTES);return B[B.length-1]|=b&$e?128:0,B}toHex(){return _t(this.toRawBytes())}}y.BASE=new y(e.Gx,e.Gy,$e,u(e.Gx*e.Gy)),y.ZERO=new y(nt,$e,$e,nt);let{BASE:E,ZERO:_}=y,L=uo(y,a*8);function I(v){return Q(v,n)}function T(v){return I(Gt(v))}function k(v){let b=t.BYTES;v=oe("private key",v,b);let A=oe("hashed private key",o(v),2*b),B=m(A.slice(0,b)),R=A.slice(b,2*b),M=T(B),F=E.multiply(M),K=F.toRawBytes();return{head:B,prefix:R,scalar:M,point:F,pointBytes:K}}function re(v){return k(v).pointBytes}function W(v=new Uint8Array,...b){let A=It(...b);return T(o(p(A,oe("context",v),!!s)))}function V(v,b,A={}){v=oe("message",v),s&&(v=s(v));let{prefix:B,scalar:R,pointBytes:M}=k(b),F=W(A.context,B,v),K=E.multiply(F).toRawBytes(),O=W(A.context,K,M,v),J=I(F+O*R);Ke("signature.s",J,nt,n);let te=It(K,dr(J,t.BYTES));return oe("result",te,t.BYTES*2)}let he=A0;function S(v,b,A,B=he){let{context:R,zip215:M}=B,F=t.BYTES;v=oe("signature",v,2*F),b=oe("message",b),A=oe("publicKey",A,F),M!==void 0&&rt("zip215",M),s&&(b=s(b));let K=Gt(v.slice(F,2*F)),O,J,te;try{O=y.fromHex(A,M),J=y.fromHex(v.slice(0,F),M),te=E.multiplyUnsafe(K)}catch{return!1}if(!M&&O.isSmallOrder())return!1;let we=W(R,J.toRawBytes(),O.toRawBytes(),b);return J.add(O.multiplyUnsafe(we)).subtract(te).clearCofactor().equals(y.ZERO)}return E._setWindowSize(8),{CURVE:e,getPublicKey:re,sign:V,verify:S,ExtendedPoint:y,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>i(t.BYTES),precompute(v=8,b=y.BASE){return b._setWindowSize(v),b.multiply(BigInt(3)),b}}}}var Rc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),nd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Gv=BigInt(0),_0=BigInt(1),sd=BigInt(2),Wv=BigInt(3),C0=BigInt(5),I0=BigInt(8);function B0(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=Rc,a=r*r%o*r%o,c=se(a,sd,o)*a%o,l=se(c,_0,o)*r%o,u=se(l,C0,o)*l%o,f=se(u,e,o)*u%o,d=se(f,t,o)*f%o,m=se(d,n,o)*d%o,p=se(m,s,o)*m%o,g=se(p,s,o)*m%o,h=se(g,e,o)*u%o;return{pow_p_5_8:se(h,sd,o)*r%o,b2:a}}function k0(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function T0(r,e){let t=Rc,n=Q(e*e*e,t),s=Q(n*n*e,t),o=B0(r*s).pow_p_5_8,i=Q(r*n*o,t),a=Q(e*i*i,t),c=i,l=Q(i*nd,t),u=a===r,f=a===Q(-r,t),d=a===Q(-r*nd,t);return u&&(i=c),(f||d)&&(i=l),Xf(i,t)&&(i=Q(-i,t)),{isValid:u||f,value:i}}var L0=jt(Rc,void 0,!0),P0={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:L0,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:I0,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:zf,randomBytes:Qr,adjustScalarBytes:k0,uvRatio:T0},Wn=rd(P0);var po=32,mo=64,Mc=32;function od(){let r=Wn.utils.randomPrivateKey(),e=Wn.getPublicKey(r);return{privateKey:N0(r,e),publicKey:e}}function id(r,e){let t=r.subarray(0,Mc);return Wn.sign(e instanceof Uint8Array?e:e.subarray(),t)}function ad(r,e,t){return Wn.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function N0(r,e){let t=new Uint8Array(mo);for(let n=0;n<Mc;n++)t[n]=r[n],t[Mc+n]=e[n];return t}var jn=class{type="Ed25519";raw;constructor(e){this.raw=yo(e,po)}toMultihash(){return At.digest(ft(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return ad(this.raw,t,e)}},go=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=yo(e,mo),this.publicKey=new jn(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return id(this.raw,e)}};function Oc(r){return r=yo(r,po),new jn(r)}async function ld(){let{privateKey:r,publicKey:e}=od();return new go(r,e)}function yo(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new D(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function le(r=0){return new Uint8Array(r)}function Ce(r=0){return new Uint8Array(r)}var D0=Math.pow(2,7),R0=Math.pow(2,14),M0=Math.pow(2,21),Uc=Math.pow(2,28),Fc=Math.pow(2,35),Vc=Math.pow(2,42),Hc=Math.pow(2,49),Y=128,Ie=127;function de(r){if(r<D0)return 1;if(r<R0)return 2;if(r<M0)return 3;if(r<Uc)return 4;if(r<Fc)return 5;if(r<Vc)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 Kc(r,e,t=0){switch(de(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function O0(r,e,t=0){switch(de(r)){case 8:e.set(t++,r&255|Y),r/=128;case 7:e.set(t++,r&255|Y),r/=128;case 6:e.set(t++,r&255|Y),r/=128;case 5:e.set(t++,r&255|Y),r/=128;case 4:e.set(t++,r&255|Y),r>>>=7;case 3:e.set(t++,r&255|Y),r>>>=7;case 2:e.set(t++,r&255|Y),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function $c(r,e){let t=r[e],n=0;if(n+=t&Ie,t<Y||(t=r[e+1],n+=(t&Ie)<<7,t<Y)||(t=r[e+2],n+=(t&Ie)<<14,t<Y)||(t=r[e+3],n+=(t&Ie)<<21,t<Y)||(t=r[e+4],n+=(t&Ie)*Uc,t<Y)||(t=r[e+5],n+=(t&Ie)*Fc,t<Y)||(t=r[e+6],n+=(t&Ie)*Vc,t<Y)||(t=r[e+7],n+=(t&Ie)*Hc,t<Y))return n;throw new RangeError("Could not decode varint")}function U0(r,e){let t=r.get(e),n=0;if(n+=t&Ie,t<Y||(t=r.get(e+1),n+=(t&Ie)<<7,t<Y)||(t=r.get(e+2),n+=(t&Ie)<<14,t<Y)||(t=r.get(e+3),n+=(t&Ie)<<21,t<Y)||(t=r.get(e+4),n+=(t&Ie)*Uc,t<Y)||(t=r.get(e+5),n+=(t&Ie)*Fc,t<Y)||(t=r.get(e+6),n+=(t&Ie)*Vc,t<Y)||(t=r.get(e+7),n+=(t&Ie)*Hc,t<Y))return n;throw new RangeError("Could not decode varint")}function Be(r,e,t=0){return e==null&&(e=Ce(de(r))),e instanceof Uint8Array?Kc(r,e,t):O0(r,e,t)}function st(r,e=0){return r instanceof Uint8Array?$c(r,e):U0(r,e)}var qc=new Float32Array([-0]),Zt=new Uint8Array(qc.buffer);function ud(r,e,t){qc[0]=r,e[t]=Zt[0],e[t+1]=Zt[1],e[t+2]=Zt[2],e[t+3]=Zt[3]}function fd(r,e){return Zt[0]=r[e],Zt[1]=r[e+1],Zt[2]=r[e+2],Zt[3]=r[e+3],qc[0]}var zc=new Float64Array([-0]),ke=new Uint8Array(zc.buffer);function dd(r,e,t){zc[0]=r,e[t]=ke[0],e[t+1]=ke[1],e[t+2]=ke[2],e[t+3]=ke[3],e[t+4]=ke[4],e[t+5]=ke[5],e[t+6]=ke[6],e[t+7]=ke[7]}function hd(r,e){return ke[0]=r[e],ke[1]=r[e+1],ke[2]=r[e+2],ke[3]=r[e+3],ke[4]=r[e+4],ke[5]=r[e+5],ke[6]=r[e+6],ke[7]=r[e+7],zc[0]}var F0=BigInt(Number.MAX_SAFE_INTEGER),V0=BigInt(Number.MIN_SAFE_INTEGER),We=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return gr;if(e<F0&&e>V0)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>pd&&(s=0n,++n>pd&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return gr;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):gr}},gr=new We(0,0);gr.toBigInt=function(){return 0n};gr.zzEncode=gr.zzDecode=function(){return this};gr.length=function(){return 1};var pd=4294967296n;function md(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function gd(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Gc(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function ot(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function wo(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Wc=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,ot(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ot(this,4);return wo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return wo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);let e=fd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ot(this,4);let e=hd(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw ot(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return gd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ot(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ot(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new We(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw ot(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw ot(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ot(this,8);let e=wo(this.buf,this.pos+=4),t=wo(this.buf,this.pos+=4);return new We(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=$c(this.buf,this.pos);return this.pos+=de(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function jc(r){return new Wc(r instanceof Uint8Array?r:r.subarray())}function Re(r,e,t){let n=jc(r);return e.decode(n,void 0,t)}var Zc={};De(Zc,{base10:()=>H0});var H0=Kt({prefix:"9",name:"base10",alphabet:"0123456789"});var Xc={};De(Xc,{base16:()=>K0,base16upper:()=>$0});var K0=ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$0=ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Yc={};De(Yc,{base2:()=>q0});var q0=ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Jc={};De(Jc,{base256emoji:()=>Z0});var wd=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}"),z0=wd.reduce((r,e,t)=>(r[t]=e,r),[]),G0=wd.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function W0(r){return r.reduce((e,t)=>(e+=z0[t],e),"")}function j0(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=G0[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Z0=Gr({prefix:"\u{1F680}",name:"base256emoji",encode:W0,decode:j0});var tl={};De(tl,{base64:()=>Qc,base64pad:()=>X0,base64url:()=>el,base64urlpad:()=>Y0});var Qc=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),X0=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),el=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Y0=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var rl={};De(rl,{base8:()=>J0});var J0=ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var nl={};De(nl,{identity:()=>Q0});var Q0=Gr({prefix:"\0",name:"identity",encode:r=>_f(r),decode:r=>Sf(r)});var C1=new TextEncoder,I1=new TextDecoder;var il={};De(il,{sha256:()=>rn,sha512:()=>ry});function ol({name:r,code:e,encode:t}){return new sl(r,e,t)}var sl=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Qe(this.code,t):t.then(n=>Qe(this.code,n))}else throw Error("Unknown type, must be binary type")}};function xd(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var rn=ol({name:"sha2-256",code:18,encode:xd("SHA-256")}),ry=ol({name:"sha2-512",code:19,encode:xd("SHA-512")});var Zn={...nl,...Yc,...rl,...Zc,...Xc,...pc,...mc,...hc,...tl,...Jc},F1={...il,...wc};function Ed(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var vd=Ed("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),al=Ed("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ce(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ny={utf8:vd,"utf-8":vd,hex:Zn.base16,latin1:al,ascii:al,binary:al,...Zn},bo=ny;function N(r,e="utf8"){let t=bo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function cl(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return Ce(i);s+i>e&&(n=Ce(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var yr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ll(){}var fl=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},sy=cl();function oy(r){return globalThis.Buffer!=null?Ce(r):sy(r)}var Yn=class{len;head;tail;states;constructor(){this.len=0,this.head=new yr(ll,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new dl((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(xo,10,We.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=We.fromBigInt(e);return this._push(xo,t.length(),t)}uint64Number(e){return this._push(Kc,de(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=We.fromBigInt(e).zzEncode();return this._push(xo,t.length(),t)}sint64Number(e){let t=We.fromNumber(e).zzEncode();return this._push(xo,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ul,1,e?1:0)}fixed32(e){return this._push(Xn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=We.fromBigInt(e);return this._push(Xn,4,t.lo)._push(Xn,4,t.hi)}fixed64Number(e){let t=We.fromNumber(e);return this._push(Xn,4,t.lo)._push(Xn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(ud,4,e)}double(e){return this._push(dd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ul,1,0):this.uint32(t)._push(ay,t,e)}string(e){let t=md(e);return t!==0?this.uint32(t)._push(Gc,t,e):this._push(ul,1,0)}fork(){return this.states=new fl(this),this.head=this.tail=new yr(ll,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(ll,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=oy(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function ul(r,e,t){e[t]=r&255}function iy(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var dl=class extends yr{next;constructor(e,t){super(iy,e,t),this.next=void 0}};function xo(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function Xn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function ay(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Yn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(cy,e,r),this},Yn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(ly,e,r),this});function cy(r,e,t){e.set(r,t)}function ly(r,e,t){r.length<40?Gc(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(N(r),t)}function hl(){return new Yn}function Me(r,e){let t=hl();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var nn;(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"})(nn||(nn={}));function vo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function pl(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,i){let a=e(o);i.int32(a)},n=function(o){let i=o.int32();return e(i)};return vo("enum",nn.VARINT,t,n)}function Oe(r,e){return vo("message",nn.LENGTH_DELIMITED,r,e)}var wr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Jn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(ge||(ge={}));var ml;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(ml||(ml={}));(function(r){r.codec=()=>pl(ml)})(ge||(ge={}));var dt;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ge.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ge.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(dt||(dt={}));var gl;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ge.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ge.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(gl||(gl={}));var ls={};De(ls,{MAX_RSA_KEY_SIZE:()=>di,generateRSAKeyPair:()=>Il,jwkToJWKKeyPair:()=>bh,jwkToPkcs1:()=>_y,jwkToPkix:()=>_l,jwkToRSAPrivateKey:()=>wh,pkcs1ToJwk:()=>mh,pkcs1ToRSAPrivateKey:()=>yh,pkixToJwk:()=>gh,pkixToRSAPublicKey:()=>Cl});var uy=new Uint32Array([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]),Xt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yt=new Uint32Array(64),yl=class extends en{constructor(){super(64,32,8,!1),this.A=Xt[0]|0,this.B=Xt[1]|0,this.C=Xt[2]|0,this.D=Xt[3]|0,this.E=Xt[4]|0,this.F=Xt[5]|0,this.G=Xt[6]|0,this.H=Xt[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Yt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Yt[f-15],m=Yt[f-2],p=tt(d,7)^tt(d,18)^d>>>3,g=tt(m,17)^tt(m,19)^m>>>10;Yt[f]=g+Yt[f-7]+p+Yt[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=tt(a,6)^tt(a,11)^tt(a,25),m=u+d+Kf(a,c,l)+uy[f]+Yt[f]|0,g=(tt(n,2)^tt(n,13)^tt(n,22))+$f(n,s,o)|0;u=l,l=c,c=a,a=i+m|0,i=o,o=s,s=n,n=m+g|0}n=n+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,l,u)}roundClean(){Yt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var sn=no(()=>new yl);var H=Vr(Sd());function br(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Jt(r,e,t=-1){let n=t,s=r,o=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),o=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),o=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*e);l[o-u-1]=Math.floor(s/f),s-=l[o-u-1]*f}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function So(...r){let e=0,t=0;for(let o of r)e+=o.length;let n=new ArrayBuffer(e),s=new Uint8Array(n);for(let o of r)s.set(o,t),t+=o.length;return s}function bl(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=br(t,8),s=new ArrayBuffer(this.valueHex.byteLength),o=new Uint8Array(s);for(let a=0;a<this.valueHex.byteLength;a++)o[a]=r[a];return o[0]&=127,br(o,8)-n}function _d(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Jt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let s=Jt(e,8,n),o=new Uint8Array(s);if(o[0]&128){let i=s.slice(0),a=new Uint8Array(i);s=new ArrayBuffer(s.byteLength+1),o=new Uint8Array(s);for(let c=0;c<i.byteLength;c++)o[c+1]=a[c];o[0]=0}return s}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Cd(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<t.length;s++)if(t[s]!==n[s])return!1;return!0}function qe(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,s=new Array(n);for(let i=0;i<n;i++)s[i]="0";return s.join("").concat(t)}var xE=Math.log(2);function _o(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function xl(r){let e=0,t=0;for(let s=0;s<r.length;s++){let o=r[s];e+=o.byteLength}let n=new Uint8Array(e);for(let s=0;s<r.length;s++){let o=r[s];n.set(new Uint8Array(o),t),t+=o.byteLength}return n.buffer}function Pt(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var es=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return xl(this.items)}},Qn=[new Uint8Array([1])],Id="0123456789";var un="",it=new ArrayBuffer(0),vl=new Uint8Array(0),ts="EndOfContent",kd="OCTET STRING",Td="BIT STRING";function Nt(r){var e;return e=class extends r{constructor(...n){var s;super(...n);let o=n[0]||{};this.isHexOnly=(s=o.isHexOnly)!==null&&s!==void 0?s:!1,this.valueHexView=o.valueHex?H.BufferSourceConverter.toUint8Array(o.valueHex):vl}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,s,o){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Pt(this,i,s,o))return-1;let a=s+o;return this.valueHexView=i.subarray(s,a),this.valueHexView.length?(this.blockLength=o,a):(this.warnings.push("Zero buffer length"),s)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",it)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:H.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var kt=class{constructor({blockLength:e=0,error:t=un,warnings:n=[],valueBeforeDecode:s=vl}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=H.BufferSourceConverter.toUint8Array(s)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:H.Convert.ToHex(this.valueBeforeDecodeView)}}};kt.NAME="baseBlock";var Te=class extends kt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Te.NAME="valueBlock";var Co=class extends Nt(kt){constructor({idBlock:e={}}={}){var t,n,s,o;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?H.BufferSourceConverter.toUint8Array(e.valueHex):vl,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(s=e.tagNumber)!==null&&s!==void 0?s:-1,this.isConstructed=(o=e.isConstructed)!==null&&o!==void 0?o:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",it}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let s=new Uint8Array(1);if(!e){let o=this.tagNumber;o&=31,t|=o,s[0]=t}return s.buffer}if(!this.isHexOnly){let s=Jt(this.tagNumber,7),o=new Uint8Array(s),i=s.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=o[c]|128;a[i]=o[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let s=this.valueHexView;for(let o=0;o<s.length-1;o++)n[o+1]=s[o]|128;n[this.valueHexView.byteLength]=s[s.length-1]}return n.buffer}fromBER(e,t,n){let s=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let o=s.subarray(t,t+n);if(o.length===0)return this.error="Zero buffer length",-1;switch(o[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(o[0]&32)===32,this.isHexOnly=!1;let a=o[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;o[c]&128;){if(l[c-1]=o[c]&127,c++,c>=o.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let m=0;m<l.length;m++)d[m]=l[m];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=o[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=br(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Co.NAME="identificationBlock";var Io=class extends kt{constructor({lenBlock:e={}}={}){var t,n,s;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(s=e.length)!==null&&s!==void 0?s:0}fromBER(e,t,n){let s=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let o=s.subarray(t,t+n);if(o.length===0)return this.error="Zero buffer length",-1;if(o[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=o[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(o[0]&128),this.longFormUsed===!1)return this.length=o[0],this.blockLength=1,t+this.blockLength;let i=o[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>o.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=s.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=br(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let s=Jt(this.length,8);if(s.byteLength>127)return this.error="Too big length",it;if(t=new ArrayBuffer(s.byteLength+1),e)return t;let o=new Uint8Array(s);n=new Uint8Array(t),n[0]=s.byteLength|128;for(let i=0;i<s.byteLength;i++)n[i+1]=o[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Io.NAME="lengthBlock";var C={},Ee=class extends kt{constructor({name:e=un,optional:t=!1,primitiveSchema:n,...s}={},o){super(s),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Co(s),this.lenBlock=new Io(s),this.valueBlock=o?new o(s):new Te(s)}fromBER(e,t,n){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,t){let n=t||new es;t||Ld(this);let s=this.idBlock.toBER(e);if(n.write(s),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let o=this.valueBlock.toBER(e);this.lenBlock.length=o.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(o)}return t?it:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():H.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${H.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Cd(t,n)}};Ee.NAME="BaseBlock";function Ld(r){if(r instanceof C.Constructed)for(let e of r.valueBlock.value)Ld(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Bo=class extends Ee{constructor({value:e=un,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Bo.NAME="BaseStringBlock";var ko=class extends Nt(Te){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};ko.NAME="PrimitiveValueBlock";var Pd,To=class extends Ee{constructor(e={}){super(e,ko),this.idBlock.isConstructed=!1}};Pd=To;C.Primitive=Pd;To.NAME="PRIMITIVE";function by(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function ui(r,e=0,t=r.length){let n=e,s=new Ee({},Te),o=new kt;if(!Pt(o,r,e,t))return s.error=o.error,{offset:-1,result:s};if(!r.subarray(e,e+t).length)return s.error="Zero buffer length",{offset:-1,result:s};let a=s.idBlock.fromBER(r,e,t);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),a===-1)return s.error=s.idBlock.error,{offset:-1,result:s};if(e=a,t-=s.idBlock.blockLength,a=s.lenBlock.fromBER(r,e,t),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),a===-1)return s.error=s.lenBlock.error,{offset:-1,result:s};if(e=a,t-=s.lenBlock.blockLength,!s.idBlock.isConstructed&&s.lenBlock.isIndefiniteForm)return s.error="Indefinite length form used for primitive encoding form",{offset:-1,result:s};let c=Ee;switch(s.idBlock.tagClass){case 1:if(s.idBlock.tagNumber>=37&&s.idBlock.isHexOnly===!1)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};c=C.EndOfContent;break;case 1:c=C.Boolean;break;case 2:c=C.Integer;break;case 3:c=C.BitString;break;case 4:c=C.OctetString;break;case 5:c=C.Null;break;case 6:c=C.ObjectIdentifier;break;case 10:c=C.Enumerated;break;case 12:c=C.Utf8String;break;case 13:c=C.RelativeObjectIdentifier;break;case 14:c=C.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:c=C.Sequence;break;case 17:c=C.Set;break;case 18:c=C.NumericString;break;case 19:c=C.PrintableString;break;case 20:c=C.TeletexString;break;case 21:c=C.VideotexString;break;case 22:c=C.IA5String;break;case 23:c=C.UTCTime;break;case 24:c=C.GeneralizedTime;break;case 25:c=C.GraphicString;break;case 26:c=C.VisibleString;break;case 27:c=C.GeneralString;break;case 28:c=C.UniversalString;break;case 29:c=C.CharacterString;break;case 30:c=C.BmpString;break;case 31:c=C.DATE;break;case 32:c=C.TimeOfDay;break;case 33:c=C.DateTime;break;case 34:c=C.Duration;break;default:{let l=s.idBlock.isConstructed?new C.Constructed:new C.Primitive;l.idBlock=s.idBlock,l.lenBlock=s.lenBlock,l.warnings=s.warnings,s=l}}break;case 2:case 3:case 4:default:c=s.idBlock.isConstructed?C.Constructed:C.Primitive}return s=by(s,c),a=s.fromBER(r,e,s.lenBlock.isIndefiniteForm?t:s.lenBlock.length),s.valueBeforeDecodeView=r.subarray(n,n+s.blockLength),{offset:a,result:s}}function El(r){if(!r.byteLength){let e=new Ee({},Te);return e.error="Input buffer has zero length",{offset:-1,result:e}}return ui(H.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function xy(r,e){return r?1:e}var ht=class extends Te{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let s=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;if(this.valueBeforeDecodeView=s.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let o=t;for(;xy(this.isIndefiniteForm,n)>0;){let i=ui(s,o,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(o=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===ts)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ts?this.value.pop():this.warnings.push("No EndOfContent block encoded")),o}toBER(e,t){let n=t||new es;for(let s=0;s<this.value.length;s++)this.value[s].toBER(e,n);return t?it:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};ht.NAME="ConstructedValueBlock";var Nd,Qt=class extends Ee{constructor(e={}){super(e,ht),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let s=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
3
- `).map(s=>` ${s}`).join(`
4
- `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
5
- ${e.join(`
6
- `)}`:`${t} :`}};Nd=Qt;C.Constructed=Nd;Qt.NAME="CONSTRUCTED";var Lo=class extends Te{fromBER(e,t,n){return t}toBER(e){return it}};Lo.override="EndOfContentValueBlock";var Dd,Po=class extends Ee{constructor(e={}){super(e,Lo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Dd=Po;C.EndOfContent=Dd;Po.NAME=ts;var Rd,an=class extends Ee{constructor(e={}){super(e,Te),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let s=new Uint8Array(n);s[0]=5,s[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Rd=an;C.Null=Rd;an.NAME="NULL";var No=class extends Nt(Te){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=H.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let s=H.BufferSourceConverter.toUint8Array(e);return Pt(this,s,t,n)?(this.valueHexView=s.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,bl.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};No.NAME="BooleanValueBlock";var Md,Do=class extends Ee{constructor(e={}){super(e,No),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Md=Do;C.Boolean=Md;Do.NAME="BOOLEAN";var Ro=class extends Nt(ht){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=ht.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let o=0;o<this.value.length;o++){let i=this.value[o].constructor.NAME;if(i===ts){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==kd)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,n),this.blockLength=n;return s}toBER(e,t){return this.isConstructed?ht.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Ro.NAME="OctetStringValueBlock";var Od,Mo=class r extends Ee{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ro),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let o=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(o.byteLength){let i=ui(o,0,o.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Qt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${H.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return H.BufferSourceConverter.concat(e)}};Od=Mo;C.OctetString=Od;Mo.NAME=kd;var Oo=class extends Nt(ht){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let s=-1;if(this.isConstructed){if(s=ht.prototype.fromBER.call(this,e,t,n),s===-1)return s;for(let a of this.value){let c=a.constructor.NAME;if(c===ts){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Td)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return s}let o=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=ui(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return ht.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return it;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Oo.NAME="BitStringValueBlock";var Ud,cn=class extends Ee{constructor({idBlock:e={},lenBlock:t={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Oo),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Qt.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let s of t)e.push(s.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Ud=cn;C.BitString=Ud;cn.NAME=Td;var Fd;function vy(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=o[i-f]+a[c-f]+t[0];break;default:l=o[i-f]+t[0]}switch(t[0]=l/10,!0){case f>=o.length:o=So(new Uint8Array([l%10]),o);break;default:o[i-f]=l%10}}return t[0]>0&&(o=So(t,o)),o}function Bd(r){if(r>=Qn.length)for(let e=Qn.length;e<=r;e++){let t=new Uint8Array([0]),n=Qn[e-1].slice(0);for(let s=n.length-1;s>=0;s--){let o=new Uint8Array([(n[s]<<1)+t[0]]);t[0]=o[0]/10,n[s]=o[0]%10}t[0]>0&&(n=So(t,n)),Qn.push(n)}return Qn[r]}function Ey(r,e){let t=0,n=new Uint8Array(r),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=o[i-u]-a[c-u]-t,!0){case l<0:t=1,o[i-u]=l+10;break;default:t=0,o[i-u]=l}if(t>0)for(let f=i-c+1;f>=0;f--,u++)if(l=o[i-u]-t,l<0)t=1,o[i-u]=l+10;else{t=0,o[i-u]=l;break}return o.slice()}var rs=class extends Nt(Te){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=bl.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(_d(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,s=0){let o=this.fromBER(e,t,n);if(o===-1)return o;let i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):s!==0&&i.length<s&&(s-i.length>1&&(s=i.length+1),this.valueHexView=i.subarray(s-i.length)),o}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let s=super.fromBER(e,t,n);return s===-1||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,s,o=this.valueHexView,i="",a=!1;for(let c=o.byteLength-1;c>=0;c--){s=o[c];for(let l=0;l<8;l++){if((s&1)===1)switch(n){case e:t=Ey(Bd(n),t),i="-";break;default:t=vy(t,Bd(n))}n++,s>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Id.charAt(t[c]));return a===!1&&(i+=Id.charAt(0)),i}};Fd=rs;rs.NAME="IntegerValueBlock";Object.defineProperty(Fd.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Vd,Ae=class r extends Ee{constructor(e={}){super(e,rs),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return _o(),BigInt(this.valueBlock.toString())}static fromBigInt(e){_o();let t=BigInt(e),n=new es,s=t.toString(16).replace(/^-/,""),o=new Uint8Array(H.Convert.FromHex(s));if(t<0){let a=new Uint8Array(o.length+(o[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${H.Convert.ToHex(a)}`)+t,u=H.BufferSourceConverter.toUint8Array(H.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else o[0]&128&&n.write(new Uint8Array([0])),n.write(o);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Vd=Ae;C.Integer=Vd;Ae.NAME="INTEGER";var Hd,Uo=class extends Ae{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Hd=Uo;C.Enumerated=Hd;Uo.NAME="ENUMERATED";var ns=class extends Nt(Te){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let s=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){_o();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let s=0;s<n.length;s++)n[s]=parseInt(t.slice(s*7,s*7+7),2)+(s+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",it;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n}toString(){let e="";if(this.isHexOnly)e=H.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};ns.NAME="sidBlock";var Fo=class extends Te{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new ns;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.value.length===0&&(o.isFirstSid=!0),this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let s=this.value[n].toBER(e);if(s.byteLength===0)return this.error=this.value[n].error,it;t.push(s)}return xl(t)}fromString(e){this.value=[];let t=0,n=0,s="",o=!1;do if(n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1,o){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(s,10);if(isNaN(c))return;i.valueDec=c+a,o=!1}else{let i=new ns;if(s>Number.MAX_SAFE_INTEGER){_o();let a=BigInt(s);i.valueBigInt=a}else if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,o=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),t?(s=`{${s}}`,this.value[n].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Fo.NAME="ObjectIdentifierValueBlock";var Kd,ln=class extends Ee{constructor(e={}){super(e,Fo),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Kd=ln;C.ObjectIdentifier=Kd;ln.NAME="OBJECT IDENTIFIER";var ss=class extends Nt(kt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let s=H.BufferSourceConverter.toUint8Array(e);if(!Pt(this,s,t,n))return-1;let o=s.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=br(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}let t=Jt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",it;let n=new Uint8Array(t.byteLength);if(!e){let s=new Uint8Array(t),o=t.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n.buffer}toString(){let e="";return this.isHexOnly?e=H.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};ss.NAME="relativeSidBlock";var Vo=class extends Te{constructor({value:e=un,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let s=t;for(;n>0;){let o=new ss;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e,t){let n=[];for(let s=0;s<this.value.length;s++){let o=this.value[s].toBER(e);if(o.byteLength===0)return this.error=this.value[s].error,it;n.push(o)}return xl(n)}fromString(e){this.value=[];let t=0,n=0,s="";do{n=e.indexOf(".",t),n===-1?s=e.substring(t):s=e.substring(t,n),t=n+1;let o=new ss;if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return!0;this.value.push(o)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(s=`{${s}}`),e+=s}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Vo.NAME="RelativeObjectIdentifierValueBlock";var $d,Ho=class extends Ee{constructor(e={}){super(e,Vo),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};$d=Ho;C.RelativeObjectIdentifier=$d;Ho.NAME="RelativeObjectIdentifier";var qd,Tt=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};qd=Tt;C.Sequence=qd;Tt.NAME="SEQUENCE";var zd,Ko=class extends Qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};zd=Ko;C.Set=zd;Ko.NAME="SET";var $o=class extends Nt(Te){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=un}toJSON(){return{...super.toJSON(),value:this.value}}};$o.NAME="StringValueBlock";var qo=class extends $o{};qo.NAME="SimpleStringValueBlock";var Ue=class extends Bo{constructor({...e}={}){super(e,qo)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,H.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);this.valueBlock.value=e}};Ue.NAME="SIMPLE STRING";var zo=class extends Ue{fromBuffer(e){this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=H.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=H.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf8String(e)),this.valueBlock.value=e}};zo.NAME="Utf8StringValueBlock";var Gd,Lt=class extends zo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Gd=Lt;C.Utf8String=Gd;Lt.NAME="UTF8String";var Go=class extends Ue{fromBuffer(e){this.valueBlock.value=H.Convert.ToUtf16String(e),this.valueBlock.valueHexView=H.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(H.Convert.FromUtf16String(e))}};Go.NAME="BmpStringValueBlock";var Wd,Wo=class extends Go{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Wd=Wo;C.BmpString=Wd;Wo.NAME="BMPString";var jo=class extends Ue{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let s=0;s<n.length;s+=4)n[s]=n[s+3],n[s+1]=n[s+2],n[s+2]=0,n[s+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let s=0;s<t;s++){let o=Jt(e.charCodeAt(s),8),i=new Uint8Array(o);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[s*4+c+a]=i[c]}this.valueBlock.value=e}};jo.NAME="UniversalStringValueBlock";var jd,Zo=class extends jo{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};jd=Zo;C.UniversalString=jd;Zo.NAME="UniversalString";var Zd,Xo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Zd=Xo;C.NumericString=Zd;Xo.NAME="NumericString";var Xd,Yo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Xd=Yo;C.PrintableString=Xd;Yo.NAME="PrintableString";var Yd,Jo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Yd=Jo;C.TeletexString=Yd;Jo.NAME="TeletexString";var Jd,Qo=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Jd=Qo;C.VideotexString=Jd;Qo.NAME="VideotexString";var Qd,ei=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Qd=ei;C.IA5String=Qd;ei.NAME="IA5String";var eh,ti=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};eh=ti;C.GraphicString=eh;ti.NAME="GraphicString";var th,os=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};th=os;C.VisibleString=th;os.NAME="VisibleString";var rh,ri=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};rh=ri;C.GeneralString=rh;ri.NAME="GeneralString";var nh,ni=class extends Ue{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};nh=ni;C.CharacterString=nh;ni.NAME="CharacterString";var sh,is=class extends os{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let s=0;s<e.length;s++)this.valueBlock.valueHexView[s]=e.charCodeAt(s)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,H.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let s=parseInt(n[1],10);s>=50?this.year=1900+s:this.year=2e3+s,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=qe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=qe(this.month,2),t[2]=qe(this.day,2),t[3]=qe(this.hour,2),t[4]=qe(this.minute,2),t[5]=qe(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};sh=is;C.UTCTime=sh;is.NAME="UTCTime";var oh,si=class extends is{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",s="",o=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),m="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(m=n.substring(d+1),n=n.substring(0,d),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(m.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*p,m.length===4){if(p=parseInt(m.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=f*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");o=f.valueOf(),s=n.substring(0,l)}else s=n;switch(!0){case s.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*o;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case s.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*o;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case s.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*o;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(s);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(qe(this.year,4)),t.push(qe(this.month,2)),t.push(qe(this.day,2)),t.push(qe(this.hour,2)),t.push(qe(this.minute,2)),t.push(qe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(qe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};oh=si;C.GeneralizedTime=oh;si.NAME="GeneralizedTime";var ih,oi=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};ih=oi;C.DATE=ih;oi.NAME="DATE";var ah,ii=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};ah=ii;C.TimeOfDay=ah;ii.NAME="TimeOfDay";var ch,ai=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};ch=ai;C.DateTime=ch;ai.NAME="DateTime";var lh,ci=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};lh=ci;C.Duration=lh;ci.NAME="Duration";var uh,li=class extends Lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};uh=li;C.TIME=uh;li.NAME="TIME";function z(r,e="utf8"){let t=bo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function fn(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0");return Qr(r)}var as=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},cs=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},fi=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var fh={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new fi("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var er=fh;async function dh(r){let e=await er.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Sy(e);return{privateKey:t[0],publicKey:t[1]}}async function hh(r,e){let t=await er.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await er.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function ph(r,e,t){let n=await er.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return er.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Sy(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required");return Promise.all([er.get().subtle.exportKey("jwk",r.privateKey),er.get().subtle.exportKey("jwk",r.publicKey)])}function Al(r){if(r.kty!=="RSA")throw new D("invalid key type");if(r.n==null)throw new D("invalid key modulus");return N(r.n,"base64url").length*8}var dn=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=ls.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return pe.createV1(114,this._multihash)}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return ph(this._key,t,e)}},us=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=ls.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return hh(this._key,e)}};var di=8192,Sl=18;function mh(r){let{result:e}=El(r),t=e.valueBlock.value;return{n:pt(t[1]),e:pt(t[2]),d:pt(t[3]),p:pt(t[4]),q:pt(t[5]),dp:pt(t[6]),dq:pt(t[7]),qi:pt(t[8]),kty:"RSA",alg:"RS256"}}function _y(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 D("JWK was missing components");let t=new Tt({value:[new Ae({value:0}),Ae.fromBigInt(mt(N(r.n,"base64url"))),Ae.fromBigInt(mt(N(r.e,"base64url"))),Ae.fromBigInt(mt(N(r.d,"base64url"))),Ae.fromBigInt(mt(N(r.p,"base64url"))),Ae.fromBigInt(mt(N(r.q,"base64url"))),Ae.fromBigInt(mt(N(r.dp,"base64url"))),Ae.fromBigInt(mt(N(r.dq,"base64url"))),Ae.fromBigInt(mt(N(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function gh(r){let{result:e}=El(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:pt(t[0]),e:pt(t[1])}}function _l(r){if(r.n==null||r.e==null)throw new D("JWK was missing components");let t=new Tt({value:[new Tt({value:[new ln({value:"1.2.840.113549.1.1.1"}),new an]}),new cn({valueHex:new Tt({value:[Ae.fromBigInt(mt(N(r.n,"base64url"))),Ae.fromBigInt(mt(N(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function pt(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return z(e,"base64url")}function mt(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}function yh(r){let e=mh(r);return wh(e)}function Cl(r){let e=gh(r);if(Al(e)>di)throw new Hr("Key size is too large");let t=sn(dt.encode({Type:ge.RSA,Data:r})),n=Qe(Sl,t);return new dn(e,n)}function wh(r){if(Al(r)>di)throw new D("Key size is too large");let e=bh(r),t=sn(dt.encode({Type:ge.RSA,Data:_l(e.publicKey)})),n=Qe(Sl,t);return new us(e.privateKey,new dn(e.publicKey,n))}async function Il(r){if(r>di)throw new D("Key size is too large");let e=await dh(r),t=sn(dt.encode({Type:ge.RSA,Data:_l(e.publicKey)})),n=Qe(Sl,t);return new us(e.privateKey,new dn(e.publicKey,n))}function bh(r){if(r==null)throw new D("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var hi=class extends Jr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ff(e);let n=$n(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?e.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),o.fill(0)}update(e){return Yr(this),this.iHash.update(e),this}digestInto(e){Yr(this),Xr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Bl=(r,e,t)=>new hi(r,e).update(t).digest();Bl.create=(r,e)=>new hi(r,e);function xh(r){r.lowS!==void 0&&rt("lowS",r.lowS),r.prehash!==void 0&&rt("prehash",r.prehash)}function Cy(r){let e=Gn(r);ut(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:s}=e;if(t){if(!n.eql(s,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:Iy,hexToBytes:By}=ao,kl=class extends Error{constructor(e=""){super(e)}},Dt={Err:kl,_tlv:{encode:(r,e)=>{let{Err:t}=Dt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=ur(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?ur(s.length/2|128):"";return ur(r)+o+s+e},decode(r,e){let{Err:t}=Dt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Dt;if(r<Rt)throw new e("integer: negative integers are not allowed");let t=ur(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Dt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Iy(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Dt,s=typeof r=="string"?By(r):r;tn(s);let{v:o,l:i}=n.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Dt,n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},Rt=BigInt(0),xe=BigInt(1),t2=BigInt(2),vh=BigInt(3),r2=BigInt(4);function ky(r){let e=Cy(r),{Fp:t}=e,n=jt(e.n,e.nBitLength),s=e.toBytes||((g,h,w)=>{let x=h.toAffine();return It(Uint8Array.from([4]),t.toBytes(x.x),t.toBytes(x.y))}),o=e.fromBytes||(g=>{let h=g.subarray(1),w=t.fromBytes(h.subarray(0,t.BYTES)),x=t.fromBytes(h.subarray(t.BYTES,2*t.BYTES));return{x:w,y:x}});function i(g){let{a:h,b:w}=e,x=t.sqr(g),y=t.mul(x,g);return t.add(t.add(y,t.mul(g,h)),w)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return qn(g,xe,e.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:x,n:y}=e;if(h&&typeof g!="bigint"){if(zt(g)&&(g=_t(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(w*2,"0")}let E;try{E=typeof g=="bigint"?g:Ct(oe("private key",g,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof g)}return x&&(E=Q(E,y)),Ke("private key",E,xe,y),E}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=hr((g,h)=>{let{px:w,py:x,pz:y}=g;if(t.eql(y,t.ONE))return{x:w,y:x};let E=g.is0();h==null&&(h=E?t.ONE:t.inv(y));let _=t.mul(w,h),L=t.mul(x,h),I=t.mul(y,h);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:_,y:L}}),f=hr(g=>{if(g.is0()){if(e.allowInfinityPoint&&!t.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=g.toAffine();if(!t.isValid(h)||!t.isValid(w))throw new Error("bad point: x or y not FE");let x=t.sqr(w),y=i(h);if(!t.eql(x,y))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,x){if(this.px=h,this.py=w,this.pz=x,h==null||!t.isValid(h))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(x==null||!t.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:x}=h||{};if(!h||!t.isValid(w)||!t.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let y=E=>t.eql(E,t.ZERO);return y(w)&&y(x)?d.ZERO:new d(w,x,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=t.invertBatch(h.map(x=>x.pz));return h.map((x,y)=>x.toAffine(w[y])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(o(oe("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return fo(d,n,h,w)}_setWindowSize(h){p.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(t.isOdd)return!t.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=t.eql(t.mul(w,L),t.mul(E,y)),T=t.eql(t.mul(x,L),t.mul(_,y));return I&&T}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:h,b:w}=e,x=t.mul(w,vh),{px:y,py:E,pz:_}=this,L=t.ZERO,I=t.ZERO,T=t.ZERO,k=t.mul(y,y),re=t.mul(E,E),W=t.mul(_,_),V=t.mul(y,E);return V=t.add(V,V),T=t.mul(y,_),T=t.add(T,T),L=t.mul(h,T),I=t.mul(x,W),I=t.add(L,I),L=t.sub(re,I),I=t.add(re,I),I=t.mul(L,I),L=t.mul(V,L),T=t.mul(x,T),W=t.mul(h,W),V=t.sub(k,W),V=t.mul(h,V),V=t.add(V,T),T=t.add(k,k),k=t.add(T,k),k=t.add(k,W),k=t.mul(k,V),I=t.add(I,k),W=t.mul(E,_),W=t.add(W,W),k=t.mul(W,V),L=t.sub(L,k),T=t.mul(W,re),T=t.add(T,T),T=t.add(T,T),new d(L,I,T)}add(h){l(h);let{px:w,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=t.ZERO,T=t.ZERO,k=t.ZERO,re=e.a,W=t.mul(e.b,vh),V=t.mul(w,E),he=t.mul(x,_),S=t.mul(y,L),P=t.add(w,x),v=t.add(E,_);P=t.mul(P,v),v=t.add(V,he),P=t.sub(P,v),v=t.add(w,y);let b=t.add(E,L);return v=t.mul(v,b),b=t.add(V,S),v=t.sub(v,b),b=t.add(x,y),I=t.add(_,L),b=t.mul(b,I),I=t.add(he,S),b=t.sub(b,I),k=t.mul(re,v),I=t.mul(W,S),k=t.add(I,k),I=t.sub(he,k),k=t.add(he,k),T=t.mul(I,k),he=t.add(V,V),he=t.add(he,V),S=t.mul(re,S),v=t.mul(W,v),he=t.add(he,S),S=t.sub(V,S),S=t.mul(re,S),v=t.add(v,S),V=t.mul(he,v),T=t.add(T,V),V=t.mul(b,v),I=t.mul(P,I),I=t.sub(I,V),V=t.mul(P,he),k=t.mul(b,k),k=t.add(k,V),new d(I,T,k)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return p.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:x}=e;Ke("scalar",h,Rt,x);let y=d.ZERO;if(h===Rt)return y;if(this.is0()||h===xe)return this;if(!w||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:E,k1:_,k2neg:L,k2:I}=w.splitScalar(h),T=y,k=y,re=this;for(;_>Rt||I>Rt;)_&xe&&(T=T.add(re)),I&xe&&(k=k.add(re)),re=re.double(),_>>=xe,I>>=xe;return E&&(T=T.negate()),L&&(k=k.negate()),k=new d(t.mul(k.px,w.beta),k.py,k.pz),T.add(k)}multiply(h){let{endo:w,n:x}=e;Ke("scalar",h,xe,x);let y,E;if(w){let{k1neg:_,k1:L,k2neg:I,k2:T}=w.splitScalar(h),{p:k,f:re}=this.wNAF(L),{p:W,f:V}=this.wNAF(T);k=p.constTimeNegate(_,k),W=p.constTimeNegate(I,W),W=new d(t.mul(W.px,w.beta),W.py,W.pz),y=k.add(W),E=re.add(V)}else{let{p:_,f:L}=this.wNAF(h);y=_,E=L}return d.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,w,x){let y=d.BASE,E=(L,I)=>I===Rt||I===xe||!L.equals(y)?L.multiplyUnsafe(I):L.multiply(I),_=E(this,w).add(E(h,x));return _.is0()?void 0:_}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=e;if(h===xe)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=e;return h===xe?this:w?w(d,this):this.multiplyUnsafe(e.h)}toRawBytes(h=!0){return rt("isCompressed",h),this.assertValidity(),s(d,this,h)}toHex(h=!0){return rt("isCompressed",h),_t(this.toRawBytes(h))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let m=e.nBitLength,p=uo(d,e.endo?Math.ceil(m/2):m);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Ty(r){let e=Gn(r);return ut(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Eh(r){let e=Ty(r),{Fp:t,n}=e,s=t.BYTES+1,o=2*t.BYTES+1;function i(S){return Q(S,n)}function a(S){return co(S,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=ky({...e,toBytes(S,P,v){let b=P.toAffine(),A=t.toBytes(b.x),B=It;return rt("isCompressed",v),v?B(Uint8Array.from([P.hasEvenY()?2:3]),A):B(Uint8Array.from([4]),A,t.toBytes(b.y))},fromBytes(S){let P=S.length,v=S[0],b=S.subarray(1);if(P===s&&(v===2||v===3)){let A=Ct(b);if(!qn(A,xe,t.ORDER))throw new Error("Point is not on curve");let B=u(A),R;try{R=t.sqrt(B)}catch(K){let O=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+O)}let M=(R&xe)===xe;return(v&1)===1!==M&&(R=t.neg(R)),{x:A,y:R}}else if(P===o&&v===4){let A=t.fromBytes(b.subarray(0,t.BYTES)),B=t.fromBytes(b.subarray(t.BYTES,2*t.BYTES));return{x:A,y:B}}else{let A=s,B=o;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+B+", got "+P)}}}),d=S=>_t(Wt(S,e.nByteLength));function m(S){let P=n>>xe;return S>P}function p(S){return m(S)?i(-S):S}let g=(S,P,v)=>Ct(S.slice(P,v));class h{constructor(P,v,b){this.r=P,this.s=v,this.recovery=b,this.assertValidity()}static fromCompact(P){let v=e.nByteLength;return P=oe("compactSignature",P,v*2),new h(g(P,0,v),g(P,v,2*v))}static fromDER(P){let{r:v,s:b}=Dt.toSig(oe("DER",P));return new h(v,b)}assertValidity(){Ke("r",this.r,xe,n),Ke("s",this.s,xe,n)}addRecoveryBit(P){return new h(this.r,this.s,P)}recoverPublicKey(P){let{r:v,s:b,recovery:A}=this,B=L(oe("msgHash",P));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?v+e.n:v;if(R>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let M=(A&1)===0?"02":"03",F=c.fromHex(M+d(R)),K=a(R),O=i(-B*K),J=i(b*K),te=c.BASE.multiplyAndAddUnsafe(F,O,J);if(!te)throw new Error("point at infinify");return te.assertValidity(),te}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return fr(this.toDERHex())}toDERHex(){return Dt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return fr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(S){try{return l(S),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let S=Tc(e.n);return Jf(e.randomBytes(S),e.n)},precompute(S=8,P=c.BASE){return P._setWindowSize(S),P.multiply(BigInt(3)),P}};function x(S,P=!0){return c.fromPrivateKey(S).toRawBytes(P)}function y(S){let P=zt(S),v=typeof S=="string",b=(P||v)&&S.length;return P?b===s||b===o:v?b===2*s||b===2*o:S instanceof c}function E(S,P,v=!0){if(y(S))throw new Error("first arg must be private key");if(!y(P))throw new Error("second arg must be public key");return c.fromHex(P).multiply(l(S)).toRawBytes(v)}let _=e.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");let P=Ct(S),v=S.length*8-e.nBitLength;return v>0?P>>BigInt(v):P},L=e.bits2int_modN||function(S){return i(_(S))},I=zn(e.nBitLength);function T(S){return Ke("num < 2^"+e.nBitLength,S,Rt,I),Wt(S,e.nByteLength)}function k(S,P,v=re){if(["recovered","canonical"].some(be=>be in v))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:A}=e,{lowS:B,prehash:R,extraEntropy:M}=v;B==null&&(B=!0),S=oe("msgHash",S),xh(v),R&&(S=oe("prehashed msgHash",b(S)));let F=L(S),K=l(P),O=[T(K),T(F)];if(M!=null&&M!==!1){let be=M===!0?A(t.BYTES):M;O.push(oe("extraEntropy",be))}let J=It(...O),te=F;function we(be){let ve=_(be);if(!f(ve))return;let _e=a(ve),He=c.BASE.multiply(ve).toAffine(),Ne=i(He.x);if(Ne===Rt)return;let lt=i(_e*i(te+Ne*K));if(lt===Rt)return;let yt=(He.x===Ne?0:2)|Number(He.y&xe),Rn=lt;return B&&m(lt)&&(Rn=p(lt),yt^=1),new h(Ne,Rn,yt)}return{seed:J,k2sig:we}}let re={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function V(S,P,v=re){let{seed:b,k2sig:A}=k(S,P,v),B=e;return Cc(B.hash.outputLen,B.nByteLength,B.hmac)(b,A)}c.BASE._setWindowSize(8);function he(S,P,v,b=W){let A=S;P=oe("msgHash",P),v=oe("publicKey",v);let{lowS:B,prehash:R,format:M}=b;if(xh(b),"strict"in b)throw new Error("options.strict was renamed to lowS");if(M!==void 0&&M!=="compact"&&M!=="der")throw new Error("format must be compact or der");let F=typeof A=="string"||zt(A),K=!F&&!M&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!F&&!K)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let O,J;try{if(K&&(O=new h(A.r,A.s)),F){try{M!=="compact"&&(O=h.fromDER(A))}catch(yt){if(!(yt instanceof Dt.Err))throw yt}!O&&M!=="der"&&(O=h.fromCompact(A))}J=c.fromHex(v)}catch{return!1}if(!O||B&&O.hasHighS())return!1;R&&(P=e.hash(P));let{r:te,s:we}=O,be=L(P),ve=a(we),_e=i(be*ve),He=i(te*ve),Ne=c.BASE.multiplyAndAddUnsafe(J,_e,He)?.toAffine();return Ne?i(Ne.x)===te:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:E,sign:V,verify:he,ProjectivePoint:c,Signature:h,utils:w}}function Ly(r){return{hash:r,hmac:(e,...t)=>Bl(r,e,bc(...t)),randomBytes:Qr}}function Ah(r,e){let t=n=>Eh({...r,...Ly(n)});return{...t(e),create:t}}var Ch=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Sh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Py=BigInt(1),Tl=BigInt(2),_h=(r,e)=>(r+e/Tl)/e;function Ny(r){let e=Ch,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=se(u,t,e)*u%e,d=se(f,t,e)*u%e,m=se(d,Tl,e)*l%e,p=se(m,s,e)*m%e,g=se(p,o,e)*p%e,h=se(g,a,e)*g%e,w=se(h,c,e)*h%e,x=se(w,a,e)*g%e,y=se(x,t,e)*u%e,E=se(y,i,e)*p%e,_=se(E,n,e)*l%e,L=se(_,Tl,e);if(!Ll.eql(Ll.sqr(L),r))throw new Error("Cannot find square root");return L}var Ll=jt(Ch,void 0,void 0,{sqrt:Ny}),Xe=Ah({a:BigInt(0),b:BigInt(7),Fp:Ll,n:Sh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Sh,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Py*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,i=BigInt("0x100000000000000000000000000000000"),a=_h(o*r,e),c=_h(-n*r,e),l=Q(r-a*t-c*s,e),u=Q(-a*n-c*o,e),f=l>i,d=u>i;if(f&&(l=e-l),d&&(u=e-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},sn),f2=BigInt(0);var d2=Xe.ProjectivePoint;function Fe(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=Ce(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}function Pl(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Ih(r,e){let t=rn.digest(e instanceof Uint8Array?e:e.subarray());if(Pl(t))return t.then(({digest:n})=>Xe.sign(n,r).toDERRawBytes()).catch(n=>{throw new as(String(n))});try{return Xe.sign(t.digest,r).toDERRawBytes()}catch(n){throw new as(String(n))}}function Bh(r,e,t){let n=rn.digest(t instanceof Uint8Array?t:t.subarray());if(Pl(n))return n.then(({digest:s})=>Xe.verify(e,s,r)).catch(s=>{throw new cs(String(s))});try{return Xe.verify(e,n.digest,r)}catch(s){throw new cs(String(s))}}var fs=class{type="secp256k1";raw;_key;constructor(e){this._key=Lh(e),this.raw=kh(this._key)}toMultihash(){return At.digest(ft(this))}toCID(){return pe.createV1(114,this.toMultihash())}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t){return Bh(this._key,t,e)}},pi=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Th(e),this.publicKey=new fs(t??Ph(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e){return Ih(this.raw,e)}};function Nl(r){return new fs(r)}async function Nh(){let r=Dy();return new pi(r)}function kh(r){return Xe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Th(r){try{return Xe.getPublicKey(r,!0),r}catch(e){throw new Mn(String(e))}}function Lh(r){try{return Xe.ProjectivePoint.fromHex(r),r}catch(e){throw new Hr(String(e))}}function Ph(r){try{return Xe.getPublicKey(r,!0)}catch(e){throw new Mn(String(e))}}function Dy(){return Xe.utils.randomPrivateKey()}async function Dh(r,e){if(r==="Ed25519")return ld();if(r==="secp256k1")return Nh();if(r==="RSA")return Il(e??2048);throw new Ht}function hn(r){let{Type:e,Data:t}=dt.decode(r),n=t??new Uint8Array;switch(e){case ge.RSA:return Cl(n);case ge.Ed25519:return Oc(n);case ge.secp256k1:return Nl(n);default:throw new Ht}}function Rh(r){let{Type:e,Data:t}=dt.decode(r.digest),n=t??new Uint8Array;switch(e){case ge.Ed25519:return Oc(n);case ge.secp256k1:return Nl(n);default:throw new Ht}}function ft(r){return dt.encode({Type:ge[r.type],Data:r.raw})}var Mh=Symbol.for("nodejs.util.inspect.custom"),Ry=114,ds=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[qs]=!0;toString(){return this.string==null&&(this.string=X.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pe.createV1(Ry,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ce(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ce(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Mh](){return`PeerId(${this.toString()})`}},hs=class extends ds{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ps=class extends ds{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ms=class extends ds{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},My=2336,gs=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=At.digest(N(this.url))}[Mh](){return`PeerId(${this.url})`}[qs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pe.createV1(My,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};var Oy=114,Oh=2336;function gt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=et(X.decode(`z${r}`));else{if(e==null)throw new D('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=et(e.decode(r))}return pn(t)}function Dl(r){if(r.type==="Ed25519")return new ps({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new ms({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new hs({multihash:r.toCID().multihash,publicKey:r});throw new Ht}function Uh(r){return Dl(r.publicKey)}function pn(r){if(Fy(r))return new hs({multihash:r});if(Uy(r))try{let e=Rh(r);if(e.type==="Ed25519")return new ps({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ms({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new gs(new URL(t))}throw new Zs("Supplied PeerID Multihash is invalid")}function mi(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Oy&&r.code!==Oh)throw new js("Supplied PeerID CID is invalid");if(r.code===Oh){let e=z(r.multihash.digest);return new gs(new URL(e))}return pn(r.multihash)}function Uy(r){return r.code===At.code}function Fy(r){return r.code===rn.code}var fe=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Ml=Vr(Vh(),1);var ws=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Ol=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Hh=r=>globalThis.DOMException===void 0?new Ol(r):new DOMException(r),Kh=r=>{let e=r.reason===void 0?Hh("This operation was aborted."):r.reason;return e instanceof Error?e:Hh(e)};function bs(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:m}=e;m.aborted&&f(Kh(m)),a=()=>{f(Kh(m))},m.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new ws;i=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?u():s instanceof Error?f(s):(d.message=s??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(m){f(m)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},l}function Ul(r,e,t){let n=0,s=r.length;for(;s>0;){let o=Math.trunc(s/2),i=n+o;t(r[i],e)<=0?(n=++i,s-=o+1):s=o}return n}var xs=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let s=Ul(this.#e,n,(o,i)=>i.priority-o.priority);this.#e.splice(s,0,n)}setPriority(e,t){let n=this.#e.findIndex(o=>o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[s]=this.#e.splice(n,1);this.enqueue(s.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var tr=class extends Ml.default{#e;#t;#o=0;#a;#c;#p=0;#n;#l;#r;#m;#s=0;#u;#i;#g;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:xs,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#c=e.interval,this.#r=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#i=e.autoStart===!1}get#x(){return this.#t||this.#o<this.#a}get#v(){return this.#s<this.#u}#E(){this.#s--,this.#f(),this.emit("next")}#A(){this.#w(),this.#y(),this.#l=void 0}get#S(){let e=Date.now();if(this.#n===void 0){let t=this.#p-e;if(t<0)this.#o=this.#e?this.#s:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#A()},t)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#i){let e=!this.#S;if(this.#x&&this.#v){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#n!==void 0||(this.#n=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#o===0&&this.#s===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#o=this.#e?this.#s:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#d()}async#_(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#r.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#b++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,s)=>{this.#r.enqueue(async()=>{this.#s++,this.#o++;try{t.signal?.throwIfAborted();let o=e({signal:t.signal});t.timeout&&(o=bs(Promise.resolve(o),{milliseconds:t.timeout})),t.signal&&(o=Promise.race([o,this.#_(t.signal)]));let i=await o;n(i),this.emit("completed",i)}catch(o){if(o instanceof ws&&!t.throwOnTimeout){n();return}s(o),this.emit("error",o)}finally{this.#E()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#i?(this.#i=!1,this.#d(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#h("next",()=>this.#r.size<e)}async onIdle(){this.#s===0&&this.#r.size===0||await this.#h("idle")}async#h(e,t){return new Promise(n=>{let s=()=>{t&&!t()||(this.off(e,s),n())};this.on(e,s)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#i}};function yi(r){let e=[je.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Fl=60;function wi(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:je[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:je[e.type],TTL:e.TTL??e.ttl??Fl,data:e.data instanceof Uint8Array?z(e.data):e.data}))}}var Ky=4;function Vl(r,e={}){let t=new tr({concurrency:e.queryConcurrency??Ky});return async(n,s={})=>{let o=new URLSearchParams;o.set("name",n),yi(s.types).forEach(a=>{o.append("type",je[a])}),s.onProgress?.(new fe("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${o}`,{headers:{accept:"application/dns-json"},signal:s?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=wi(await a.json());return s.onProgress?.(new fe("dns:response",{detail:c})),c},{signal:s.signal});if(i==null)throw new Error("No DNS response received");return i}}function $h(){return[Vl("https://cloudflare-dns.com/dns-query"),Vl("https://dns.google/resolve")]}var Gh=Vr(zh(),1);var Hl=class{lru;constructor(e){this.lru=(0,Gh.default)(e)}get(e,t){let n=!0,s=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){n=!1;break}s.push(...i)}if(n)return wi({answers:s})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,s=this.lru.get(n);if(s!=null){let o=s.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:je[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,s=this.lru.get(n)??[];s.push({expires:Date.now()+(t.TTL??Fl)*1e3,value:t}),this.lru.set(n,s)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Wh(r){return new Hl(r)}var $y=1e3,bi=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Wh(e.cacheSize??$y),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=$h())}async query(e,t={}){let n=yi(t.types),s=t.cached!==!1?this.cache.get(e,n):void 0;if(s!=null)return t.onProgress?.(new fe("dns:cache",{detail:s})),s;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new fe("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var je;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(je||(je={}));function jh(r={}){return new bi(r)}var xi=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Zh=45,qy=15,mn=new xi;function vi(r){if(!(r.length>qy))return mn.new(r).parseWith(()=>mn.readIPv4Addr())}function Ei(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Zh))return mn.new(r).parseWith(()=>mn.readIPv6Addr())}function xr(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Zh)return;let t=mn.new(r).parseWith(()=>mn.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function Xh(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function Yh(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function Kl(r){switch(r.length){case vr:return r.join(".");case Er:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Jh(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function Qh(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var vr=4,Er=16,JA=parseInt("0xFFFF",16),zy=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function vs(r,e){e.length===Er&&r.length===vr&&Xh(e,0,11)&&(e=e.slice(12)),e.length===vr&&r.length===Er&&Yh(r,zy,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function ep(r,e){if(typeof e=="string"&&(e=xr(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function $l(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=vr,s=vi(e);if(s==null&&(n=Er,s=Ei(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=ql(o,8*n);return{network:vs(s,i),mask:i}}function ql(r,e){if(e!==8*vr&&e!==8*Er)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var gn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=$l(e));else{let n=xr(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=xr(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=ql(s,8*n.length);this.network=vs(n,this.mask)}}contains(e){return ep({network:this.network,mask:this.mask},e)}toString(){let e=Jh(this.mask),t=e!==-1?String(e):Qh(this.mask);return Kl(this.network)+"/"+t}};function at(r){return!!vi(r)}function yn(r){return!!Ei(r)}function Ai(r){return!!xr(r)}var tp=at,Gy=yn,zl=function(r){let e=0;if(r=r.toString().trim(),tp(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Gy(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=tp(t[n]),i;o&&(i=zl(t[n]),t[n]=z(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){let o=parseInt(t[n],16);s[e++]=o>>8&255,s[e++]=o&255}return s}throw new Error("invalid ip address")},rp=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let s=[];for(let o=0;o<t;o++)s.push(r[e+o]);return s.join(".")}if(t===16){let s=[];for(let o=0;o<t;o+=2)s.push(n.getUint16(e+o).toString(16));return s.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var wn={},Gl={},jy=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];jy.forEach(r=>{let e=Zy(...r);Gl[e.code]=e,wn[e.name]=e});function Zy(r,e,t,n,s){return{code:r,size:e,name:t,resolvable:!!n,path:!!s}}function G(r){if(typeof r=="number"){if(Gl[r]!=null)return Gl[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(wn[r]!=null)return wn[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Xy=G("ip4"),Yy=G("ip6"),Jy=G("ipcidr");function Xl(r,e){switch(G(r).code){case 4:case 41:return ew(e);case 42:return Zl(e);case 43:return z(e,"base10");case 6:case 273:case 33:case 132:return op(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Zl(e);case 421:return sw(e);case 444:return sp(e);case 445:return sp(e);case 466:return nw(e);case 481:return globalThis.encodeURIComponent(Zl(e));default:return z(e,"base16")}}function Yl(r,e){switch(G(r).code){case 4:return np(e);case 41:return np(e);case 42:return jl(e);case 43:return N(e,"base10");case 6:case 273:case 33:case 132:return Ql(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return jl(e);case 421:return tw(e);case 444:return ow(e);case 445:return iw(e);case 466:return rw(e);case 481:return jl(globalThis.decodeURIComponent(e));default:return N(e,"base16")}}function Jl(r){let e,t;if(r.stringTuples().forEach(([n,s])=>{(n===Xy.code||n===Yy.code)&&(t=s),n===Jy.code&&(e=s)}),e==null||t==null)throw new Error("Invalid multiaddr");return new gn(t,e)}var Wl=Object.values(Zn).map(r=>r.decoder),Qy=function(){let r=Wl[0].or(Wl[1]);return Wl.slice(2).forEach(e=>r=r.or(e)),r}();function np(r){if(!Ai(r))throw new Error("invalid ip address");return zl(r)}function ew(r){let e=rp(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Ai(e))throw new Error("invalid ip address");return e}function Ql(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function op(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function jl(r){let e=N(r),t=Uint8Array.from(Be(e.length));return Fe([t,e],t.length+e.length)}function Zl(r){let e=st(r);if(r=r.slice(de(e)),r.length!==e)throw new Error("inconsistent lengths");return z(r)}function tw(r){let e;r[0]==="Q"||r[0]==="1"?e=et(X.decode(`z${r}`)).bytes:e=pe.parse(r).multihash.bytes;let t=Uint8Array.from(Be(e.length));return Fe([t,e],t.length+e.length)}function rw(r){let e=Qy.decode(r),t=Uint8Array.from(Be(e.length));return Fe([t,e],t.length+e.length)}function nw(r){let e=st(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+z(t,"base64url")}function sw(r){let e=st(r),t=r.slice(de(e));if(t.length!==e)throw new Error("inconsistent lengths");return z(t,"base58btc")}function ow(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Ge.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Ql(n);return Fe([t,s],t.length+s.length)}function iw(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Ge.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=Ql(n);return Fe([t,s],t.length+s.length)}function sp(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=z(e,"base32"),s=op(t);return`${n}:${s}`}function ip(r){r=eu(r);let e=[],t=[],n=null,s=r.split("/").slice(1);if(s.length===1&&s[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<s.length;o++){let i=s[o],a=G(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(o++,o>=s.length)throw new Si("invalid address: "+r);if(a.path===!0){n=eu(s.slice(o).join("/")),e.push([a.code,Yl(a.code,n)]),t.push([a.code,n]);break}let c=Yl(a.code,s[o]);e.push([a.code,c]),t.push([a.code,Xl(a.code,c)])}return{string:ap(t),bytes:_i(e),tuples:e,stringTuples:t,path:n}}function tu(r){let e=[],t=[],n=null,s=0;for(;s<r.length;){let o=st(r,s),i=de(o),a=G(o),c=aw(a,r.slice(s+i));if(c===0){e.push([o]),t.push([o]),s+=i;continue}let l=r.slice(s+i,s+i+c);if(s+=c+i,s>r.length)throw new Si("Invalid address Uint8Array: "+z(r,"base16"));e.push([o,l]);let u=Xl(o,l);if(t.push([o,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:ap(t),tuples:e,stringTuples:t,path:n}}function ap(r){let e=[];return r.map(t=>{let n=G(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),eu(e.join("/"))}function _i(r){return Fe(r.map(e=>{let t=G(e[0]),n=Uint8Array.from(Be(t.code));return e.length>1&&e[1]!=null&&(n=Fe([n,e[1]])),n}))}function aw(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=st(e instanceof Uint8Array?e:Uint8Array.from(e));return t+de(t)}}function eu(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}var Si=class extends Error{static name="ParseError";name="ParseError";constructor(e){super(`Error parsing address: ${e}`)}};var cw=Symbol.for("nodejs.util.inspect.custom"),nu=Symbol.for("@multiformats/js-multiaddr/multiaddr"),lw=[G("dns").code,G("dns4").code,G("dns6").code,G("dnsaddr").code],ru=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},Ci=class r{bytes;#e;#t;#o;#a;[nu]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=tu(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=ip(e)}else if(rr(e))t=tu(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#o=t.stringTuples,this.#a=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,s,o="",i=G("tcp"),a=G("udp"),c=G("ip4"),l=G("ip6"),u=G("dns6"),f=G("ip6zone");for(let[m,p]of this.stringTuples())m===f.code&&(o=`%${p??""}`),lw.includes(m)&&(t=i.name==="tcp"?"tcp":"udp",s=443,n=`${p??""}${o}`,e=m===u.code?6:4),(m===i.code||m===a.code)&&(t=G(m).name==="tcp"?"tcp":"udp",s=parseInt(p??"")),(m===c.code||m===l.code)&&(t=G(m).name==="tcp"?"tcp":"udp",n=`${p??""}${o}`,e=m===l.code?6:4);if(e==null||t==null||n==null||s==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:s}}protos(){return this.#t.map(([e])=>Object.assign({},G(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>G(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#o.map(([e,t])=>t==null?[e]:[e,t])}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,s))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(_i(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,s])=>{n===wn.p2p.code&&e.push([n,s]),n===wn["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?z(X.decode(`z${n}`),"base58btc"):z(pe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(e){return ce(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=bn.get(t.name);if(n==null)throw new ru(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>j(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[cw](){return`Multiaddr(${this.#e})`}};var bn=new Map;function rr(r){return!!r?.[nu]}function j(r){return new Ci(r)}var uw=32,{code:fw}=G("dnsaddr"),su=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},Ar=async function(e,t={}){let n=t.maxRecursiveDepth??uw;if(n===0)throw new su("Max recursive depth reached");let[,s]=e.stringTuples().find(([l])=>l===fw)??[],i=await(t?.dns??jh()).query(`_dnsaddr.${s}`,{signal:t?.signal,types:[je.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let u=l.data.replace(/["']/g,"").trim().split("=")[1];if(u==null||a!=null&&!u.includes(a))continue;let f=j(u);if(u.startsWith("/dnsaddr")){let d=await f.resolve({...t,maxRecursiveDepth:n-1});c.push(...d.map(m=>m.toString()))}else c.push(f.toString())}return c};var gp=Vr(mp(),1),ki=gp.default;var yw={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ar}},transportManager:{faultTolerance:cr.FATAL_ALL}};async function yp(r){let e=ki(yw,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new D("Private network is enforced, but no protector was provided");return e}function ww(r,e){try{if(typeof r=="string"&&r.length>0)return bw(r);if(typeof r=="number"&&isFinite(r))return e?.long?vw(r):xw(r);throw new Error("Value is not a string or number.")}catch(t){let n=Ew(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function bw(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\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(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Li=ww;function xw(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function vw(r){let e=Math.abs(r);return e>=864e5?Ti(r,e,864e5,"day"):e>=36e5?Ti(r,e,36e5,"hour"):e>=6e4?Ti(r,e,6e4,"minute"):e>=1e3?Ti(r,e,1e3,"second"):`${r} ms`}function Ti(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}function Ew(r){return typeof r=="object"&&r!==null&&"message"in r}function iu(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=Li,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,m,p;function g(...h){if(!g.enabled)return;let w=g,x=Number(new Date),y=x-(f||x);w.diff=y,w.prev=f,w.curr=x,f=x,h[0]=t.coerce(h[0]),typeof h[0]!="string"&&h.unshift("%O");let E=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(L,I)=>{if(L==="%%")return"%";E++;let T=t.formatters[I];if(typeof T=="function"){let k=h[E];L=T.call(w,k),h.splice(E,1),E--}return L}),t.formatArgs.call(w,h),(w.log||t.log).apply(w,h)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(m!==t.namespaces&&(m=t.namespaces,p=t.enabled(u)),p),set:h=>{d=h}}),typeof t.init=="function"&&t.init(g),g}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),m=d.length;for(f=0;f<m;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Pi=kw(),Aw=["#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 Sw(){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 _w(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Li(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}var Cw=console.debug??console.log??(()=>{});function Iw(r){try{r?Pi?.setItem("debug",r):Pi?.removeItem("debug")}catch{}}function Bw(){let r;try{r=Pi?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function kw(){try{return localStorage}catch{}}function Tw(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var wp=iu({formatArgs:_w,save:Iw,load:Bw,useColors:Sw,setupFormatters:Tw,colors:Aw,storage:Pi,log:Cw});var ze=wp;ze.formatters.b=r=>r==null?"undefined":X.baseEncode(r);ze.formatters.t=r=>r==null?"undefined":Ge.baseEncode(r);ze.formatters.m=r=>r==null?"undefined":Qc.baseEncode(r);ze.formatters.p=r=>r==null?"undefined":r.toString();ze.formatters.c=r=>r==null?"undefined":r.toString();ze.formatters.k=r=>r==null?"undefined":r.toString();ze.formatters.a=r=>r==null?"undefined":r.toString();ze.formatters.e=r=>r==null?"undefined":bp(r.stack)??bp(r.message)??r.toString();function Lw(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ni(){return{forComponent(r){return Pw(r)}}}function Pw(r){let e=Lw(`${r}:trace`);return ze.enabled(`${r}:trace`)&&ze.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=ze(`${r}:trace`)),Object.assign(ze(r),{error:ze(`${r}:error`),trace:e})}function bp(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function Sr(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function Di(r){let e=et(X.decode(`z${r}`));return pn(e)}var Mt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Sr(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Sr(this.map.values(),e=>e.key)}values(){return Sr(this.map.values(),e=>e.value)}get size(){return this.map.size}};var _r=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Sr(this.set.entries(),e=>{let t=Di(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Di(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Sr(this.set.values(),e=>Di(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var vp=Symbol.for("@achingbrain/uint8arraylist");function xp(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Ri(r){return!!r?.[vp]}var ye=class r{bufs;length;[vp]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Ri(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ri(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=xp(this.bufs,e);return t.buf[t.index]}set(e,t){let n=xp(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Ri(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Fe(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Fe(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ri(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let f=0;f<o;f++)i[f]=-1;for(let f=0;f<s;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=le(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=le(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=le(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ce(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=le(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=le(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=le(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=le(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=le(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ce(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var au={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Ep={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Ap=new globalThis.TextEncoder;function Nw(r,e){let t=au[e],n=Ep[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function Dw(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=au[e],s=Ep[e],o=r;for(;o.length>0;){let i=Ap.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function cu(r,{size:e=32,utf8Buffer:t}={}){if(!au[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Dw(r,e,t);r=Ap.encode(r)}return Nw(r,e)}var Es={hash:r=>Number(cu(r,{size:32})),hashV:(r,e)=>Rw(Es.hash(r,e))};function Rw(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),N(e,"base16")}var lu=64,ct=class{fp;h;seed;constructor(e,t,n,s=2){if(s>lu)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=le(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ce(this.fp,e.fp):!1}};function Cr(r,e){return Math.floor(Math.random()*(e-r))+r}var Ir=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");let t=Cr(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ct))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Mw=500,As=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??Es,this.seed=e.seed??Cr(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=N(e));let t=new ct(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Ir(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new Ir(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[Cr(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize));for(let a=0;a<Mw;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Ir(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=N(e));let t=new ct(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=N(e));let t=new ct(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Ow={1:.5,2:.84,4:.95,8:.98};function Uw(r=.001){return r>.002?2:r>1e-5?4:8}function Sp(r,e=.001){let t=Uw(e),n=Ow[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),lu);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Mi=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Es,this.seed=e.seed??Cr(0,Math.pow(2,10)),this.filterSeries=[new As({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=N(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new As({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=N(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=N(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Ss(r,e=.001,t){return new Mi({...Sp(r,e),...t??{}})}var _s;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={publicKey:le(0),payloadType:le(0),payload:le(0),signature:le(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(_s||(_s={}));var Oi=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var En=class r{static createFromProtobuf=async e=>{let t=_s.decode(e),n=hn(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(t==null)throw new Error("Missing private key");let n=e.domain,s=e.codec,o=e.marshal(),i=_p(n,s,o),a=await t.sign(i.subarray());return new r({publicKey:t.publicKey,payloadType:s,payload:o,signature:a})};static openAndCertify=async(e,t)=>{let n=await r.createFromProtobuf(e);if(!await n.validate(t))throw new Oi("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:s,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=s,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=_s.encode({publicKey:ft(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return ce(this.marshal(),e.marshal())}async validate(e){let t=_p(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}},_p=(r,e,t)=>{let n=N(r),s=Be(n.byteLength),o=Be(e.length),i=Be(t.length);return new ye(s,n,o,e,i,t)};function Cp(r,e){let t=(n,s)=>n.toString().localeCompare(s.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,s)=>e[s].equals(n)))}var Ip="libp2p-peer-record",Bp=Uint8Array.from([3,1]);var Cs;(function(r){let e;(function(n){let s;n.codec=()=>(s==null&&(s=Oe((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:le(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),s),n.encode=o=>Me(o,n.codec()),n.decode=(o,i)=>Re(o,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Oe((n,s,o={})=>{if(o.lengthDelimited!==!1&&s.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(s.uint32(10),s.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(s.uint32(16),s.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)s.uint32(26),r.AddressInfo.codec().encode(i,s);o.lengthDelimited!==!1&&s.ldelim()},(n,s,o={})=>{let i={peerId:le(0),seq:0n,addresses:[]},a=s==null?n.len:n.pos+s;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(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new wr('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Me(n,r.codec()),r.decode=(n,s)=>Re(n,r.codec(),s)})(Cs||(Cs={}));var Br=class r{static createFromProtobuf=e=>{let t=Cs.decode(e),n=pn(et(t.peerId)),s=(t.addresses??[]).map(i=>j(i.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:s,seqNumber:o})};static DOMAIN=Ip;static CODEC=Bp;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:s}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=s??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Cs.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Cp(this.multiaddrs,e.multiaddrs))}};function Fw(r){return r[Symbol.asyncIterator]!=null}function Vw(r){if(Fw(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Is=Vw;var nr={},An=r=>{r.addEventListener("message",e=>{An.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{An.dispatchEvent("message",r,e)})};An.addEventListener=(r,e)=>{nr[r]==null&&(nr[r]=[]),nr[r].push(e)};An.removeEventListener=(r,e)=>{nr[r]!=null&&(nr[r]=nr[r].filter(t=>t===e))};An.dispatchEvent=function(r,e,t){nr[r]!=null&&nr[r].forEach(n=>n(e,t))};var uu=An;var fu="lock:worker:request-read",du="lock:worker:release-read",hu="lock:master:grant-read",pu="lock:worker:request-write",mu="lock:worker:release-write",gu="lock:master:grant-write";var kp=(r=21)=>Math.random().toString().substring(2);var Tp=(r,e,t,n,s)=>(o,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{o.postMessage({type:s,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u?.data==null)return;let f={type:u.data.type,name:u.data.name,identifier:u.data.identifier};f.type===n&&f.identifier===a.identifier&&(o.removeEventListener("message",l),c())};o.addEventListener("message",l)})}}}))},Lp=(r,e,t,n)=>async()=>{let s=kp();return globalThis.postMessage({type:e,identifier:s,name:r}),new Promise(o=>{let i=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===s&&(globalThis.removeEventListener("message",i),o(()=>{globalThis.postMessage({type:n,identifier:s,name:r})}))};globalThis.addEventListener("message",i)})},Hw={singleProcess:!1},Pp=r=>{if(r=Object.assign({},Hw,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return uu.addEventListener("message",Tp(t,"requestReadLock",fu,du,hu)),uu.addEventListener("message",Tp(t,"requestWriteLock",pu,mu,gu)),t}return{isWorker:!0,readLock:t=>Lp(t,fu,hu,du),writeLock:t=>Lp(t,pu,gu,mu)}};var kr={},sr;async function yu(r,e){let t,n=new Promise(s=>{t=s});return r.add(async()=>bs((async()=>{await new Promise(s=>{t(()=>{s()})})})(),{milliseconds:e.timeout})),n}var Kw=(r,e)=>{if(sr.isWorker===!0)return{readLock:sr.readLock(r,e),writeLock:sr.writeLock(r,e)};let t=new tr({concurrency:1}),n;return{async readLock(){if(n!=null)return yu(n,e);n=new tr({concurrency:e.concurrency,autoStart:!1});let s=n,o=yu(n,e);return t.add(async()=>{s.start(),await s.onIdle().then(()=>{n===s&&(n=null)})}),o},async writeLock(){return n=null,yu(t,e)}}},$w={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function wu(r){let e=Object.assign({},$w,r);return sr==null&&(sr=Pp(e),sr.isWorker!==!0&&(sr.addEventListener("requestReadLock",t=>{kr[t.data.name]!=null&&kr[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),sr.addEventListener("requestWriteLock",async t=>{kr[t.data.name]!=null&&kr[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),kr[e.name]==null&&(kr[e.name]=Kw(e.name,e)),kr[e.name]}var Sn;(function(r){let e;(function(s){let o;s.codec=()=>(o==null&&(o=Oe((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:le(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})),o),s.encode=i=>Me(i,s.codec()),s.decode=(i,a)=>Re(i,s.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(s){let o;s.codec=()=>(o==null&&(o=Oe((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),Fi.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=Fi.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),o),s.encode=i=>Me(i,s.codec()),s.decode=(i,a)=>Re(i,s.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Oe((s,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),s.addresses!=null)for(let a of s.addresses)o.uint32(10),Ui.codec().encode(a,o);if(s.protocols!=null)for(let a of s.protocols)o.uint32(18),o.string(a);if(s.publicKey!=null&&(o.uint32(34),o.bytes(s.publicKey)),s.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(s.peerRecordEnvelope)),s.metadata!=null&&s.metadata.size!==0)for(let[a,c]of s.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(s.tags!=null&&s.tags.size!==0)for(let[a,c]of s.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);i.lengthDelimited!==!1&&o.ldelim()},(s,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?s.len:s.pos+o;for(;s.pos<c;){let l=s.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new wr('Decode error - map field "addresses" had too many elements');a.addresses.push(Ui.codec().decode(s,s.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new wr('Decode error - map field "protocols" had too many elements');a.protocols.push(s.string());break}case 4:{a.publicKey=s.bytes();break}case 5:{a.peerRecordEnvelope=s.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new Jn('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(s,s.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Jn('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(s,s.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}default:{s.skipType(l&7);break}}}return a})),n),r.encode=s=>Me(s,r.codec()),r.decode=(s,o)=>Re(s,r.codec(),o)})(Sn||(Sn={}));var Ui;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={multiaddr:le(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Ui||(Ui={}));var Fi;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,s={})=>{s.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),s.lengthDelimited!==!1&&n.ldelim()},(t,n,s={})=>{let o={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>Me(t,r.codec()),r.decode=(t,n)=>Re(t,r.codec(),n)})(Fi||(Fi={}));function _n(r,e){let t=Sn.decode(e);if(t.publicKey!=null&&r.publicKey==null){let o=hn(t.publicKey);r=Dl(o)}let n=new Map,s=BigInt(Date.now());for(let[o,i]of t.tags.entries())i.expiry!=null&&i.expiry<s||n.set(o,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:o,isCertified:i})=>({multiaddr:j(o),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Ot="/",Np=new TextEncoder().encode(Ot),Vi=Np[0],Tr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=N(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Vi)throw new Error("Invalid key")}toString(e="utf8"){return z(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ot))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Np),this._buf[0]!==Vi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Vi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Vi;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let s=0;s<t.length;s++){if(n.length<s+1)return!1;let o=t[s],i=n[s];if(o<i)return!0;if(o>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ot).slice(1)}type(){return qw(this.baseNamespace())}name(){return zw(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ot)||(e+=Ot),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ot):new r(e.slice(0,-1).join(Ot))}child(e){return this.toString()===Ot?e:e.toString()===Ot?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Gw(e.map(t=>t.namespaces()))])}};function qw(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function zw(r){let e=r.split(":");return e[e.length-1]}function Gw(r){return[].concat(...r)}var bu="/peers/";function Cn(r){if(!zs(r)||r.type==null)throw new D("Invalid PeerId");let e=r.toCID().toString();return new Tr(`${bu}${e}`)}async function Dp(r,e,t){let n=new Map;for(let s of t){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=j(s.multiaddr)),!rr(s.multiaddr))throw new D("Multiaddr was invalid");if(!await e(r,s.multiaddr))continue;let o=s.isCertified??!1,i=s.multiaddr.toString(),a=n.get(i);a!=null?s.isCertified=a.isCertified||o:n.set(i,{multiaddr:s.multiaddr,isCertified:o})}return[...n.values()].sort((s,o)=>s.multiaddr.toString().localeCompare(o.multiaddr.toString())).map(({isCertified:s,multiaddr:o})=>({isCertified:s,multiaddr:o.bytes}))}async function Ki(r,e,t,n){if(e==null)throw new D("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new D("publicKey bytes do not match peer id publicKey bytes");let s=n.existingPeer;if(s!=null&&!r.equals(s.id))throw new D("peer id did not match existing peer id");let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Hi(d,{validate:Rp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Hi(d,{validate:Mp,map:Op})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[m,p]of d)p==null?a.delete(m):a.set(m,p);a=Hi([...a.entries()],{validate:Rp})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),m=new Map(c);for(let[p,g]of d)g==null?m.delete(p):m.set(p,g);c=Hi([...m.entries()],{validate:Mp,map:Op})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;s?.id.publicKey!=null?u=ft(s.id.publicKey):e.publicKey!=null?u=ft(e.publicKey):r.publicKey!=null&&(u=ft(r.publicKey));let f={addresses:await Dp(r,n.addressFilter??(async()=>!0),o),protocols:[...i.values()].sort((d,m)=>d.localeCompare(m)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return r.type!=="RSA"&&delete f.publicKey,f}function Hi(r,e){let t=new Map;for(let[n,s]of r)s!=null&&e.validate(n,s);for(let[n,s]of r.sort(([o],[i])=>o.localeCompare(i)))s!=null&&t.set(n,e.map?.(n,s)??s);return t}function Rp(r,e){if(typeof r!="string")throw new D("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new D("Metadata value must be a Uint8Array")}function Mp(r,e){if(typeof r!="string")throw new D("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new D("Tag value must be an integer");if(e.value<0||e.value>100)throw new D("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new D("Tag ttl must be an integer");if(e.ttl<0)throw new D("Tag ttl must be between greater than 0")}}function Op(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function $i(r,e){let t=r.toString().split("/")[2],n=pe.parse(t,Ge),s=mi(n);return _n(s,e)}function Ww(r){return r==null?{}:{prefix:bu,filters:(r.filters??[]).map(e=>({key:t,value:n})=>e($i(t,n))),orders:(r.orders??[]).map(e=>(t,n)=>e($i(t.key,t.value),$i(n.key,n.value)))}}var qi=class{peerId;datastore;lock;addressFilter;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=wu({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Cn(e))}async delete(e){if(this.peerId.equals(e))throw new D("Cannot delete self peer");await this.datastore.delete(Cn(e))}async load(e){let t=await this.datastore.get(Cn(e));return _n(e,t)}async save(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await Ki(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,o,n,s)}async patch(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await Ki(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,n,s)}async merge(e,t){let{existingBuf:n,existingPeer:s}=await this.#e(e),o=await Ki(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:s});return this.#t(e,o,n,s)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(Ww(e??{}))){let s=$i(t,n);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(Cn(e)),n=_n(e,t);return{existingBuf:t,existingPeer:n}}catch(t){t.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",t)}return{}}async#t(e,t,n,s){let o=Sn.encode(t);return n!=null&&ce(o,n)?{peer:_n(e,o),previous:s,updated:!1}:(await this.datastore.put(Cn(e),o),{peer:_n(e,o),previous:s,updated:!0})}};var xu=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new qi(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let s of this.store.all(t))e(s)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Is(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let s=await this.store.save(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let s=await this.store.patch(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let s=await this.store.merge(e,t);return this.#e(e,s),s.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await En.openAndCertify(e,Br.DOMAIN),s=mi(n.publicKey.toCID());if(t?.equals(s)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,s),!1;let o=Br.createFromProtobuf(n.payload),i;try{i=await this.get(s)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await En.createFromProtobuf(i.peerRecordEnvelope),c=Br.createFromProtobuf(a.payload);if(c.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function Up(r,e={}){return new xu(r,e)}var zi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function jw(r){return r[Symbol.asyncIterator]!=null}function Zw(r){if(jw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var vu=Zw;function Xw(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Fp=Xw;function Yw(r){return r[Symbol.asyncIterator]!=null}function Jw(r,e){let t=0;if(Yw(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Fp(r),{value:s,done:o}=n.next();if(o===!0)return function*(){}();let i=e(s,t++);if(typeof i.then=="function")return async function*(){await i&&(yield s);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)}()}var Lr=Jw;function Qw(r){return r[Symbol.asyncIterator]!=null}function eb(r,e){return Qw(r)?async function*(){yield*(await Is(r)).sort(e)}():function*(){yield*Is(r).sort(e)}()}var Eu=eb;function tb(r){return r[Symbol.asyncIterator]!=null}function rb(r,e){return tb(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var Au=rb;var Gi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:s}of e)await this.put(n,s,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,s){e.push({key:n,value:s})},delete(n){t.push(n)},commit:async n=>{await vu(this.putMany(e,n)),e=[],await vu(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let s=e.prefix;n=Lr(n,o=>o.key.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Lr(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>Eu(s,o),n)),e.offset!=null){let s=0,o=e.offset;n=Lr(n,()=>s++>=o)}return e.limit!=null&&(n=Au(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let s=e.prefix;n=Lr(n,o=>o.toString().startsWith(s))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((s,o)=>Lr(s,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((s,o)=>Eu(s,o),n)),e.offset!=null){let s=e.offset,o=0;n=Lr(n,()=>o++>=s)}return e.limit!=null&&(n=Au(n,e.limit)),n}};var Wi=class extends Gi{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw new zi;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new Tr(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new Tr(e)}};function Vp(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Kp=Vr(Hp(),1),nb=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],sb=nb.map(r=>new Kp.Netmask(r));function Su(r){for(let e of sb)if(e.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 ib(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Su(s)}function ab(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function cb(r){let e=r.split(":"),t=e[e.length-1];return Su(t)}function lb(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function or(r){return at(r)?Su(r):ob(r)?ib(r):ab(r)?cb(r):yn(r)?lb(r):void 0}var ub=r=>r.toString().split("/").slice(1),In=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),$=r=>({match:e=>In(t=>t===r).match(e),pattern:r}),Pr=()=>({match:r=>In(e=>typeof e=="string").match(r),pattern:"{string}"}),ks=()=>({match:r=>In(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),ee=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{X.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ts=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{el.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Z=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Pe=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),q=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function ie(...r){function e(s){let o=ub(s);for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var Zi=q($("dns4"),Pr()),Xi=q($("dns6"),Pr()),Yi=q($("dnsaddr"),Pr()),Cu=q($("dns"),Pr()),lI=ie(Zi,Z(ee())),uI=ie(Xi,Z(ee())),fI=ie(Yi,Z(ee())),dI=ie(Pe(Cu,Yi,Zi,Xi),Z(ee())),$p=q($("ip4"),In(at)),qp=q($("ip6"),In(yn)),Iu=Pe($p,qp),Ut=Pe(Iu,Cu,Zi,Xi,Yi),hI=ie(Pe(Iu,q(Pe(Cu,Yi,Zi,Xi),Z(ee())))),Bu=ie($p),ku=ie(qp),pI=ie(Iu),Tu=q(Ut,$("tcp"),ks()),Ls=q(Ut,$("udp"),ks()),Ps=ie(q(Tu,Z(ee()))),mI=ie(Ls),Lu=q(Ls,$("quic"),Z(ee())),Ji=q(Ls,$("quic-v1"),Z(ee())),fb=Pe(Lu,Ji),gI=ie(Lu),zp=ie(Ji),_u=Pe(Ut,Tu,Ls,Lu,Ji),Gp=Pe(q(_u,$("ws"),Z(ee()))),Nr=ie(Gp),Wp=Pe(q(_u,$("wss"),Z(ee())),q(_u,$("tls"),Z(q($("sni"),Pr())),$("ws"),Z(ee()))),Ns=ie(Wp),jp=q(Ls,$("webrtc-direct"),Z(Ts()),Z(Ts()),Z(ee())),Pu=ie(jp),Zp=q(Ji,$("webtransport"),Z(Ts()),Z(Ts()),Z(ee())),Nu=ie(Zp),ji=Pe(Gp,Wp,q(Tu,Z(ee())),q(fb,Z(ee())),q(Ut,Z(ee())),jp,Zp,ee()),yI=ie(ji),db=q(ji,$("p2p-circuit"),ee()),Ds=ie(db),hb=Pe(q(ji,$("p2p-circuit"),$("webrtc"),Z(ee())),q(ji,$("webrtc"),Z(ee())),q($("webrtc"),Z(ee()))),Du=ie(hb),pb=Pe(q(Ut,$("tcp"),ks(),$("http"),Z(ee())),q(Ut,$("http"),Z(ee()))),wI=ie(pb),mb=Pe(q(Ut,$("tcp"),Pe(q($("443"),$("http")),q(ks(),$("https"))),Z(ee())),q(Ut,$("tls"),$("http"),Z(ee())),q(Ut,$("https"),Z(ee()))),bI=ie(mb),gb=Pe(q($("memory"),Pr(),Z(ee()))),xI=ie(gb);var Xp=864e13;var yb=448,Ru=449,wb=53,bb=54,xb=55,vb=56,Qi=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let s=or(n)===!0;this.mappings.set(n,{domain:e,verified:s,expires:s?Xp-Date.now():0,lastVerified:s?Xp-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[s,o]of this.mappings.entries())o.domain===t&&(this.log("removing %s to %s DNS mapping %e",s,o.domain,new Error("where")),this.mappings.delete(s),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr.stringTuples(),i=o[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(o,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:j(`/${o.map(u=>[G(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===yb&&e[n+1]?.[0]!==Ru)return e.splice(n+1,0,[Ru,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),s=!1;for(let[o,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",o,i.domain),s=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return s}unconfirm(e,t){let n=this.findHost(e),s=!1;for(let[o,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",o,i.domain),s=s||i.verified,i.verified=!1,i.expires=Date.now()+t);return s}findHost(e){for(let t of e.stringTuples())if(t[0]===Ru||t[0]===wb||t[0]===bb||t[0]===xb||t[0]===vb)return t[1]}};var Mu=4,Ou=41,Uu=6,Eb=273,ea=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let s of n)if(s.externalIp===t[0][1])return!0;return!1}add(e,t,n,s=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:s,externalFamily:at(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",s=t[1][0]===Uu?"tcp":"udp",o=parseInt(t[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===o&&u.protocol===s&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,o,s),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(e){let t=[];for(let{multiaddr:n}of e){let s=n.stringTuples(),o;if((s[0][0]===Mu||s[0][0]===Ou)&&s[1][0]===Uu?o=`${s[0][1]}-${s[1][1]}-tcp`:(s[0][0]===Mu||s[0][0]===Ou)&&s[1][0]===Eb&&(o=`${s[0][1]}-${s[1][1]}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)s[0][0]=a.externalFamily===4?Mu:Ou,s[0][1]=a.externalIp,s[1][1]=`${a.externalPort}`,t.push({multiaddr:j(`/${s.map(c=>[G(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let s=e.stringTuples()[0][1],o=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===s&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=e.stringTuples(),s=n[0][1]??"",o=n[1][0]===Uu?"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===s&&u.externalPort===i&&u.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,s,i,o),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function Yp(r){try{let[[e,t]]=r.stringTuples();if(t==null)return!1;if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}catch{}return!1}function ta(r){try{let[[e]]=r.stringTuples();return e===4||e===41}catch{}return!1}function Dr(r){try{if(!ta(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:or(e)??!1}catch{}return!0}var Ab={maxObservedAddresses:10},ra=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??Ab.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Dr(e)||Yp(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:j(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),s=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,s),o}};var Sb=[4,41,53,54,55,56];function Fu(r){try{let[[e]]=r.stringTuples();return Sb.includes(e)}catch{}return!1}var _b={maxObservedAddresses:10},na=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??_b.maxObservedAddresses}get(e,t){if(Dr(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),s=this.addresses.get(n);return s==null&&(s={verified:!Fu(e),expires:0},this.addresses.set(n,s)),{multiaddr:e,verified:s.verified,type:"transport",expires:s.expires,lastVerified:s.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=s.verified;return s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now(),this.addresses.set(n,s),o}unconfirm(e,t){let n=this.toKey(e),s=this.addresses.get(n)??{verified:!1,expires:0},o=s.verified;return s.verified=!1,s.expires=Date.now()+t,this.addresses.set(n,s),o}toKey(e){if(Fu(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var Jp=6e4,Qp={maxObservedAddresses:10,addressVerificationTTL:Jp*10,addressVerificationRetry:Jp*5},Cb=r=>r;function Vu(r,e){let t=r.getPeerId();return t!=null&&gt(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var sa=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:s=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(s.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new ra(e,t),this.dnsMappings=new Qi(e,t),this.ipMappings=new ea(e,t),this.transportAddresses=new na(e,t),this.announceFilter=t.announceFilter??Cb,this.observedAddressFilter=Ss(1024),this.addressVerificationTTL=t.addressVerificationTTL??Qp.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Qp.addressVerificationRetry,this._updatePeerStoreAddresses=Vp(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>j(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Vu(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Vu(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Vu(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let s=n.multiaddr.toString();return e.has(s)?!1:(e.add(s),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let s=j(n);return s.protos().pop()?.path===!0||s.getPeerId()===this.components.peerId.toString()?s:s.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(e)}),e.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];return t=t.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL))),t=t.concat(this.getAppendAnnounceAddrs().map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(j(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.add(e,t,n,s,o),this.observed.removePrefixed(`/ip${at(n)?4:6}/${n}/${o}/${s}`)}removePublicAddressMapping(e,t,n,s=t,o="tcp"){this.ipMappings.remove(j(`/ip${at(n)?4:6}/${n}/${o}/${s}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||or(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),s=[o=>Nr.exactMatch(o)||Ns.exactMatch(o),o=>Ps.exactMatch(o),o=>zp.exactMatch(o)];for(let o of s){if(!o(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&o(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(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};var em;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(em||(em={}));var oa=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},ia=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Bn=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Rs=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},aa=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},ca=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},la=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Ms=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},ua=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},fa=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},da=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},ha=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},pa=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Rr=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Mr=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},ma=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var Hu=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Ni())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>eo(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},Bb=["metrics","connectionProtector","dns"],kb=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function tm(r={}){let e=new Hu(r);return new Proxy(e,{get(n,s,o){if(typeof s=="string"&&!kb.includes(s)){let i=e.components[s];if(i==null&&!Bb.includes(s))throw new oa(`${s} not set`);return i}return Reflect.get(n,s,o)},set(n,s,o){return typeof s=="string"?e.components[s]=o:Reflect.set(n,s,o),!0}})}function rm(r){let e={};for(let t of Object.values(r.components))for(let n of Tb(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of Lb(t))if(e[n]!==!0)throw new ia(`Service "${Pb(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function Tb(r){return Array.isArray(r?.[Un])?r[Un]:[]}function Lb(r){return Array.isArray(r?.[cc])?r[cc]:[]}function Pb(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Nb=4,Db=41;function nm(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(Nr.matches(e))return!1;let t=e.stringTuples();return t[0][0]===Nb||t[0][0]===Db?!!or(`${t[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 sm=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Rb=new WeakMap;function Mb({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(sm());let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(sm())},u=()=>{s&&s.removeEventListener("abort",l)},f=new Promise((d,m)=>{i=()=>{u(),d(n)},a=m,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",l,{once:!0}),Rb.set(f,()=>{c(o),o=null,i()}),f}}var Ob=Mb(),om=Ob;var ga=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},ya=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var wa=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Ku}async consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new ga("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 om(a)}return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Ku=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function ba(r){if(zs(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:gt(t),r.forEach(n=>{if(!rr(n))throw new Vt("Invalid multiaddr");let s=n.getPeerId();if(s==null){if(e!=null)throw new D("Multiaddrs must all have the same peer id or have no peer id")}else{let o=gt(s);if(e?.equals(o)!==!0)throw new D("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var Ub=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function im(r,e){let t=r?.streams?.map(s=>s.protocol)??[],n=e?.closableProtocols??Ub;if(!(t.filter(s=>s!=null&&!n.includes(s)).length>0))try{await r?.close(e)}catch(s){r?.abort(s)}}var am="last-dial-failure",cm="last-dial-success";var xa=100,va=50;async function lm(r,e){let t=!1;for(let s of bn.keys())if(t=r.protoNames().includes(s),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(s=>s.toString())),n}function Os(r){try{let e;if(typeof r=="string"?e=j(r):e=r,!e.protoNames().includes("ipcidr")){let n=e.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(n)}return Jl(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Fb={maxConnections:xa,allow:[]},Ea=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Fb.maxConnections,this.allow=(t.allow??[]).map(n=>Os(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new Mt;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((u,f)=>u+f.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let s=this.sortConnections(e,n),o=Math.max(t-this.maxConnections,0),i=[];for(let a of s)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>l.contains(a.remoteAddr.nodeAddress().address))||i.push(a),i.length===o)break;await Promise.all(i.map(async a=>{await im(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,s)=>{let o=n.timeline.open,i=s.timeline.open;return o<i?1:o>i?-1:0}).sort((n,s)=>n.direction==="outbound"&&s.direction==="inbound"?1:n.direction==="inbound"&&s.direction==="outbound"?-1:0).sort((n,s)=>n.streams.length>s.streams.length?1:n.streams.length<s.streams.length?-1:0).sort((n,s)=>{let o=t.get(n.remotePeer)??0,i=t.get(s.remotePeer)??0;return o>i?1:o<i?-1:0})}};function ue(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Aa=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},kn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Aa(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Aa(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var $u=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Sa(r={}){return Vb(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Vb(r,e){e=e??{};let t=e.onEnd,n=new kn,s,o,i,a=ue(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{o=x=>{o=null,n.push(x);try{h(r(n))}catch(y){w(y)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ue()})}},l=h=>o!=null?o(h):(n.push(h),s),u=h=>(n=new kn,o!=null?o({error:h}):(n.push({error:h}),s)),f=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?s:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new kn,d(),{done:!0}),p=h=>(d(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,y;w!=null&&(x=new Promise((E,_)=>{y=()=>{_(new $u)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,x])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},t==null)return s;let g=s;return s={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(h){return g.end(h),t!=null&&(t(h),t=void 0),s},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},s}var qu=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Tn(r,e,t,n){let s=new qu(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(s):new Promise((o,i)=>{function a(){t?.removeEventListener("abort",u),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),o(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(s)};t?.addEventListener("abort",u),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var _a=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function ir(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new _a(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new _a(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ca=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ue(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Hb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ia=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Hb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Je),this.cleanup())}async join(e={}){let t=new Ca(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await ir(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Pn=class extends xt{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ya;let n=new Ia(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Je)}),this.clear()}async onEmpty(e){this.size!==0&&await Tn(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Tn(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Tn(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Sa({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new Je("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("error",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("error",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Ba=class extends Pn{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Ft(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}function um(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function zu(r){if(!ta(r))return!1;let{address:e}=r.nodeAddress();return um(e)}function Kb(r,e){let t=Ps.exactMatch(r.multiaddr),n=Ps.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let s=Ns.exactMatch(r.multiaddr),o=Ns.exactMatch(e.multiaddr);if(s&&!o)return-1;if(!s&&o)return 1;let i=Nr.exactMatch(r.multiaddr),a=Nr.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Du.exactMatch(r.multiaddr),l=Du.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Pu.exactMatch(r.multiaddr),f=Pu.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Nu.exactMatch(r.multiaddr),m=Nu.exactMatch(e.multiaddr);return d&&!m?-1:!d&&m?1:0}function $b(r,e){let t=zu(r.multiaddr),n=zu(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function qb(r,e){let t=Dr(r.multiaddr),n=Dr(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function zb(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function Gb(r,e){let t=Ds.exactMatch(r.multiaddr),n=Ds.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function fm(r){return r.sort(Kb).sort(zb).sort(Gb).sort(qb).sort($b)}var ka={maxParallelDials:va,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Ar}},Ta=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??ka.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??ka.maxDialQueueLength,this.dialTimeout=t.dialTimeout??ka.dialTimeout,this.connections=t.connections??new Mt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(let[n,s]of Object.entries(t.resolvers??{}))bn.set(n,s);this.queue=new Ba({concurrency:t.maxParallelDials??ka.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==Je.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(e,t={}){let{peerId:n,multiaddrs:s}=ba(e),o=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:s.find(c=>c.equals(a.remoteAddr)));if(o?.status==="open")return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new fe("dial-queue:already-connected")),o;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 s)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 s)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new fe("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new qr("Dial queue is full");return this.log("creating dial target for %p",n,s.map(a=>a.toString())),t.onProgress?.(new fe("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new fe("dial-queue:start-dial"));let c=Ft([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:t.priority??Zu,multiaddrs:new Set(s.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,s=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||s.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);s.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let m of d){if(o.has(m.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",m.multiaddr,n);continue}u.push(m)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(m=>m.multiaddr.toString())),e?.onProgress?.(new fe("dial-queue:calculated-addresses",u));for(let m of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new qr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(m.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",m.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[cm]:N(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",m.multiaddr,p),o.add(m.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[am]:N(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(t.aborted)throw new Ys(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let s=[...t].map(f=>({multiaddr:j(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new qr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Ms("The dial request is blocked by gater.allowDialPeer");if(s.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);s.push(...f.addresses),this.log("loaded multiaddrs for %p",e,s.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(s.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,s.map(({multiaddr:d})=>d.toString())),s.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let o=(await Promise.all(s.map(async f=>{let d=await lm(f.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(m=>({multiaddr:m,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;o=o.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=o.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),m=a.get(d);if(m!=null){m.isCertified=m.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new da("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?fm(l):l.sort(this.addressSorter);if(u.length===0)throw new Ms("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(s=>s.toString())),t);return t.runOnLimitedConnection===!1?n.find(s=>!Ds.matches(s.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var La=class extends Pn{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var wm=Vr(gm(),1);var jb=Object.prototype.toString,Zb=r=>jb.call(r)==="[object Error]",Xb=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 Xu(r){return r&&Zb(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:Xb.has(r.message):!1}var Yu=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},ym=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Ju(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let s=wm.default.operation(e),o=()=>{s.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),s.stop()};s.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof Yu)throw c.originalError;if(c instanceof TypeError&&!Xu(c))throw c;if(ym(c,a,e),await e.shouldRetry(c)||(s.stop(),n(c)),await e.onFailedAttempt(c),!s.retry(c))throw s.mainError()}catch(l){ym(l,a,e),i(),n(l)}}})})}var Pa=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new La({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(s=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,s)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);bm(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Ju(async s=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,s,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let s={};[...t.tags.keys()].forEach(o=>{o.startsWith(ac)&&(s[o]=void 0)}),await this.peerStore.merge(e,{tags:s}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>bm(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function bm(r){for(let e of r.tags.keys())if(e.startsWith(ac))return!0;return!1}var Zu=50,Qu={maxConnections:xa,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Na=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??Qu.maxConnections,this.maxConnections<1)throw new D("Connection Manager maxConnections must be greater than 0");this.connections=new Mt,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Os(n)),this.deny=(t.deny??[]).map(n=>Os(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Qu.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new wa({points:t.inboundConnectionThreshold??Qu.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Ea({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:t.allow?.map(n=>j(n))}),this.dialQueue=new Ta(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??va,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Ar},connections:this.connections}),this.reconnectQueue=new Pa({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let s of n.streams){let o=`${s.direction} ${s.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let s of n){let o={};for(let i of s.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,s]of Object.entries(e)){s=s.sort((i,a)=>i-a);let o=Math.floor(s.length*.9);t[n]=s[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await vf(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 Ef(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(s){this.log.error(s)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,s=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new bt("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=ba(e);if(this.peerId.equals(n))throw new $r("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new fe("dial-queue:already-connected")),a}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Zu});if(s.status!=="open")throw new Kr("Remote closed connection during opening");let o=this.connections.get(s.remotePeer);o==null&&(o=[],this.connections.set(s.remotePeer,o));let i=!1;for(let a of o)if(a.id===s.id&&(i=!0),t.force!==!0&&a.id!==s.id&&a.remoteAddr.equals(s.remoteAddr))return s.abort(new Vt("Duplicate multiaddr connection")),a;return i||o.push(s),s}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async s=>{try{await s.close(t)}catch(o){s.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(s=>s.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(s=>s.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let s=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(s,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,s),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Nn=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var Qb=1.2,ex=2,tx=2e3,Da=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Nn(e.interval??5e3),this.failure=new Nn(e.interval??5e3),this.next=new Nn(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??ex,this.timeoutMultiplier=e.timeoutMultiplier??Qb,this.minTimeout=e.minTimeout??tx,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(t),s=Ft([e.signal,n]);return s.start=Date.now(),s.timeout=t,s}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var ef=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ue(),this.haveNext=ue()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ue(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ue(),await ir(this.readNext.promise,t?.signal,t)}};function xm(){return new ef}var Ra=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var tf=class extends Error{code;constructor(e,t){super(e),this.code=t}},rf=class extends tf{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Ma(r,e){let t=xm();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.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 s=new ye;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new rf("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new ye:d}for(;s.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Ra("unexpected end of input");s.append(f)}let u=s.sublist(0,i);return s.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(s.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield s:yield*s,yield*i}()}return r}}}var rx=1e4,nx="1.0.0",sx="ping",ox="ipfs",vm=32,ix=!0,Oa=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??ox}/${sx}/${nx}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??rx,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??ix,this.timeout=new Da({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Un]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),s=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=Ma(s);t=Date.now(),await Promise.all([o.write(fn(vm),{signal:n}),o.read(vm,{signal:n})]),e.rtt=Date.now()-t,await o.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};function ax(r){return r[Symbol.asyncIterator]!=null}function cx(...r){let e=[];for(let t of r)ax(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Sa({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let s of n)t.push(s)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Us=cx;var Ua=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()}),getAttributesFromYieldedValue:(n,s)=>({...s,providers:[...Array.isArray(s.providers)?s.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");let n=this,s=new _r;for await(let o of Us(...n.routers.map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!s.has(o.id)&&(s.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Bn("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new bt;await Promise.all(this.routers.map(async s=>{await s.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new bt;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var Fa=globalThis.CustomEvent??Event;async function*nf(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,s=new EventTarget,o=[],i=ue(),a=ue(),c=!1,l,u=!1;s.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(i=ue(),await i.promise),u)break;let g={done:!1};o.push(g),p().then(h=>{g.done=!0,g.ok=!0,g.value=h,s.dispatchEvent(new Fa("task-complete"))},h=>{g.done=!0,g.err=h,s.dispatchEvent(new Fa("task-complete"))})}c=!0,s.dispatchEvent(new Fa("task-complete"))}catch(p){l=p,s.dispatchEvent(new Fa("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(p=>p.done)}function*d(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*m(){for(;f();)for(let p=0;p<o.length;p++)if(o[p].done){let g=o[p];if(o.splice(p,1),p--,g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=ue(),await a.promise),l!=null)throw l;if(n?yield*d():yield*m(),c&&o.length===0)break}}var Va=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],s)=>({...s,key:z(n,"base36")}),getAttributesFromYieldedValue:(n,s)=>({...s,peers:[...Array.isArray(s.peers)?s.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Rs("No peer routers available");if(e.toString()===this.peerId.toString())throw new aa("Should not try to find self");let n=this,s=Us(...this.routers.map(o=>async function*(){try{yield await o.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let o of s)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),o;throw new Ws}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Rs("No peer routers available");let n=this,s=Ss(1024);for await(let o of nf(async function*(){let i=Us(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),!s.has(o.id.toMultihash().bytes)&&(s.add(o.id.toMultihash().bytes),yield o))}};var Ha=class extends xt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ft([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ue(),yield(await Tn(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Ft([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let s=fn(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(s,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await ir(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",s,this.walkers,n)}catch(s){this.log.error("random walk errored",s),this.safeDispatchEvent("walk:error",{detail:s})}this.log("no walkers left, ended walk")}).catch(s=>{this.log.error("random walk errored",s)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var sf=32,of=64,Ka=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new ca(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new la(`Handler already registered for protocol ${e}`);let s=ki.bind({ignoreUndefined:!0})({maxInboundStreams:sf,maxOutboundStreams:of},n);this.handlers.set(e,{handler:t,options:s}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new D("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,s=this.topologies.get(e);return s==null&&(s=new Map,this.topologies.set(e,s)),s.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let s of n.protocols){let o=this.topologies.get(s);if(o!=null)for(let i of o.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,s=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));for(let o of s){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,s=e.detail.peerId;for(let o of t){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(s)!==!0&&(a.filter?.add(s),a.onConnect?.(s,n))}}};var af=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Em(r){let{name:e,metrics:t}=r,n;return t!=null?n=new af({name:e,metrics:t}):n=new Map,n}var $a=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Em({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??cr.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new D("Transport must have a valid tag");if(this.transports.has(t))throw new D(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let s=n.pop();s!=null&&e.push(s.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new ma(`No transport available for address ${String(e)}`);return t?.onProgress?.(new fe("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new bt("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new ua)});let n=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,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})}),Bu.matches(c)?t.ipv4.attempts++:ku.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),Bu.matches(c)&&t.ipv4.success++,ku.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,f),t.errors.set(c.toString(),f),f}))}}let s=await Promise.allSettled(n);if(!(s.length>0&&s.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===cr.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new fa(`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:
7
- ${[...t.errors.entries()].map(([o,i])=>`
8
- ${o}: ${`${i.stack??i}`.split(`
2
+ "use strict";var Libp2P=(()=>{var kh=Object.create;var fo=Object.defineProperty;var Rh=Object.getOwnPropertyDescriptor;var Mh=Object.getOwnPropertyNames;var Nh=Object.getPrototypeOf,Bh=Object.prototype.hasOwnProperty;var Ee=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Pt=(r,t)=>{for(var e in t)fo(r,e,{get:t[e],enumerable:!0})},Zl=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Mh(t))!Bh.call(r,o)&&o!==e&&fo(r,o,{get:()=>t[o],enumerable:!(n=Rh(t,o))||n.enumerable});return r};var un=(r,t,e)=>(e=r!=null?kh(Nh(r)):{},Zl(t||!r||!r.__esModule?fo(e,"default",{value:r,enumerable:!0}):e,r)),Oh=r=>Zl(fo({},"__esModule",{value:!0}),r);var Bf=Ee((iv,hc)=>{"use strict";var Lg=Object.prototype.hasOwnProperty,Mt="~";function Un(){}Object.create&&(Un.prototype=Object.create(null),new Un().__proto__||(Mt=!1));function Dg(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Nf(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new Dg(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 Yo(r,t){--r._eventsCount===0?r._events=new Un:delete r._events[t]}function It(){this._events=new Un,this._eventsCount=0}It.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)Lg.call(e,n)&&t.push(Mt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};It.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};It.prototype.listenerCount=function(t){var e=Mt?Mt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};It.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],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,s),!0;case 6:return c.fn.call(c.context,e,n,o,s,i),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var d=c.length,m;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(t,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!l)for(m=1,l=new Array(u-1);m<u;m++)l[m-1]=arguments[m];c[f].fn.apply(c[f].context,l)}}return!0};It.prototype.on=function(t,e,n){return Nf(this,t,e,n,!1)};It.prototype.once=function(t,e,n){return Nf(this,t,e,n,!0)};It.prototype.removeListener=function(t,e,n,o){var s=Mt?Mt+t:t;if(!this._events[s])return this;if(!e)return Yo(this,s),this;var i=this._events[s];if(i.fn)i.fn===e&&(!o||i.once)&&(!n||i.context===n)&&Yo(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==e||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Yo(this,s)}return this};It.prototype.removeAllListeners=function(t){var e;return t?(e=Mt?Mt+t:t,this._events[e]&&Yo(this,e)):(this._events=new Un,this._eventsCount=0),this};It.prototype.off=It.prototype.removeListener;It.prototype.addListener=It.prototype.on;It.prefixed=Mt;It.EventEmitter=It;typeof hc<"u"&&(hc.exports=It)});var qf=Ee((Pv,Kf)=>{Kf.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 sd=Ee((rS,od)=>{"use strict";od.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let t=Object.getPrototypeOf(r);return t===null||t===Object.prototype}});var fd=Ee((ld,ud)=>{"use strict";var cs=sd(),{hasOwnProperty:ad}=Object.prototype,{propertyIsEnumerable:r0}=Object,Wr=(r,t,e)=>Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),n0=ld,id={concatArrays:!1,ignoreUndefined:!1},ls=r=>{let t=[];for(let e in r)ad.call(r,e)&&t.push(e);if(Object.getOwnPropertySymbols){let e=Object.getOwnPropertySymbols(r);for(let n of e)r0.call(r,n)&&t.push(n)}return t};function Xr(r){return Array.isArray(r)?o0(r):cs(r)?s0(r):r}function o0(r){let t=r.slice(0,0);return ls(r).forEach(e=>{Wr(t,e,Xr(r[e]))}),t}function s0(r){let t=Object.getPrototypeOf(r)===null?Object.create(null):{};return ls(r).forEach(e=>{Wr(t,e,Xr(r[e]))}),t}var cd=(r,t,e,n)=>(e.forEach(o=>{typeof t[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Wr(r,o,Oc(r[o],t[o],n)):Wr(r,o,Xr(t[o])))}),r),i0=(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++)ad.call(s,a)&&(i.push(String(a)),s===r?Wr(n,o++,s[a]):Wr(n,o++,Xr(s[a])));n=cd(n,s,ls(s).filter(a=>!i.includes(a)),e)}),n};function Oc(r,t,e){return e.concatArrays&&Array.isArray(r)&&Array.isArray(t)?i0(r,t,e):!cs(t)||!cs(r)?Xr(t):cd(r,t,ls(t),e)}ud.exports=function(...r){let t=Oc(Xr(id),this!==n0&&this||{},id),e={_:{}};for(let n of r)if(n!==void 0){if(!cs(n))throw new TypeError("`"+n+"` is not an Option Object");e=Oc(e,{_:n},t)}return e._}});var Nd=Ee(Zn=>{(function(){var r,t,e,n,o,s,i,a;a=function(c){var u,l,f,d;return u=(c&255<<24)>>>24,l=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[u,l,f,d].join(".")},i=function(c){var u,l,f,d,m,p;for(u=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=t(c),m=p[0],l=p[1],c=c.substring(l),u.push(m)}if(c.length!==0)throw new Error("Invalid IP");switch(u.length){case 1:if(u[0]>4294967295)throw new Error("Invalid IP");return u[0]>>>0;case 2:if(u[0]>255||u[1]>16777215)throw new Error("Invalid IP");return(u[0]<<24|u[1])>>>0;case 3:if(u[0]>255||u[1]>255||u[2]>65535)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2])>>>0;case 4:if(u[0]>255||u[1]>255||u[2]>255||u[3]>255)throw new Error("Invalid IP");return(u[0]<<24|u[1]<<16|u[2]<<8|u[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),s=e("a"),o=e("A"),t=function(c){var u,l,f,d,m;for(d=0,u=10,l="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,u=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,u=8,l="7")),m=f;f<c.length;){if("0"<=c[f]&&c[f]<=l)d=d*u+(e(c[f])-n)>>>0;else if(u===16)if("a"<=c[f]&&c[f]<="f")d=d*u+(10+e(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*u+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===m)throw new Error("empty octet");return[d,f]},r=function(){function c(u,l){var f,d,m,p;if(typeof u!="string")throw new Error("Missing `net' parameter");if(l||(p=u.split("/",2),u=p[0],l=p[1]),l||(l=32),typeof l=="string"&&l.indexOf(".")>-1){try{this.maskLong=i(l)}catch(g){throw f=g,new Error("Invalid mask: "+l)}for(d=m=32;m>=0;d=--m)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(l||l===0)this.bitmask=parseInt(l,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(u)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+u)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+l);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(u){return typeof u=="string"&&(u.indexOf("/")>0||u.split(".").length!==4)&&(u=new c(u)),u instanceof c?this.contains(u.base)&&this.contains(u.broadcast||u.last):(i(u)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(u){return u==null&&(u=1),new c(a(this.netLong+this.size*u),this.mask)},c.prototype.forEach=function(u){var l,f,d;for(d=i(this.first),f=i(this.last),l=0;d<=f;)u(a(d),d,l),l++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Zn.ip2long=i,Zn.long2ip=a,Zn.Netmask=r}).call(Zn)});var ah=Ee((mI,ih)=>{function Ht(r,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}ih.exports=Ht;Ht.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ht.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ht.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var t=new Date().getTime();if(r&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},e),this._options.unref&&this._timer.unref(),!0};Ht.prototype.attempt=function(r,t){this._fn=r,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Ht.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ht.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ht.prototype.start=Ht.prototype.try;Ht.prototype.errors=function(){return this._errors};Ht.prototype.attempts=function(){return this._attempts};Ht.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},t=null,e=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=e&&(t=o,e=i)}return t}});var ch=Ee(yr=>{var Fy=ah();yr.operation=function(r){var t=yr.timeouts(r);return new Fy(t,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};yr.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};yr.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};yr.wrap=function(r,t,e){if(t instanceof Array&&(e=t,t=null),!e){e=[];for(var n in r)typeof r[n]=="function"&&e.push(n)}for(var o=0;o<e.length;o++){var s=e[o],i=r[s];r[s]=function(c){var u=yr.operation(t),l=Array.prototype.slice.call(arguments,1),f=l.pop();l.push(function(d){u.retry(d)||(d&&(arguments[0]=u.mainError()),f.apply(this,arguments))}),u.attempt(function(){c.apply(r,l)})}.bind(r,i),r[s].options=t}}});var uh=Ee((yI,lh)=>{lh.exports=ch()});var ub={};Pt(ub,{createLibp2p:()=>lb});var Yl=Symbol.for("@libp2p/connection");var Fi=Symbol.for("@libp2p/content-routing");var Ui=Symbol.for("@libp2p/peer-discovery");var ho=Symbol.for("@libp2p/peer-id");function po(r){return!!r?.[ho]}var Ki=Symbol.for("@libp2p/peer-routing");var qi="keep-alive";var bb=Symbol.for("@libp2p/transport");var Ve;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ve||(Ve={}));var Gt=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"}},xr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}},fn=class extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}};var mo=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 go=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}},Er=class extends Error{static name="InvalidPeerIdError";constructor(t="Invalid PeerID"){super(t),this.name="InvalidPeerIdError"}},Se=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},yo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},bo=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}},dn=class extends Error{static name="UnsupportedProtocolError";constructor(t="Unsupported protocol error"){super(t),this.name="UnsupportedProtocolError"}},wo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var xo=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}},ce=class extends Error{static name="NotStartedError";constructor(t="Not started"){super(t),this.name="NotStartedError"}};var Sr=class extends Error{static name="DialError";constructor(t="Dial error"){super(t),this.name="DialError"}};var Ar=class extends Error{static name="LimitedConnectionError";constructor(t="Limited connection"){super(t),this.name="LimitedConnectionError"}},vo=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(t="Too many inbound protocol streams"){super(t),this.name="TooManyInboundProtocolStreamsError"}},Eo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(t="Too many outbound protocol streams"){super(t),this.name="TooManyOutboundProtocolStreamsError"}},Ae=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var le=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 So(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Ql(...r){let t=[];for(let e of r)So(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 Jl(...r){let t=[];for(let e of r)So(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 hn=Symbol.for("@libp2p/service-capabilities"),zi=Symbol.for("@libp2p/service-dependencies");var Wi={};Pt(Wi,{base58btc:()=>G,base58flickr:()=>Vh});var Hb=new Uint8Array(0);function tu(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 ue(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 eu(r){return new TextEncoder().encode(r)}function ru(r){return new TextDecoder().decode(r)}function Fh(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,h=0,b=0,x=p.length;b!==x&&p[b]===0;)b++,g++;for(var y=(x-b)*l+1>>>0,E=new Uint8Array(y);b!==x;){for(var _=p[b],L=0,I=y-1;(_!==0||L<h)&&I!==-1;I--,L++)_+=256*E[I]>>>0,E[I]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");h=L,b++}for(var P=y-h;P!==y&&E[P]===0;)P++;for(var T=c.repeat(g);P<y;++P)T+=r.charAt(E[P]);return T}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 h=0,b=0;p[g]===c;)h++,g++;for(var x=(p.length-g)*u+1>>>0,y=new Uint8Array(x);p[g];){var E=e[p.charCodeAt(g)];if(E===255)return;for(var _=0,L=x-1;(E!==0||_<b)&&L!==-1;L--,_++)E+=a*y[L]>>>0,y[L]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");b=_,g++}if(p[g]!==" "){for(var I=x-b;I!==x&&y[I]===0;)I++;for(var P=new Uint8Array(h+(x-I)),T=h;I!==x;)P[T++]=y[I++];return P}}}function m(p){var g=d(p);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var Uh=Fh,Kh=Uh,ou=Kh;var Vi=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")}},$i=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 su(this,t)}},Hi=class{decoders;constructor(t){this.decoders=t}or(t){return su(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 su(r,t){return new Hi({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Gi=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 Vi(t,e,n),this.decoder=new $i(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function _r({name:r,prefix:t,encode:e,decode:n}){return new Gi(r,t,e,n)}function _e({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ou(e,r);return _r({prefix:t,name:r,encode:n,decode:s=>ue(o(s))})}function qh(r,t,e,n){let o={};for(let l=0;l<t.length;++l)o[t[l]]=l;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,u=0;for(let l=0;l<s;++l){let f=o[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=e||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function zh(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 it({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return _r({prefix:t,name:r,encode(o){return zh(o,n,e)},decode(o){return qh(o,n,e,r)}})}var G=_e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vh=_e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Xi={};Pt(Xi,{base32:()=>Ut,base32hex:()=>Wh,base32hexpad:()=>jh,base32hexpadupper:()=>Zh,base32hexupper:()=>Xh,base32pad:()=>Hh,base32padupper:()=>Gh,base32upper:()=>$h,base32z:()=>Yh});var Ut=it({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$h=it({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Hh=it({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Gh=it({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Wh=it({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Xh=it({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jh=it({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zh=it({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yh=it({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ji={};Pt(ji,{base36:()=>pn,base36upper:()=>Qh});var pn=_e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qh=_e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Jh=cu,iu=128,tp=127,ep=~tp,rp=Math.pow(2,31);function cu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=rp;)t[e++]=r&255|iu,r/=128;for(;r&ep;)t[e++]=r&255|iu,r>>>=7;return t[e]=r|0,cu.bytes=e-n+1,t}var np=Zi,op=128,au=127;function Zi(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Zi.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&au)<<o:(i&au)*Math.pow(2,o),o+=7}while(i>=op);return Zi.bytes=s-n,e}var sp=Math.pow(2,7),ip=Math.pow(2,14),ap=Math.pow(2,21),cp=Math.pow(2,28),lp=Math.pow(2,35),up=Math.pow(2,42),fp=Math.pow(2,49),dp=Math.pow(2,56),hp=Math.pow(2,63),pp=function(r){return r<sp?1:r<ip?2:r<ap?3:r<cp?4:r<lp?5:r<up?6:r<fp?7:r<dp?8:r<hp?9:10},mp={encode:Jh,decode:np,encodingLength:pp},gp=mp,mn=gp;function gn(r,t=0){return[mn.decode(r,t),mn.decode.bytes]}function Ir(r,t,e=0){return mn.encode(r,t,e),t}function Cr(r){return mn.encodingLength(r)}function Wt(r,t){let e=t.byteLength,n=Cr(r),o=n+Cr(e),s=new Uint8Array(o+e);return Ir(r,s,0),Ir(e,s,n),s.set(t,o),new Tr(r,e,t,s)}function Kt(r){let t=ue(r),[e,n]=gn(t),[o,s]=gn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Tr(e,o,i,t)}function lu(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&tu(r.bytes,e.bytes)}}var Tr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function uu(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return bp(e,Yi(r),t??G.encoder);default:return wp(e,Yi(r),t??Ut.encoder)}}var fu=new WeakMap;function Yi(r){let t=fu.get(r);if(t==null){let e=new Map;return fu.set(r,e),e}return t}var ht=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!==yn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==xp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Wt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&lu(t.multihash,n.multihash)}toString(t){return uu(this,t)}toJSON(){return{"/":uu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??du(n,o,s.bytes))}else if(e[vp]===!0){let{version:n,multihash:o,code:s}=e,i=Kt(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!==yn)throw new Error(`Version 0 CID must use dag-pb (code: ${yn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=du(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,yn,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=ue(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 Tr(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]=gn(t.subarray(e));return e+=d,f},o=n(),s=yn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(t,e){let[n,o]=yp(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 Yi(s).set(n,t),s}};function yp(r,t){switch(r[0]){case"Q":{let e=t??G;return[G.prefix,e.decode(`${G.prefix}${r}`)]}case G.prefix:{let e=t??G;return[G.prefix,e.decode(r)]}case Ut.prefix:{let e=t??Ut;return[Ut.prefix,e.decode(r)]}case pn.prefix:{let e=t??pn;return[pn.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 bp(r,t,e){let{prefix:n}=e;if(n!==G.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 wp(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 yn=112,xp=18;function du(r,t,e){let n=Cr(r),o=n+Cr(t),s=new Uint8Array(o+e.byteLength);return Ir(r,s,0),Ir(t,s,n),s.set(e,o),s}var vp=Symbol.for("@ipld/js-cid/CID");var Qi={};Pt(Qi,{identity:()=>fe});var hu=0,Ep="identity",pu=ue;function Sp(r){return Wt(hu,pu(r))}var fe={code:hu,name:Ep,encode:pu,digest:Sp};function at(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 mu(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Ap(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Pr(r,...t){if(!Ap(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 gu(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");mu(r.outputLen),mu(r.blockLen)}function Lr(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 yu(r,t){Pr(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var $e=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function _o(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Xt(r,t){return r<<32-t|r>>>t}function bu(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function bn(r){return typeof r=="string"&&(r=bu(r)),Pr(r),r}function Ji(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Pr(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 Dr=class{clone(){return this._cloneInto()}};function Io(r){let t=n=>r().update(bn(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function kr(r=32){if($e&&typeof $e.getRandomValues=="function")return $e.getRandomValues(new Uint8Array(r));if($e&&typeof $e.randomBytes=="function")return $e.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function _p(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,u=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+u,a,n)}function wu(r,t,e){return r&t^~r&e}function xu(r,t,e){return r&t^r&e^t&e}var Rr=class extends Dr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=_o(this.buffer)}update(t){Lr(this);let{view:e,buffer:n,blockLen:o}=this;t=bn(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=_o(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){Lr(this),yu(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;_p(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=_o(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Co=BigInt(4294967295),ta=BigInt(32);function vu(r,t=!1){return t?{h:Number(r&Co),l:Number(r>>ta&Co)}:{h:Number(r>>ta&Co)|0,l:Number(r&Co)|0}}function Ip(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=vu(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Cp=(r,t)=>BigInt(r>>>0)<<ta|BigInt(t>>>0),Tp=(r,t,e)=>r>>>e,Pp=(r,t,e)=>r<<32-e|t>>>e,Lp=(r,t,e)=>r>>>e|t<<32-e,Dp=(r,t,e)=>r<<32-e|t>>>e,kp=(r,t,e)=>r<<64-e|t>>>e-32,Rp=(r,t,e)=>r>>>e-32|t<<64-e,Mp=(r,t)=>t,Np=(r,t)=>r,Bp=(r,t,e)=>r<<e|t>>>32-e,Op=(r,t,e)=>t<<e|r>>>32-e,Fp=(r,t,e)=>t<<e-32|r>>>64-e,Up=(r,t,e)=>r<<e-32|t>>>64-e;function Kp(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var qp=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),zp=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Vp=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),$p=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Hp=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Gp=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Wp={fromBig:vu,split:Ip,toBig:Cp,shrSH:Tp,shrSL:Pp,rotrSH:Lp,rotrSL:Dp,rotrBH:kp,rotrBL:Rp,rotr32H:Mp,rotr32L:Np,rotlSH:Bp,rotlSL:Op,rotlBH:Fp,rotlBL:Up,add:Kp,add3L:qp,add3H:zp,add4L:Vp,add4H:$p,add5H:Gp,add5L:Hp},F=Wp;var[Xp,jp]=F.split(["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))),Ie=new Uint32Array(80),Ce=new Uint32Array(80),ea=class extends Rr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:m,Gl:p,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,u,l,f,d,m,p,g,h]}set(t,e,n,o,s,i,a,c,u,l,f,d,m,p,g,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=d|0,this.Gh=m|0,this.Gl=p|0,this.Hh=g|0,this.Hl=h|0}process(t,e){for(let y=0;y<16;y++,e+=4)Ie[y]=t.getUint32(e),Ce[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let E=Ie[y-15]|0,_=Ce[y-15]|0,L=F.rotrSH(E,_,1)^F.rotrSH(E,_,8)^F.shrSH(E,_,7),I=F.rotrSL(E,_,1)^F.rotrSL(E,_,8)^F.shrSL(E,_,7),P=Ie[y-2]|0,T=Ce[y-2]|0,et=F.rotrSH(P,T,19)^F.rotrBH(P,T,61)^F.shrSH(P,T,6),H=F.rotrSL(P,T,19)^F.rotrBL(P,T,61)^F.shrSL(P,T,6),K=F.add4L(I,H,Ce[y-7],Ce[y-16]),dt=F.add4H(K,L,et,Ie[y-7],Ie[y-16]);Ie[y]=dt|0,Ce[y]=K|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:m,Fl:p,Gh:g,Gl:h,Hh:b,Hl:x}=this;for(let y=0;y<80;y++){let E=F.rotrSH(f,d,14)^F.rotrSH(f,d,18)^F.rotrBH(f,d,41),_=F.rotrSL(f,d,14)^F.rotrSL(f,d,18)^F.rotrBL(f,d,41),L=f&m^~f&g,I=d&p^~d&h,P=F.add5L(x,_,I,jp[y],Ce[y]),T=F.add5H(P,b,E,L,Xp[y],Ie[y]),et=P|0,H=F.rotrSH(n,o,28)^F.rotrBH(n,o,34)^F.rotrBH(n,o,39),K=F.rotrSL(n,o,28)^F.rotrBL(n,o,34)^F.rotrBL(n,o,39),dt=n&s^n&a^s&a,A=o&i^o&c^i&c;b=g|0,x=h|0,g=m|0,h=p|0,m=f|0,p=d|0,{h:f,l:d}=F.add(u|0,l|0,T|0,et|0),u=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=F.add3L(et,K,A);n=F.add3H(D,T,H,dt),o=D|0}({h:n,l:o}=F.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=F.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=F.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=F.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=F.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:p}=F.add(this.Fh|0,this.Fl|0,m|0,p|0),{h:g,l:h}=F.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:b,l:x}=F.add(this.Hh|0,this.Hl|0,b|0,x|0),this.set(n,o,s,i,a,c,u,l,f,d,m,p,g,h,b,x)}roundClean(){Ie.fill(0),Ce.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Eu=Io(()=>new ea);var Lo={};Pt(Lo,{aInRange:()=>Bt,abool:()=>jt,abytes:()=>Mr,bitGet:()=>em,bitLen:()=>sa,bitMask:()=>xn,bitSet:()=>rm,bytesToHex:()=>he,bytesToNumberBE:()=>pe,bytesToNumberLE:()=>Pe,concatBytes:()=>me,createHmacDrbg:()=>ia,ensureBytes:()=>ot,equalBytes:()=>Jp,hexToBytes:()=>Ge,hexToNumber:()=>oa,inRange:()=>wn,isBytes:()=>Te,memoized:()=>Xe,notImplemented:()=>om,numberToBytesBE:()=>Le,numberToBytesLE:()=>We,numberToHexUnpadded:()=>He,numberToVarBytesBE:()=>Qp,utf8ToBytes:()=>tm,validateObject:()=>ne});var To=BigInt(0),Po=BigInt(1),Zp=BigInt(2);function Te(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Mr(r){if(!Te(r))throw new Error("Uint8Array expected")}function jt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var Yp=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function he(r){Mr(r);let t="";for(let e=0;e<r.length;e++)t+=Yp[r[e]];return t}function He(r){let t=r.toString(16);return t.length&1?"0"+t:t}function oa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?To:BigInt("0x"+r)}var de={_0:48,_9:57,A:65,F:70,a:97,f:102};function Su(r){if(r>=de._0&&r<=de._9)return r-de._0;if(r>=de.A&&r<=de.F)return r-(de.A-10);if(r>=de.a&&r<=de.f)return r-(de.a-10)}function Ge(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof 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=Su(r.charCodeAt(s)),a=Su(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 pe(r){return oa(he(r))}function Pe(r){return Mr(r),oa(he(Uint8Array.from(r).reverse()))}function Le(r,t){return Ge(r.toString(16).padStart(t*2,"0"))}function We(r,t){return Le(r,t).reverse()}function Qp(r){return Ge(He(r))}function ot(r,t,e){let n;if(typeof t=="string")try{n=Ge(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Te(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 me(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Mr(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}function Jp(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 tm(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var ra=r=>typeof r=="bigint"&&To<=r;function wn(r,t,e){return ra(r)&&ra(t)&&ra(e)&&t<=r&&r<e}function Bt(r,t,e,n){if(!wn(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function sa(r){let t;for(t=0;r>To;r>>=Po,t+=1);return t}function em(r,t){return r>>BigInt(t)&Po}function rm(r,t,e){return r|(e?Po:To)<<BigInt(t)}var xn=r=>(Zp<<BigInt(r-1))-Po,na=r=>new Uint8Array(r),Au=r=>Uint8Array.from(r);function ia(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=na(r),o=na(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=na())=>{o=a(Au([0]),f),n=a(),f.length!==0&&(o=a(Au([1]),f),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let m=n.slice();d.push(m),f+=n.length}return me(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(u()));)c();return i(),m}}var nm={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Te(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function ne(r,t,e={}){let n=(o,s,i)=>{let a=nm[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var om=()=>{throw new Error("not implemented")};function Xe(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),rt=BigInt(1),je=BigInt(2),sm=BigInt(3),aa=BigInt(4),_u=BigInt(5),Iu=BigInt(8),im=BigInt(9),am=BigInt(16);function Y(r,t){let e=r%t;return e>=pt?e:t+e}function cm(r,t,e){if(t<pt)throw new Error("invalid exponent, negatives unsupported");if(e<=pt)throw new Error("invalid modulus");if(e===rt)return pt;let n=rt;for(;t>pt;)t&rt&&(n=n*r%e),r=r*r%e,t>>=rt;return n}function nt(r,t,e){let n=r;for(;t-- >pt;)n*=n,n%=e;return n}function Do(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=Y(r,t),n=t,o=pt,s=rt,i=rt,a=pt;for(;e!==pt;){let u=n/e,l=n%e,f=o-i*u,d=s-a*u;n=e,e=l,o=i,s=a,i=f,a=d}if(n!==rt)throw new Error("invert: does not exist");return Y(o,t)}function lm(r){let t=(r-rt)/je,e,n,o;for(e=r-rt,n=0;e%je===pt;e/=je,n++);for(o=je;o<r&&cm(o,t,r)!==r-rt;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+rt)/aa;return function(c,u){let l=c.pow(u,i);if(!c.eql(c.sqr(l),u))throw new Error("Cannot find square root");return l}}let s=(e+rt)/je;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,l=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let m=1;for(let g=a.sqr(d);m<u&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let p=a.pow(l,rt<<BigInt(u-m-1));l=a.sqr(p),f=a.mul(f,p),d=a.mul(d,l),u=m}return f}}function um(r){if(r%aa===sm){let t=(r+rt)/aa;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%Iu===_u){let t=(r-_u)/Iu;return function(n,o){let s=n.mul(o,je),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,je),i),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%am,lm(r)}var Cu=(r,t)=>(Y(r,t)&rt)===rt,fm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ca(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=fm.reduce((n,o)=>(n[o]="function",n),t);return ne(r,e)}function dm(r,t,e){if(e<pt)throw new Error("invalid exponent, negatives unsupported");if(e===pt)return r.ONE;if(e===rt)return t;let n=r.ONE,o=t;for(;e>pt;)e&rt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=rt;return n}function hm(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function la(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function De(r,t,e=!1,n={}){if(r<=pt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=la(r,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:s,MASK:xn(o),ZERO:pt,ONE:rt,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return pt<=c&&c<r},is0:c=>c===pt,isOdd:c=>(c&rt)===rt,neg:c=>Y(-c,r),eql:(c,u)=>c===u,sqr:c=>Y(c*c,r),add:(c,u)=>Y(c+u,r),sub:(c,u)=>Y(c-u,r),mul:(c,u)=>Y(c*u,r),pow:(c,u)=>dm(a,c,u),div:(c,u)=>Y(c*Do(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Do(c,r),sqrt:n.sqrt||(c=>(i||(i=um(r)),i(a,c))),invertBatch:c=>hm(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>e?We(c,s):Le(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?Pe(c):pe(c)}});return Object.freeze(a)}function Tu(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 ua(r){let t=Tu(r);return t+Math.ceil(t/2)}function Pu(r,t,e=!1){let n=r.length,o=Tu(t),s=ua(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Pe(r):pe(r),a=Y(i,t-rt)+rt;return e?We(a,o):Le(a,o)}var Lu=BigInt(0),ko=BigInt(1);function fa(r,t){let e=t.negate();return r?e:t}function Du(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function da(r,t){Du(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function pm(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 mm(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 ha=new WeakMap,ku=new WeakMap;function pa(r){return ku.get(r)||1}function Ro(r,t){return{constTimeNegate:fa,hasPrecomputes(e){return pa(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Lu;)n&ko&&(o=o.add(s)),s=s.double(),n>>=ko;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=da(n,t),i=[],a=e,c=a;for(let u=0;u<o;u++){c=a,i.push(c);for(let l=1;l<s;l++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let{windows:s,windowSize:i}=da(e,t),a=r.ZERO,c=r.BASE,u=BigInt(2**e-1),l=2**e,f=BigInt(e);for(let d=0;d<s;d++){let m=d*i,p=Number(o&u);o>>=f,p>i&&(p-=l,o+=ko);let g=m,h=m+Math.abs(p)-1,b=d%2!==0,x=p<0;p===0?c=c.add(fa(b,n[g])):a=a.add(fa(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=da(e,t),c=BigInt(2**e-1),u=2**e,l=BigInt(e);for(let f=0;f<i;f++){let d=f*a;if(o===Lu)break;let m=Number(o&c);if(o>>=l,m>a&&(m-=u,o+=ko),m===0)continue;let p=n[d+Math.abs(m)-1];m<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(e,n,o){let s=ha.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&ha.set(n,o(s))),s},wNAFCached(e,n,o){let s=pa(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=pa(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Du(n,t),ku.set(e,n),ha.delete(e)}}}function Mo(r,t,e,n){if(pm(e,r),mm(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=sa(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),u=Math.floor((t.BITS-1)/i)*i,l=o;for(let f=u;f>=0;f-=i){c.fill(o);for(let m=0;m<n.length;m++){let p=n[m],g=Number(p>>BigInt(f)&BigInt(a));c[g]=c[g].add(e[m])}let d=o;for(let m=c.length-1,p=o;m>0;m--)p=p.add(c[m]),d=d.add(p);if(l=l.add(d),f!==0)for(let m=0;m<i;m++)l=l.double()}return l}function vn(r){return ca(r.Fp),ne(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...la(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Zt=BigInt(0),Ot=BigInt(1),No=BigInt(2),gm=BigInt(8),ym={zip215:!0};function bm(r){let t=vn(r);return ne(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Ru(r){let t=bm(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,u=No<<BigInt(a*8)-Ot,l=e.create,f=De(t.n,t.nBitLength),d=t.uvRatio||((v,w)=>{try{return{isValid:!0,value:e.sqrt(v*e.inv(w))}}catch{return{isValid:!1,value:Zt}}}),m=t.adjustScalarBytes||(v=>v),p=t.domain||((v,w,S)=>{if(jt("phflag",S),w.length||S)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,w){Bt("coordinate "+v,w,Zt,u)}function h(v){if(!(v instanceof y))throw new Error("ExtendedPoint expected")}let b=Xe((v,w)=>{let{ex:S,ey:C,ez:M}=v,N=v.is0();w==null&&(w=N?gm:e.inv(M));let U=l(S*w),q=l(C*w),O=l(M*w);if(N)return{x:Zt,y:Ot};if(O!==Ot)throw new Error("invZ was invalid");return{x:U,y:q}}),x=Xe(v=>{let{a:w,d:S}=t;if(v.is0())throw new Error("bad point: ZERO");let{ex:C,ey:M,ez:N,et:U}=v,q=l(C*C),O=l(M*M),Z=l(N*N),tt=l(Z*Z),gt=l(q*w),yt=l(Z*l(gt+O)),wt=l(tt+l(S*l(q*O)));if(yt!==wt)throw new Error("bad point: equation left != right (1)");let vt=l(C*M),Nt=l(N*U);if(vt!==Nt)throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(w,S,C,M){this.ex=w,this.ey=S,this.ez=C,this.et=M,g("x",w),g("y",S),g("z",C),g("t",M),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof y)throw new Error("extended point not allowed");let{x:S,y:C}=w||{};return g("x",S),g("y",C),new y(S,C,Ot,l(S*C))}static normalizeZ(w){let S=e.invertBatch(w.map(C=>C.ez));return w.map((C,M)=>C.toAffine(S[M])).map(y.fromAffine)}static msm(w,S){return Mo(y,f,w,S)}_setWindowSize(w){L.setWindowSize(this,w)}assertValidity(){x(this)}equals(w){h(w);let{ex:S,ey:C,ez:M}=this,{ex:N,ey:U,ez:q}=w,O=l(S*q),Z=l(N*M),tt=l(C*q),gt=l(U*M);return O===Z&&tt===gt}is0(){return this.equals(y.ZERO)}negate(){return new y(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:w}=t,{ex:S,ey:C,ez:M}=this,N=l(S*S),U=l(C*C),q=l(No*l(M*M)),O=l(w*N),Z=S+C,tt=l(l(Z*Z)-N-U),gt=O+U,yt=gt-q,wt=O-U,vt=l(tt*yt),Nt=l(gt*wt),Tt=l(tt*wt),ee=l(yt*gt);return new y(vt,Nt,ee,Tt)}add(w){h(w);let{a:S,d:C}=t,{ex:M,ey:N,ez:U,et:q}=this,{ex:O,ey:Z,ez:tt,et:gt}=w;if(S===BigInt(-1)){let Vl=l((N-M)*(Z+O)),$l=l((N+M)*(Z-O)),Oi=l($l-Vl);if(Oi===Zt)return this.double();let Hl=l(U*No*gt),Gl=l(q*No*tt),Wl=Gl+Hl,Xl=$l+Vl,jl=Gl-Hl,Th=l(Wl*Oi),Ph=l(Xl*jl),Lh=l(Wl*jl),Dh=l(Oi*Xl);return new y(Th,Ph,Dh,Lh)}let yt=l(M*O),wt=l(N*Z),vt=l(q*C*gt),Nt=l(U*tt),Tt=l((M+N)*(O+Z)-yt-wt),ee=Nt-vt,ae=Nt+vt,ln=l(wt-S*yt),Ah=l(Tt*ee),_h=l(ae*ln),Ih=l(Tt*ln),Ch=l(ee*ae);return new y(Ah,_h,Ch,Ih)}subtract(w){return this.add(w.negate())}wNAF(w){return L.wNAFCached(this,w,y.normalizeZ)}multiply(w){let S=w;Bt("scalar",S,Ot,n);let{p:C,f:M}=this.wNAF(S);return y.normalizeZ([C,M])[0]}multiplyUnsafe(w,S=y.ZERO){let C=w;return Bt("scalar",C,Zt,n),C===Zt?_:this.is0()||C===Ot?this:L.wNAFCachedUnsafe(this,C,y.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return L.unsafeLadder(this,n).is0()}toAffine(w){return b(this,w)}clearCofactor(){let{h:w}=t;return w===Ot?this:this.multiplyUnsafe(w)}static fromHex(w,S=!1){let{d:C,a:M}=t,N=e.BYTES;w=ot("pointHex",w,N),jt("zip215",S);let U=w.slice(),q=w[N-1];U[N-1]=q&-129;let O=Pe(U),Z=S?u:e.ORDER;Bt("pointHex.y",O,Zt,Z);let tt=l(O*O),gt=l(tt-Ot),yt=l(C*tt-M),{isValid:wt,value:vt}=d(gt,yt);if(!wt)throw new Error("Point.fromHex: invalid y coordinate");let Nt=(vt&Ot)===Ot,Tt=(q&128)!==0;if(!S&&vt===Zt&&Tt)throw new Error("Point.fromHex: x=0 and x_0=1");return Tt!==Nt&&(vt=l(-vt)),y.fromAffine({x:vt,y:O})}static fromPrivateKey(w){return T(w).point}toRawBytes(){let{x:w,y:S}=this.toAffine(),C=We(S,e.BYTES);return C[C.length-1]|=w&Ot?128:0,C}toHex(){return he(this.toRawBytes())}}y.BASE=new y(t.Gx,t.Gy,Ot,l(t.Gx*t.Gy)),y.ZERO=new y(Zt,Ot,Ot,Zt);let{BASE:E,ZERO:_}=y,L=Ro(y,a*8);function I(v){return Y(v,n)}function P(v){return I(Pe(v))}function T(v){let w=e.BYTES;v=ot("private key",v,w);let S=ot("hashed private key",s(v),2*w),C=m(S.slice(0,w)),M=S.slice(w,2*w),N=P(C),U=E.multiply(N),q=U.toRawBytes();return{head:C,prefix:M,scalar:N,point:U,pointBytes:q}}function et(v){return T(v).pointBytes}function H(v=new Uint8Array,...w){let S=me(...w);return P(s(p(S,ot("context",v),!!o)))}function K(v,w,S={}){v=ot("message",v),o&&(v=o(v));let{prefix:C,scalar:M,pointBytes:N}=T(w),U=H(S.context,C,v),q=E.multiply(U).toRawBytes(),O=H(S.context,q,N,v),Z=I(U+O*M);Bt("signature.s",Z,Zt,n);let tt=me(q,We(Z,e.BYTES));return ot("result",tt,e.BYTES*2)}let dt=ym;function A(v,w,S,C=dt){let{context:M,zip215:N}=C,U=e.BYTES;v=ot("signature",v,2*U),w=ot("message",w),S=ot("publicKey",S,U),N!==void 0&&jt("zip215",N),o&&(w=o(w));let q=Pe(v.slice(U,2*U)),O,Z,tt;try{O=y.fromHex(S,N),Z=y.fromHex(v.slice(0,U),N),tt=E.multiplyUnsafe(q)}catch{return!1}if(!N&&O.isSmallOrder())return!1;let gt=H(M,Z.toRawBytes(),O.toRawBytes(),w);return Z.add(O.multiplyUnsafe(gt)).subtract(tt).clearCofactor().equals(y.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:et,sign:K,verify:A,ExtendedPoint:y,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(v=8,w=y.BASE){return w._setWindowSize(v),w.multiply(BigInt(3)),w}}}}var ma=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Mu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Ow=BigInt(0),wm=BigInt(1),Nu=BigInt(2),Fw=BigInt(3),xm=BigInt(5),vm=BigInt(8);function Em(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ma,a=r*r%s*r%s,c=nt(a,Nu,s)*a%s,u=nt(c,wm,s)*r%s,l=nt(u,xm,s)*u%s,f=nt(l,t,s)*l%s,d=nt(f,e,s)*f%s,m=nt(d,n,s)*d%s,p=nt(m,o,s)*m%s,g=nt(p,o,s)*m%s,h=nt(g,t,s)*l%s;return{pow_p_5_8:nt(h,Nu,s)*r%s,b2:a}}function Sm(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Am(r,t){let e=ma,n=Y(t*t*t,e),o=Y(n*n*t,e),s=Em(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,u=Y(i*Mu,e),l=a===r,f=a===Y(-r,e),d=a===Y(-r*Mu,e);return l&&(i=c),(f||d)&&(i=u),Cu(i,e)&&(i=Y(-i,e)),{isValid:l||f,value:i}}var _m=De(ma,void 0,!0),Im={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:_m,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:vm,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Eu,randomBytes:kr,adjustScalarBytes:Sm,uvRatio:Am},En=Ru(Im);var Bo=32,Oo=64,ga=32;function Bu(){let r=En.utils.randomPrivateKey(),t=En.getPublicKey(r);return{privateKey:Cm(r,t),publicKey:t}}function Ou(r,t){let e=r.subarray(0,ga);return En.sign(t instanceof Uint8Array?t:t.subarray(),e)}function Fu(r,t,e){return En.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function Cm(r,t){let e=new Uint8Array(Oo);for(let n=0;n<ga;n++)e[n]=r[n],e[ga+n]=t[n];return e}var Sn=class{type="Ed25519";raw;constructor(t){this.raw=Uo(t,Bo)}toMultihash(){return fe.digest(oe(this))}toCID(){return ht.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e){return Fu(this.raw,e,t)}},Fo=class{type="Ed25519";raw;publicKey;constructor(t,e){this.raw=Uo(t,Oo),this.publicKey=new Sn(e)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}sign(t){return Ou(this.raw,t)}};function ya(r){return r=Uo(r,Bo),new Sn(r)}async function Ku(){let{privateKey:r,publicKey:t}=Bu();return new Fo(r,t)}function Uo(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}function ct(r=0){return new Uint8Array(r)}function Et(r=0){return new Uint8Array(r)}var Tm=Math.pow(2,7),Pm=Math.pow(2,14),Lm=Math.pow(2,21),ba=Math.pow(2,28),wa=Math.pow(2,35),xa=Math.pow(2,42),va=Math.pow(2,49),j=128,St=127;function ft(r){if(r<Tm)return 1;if(r<Pm)return 2;if(r<Lm)return 3;if(r<ba)return 4;if(r<wa)return 5;if(r<xa)return 6;if(r<va)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ea(r,t,e=0){switch(ft(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 Dm(r,t,e=0){switch(ft(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 Sa(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)*ba,e<j)||(e=r[t+5],n+=(e&St)*wa,e<j)||(e=r[t+6],n+=(e&St)*xa,e<j)||(e=r[t+7],n+=(e&St)*va,e<j))return n;throw new RangeError("Could not decode varint")}function km(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)*ba,e<j)||(e=r.get(t+5),n+=(e&St)*wa,e<j)||(e=r.get(t+6),n+=(e&St)*xa,e<j)||(e=r.get(t+7),n+=(e&St)*va,e<j))return n;throw new RangeError("Could not decode varint")}function At(r,t,e=0){return t==null&&(t=Et(ft(r))),t instanceof Uint8Array?Ea(r,t,e):Dm(r,t,e)}function Yt(r,t=0){return r instanceof Uint8Array?Sa(r,t):km(r,t)}var Aa=new Float32Array([-0]),ke=new Uint8Array(Aa.buffer);function qu(r,t,e){Aa[0]=r,t[e]=ke[0],t[e+1]=ke[1],t[e+2]=ke[2],t[e+3]=ke[3]}function zu(r,t){return ke[0]=r[t],ke[1]=r[t+1],ke[2]=r[t+2],ke[3]=r[t+3],Aa[0]}var _a=new Float64Array([-0]),_t=new Uint8Array(_a.buffer);function Vu(r,t,e){_a[0]=r,t[e]=_t[0],t[e+1]=_t[1],t[e+2]=_t[2],t[e+3]=_t[3],t[e+4]=_t[4],t[e+5]=_t[5],t[e+6]=_t[6],t[e+7]=_t[7]}function $u(r,t){return _t[0]=r[t],_t[1]=r[t+1],_t[2]=r[t+2],_t[3]=r[t+3],_t[4]=r[t+4],_t[5]=r[t+5],_t[6]=r[t+6],_t[7]=r[t+7],_a[0]}var Rm=BigInt(Number.MAX_SAFE_INTEGER),Mm=BigInt(Number.MIN_SAFE_INTEGER),qt=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 Ye;if(t<Rm&&t>Mm)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>Hu&&(o=0n,++n>Hu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ye;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):Ye}},Ye=new qt(0,0);Ye.toBigInt=function(){return 0n};Ye.zzEncode=Ye.zzDecode=function(){return this};Ye.length=function(){return 1};var Hu=4294967296n;function Gu(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 Wu(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 Ia(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 Qt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Ko(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ca=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,Qt(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 Qt(this,4);return Ko(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qt(this,4);return Ko(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qt(this,4);let t=zu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Qt(this,4);let t=$u(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 Qt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Wu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Qt(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 qt(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 Qt(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 Qt(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 Qt(this,8);let t=Ko(this.buf,this.pos+=4),e=Ko(this.buf,this.pos+=4);return new qt(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=Sa(this.buf,this.pos);return this.pos+=ft(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Ta(r){return new Ca(r instanceof Uint8Array?r:r.subarray())}function Lt(r,t,e){let n=Ta(r);return t.decode(n,void 0,e)}var Pa={};Pt(Pa,{base10:()=>Nm});var Nm=_e({prefix:"9",name:"base10",alphabet:"0123456789"});var La={};Pt(La,{base16:()=>Bm,base16upper:()=>Om});var Bm=it({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Om=it({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Da={};Pt(Da,{base2:()=>Fm});var Fm=it({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ka={};Pt(ka,{base256emoji:()=>Vm});var ju=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}"),Um=ju.reduce((r,t,e)=>(r[e]=t,r),[]),Km=ju.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function qm(r){return r.reduce((t,e)=>(t+=Um[e],t),"")}function zm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Km[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Vm=_r({prefix:"\u{1F680}",name:"base256emoji",encode:qm,decode:zm});var Na={};Pt(Na,{base64:()=>Ra,base64pad:()=>$m,base64url:()=>Ma,base64urlpad:()=>Hm});var Ra=it({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$m=it({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ma=it({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Hm=it({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ba={};Pt(Ba,{base8:()=>Gm});var Gm=it({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Oa={};Pt(Oa,{identity:()=>Wm});var Wm=_r({prefix:"\0",name:"identity",encode:r=>ru(r),decode:r=>eu(r)});var yx=new TextEncoder,bx=new TextDecoder;var Ka={};Pt(Ka,{sha256:()=>Nr,sha512:()=>Zm});function Ua({name:r,code:t,encode:e}){return new Fa(r,t,e)}var Fa=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Wt(this.code,e):e.then(n=>Wt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Yu(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Nr=Ua({name:"sha2-256",code:18,encode:Yu("SHA-256")}),Zm=Ua({name:"sha2-512",code:19,encode:Yu("SHA-512")});var An={...Oa,...Da,...Ba,...Pa,...La,...Xi,...ji,...Wi,...Na,...ka},Lx={...Ka,...Qi};function Ju(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Qu=Ju("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),qa=Ju("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}),Ym={utf8:Qu,"utf-8":Qu,hex:An.base16,latin1:qa,ascii:qa,binary:qa,...An},qo=Ym;function k(r,t="utf8"){let e=qo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function za(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 Qe=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Va(){}var Ha=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Qm=za();function Jm(r){return globalThis.Buffer!=null?Et(r):Qm(r)}var In=class{len;head;tail;states;constructor(){this.len=0,this.head=new Qe(Va,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Qe(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ga((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(zo,10,qt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=qt.fromBigInt(t);return this._push(zo,e.length(),e)}uint64Number(t){return this._push(Ea,ft(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=qt.fromBigInt(t).zzEncode();return this._push(zo,e.length(),e)}sint64Number(t){let e=qt.fromNumber(t).zzEncode();return this._push(zo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push($a,1,t?1:0)}fixed32(t){return this._push(_n,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=qt.fromBigInt(t);return this._push(_n,4,e.lo)._push(_n,4,e.hi)}fixed64Number(t){let e=qt.fromNumber(t);return this._push(_n,4,e.lo)._push(_n,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(qu,4,t)}double(t){return this._push(Vu,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push($a,1,0):this.uint32(e)._push(eg,e,t)}string(t){let e=Gu(t);return e!==0?this.uint32(e)._push(Ia,e,t):this._push($a,1,0)}fork(){return this.states=new Ha(this),this.head=this.tail=new Qe(Va,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 Qe(Va,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=Jm(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function $a(r,t,e){t[e]=r&255}function tg(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ga=class extends Qe{next;constructor(t,e){super(tg,t,e),this.next=void 0}};function zo(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 _n(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 eg(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(In.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(rg,t,r),this},In.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(ng,t,r),this});function rg(r,t,e){t.set(r,e)}function ng(r,t,e){r.length<40?Ia(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(k(r),e)}function Wa(){return new In}function Dt(r,t){let e=Wa();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Br;(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"})(Br||(Br={}));function Vo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Xa(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 Vo("enum",Br.VARINT,e,n)}function kt(r,t){return Vo("message",Br.LENGTH_DELIMITED,r,t)}var Je=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Cn=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var mt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(mt||(mt={}));var ja;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(ja||(ja={}));(function(r){r.codec=()=>Xa(ja)})(mt||(mt={}));var se;(function(r){let t;r.codec=()=>(t==null&&(t=kt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),mt.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=mt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(e,r.codec(),n)})(se||(se={}));var Za;(function(r){let t;r.codec=()=>(t==null&&(t=kt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),mt.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=mt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(e,r.codec(),n)})(Za||(Za={}));var Dn={};Pt(Dn,{MAX_RSA_KEY_SIZE:()=>ec,generateRSAKeyPair:()=>sc,jwkToJWKKeyPair:()=>mf,jwkToPkcs1:()=>mg,jwkToPkix:()=>nc,jwkToRSAPrivateKey:()=>pf,pkcs1ToJwk:()=>ff,pkcs1ToRSAPrivateKey:()=>hf,pkixToJwk:()=>df,pkixToRSAPublicKey:()=>oc});var og=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Re=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Me=new Uint32Array(64),Ya=class extends Rr{constructor(){super(64,32,8,!1),this.A=Re[0]|0,this.B=Re[1]|0,this.C=Re[2]|0,this.D=Re[3]|0,this.E=Re[4]|0,this.F=Re[5]|0,this.G=Re[6]|0,this.H=Re[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)Me[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Me[f-15],m=Me[f-2],p=Xt(d,7)^Xt(d,18)^d>>>3,g=Xt(m,17)^Xt(m,19)^m>>>10;Me[f]=g+Me[f-7]+p+Me[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let d=Xt(a,6)^Xt(a,11)^Xt(a,25),m=l+d+wu(a,c,u)+og[f]+Me[f]|0,g=(Xt(n,2)^Xt(n,13)^Xt(n,22))+xu(n,o,s)|0;l=u,u=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,u,l)}roundClean(){Me.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Or=Io(()=>new Ya);function B(r,t="utf8"){let e=qo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function Rt(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 rf=Symbol.for("@achingbrain/uint8arraylist");function ef(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function $o(r){return!!r?.[rf]}var Q=class r{bufs;length;[rf]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if($o(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($o(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=ef(this.bufs,t);return e.buf[e.index]}set(t,e){let n=ef(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if($o(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 Rt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Rt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,l=e>a&&e<=c;if(u&&l){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!$o(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let f=e;f<=c;f+=l){l=0;for(let d=u;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){l=Math.max(1,d-a[m]);break}}if(l===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=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=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=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=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(!at(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 sg=parseInt("11111",2),Ja=parseInt("10000000",2),ig=parseInt("01111111",2),nf={2:ag,3:ug,5:lg,6:cg,16:Qa,22:Qa,48:Qa};function Tn(r,t={offset:0}){let e=r[t.offset]&sg;if(t.offset++,nf[e]!=null)return nf[e](r,t);throw new Error("No decoder for tag "+e)}function Ho(r,t){let e=0;if((r[t.offset]&Ja)===Ja){let n=r[t.offset]&ig,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 Qa(r,t){Ho(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Tn(r,t);if(n===null)break;e.push(n)}return e}function ag(r,t){let e=Ho(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=Ho(r,t);return t.offset+=e,["oid-unimplemented"]}function lg(r,t){return t.offset++,null}function ug(r,t){let e=Ho(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return Tn(o,{offset:0})}function fg(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new Q;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function tc(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=fg(r.byteLength);return new Q(Uint8Array.from([t.byteLength|Ja]),t)}function Vt(r){let t=new Q,e=parseInt("10000000",2);return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new Q(Uint8Array.from([2]),tc(t),t)}function of(r){let t=Uint8Array.from([0]),e=new Q(t,r);return new Q(Uint8Array.from([3]),tc(e),e)}function Go(r){let t=new Q;for(let e of r)t.append(e);return new Q(Uint8Array.from([48]),tc(t),t)}function Fr(r){if(isNaN(r)||r<=0)throw new R("random bytes length must be a Number bigger than 0");return kr(r)}var Pn=class extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}},Ln=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Wo=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var sf={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Wo("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 Ne=sf;async function af(r){let t=await Ne.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await dg(t);return{privateKey:e[0],publicKey:e[1]}}async function cf(r,t){let e=await Ne.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ne.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function lf(r,t,e){let n=await Ne.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ne.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function dg(r){if(r.privateKey==null||r.publicKey==null)throw new R("Private and public key are required");return Promise.all([Ne.get().subtle.exportKey("jwk",r.privateKey),Ne.get().subtle.exportKey("jwk",r.publicKey)])}function uf(r){if(r.kty!=="RSA")throw new R("invalid key type");if(r.n==null)throw new R("invalid key modulus");return k(r.n,"base64url").length*8}var Ur=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Dn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return ht.createV1(114,this._multihash)}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e){return lf(this._key,e,t)}},kn=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Dn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}sign(t){return cf(this._key,t)}};var ec=8192,rc=18,hg=1062,pg=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ff(r){let t=Tn(r);return{n:B(t[1],"base64url"),e:B(t[2],"base64url"),d:B(t[3],"base64url"),p:B(t[4],"base64url"),q:B(t[5],"base64url"),dp:B(t[6],"base64url"),dq:B(t[7],"base64url"),qi:B(t[8],"base64url"),kty:"RSA"}}function mg(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 Go([Vt(Uint8Array.from([0])),Vt(k(r.n,"base64url")),Vt(k(r.e,"base64url")),Vt(k(r.d,"base64url")),Vt(k(r.p,"base64url")),Vt(k(r.q,"base64url")),Vt(k(r.dp,"base64url")),Vt(k(r.dq,"base64url")),Vt(k(r.qi,"base64url"))]).subarray()}function df(r){let t=Tn(r,{offset:0});return{kty:"RSA",n:B(t[1][0],"base64url"),e:B(t[1][1],"base64url")}}function nc(r){if(r.n==null||r.e==null)throw new R("JWK was missing components");return Go([pg,of(Go([Vt(k(r.n,"base64url")),Vt(k(r.e,"base64url"))]))]).subarray()}function hf(r){let t=ff(r);return pf(t)}function oc(r,t){if(r.byteLength>=hg)throw new xr("Key size is too large");let e=df(r);if(t==null){let n=Or(se.encode({Type:mt.RSA,Data:r}));t=Wt(rc,n)}return new Ur(e,t)}function pf(r){if(uf(r)>ec)throw new R("Key size is too large");let t=mf(r),e=Or(se.encode({Type:mt.RSA,Data:nc(t.publicKey)})),n=Wt(rc,e);return new kn(t.privateKey,new Ur(t.publicKey,n))}async function sc(r){if(r>ec)throw new R("Key size is too large");let t=await af(r),e=Or(se.encode({Type:mt.RSA,Data:nc(t.publicKey)})),n=Wt(rc,e);return new kn(t.privateKey,new Ur(t.publicKey,n))}function mf(r){if(r==null)throw new R("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Xo=class extends Dr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,gu(t);let n=bn(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return Lr(this),this.iHash.update(t),this}digestInto(t){Lr(this),Pr(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}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ic=(r,t,e)=>new Xo(r,t).update(e).digest();ic.create=(r,t)=>new Xo(r,t);function gf(r){r.lowS!==void 0&&jt("lowS",r.lowS),r.prehash!==void 0&&jt("prehash",r.prehash)}function gg(r){let t=vn(r);ne(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:yg,hexToBytes:bg}=Lo,ac=class extends Error{constructor(t=""){super(t)}},ge={Err:ac,_tlv:{encode:(r,t)=>{let{Err:e}=ge;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=He(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?He(o.length/2|128):"";return He(r)+s+o+t},decode(r,t){let{Err:e}=ge,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let l of u)i=i<<8|l;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=ge;if(r<ye)throw new t("integer: negative integers are not allowed");let e=He(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}=ge;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 yg(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=ge,o=typeof r=="string"?bg(r):r;Mr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=ge,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},ye=BigInt(0),bt=BigInt(1),e2=BigInt(2),yf=BigInt(3),r2=BigInt(4);function wg(r){let t=gg(r),{Fp:e}=t,n=De(t.n,t.nBitLength),o=t.toBytes||((g,h,b)=>{let x=h.toAffine();return me(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),b=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:b,y:x}});function i(g){let{a:h,b}=t,x=e.sqr(g),y=e.mul(x,g);return e.add(e.add(y,e.mul(g,h)),b)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return wn(g,bt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:b,wrapPrivateKey:x,n:y}=t;if(h&&typeof g!="bigint"){if(Te(g)&&(g=he(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(b*2,"0")}let E;try{E=typeof g=="bigint"?g:pe(ot("private key",g,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof g)}return x&&(E=Y(E,y)),Bt("private key",E,bt,y),E}function u(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let l=Xe((g,h)=>{let{px:b,py:x,pz:y}=g;if(e.eql(y,e.ONE))return{x:b,y:x};let E=g.is0();h==null&&(h=E?e.ONE:e.inv(y));let _=e.mul(b,h),L=e.mul(x,h),I=e.mul(y,h);if(E)return{x:e.ZERO,y:e.ZERO};if(!e.eql(I,e.ONE))throw new Error("invZ was invalid");return{x:_,y:L}}),f=Xe(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:b}=g.toAffine();if(!e.isValid(h)||!e.isValid(b))throw new Error("bad point: x or y not FE");let x=e.sqr(b),y=i(h);if(!e.eql(x,y))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,b,x){if(this.px=h,this.py=b,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(b==null||!e.isValid(b))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:b,y:x}=h||{};if(!h||!e.isValid(b)||!e.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let y=E=>e.eql(E,e.ZERO);return y(b)&&y(x)?d.ZERO:new d(b,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let b=e.invertBatch(h.map(x=>x.pz));return h.map((x,y)=>x.toAffine(b[y])).map(d.fromAffine)}static fromHex(h){let b=d.fromAffine(s(ot("pointHex",h)));return b.assertValidity(),b}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,b){return Mo(d,n,h,b)}_setWindowSize(h){p.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){u(h);let{px:b,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=e.eql(e.mul(b,L),e.mul(E,y)),P=e.eql(e.mul(x,L),e.mul(_,y));return I&&P}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b}=t,x=e.mul(b,yf),{px:y,py:E,pz:_}=this,L=e.ZERO,I=e.ZERO,P=e.ZERO,T=e.mul(y,y),et=e.mul(E,E),H=e.mul(_,_),K=e.mul(y,E);return K=e.add(K,K),P=e.mul(y,_),P=e.add(P,P),L=e.mul(h,P),I=e.mul(x,H),I=e.add(L,I),L=e.sub(et,I),I=e.add(et,I),I=e.mul(L,I),L=e.mul(K,L),P=e.mul(x,P),H=e.mul(h,H),K=e.sub(T,H),K=e.mul(h,K),K=e.add(K,P),P=e.add(T,T),T=e.add(P,T),T=e.add(T,H),T=e.mul(T,K),I=e.add(I,T),H=e.mul(E,_),H=e.add(H,H),T=e.mul(H,K),L=e.sub(L,T),P=e.mul(H,et),P=e.add(P,P),P=e.add(P,P),new d(L,I,P)}add(h){u(h);let{px:b,py:x,pz:y}=this,{px:E,py:_,pz:L}=h,I=e.ZERO,P=e.ZERO,T=e.ZERO,et=t.a,H=e.mul(t.b,yf),K=e.mul(b,E),dt=e.mul(x,_),A=e.mul(y,L),D=e.add(b,x),v=e.add(E,_);D=e.mul(D,v),v=e.add(K,dt),D=e.sub(D,v),v=e.add(b,y);let w=e.add(E,L);return v=e.mul(v,w),w=e.add(K,A),v=e.sub(v,w),w=e.add(x,y),I=e.add(_,L),w=e.mul(w,I),I=e.add(dt,A),w=e.sub(w,I),T=e.mul(et,v),I=e.mul(H,A),T=e.add(I,T),I=e.sub(dt,T),T=e.add(dt,T),P=e.mul(I,T),dt=e.add(K,K),dt=e.add(dt,K),A=e.mul(et,A),v=e.mul(H,v),dt=e.add(dt,A),A=e.sub(K,A),A=e.mul(et,A),v=e.add(v,A),K=e.mul(dt,v),P=e.add(P,K),K=e.mul(w,v),I=e.mul(D,I),I=e.sub(I,K),K=e.mul(D,dt),T=e.mul(w,T),T=e.add(T,K),new d(I,P,T)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return p.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:b,n:x}=t;Bt("scalar",h,ye,x);let y=d.ZERO;if(h===ye)return y;if(this.is0()||h===bt)return this;if(!b||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:E,k1:_,k2neg:L,k2:I}=b.splitScalar(h),P=y,T=y,et=this;for(;_>ye||I>ye;)_&bt&&(P=P.add(et)),I&bt&&(T=T.add(et)),et=et.double(),_>>=bt,I>>=bt;return E&&(P=P.negate()),L&&(T=T.negate()),T=new d(e.mul(T.px,b.beta),T.py,T.pz),P.add(T)}multiply(h){let{endo:b,n:x}=t;Bt("scalar",h,bt,x);let y,E;if(b){let{k1neg:_,k1:L,k2neg:I,k2:P}=b.splitScalar(h),{p:T,f:et}=this.wNAF(L),{p:H,f:K}=this.wNAF(P);T=p.constTimeNegate(_,T),H=p.constTimeNegate(I,H),H=new d(e.mul(H.px,b.beta),H.py,H.pz),y=T.add(H),E=et.add(K)}else{let{p:_,f:L}=this.wNAF(h);y=_,E=L}return d.normalizeZ([y,E])[0]}multiplyAndAddUnsafe(h,b,x){let y=d.BASE,E=(L,I)=>I===ye||I===bt||!L.equals(y)?L.multiplyUnsafe(I):L.multiply(I),_=E(this,b).add(E(h,x));return _.is0()?void 0:_}toAffine(h){return l(this,h)}isTorsionFree(){let{h,isTorsionFree:b}=t;if(h===bt)return!0;if(b)return b(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:b}=t;return h===bt?this:b?b(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return jt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return jt("isCompressed",h),he(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let m=t.nBitLength,p=Ro(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function xg(r){let t=vn(r);return ne(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function bf(r){let t=xg(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(A){return Y(A,n)}function a(A){return Do(A,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:f}=wg({...t,toBytes(A,D,v){let w=D.toAffine(),S=e.toBytes(w.x),C=me;return jt("isCompressed",v),v?C(Uint8Array.from([D.hasEvenY()?2:3]),S):C(Uint8Array.from([4]),S,e.toBytes(w.y))},fromBytes(A){let D=A.length,v=A[0],w=A.subarray(1);if(D===o&&(v===2||v===3)){let S=pe(w);if(!wn(S,bt,e.ORDER))throw new Error("Point is not on curve");let C=l(S),M;try{M=e.sqrt(C)}catch(q){let O=q instanceof Error?": "+q.message:"";throw new Error("Point is not on curve"+O)}let N=(M&bt)===bt;return(v&1)===1!==N&&(M=e.neg(M)),{x:S,y:M}}else if(D===s&&v===4){let S=e.fromBytes(w.subarray(0,e.BYTES)),C=e.fromBytes(w.subarray(e.BYTES,2*e.BYTES));return{x:S,y:C}}else{let S=o,C=s;throw new Error("invalid Point, expected length of "+S+", or uncompressed "+C+", got "+D)}}}),d=A=>he(Le(A,t.nByteLength));function m(A){let D=n>>bt;return A>D}function p(A){return m(A)?i(-A):A}let g=(A,D,v)=>pe(A.slice(D,v));class h{constructor(D,v,w){this.r=D,this.s=v,this.recovery=w,this.assertValidity()}static fromCompact(D){let v=t.nByteLength;return D=ot("compactSignature",D,v*2),new h(g(D,0,v),g(D,v,2*v))}static fromDER(D){let{r:v,s:w}=ge.toSig(ot("DER",D));return new h(v,w)}assertValidity(){Bt("r",this.r,bt,n),Bt("s",this.s,bt,n)}addRecoveryBit(D){return new h(this.r,this.s,D)}recoverPublicKey(D){let{r:v,s:w,recovery:S}=this,C=L(ot("msgHash",D));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let M=S===2||S===3?v+t.n:v;if(M>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let N=(S&1)===0?"02":"03",U=c.fromHex(N+d(M)),q=a(M),O=i(-C*q),Z=i(w*q),tt=c.BASE.multiplyAndAddUnsafe(U,O,Z);if(!tt)throw new Error("point at infinify");return tt.assertValidity(),tt}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Ge(this.toDERHex())}toDERHex(){return ge.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ge(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let b={isValidPrivateKey(A){try{return u(A),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let A=ua(t.n);return Pu(t.randomBytes(A),t.n)},precompute(A=8,D=c.BASE){return D._setWindowSize(A),D.multiply(BigInt(3)),D}};function x(A,D=!0){return c.fromPrivateKey(A).toRawBytes(D)}function y(A){let D=Te(A),v=typeof A=="string",w=(D||v)&&A.length;return D?w===o||w===s:v?w===2*o||w===2*s:A instanceof c}function E(A,D,v=!0){if(y(A))throw new Error("first arg must be private key");if(!y(D))throw new Error("second arg must be public key");return c.fromHex(D).multiply(u(A)).toRawBytes(v)}let _=t.bits2int||function(A){if(A.length>8192)throw new Error("input is too large");let D=pe(A),v=A.length*8-t.nBitLength;return v>0?D>>BigInt(v):D},L=t.bits2int_modN||function(A){return i(_(A))},I=xn(t.nBitLength);function P(A){return Bt("num < 2^"+t.nBitLength,A,ye,I),Le(A,t.nByteLength)}function T(A,D,v=et){if(["recovered","canonical"].some(yt=>yt in v))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:S}=t,{lowS:C,prehash:M,extraEntropy:N}=v;C==null&&(C=!0),A=ot("msgHash",A),gf(v),M&&(A=ot("prehashed msgHash",w(A)));let U=L(A),q=u(D),O=[P(q),P(U)];if(N!=null&&N!==!1){let yt=N===!0?S(e.BYTES):N;O.push(ot("extraEntropy",yt))}let Z=me(...O),tt=U;function gt(yt){let wt=_(yt);if(!f(wt))return;let vt=a(wt),Nt=c.BASE.multiply(wt).toAffine(),Tt=i(Nt.x);if(Tt===ye)return;let ee=i(vt*i(tt+Tt*q));if(ee===ye)return;let ae=(Nt.x===Tt?0:2)|Number(Nt.y&bt),ln=ee;return C&&m(ee)&&(ln=p(ee),ae^=1),new h(Tt,ln,ae)}return{seed:Z,k2sig:gt}}let et={lowS:t.lowS,prehash:!1},H={lowS:t.lowS,prehash:!1};function K(A,D,v=et){let{seed:w,k2sig:S}=T(A,D,v),C=t;return ia(C.hash.outputLen,C.nByteLength,C.hmac)(w,S)}c.BASE._setWindowSize(8);function dt(A,D,v,w=H){let S=A;D=ot("msgHash",D),v=ot("publicKey",v);let{lowS:C,prehash:M,format:N}=w;if(gf(w),"strict"in w)throw new Error("options.strict was renamed to lowS");if(N!==void 0&&N!=="compact"&&N!=="der")throw new Error("format must be compact or der");let U=typeof S=="string"||Te(S),q=!U&&!N&&typeof S=="object"&&S!==null&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!U&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let O,Z;try{if(q&&(O=new h(S.r,S.s)),U){try{N!=="compact"&&(O=h.fromDER(S))}catch(ae){if(!(ae instanceof ge.Err))throw ae}!O&&N!=="der"&&(O=h.fromCompact(S))}Z=c.fromHex(v)}catch{return!1}if(!O||C&&O.hasHighS())return!1;M&&(D=t.hash(D));let{r:tt,s:gt}=O,yt=L(D),wt=a(gt),vt=i(yt*wt),Nt=i(tt*wt),Tt=c.BASE.multiplyAndAddUnsafe(Z,vt,Nt)?.toAffine();return Tt?i(Tt.x)===tt:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:E,sign:K,verify:dt,ProjectivePoint:c,Signature:h,utils:b}}function vg(r){return{hash:r,hmac:(t,...e)=>ic(r,t,Ji(...e)),randomBytes:kr}}function wf(r,t){let e=n=>bf({...r,...vg(n)});return{...e(t),create:e}}var Ef=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),xf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Eg=BigInt(1),cc=BigInt(2),vf=(r,t)=>(r+t/cc)/t;function Sg(r){let t=Ef,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,l=u*u*r%t,f=nt(l,e,t)*l%t,d=nt(f,e,t)*l%t,m=nt(d,cc,t)*u%t,p=nt(m,o,t)*m%t,g=nt(p,s,t)*p%t,h=nt(g,a,t)*g%t,b=nt(h,c,t)*h%t,x=nt(b,a,t)*g%t,y=nt(x,e,t)*l%t,E=nt(y,i,t)*p%t,_=nt(E,n,t)*u%t,L=nt(_,cc,t);if(!lc.eql(lc.sqr(L),r))throw new Error("Cannot find square root");return L}var lc=De(Ef,void 0,void 0,{sqrt:Sg}),$t=wf({a:BigInt(0),b:BigInt(7),Fp:lc,n:xf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=xf,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Eg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=vf(s*r,t),c=vf(-n*r,t),u=Y(r-a*e-c*o,t),l=Y(-a*n-c*s,t),f=u>i,d=l>i;if(f&&(u=t-u),d&&(l=t-l),u>i||l>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:d,k2:l}}}},Or),f2=BigInt(0);var d2=$t.ProjectivePoint;function uc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Sf(r,t){let e=Nr.digest(t instanceof Uint8Array?t:t.subarray());if(uc(e))return e.then(({digest:n})=>$t.sign(n,r).toDERRawBytes()).catch(n=>{throw new Pn(String(n))});try{return $t.sign(e.digest,r).toDERRawBytes()}catch(n){throw new Pn(String(n))}}function Af(r,t,e){let n=Nr.digest(e instanceof Uint8Array?e:e.subarray());if(uc(n))return n.then(({digest:o})=>$t.verify(t,o,r)).catch(o=>{throw new Ln(String(o))});try{return $t.verify(t,n.digest,r)}catch(o){throw new Ln(String(o))}}var Rn=class{type="secp256k1";raw;_key;constructor(t){this._key=Cf(t),this.raw=_f(this._key)}toMultihash(){return fe.digest(oe(this))}toCID(){return ht.createV1(114,this.toMultihash())}toString(){return G.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}verify(t,e){return Af(this._key,e,t)}},jo=class{type="secp256k1";raw;publicKey;constructor(t,e){this.raw=If(t),this.publicKey=new Rn(e??Tf(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:at(this.raw,t.raw)}sign(t){return Sf(this.raw,t)}};function fc(r){return new Rn(r)}async function Pf(){let r=Ag();return new jo(r)}function _f(r){return $t.ProjectivePoint.fromHex(r).toRawBytes(!0)}function If(r){try{return $t.getPublicKey(r,!0),r}catch(t){throw new fn(String(t))}}function Cf(r){try{return $t.ProjectivePoint.fromHex(r),r}catch(t){throw new xr(String(t))}}function Tf(r){try{return $t.getPublicKey(r,!0)}catch(t){throw new fn(String(t))}}function Ag(){return $t.utils.randomPrivateKey()}async function Lf(r,t){if(r==="Ed25519")return Ku();if(r==="secp256k1")return Pf();if(r==="RSA")return sc(t??2048);throw new Ae}function Kr(r,t){let{Type:e,Data:n}=se.decode(r),o=n??new Uint8Array;switch(e){case mt.RSA:return oc(o,t);case mt.Ed25519:return ya(o);case mt.secp256k1:return fc(o);default:throw new Ae}}function Df(r){let{Type:t,Data:e}=se.decode(r.digest),n=e??new Uint8Array;switch(t){case mt.Ed25519:return ya(n);case mt.secp256k1:return fc(n);default:throw new Ae}}function oe(r){return se.encode({Type:mt[r.type],Data:r.raw})}var kf=Symbol.for("nodejs.util.inspect.custom"),_g=114,Mn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[ho]=!0;toString(){return this.string==null&&(this.string=G.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ht.createV1(_g,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return at(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return at(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[kf](){return`PeerId(${this.toString()})`}},Nn=class extends Mn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Bn=class extends Mn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},On=class extends Mn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Ig=2336,Fn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=fe.digest(k(this.url))}[kf](){return`PeerId(${this.url})`}[ho]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ht.createV1(Ig,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=B(t)),t.toString()===this.toString())}};var Cg=114,Rf=2336;function ie(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Kt(G.decode(`z${r}`));else{if(t==null)throw new R('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Kt(t.decode(r))}return qr(e)}function dc(r){if(r.type==="Ed25519")return new Bn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new On({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Nn({multihash:r.toCID().multihash,publicKey:r});throw new Ae}function Mf(r){return dc(r.publicKey)}function qr(r){if(Pg(r))return new Nn({multihash:r});if(Tg(r))try{let t=Df(r);if(t.type==="Ed25519")return new Bn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new On({multihash:r,publicKey:t})}catch{let e=B(r.digest);return new Fn(new URL(e))}throw new bo("Supplied PeerID Multihash is invalid")}function Zo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Cg&&r.code!==Rf)throw new yo("Supplied PeerID CID is invalid");if(r.code===Rf){let t=B(r.multihash.digest);return new Fn(new URL(t))}return qr(r.multihash)}function Tg(r){return r.code===fe.code}function Pg(r){return r.code===Nr.code}var ut=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var pc=un(Bf(),1);var Kn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},mc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Of=r=>globalThis.DOMException===void 0?new mc(r):new DOMException(r),Ff=r=>{let t=r.reason===void 0?Of("This operation was aborted."):r.reason;return t instanceof Error?t:Of(t)};function qn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,u=new Promise((l,f)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:m}=t;m.aborted&&f(Ff(m)),a=()=>{f(Ff(m))},m.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(l,f);return}let d=new Kn;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{l(await r)}catch(m){f(m)}})()}).finally(()=>{u.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return u.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},u}function gc(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 zn=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=gc(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 Be=class extends pc.default{#t;#e;#s=0;#a;#c;#p=0;#n;#l;#r;#m;#o=0;#u;#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:zn,...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.#e=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#a=t.intervalCap,this.#c=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.#e||this.#s<this.#a}get#v(){return this.#o<this.#u}#E(){this.#o--,this.#f(),this.emit("next")}#S(){this.#b(),this.#y(),this.#l=void 0}get#A(){let t=Date.now();if(this.#n===void 0){let e=this.#p-t;if(e<0)this.#s=this.#t?this.#o:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#S()},e)),!0}return!1}#f(){if(this.#r.size===0)return this.#n&&clearInterval(this.#n),this.#n=void 0,this.emit("empty"),this.#o===0&&this.emit("idle"),!1;if(!this.#i){let t=!this.#A;if(this.#x&&this.#v){let e=this.#r.dequeue();return e?(this.emit("active"),e(),t&&this.#y(),!0):!1}}return!1}#y(){this.#e||this.#n!==void 0||(this.#n=setInterval(()=>{this.#b()},this.#c),this.#p=Date.now()+this.#c)}#b(){this.#s===0&&this.#o===0&&this.#n&&(clearInterval(this.#n),this.#n=void 0),this.#s=this.#t?this.#o:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}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.#u=t,this.#d()}async#_(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.#o++,this.#s++;try{e.signal?.throwIfAborted();let s=t({signal:e.signal});e.timeout&&(s=qn(Promise.resolve(s),{milliseconds:e.timeout})),e.signal&&(s=Promise.race([s,this.#_(e.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof Kn&&!e.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#E()}},e),this.emit("add"),this.#f()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#i?(this.#i=!1,this.#d(),this):this}pause(){this.#i=!0}clear(){this.#r=new this.#m}async onEmpty(){this.#r.size!==0&&await this.#h("empty")}async onSizeLessThan(t){this.#r.size<t||await this.#h("next",()=>this.#r.size<t)}async onIdle(){this.#o===0&&this.#r.size===0||await this.#h("idle")}async#h(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.#o}get isPaused(){return this.#i}};function Qo(r){let t=[zt.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var yc=60;function Jo(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:zt[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:zt[t.type],TTL:t.TTL??t.ttl??yc,data:t.data instanceof Uint8Array?B(t.data):t.data}))}}var kg=4;function bc(r,t={}){let e=new Be({concurrency:t.queryConcurrency??kg});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),Qo(o.types).forEach(a=>{s.append("type",zt[a])}),o.onProgress?.(new ut("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=Jo(await a.json());return o.onProgress?.(new ut("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Uf(){return[bc("https://cloudflare-dns.com/dns-query"),bc("https://dns.google/resolve")]}var zf=un(qf(),1);var wc=class{lru;constructor(t){this.lru=(0,zf.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 Jo({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:zt[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??yc)*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 Vf(r){return new wc(r)}var Rg=1e3,ts=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=Vf(t.cacheSize??Rg),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["."]=Uf())}async query(t,e={}){let n=Qo(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new ut("dns:cache",{detail:o})),o;let s=`${t.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(e.signal?.aborted===!0)break;try{let u=await c(t,{...e,types:n});for(let l of u.Answer)this.cache.add(t,l);return u}catch(u){a.push(u),e.onProgress?.(new ut("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var zt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(zt||(zt={}));function $f(r={}){return new ts(r)}var es=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=t,s+=l,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Hf=45,Mg=15,zr=new es;function rs(r){if(!(r.length>Mg))return zr.new(r).parseWith(()=>zr.readIPv4Addr())}function ns(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hf))return zr.new(r).parseWith(()=>zr.readIPv6Addr())}function tr(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Hf)return;let e=zr.new(r).parseWith(()=>zr.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 Gf(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 Wf(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 xc(r){switch(r.length){case er:return r.join(".");case rr:{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 Xf(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 jf(r){let t="0x";for(let e of r)t+=(e>>4).toString(16)+(e&15).toString(16);return t}var er=4,rr=16,Wv=parseInt("0xFFFF",16),Ng=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Vn(r,t){t.length===rr&&r.length===er&&Gf(t,0,11)&&(t=t.slice(12)),t.length===er&&r.length===rr&&Wf(r,Ng,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 Zf(r,t){if(typeof t=="string"&&(t=tr(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 vc(r){let[t,e]=r.split("/");if(!t||!e)throw new Error("Failed to parse given CIDR: "+r);let n=er,o=rs(t);if(o==null&&(n=rr,o=ns(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=Ec(s,8*n);return{network:Vn(o,i),mask:i}}function Ec(r,t){if(t!==8*er&&t!==8*rr)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 Vr=class{constructor(t,e){if(e==null)({network:this.network,mask:this.mask}=vc(t));else{let n=tr(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=tr(e);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=Ec(o,8*n.length);this.network=Vn(n,this.mask)}}contains(t){return Zf({network:this.network,mask:this.mask},t)}toString(){let t=Xf(this.mask),e=t!==-1?String(t):jf(this.mask);return xc(this.network)+"/"+e}};function Jt(r){return!!rs(r)}function $r(r){return!!ns(r)}function os(r){return!!tr(r)}var Yf=Jt,Bg=$r,Sc=function(r){let t=0;if(r=r.toString().trim(),Yf(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Bg(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Yf(e[n]),i;s&&(i=Sc(e[n]),e[n]=B(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,B(i.slice(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++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},Qf=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Hr={},Ac={},Fg=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];Fg.forEach(r=>{let t=Ug(...r);Ac[t.code]=t,Hr[t.name]=t});function Ug(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function $(r){if(typeof r=="number"){if(Ac[r]!=null)return Ac[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Hr[r]!=null)return Hr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var Kg=$("ip4"),qg=$("ip6"),zg=$("ipcidr");function Tc(r,t){switch($(r).code){case 4:case 41:return $g(t);case 42:return Cc(t);case 43:return B(t,"base10");case 6:case 273:case 33:case 132:return ed(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Cc(t);case 421:return Xg(t);case 444:return td(t);case 445:return td(t);case 466:return Wg(t);case 481:return globalThis.encodeURIComponent(Cc(t));default:return B(t,"base16")}}function Pc(r,t){switch($(r).code){case 4:return Jf(t);case 41:return Jf(t);case 42:return Ic(t);case 43:return k(t,"base10");case 6:case 273:case 33:case 132:return Dc(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ic(t);case 421:return Hg(t);case 444:return jg(t);case 445:return Zg(t);case 466:return Gg(t);case 481:return Ic(globalThis.decodeURIComponent(t));default:return k(t,"base16")}}function Lc(r){let t,e;if(r.stringTuples().forEach(([n,o])=>{(n===Kg.code||n===qg.code)&&(e=o),n===zg.code&&(t=o)}),t==null||e==null)throw new Error("Invalid multiaddr");return new Vr(e,t)}var _c=Object.values(An).map(r=>r.decoder),Vg=function(){let r=_c[0].or(_c[1]);return _c.slice(2).forEach(t=>r=r.or(t)),r}();function Jf(r){if(!os(r))throw new Error("invalid ip address");return Sc(r)}function $g(r){let t=Qf(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!os(t))throw new Error("invalid ip address");return t}function Dc(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function ed(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ic(r){let t=k(r),e=Uint8Array.from(At(t.length));return Rt([e,t],e.length+t.length)}function Cc(r){let t=Yt(r);if(r=r.slice(ft(t)),r.length!==t)throw new Error("inconsistent lengths");return B(r)}function Hg(r){let t;r[0]==="Q"||r[0]==="1"?t=Kt(G.decode(`z${r}`)).bytes:t=ht.parse(r).multihash.bytes;let e=Uint8Array.from(At(t.length));return Rt([e,t],e.length+t.length)}function Gg(r){let t=Vg.decode(r),e=Uint8Array.from(At(t.length));return Rt([e,t],e.length+t.length)}function Wg(r){let t=Yt(r),e=r.slice(ft(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+B(e,"base64url")}function Xg(r){let t=Yt(r),e=r.slice(ft(t));if(e.length!==t)throw new Error("inconsistent lengths");return B(e,"base58btc")}function jg(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=Ut.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=Dc(n);return Rt([e,o],e.length+o.length)}function Zg(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=Ut.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=Dc(n);return Rt([e,o],e.length+o.length)}function td(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=B(t,"base32"),o=ed(e);return`${n}:${o}`}function rd(r){r=kc(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=$(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new ss("invalid address: "+r);if(a.path===!0){n=kc(o.slice(s).join("/")),t.push([a.code,Pc(a.code,n)]),e.push([a.code,n]);break}let c=Pc(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Tc(a.code,c)])}return{string:nd(e),bytes:is(t),tuples:t,stringTuples:e,path:n}}function Rc(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Yt(r,o),i=ft(s),a=$(s),c=Yg(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let u=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw new ss("Invalid address Uint8Array: "+B(r,"base16"));t.push([s,u]);let l=Tc(s,u);if(e.push([s,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:nd(e),tuples:t,stringTuples:e,path:n}}function nd(r){let t=[];return r.map(e=>{let n=$(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),kc(t.join("/"))}function is(r){return Rt(r.map(t=>{let e=$(t[0]),n=Uint8Array.from(At(e.code));return t.length>1&&t[1]!=null&&(n=Rt([n,t[1]])),n}))}function Yg(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Yt(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ft(e)}}function kc(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var ss=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var Qg=Symbol.for("nodejs.util.inspect.custom"),Nc=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Jg=[$("dns").code,$("dns4").code,$("dns6").code,$("dnsaddr").code],Mc=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},as=class r{bytes;#t;#e;#s;#a;[Nc]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Rc(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=rd(t)}else if(Oe(t))e=Rc(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#s=e.stringTuples,this.#a=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=$("tcp"),a=$("udp"),c=$("ip4"),u=$("ip6"),l=$("dns6"),f=$("ip6zone");for(let[m,p]of this.stringTuples())m===f.code&&(s=`%${p??""}`),Jg.includes(m)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${p??""}${s}`,t=m===l.code?6:4),(m===i.code||m===a.code)&&(e=$(m).name==="tcp"?"tcp":"udp",o=parseInt(p??"")),(m===c.code||m===u.code)&&(e=$(m).name==="tcp"?"tcp":"udp",n=`${p??""}${s}`,t=m===u.code?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}}protos(){return this.#e.map(([t])=>Object.assign({},$(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>$(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#s.map(([t,e])=>e==null?[t]:[t,e])}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(is(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Hr.p2p.code&&t.push([n,o]),n===Hr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?B(G.decode(`z${n}`),"base58btc"):B(ht.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#a}equals(t){return at(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Gr.get(e.name);if(n==null)throw new Mc(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>W(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(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Qg](){return`Multiaddr(${this.#t})`}};var Gr=new Map;function Oe(r){return!!r?.[Nc]}function W(r){return new as(r)}var t0=32,{code:e0}=$("dnsaddr"),Bc=class extends Error{constructor(t="Max recursive depth reached"){super(t),this.name="RecursionLimitError"}},nr=async function(t,e={}){let n=e.maxRecursiveDepth??t0;if(n===0)throw new Bc("Max recursive depth reached");let[,o]=t.stringTuples().find(([u])=>u===e0)??[],i=await(e?.dns??$f()).query(`_dnsaddr.${o}`,{signal:e?.signal,types:[zt.TXT]}),a=t.getPeerId(),c=[];for(let u of i.Answer){let l=u.data.replace(/["']/g,"").trim().split("=")[1];if(l==null||a!=null&&!l.includes(a))continue;let f=W(l);if(l.startsWith("/dnsaddr")){let d=await f.resolve({...e,maxRecursiveDepth:n-1});c.push(...d.map(m=>m.toString()))}else c.push(f.toString())}return c};var dd=un(fd(),1),us=dd.default;var a0={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:nr}},transportManager:{faultTolerance:Ve.FATAL_ALL}};async function hd(r){let t=us(a0,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 c0(r,t){try{if(typeof r=="string"&&r.length>0)return l0(r);if(typeof r=="number"&&isFinite(r))return t?.long?f0(r):u0(r);throw new Error("Value is not a string or number.")}catch(e){let n=d0(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function l0(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 ds=c0;function u0(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 f0(r){let t=Math.abs(r);return t>=864e5?fs(r,t,864e5,"day"):t>=36e5?fs(r,t,36e5,"hour"):t>=6e4?fs(r,t,6e4,"minute"):t>=1e3?fs(r,t,1e3,"second"):`${r} ms`}function fs(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function d0(r){return typeof r=="object"&&r!==null&&"message"in r}function Fc(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=ds,e.destroy=u,Object.keys(r).forEach(l=>{e[l]=r[l]}),e.names=[],e.skips=[],e.formatters={};function t(l){let f=0;for(let d=0;d<l.length;d++)f=(f<<5)-f+l.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(l){let f,d=null,m,p;function g(...h){if(!g.enabled)return;let b=g,x=Number(new Date),y=x-(f||x);b.diff=y,b.prev=f,b.curr=x,f=x,h[0]=e.coerce(h[0]),typeof h[0]!="string"&&h.unshift("%O");let E=0;h[0]=h[0].replace(/%([a-zA-Z%])/g,(L,I)=>{if(L==="%%")return"%";E++;let P=e.formatters[I];if(typeof P=="function"){let T=h[E];L=P.call(b,T),h.splice(E,1),E--}return L}),e.formatArgs.call(b,h),(b.log||e.log).apply(b,h)}return g.namespace=l,g.useColors=e.useColors(),g.color=e.selectColor(l),g.extend=n,g.destroy=e.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(m!==e.namespaces&&(m=e.namespaces,p=e.enabled(l)),p),set:h=>{d=h}}),typeof e.init=="function"&&e.init(g),g}function n(l,f){let d=e(this.namespace+(typeof f>"u"?":":f)+l);return d.log=this.log,d}function o(l){e.save(l),e.namespaces=l,e.names=[],e.skips=[];let f,d=(typeof l=="string"?l:"").split(/[\s,]+/),m=d.length;for(f=0;f<m;f++)d[f]&&(l=d[f].replace(/\*/g,".*?"),l[0]==="-"?e.skips.push(new RegExp("^"+l.substr(1)+"$")):e.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(l))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.setupFormatters(e.formatters),e.enable(e.load()),e}var hs=w0(),h0=["#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 p0(){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 m0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+ds(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 g0=console.debug??console.log??(()=>{});function y0(r){try{r?hs?.setItem("debug",r):hs?.removeItem("debug")}catch{}}function b0(){let r;try{r=hs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function w0(){try{return localStorage}catch{}}function x0(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var pd=Fc({formatArgs:m0,save:y0,load:b0,useColors:p0,setupFormatters:x0,colors:h0,storage:hs,log:g0});var Ft=pd;Ft.formatters.b=r=>r==null?"undefined":G.baseEncode(r);Ft.formatters.t=r=>r==null?"undefined":Ut.baseEncode(r);Ft.formatters.m=r=>r==null?"undefined":Ra.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":md(r.stack)??md(r.message)??r.toString();function v0(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 ps(){return{forComponent(r){return E0(r)}}}function E0(r){let t=v0(`${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})}function md(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}function or(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 ms(r){let t=Kt(G.decode(`z${r}`));return qr(t)}var be=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 or(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 or(this.map.values(),t=>t.key)}values(){return or(this.map.values(),t=>t.value)}get size(){return this.map.size}};var sr=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 or(this.set.entries(),t=>{let e=ms(t[0]);return[e,e]})}forEach(t){this.set.forEach(e=>{let n=ms(e);t(n,n,this)})}has(t){return this.set.has(t.toString())}values(){return or(this.set.values(),t=>ms(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 Uc={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},gd={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},yd=new globalThis.TextEncoder;function S0(r,t){let e=Uc[t],n=gd[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function A0(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Uc[t],o=gd[t],s=r;for(;s.length>0;){let i=yd.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 Kc(r,{size:t=32,utf8Buffer:e}={}){if(!Uc[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 A0(r,t,e);r=yd.encode(r)}return S0(r,t)}var $n={hash:r=>Number(Kc(r,{size:32})),hashV:(r,t)=>_0($n.hash(r,t))};function _0(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),k(t,"base16")}var qc=64,te=class{fp;h;seed;constructor(t,e,n,o=2){if(o>qc)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?at(this.fp,t.fp):!1}};function ir(r,t){return Math.floor(Math.random()*(t-r))+r}var ar=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof te))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof te))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 te))throw new TypeError("Invalid Fingerprint");let e=ir(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof te))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var I0=500,Hn=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??$n,this.seed=t.seed??ir(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=k(t));let e=new te(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 ar(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new ar(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[ir(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new ar(this.bucketSize));for(let a=0;a<I0;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 ar(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=k(t));let e=new te(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=k(t));let e=new te(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}},C0={1:.5,2:.84,4:.95,8:.98};function T0(r=.001){return r>.002?2:r>1e-5?4:8}function bd(r,t=.001){let e=T0(t),n=C0[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),qc);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var gs=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??$n,this.seed=t.seed??ir(0,Math.pow(2,10)),this.filterSeries=[new Hn({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=k(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 Hn({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=k(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=k(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 Gn(r,t=.001,e){return new gs({...bd(r,t),...e??{}})}var Wn;(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=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(e,r.codec(),n)})(Wn||(Wn={}));var ys=class extends Error{constructor(t="Invalid signature"){super(t),this.name="InvalidSignatureError"}};var jr=class r{static createFromProtobuf=async t=>{let e=Wn.decode(t),n=Kr(e.publicKey);return new r({publicKey:n,payloadType:e.payloadType,payload:e.payload,signature:e.signature})};static seal=async(t,e)=>{if(e==null)throw new Error("Missing private key");let n=t.domain,o=t.codec,s=t.marshal(),i=wd(n,o,s),a=await e.sign(i.subarray());return new r({publicKey:e.publicKey,payloadType:o,payload:s,signature:a})};static openAndCertify=async(t,e)=>{let n=await r.createFromProtobuf(t);if(!await n.validate(e))throw new ys("Envelope signature is not valid for the given domain");return n};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=Wn.encode({publicKey:oe(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(t){return at(this.marshal(),t.marshal())}async validate(t){let e=wd(t,this.payloadType,this.payload);return this.publicKey.verify(e.subarray(),this.signature)}},wd=(r,t,e)=>{let n=k(r),o=At(n.byteLength),s=At(t.length),i=At(e.length);return new Q(o,n,s,t,i,e)};function xd(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 vd="libp2p-peer-record",Ed=Uint8Array.from([3,1]);var Xn;(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)},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(l&7);break}}}return c})),o),n.encode=s=>Dt(s,n.codec()),n.decode=(s,i)=>Lt(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 Je('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),e),r.encode=n=>Dt(n,r.codec()),r.decode=(n,o)=>Lt(n,r.codec(),o)})(Xn||(Xn={}));var cr=class r{static createFromProtobuf=t=>{let e=Xn.decode(t),n=qr(Kt(e.peerId)),o=(e.addresses??[]).map(i=>W(i.multiaddr)),s=e.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=vd;static CODEC=Ed;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=Xn.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||!xd(this.multiaddrs,t.multiaddrs))}};function P0(r){return r[Symbol.asyncIterator]!=null}function L0(r){if(P0(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 jn=L0;var Fe={},Zr=r=>{r.addEventListener("message",t=>{Zr.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{Zr.dispatchEvent("message",r,t)})};Zr.addEventListener=(r,t)=>{Fe[r]==null&&(Fe[r]=[]),Fe[r].push(t)};Zr.removeEventListener=(r,t)=>{Fe[r]!=null&&(Fe[r]=Fe[r].filter(e=>e===t))};Zr.dispatchEvent=function(r,t,e){Fe[r]!=null&&Fe[r].forEach(n=>n(t,e))};var zc=Zr;var Vc="lock:worker:request-read",$c="lock:worker:release-read",Hc="lock:master:grant-read",Gc="lock:worker:request-write",Wc="lock:worker:release-write",Xc="lock:master:grant-write";var Sd=(r=21)=>Math.random().toString().substring(2);var Ad=(r,t,e,n,o)=>(s,i)=>{if(i.data.type!==e)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l?.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(s.removeEventListener("message",u),c())};s.addEventListener("message",u)})}}}))},_d=(r,t,e,n)=>async()=>{let o=Sd();return globalThis.postMessage({type:t,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===e&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},D0={singleProcess:!1},Id=r=>{if(r=Object.assign({},D0,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return zc.addEventListener("message",Ad(e,"requestReadLock",Vc,$c,Hc)),zc.addEventListener("message",Ad(e,"requestWriteLock",Gc,Wc,Xc)),e}return{isWorker:!0,readLock:e=>_d(e,Vc,Hc,$c),writeLock:e=>_d(e,Gc,Xc,Wc)}};var lr={},Ue;async function jc(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>qn((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var k0=(r,t)=>{if(Ue.isWorker===!0)return{readLock:Ue.readLock(r,t),writeLock:Ue.writeLock(r,t)};let e=new Be({concurrency:1}),n;return{async readLock(){if(n!=null)return jc(n,t);n=new Be({concurrency:t.concurrency,autoStart:!1});let o=n,s=jc(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,jc(e,t)}}},R0={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Zc(r){let t=Object.assign({},R0,r);return Ue==null&&(Ue=Id(t),Ue.isWorker!==!0&&(Ue.addEventListener("requestReadLock",e=>{lr[e.data.name]!=null&&lr[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),Ue.addEventListener("requestWriteLock",async e=>{lr[e.data.name]!=null&&lr[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),lr[t.name]==null&&(lr[t.name]=k0(t.name,t)),lr[t.name]}var Yr;(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 u={key:"",value:ct(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.key=i.string();break}case 2:{u.value=i.bytes();break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Dt(i,o.codec()),o.decode=(i,a)=>Lt(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),ws.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let u={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let f=i.uint32();switch(f>>>3){case 1:{u.key=i.string();break}case 2:{u.value=ws.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return u})),s),o.encode=i=>Dt(i,o.codec()),o.decode=(i,a)=>Lt(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),bs.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);i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let u=o.uint32();switch(u>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new Je('Decode error - map field "addresses" had too many elements');a.addresses.push(bs.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 Je('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 Cn('Decode error - map field "metadata" had too many elements');let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(l.key,l.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new Cn('Decode error - map field "tags" had too many elements');let l=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(l.key,l.value);break}default:{o.skipType(u&7);break}}}return a})),n),r.encode=o=>Dt(o,r.codec()),r.decode=(o,s)=>Lt(o,r.codec(),s)})(Yr||(Yr={}));var bs;(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)),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}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(e,r.codec(),n)})(bs||(bs={}));var ws;(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=>Dt(e,r.codec()),r.decode=(e,n)=>Lt(e,r.codec(),n)})(ws||(ws={}));function M0(r,t){if(r.publicKey!=null||t.publicKey==null)return r;let e;if(r.type==="RSA"){let o=G.decode(`z${r}`);e=Kt(o)}let n=Kr(t.publicKey,e);return dc(n)}function Qr(r,t){let e=Yr.decode(t),n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:M0(r,e),addresses:e.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:W(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}var we="/",Cd=new TextEncoder().encode(we),xs=Cd[0],ur=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=k(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]!==xs)throw new Error("Invalid key")}toString(t="utf8"){return B(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(we))}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=Cd),this._buf[0]!==xs){let t=new Uint8Array(this._buf.byteLength+1);t.fill(xs,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===xs;)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(we).slice(1)}type(){return N0(this.baseNamespace())}name(){return B0(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(we)||(t+=we),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(we):new r(t.slice(0,-1).join(we))}child(t){return this.toString()===we?t:t.toString()===we?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(),...O0(t.map(e=>e.namespaces()))])}};function N0(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function B0(r){let t=r.split(":");return t[t.length-1]}function O0(r){return[].concat(...r)}var Yc="/peers/";function Jr(r){if(!po(r)||r.type==null)throw new R("Invalid PeerId");let t=r.toCID().toString();return new ur(`${Yc}${t}`)}async function Td(r,t,e){let n=new Map;for(let o of e){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=W(o.multiaddr)),!Oe(o.multiaddr))throw new R("Multiaddr was invalid");if(!await t(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function Es(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;if(o!=null&&!r.equals(o.id))throw new R("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,u=o?.peerRecordEnvelope;if(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=vs(d,{validate:Pd})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags);c=vs(d,{validate:Ld,map:Dd})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}if(e==="merge"){if(t.multiaddrs!=null&&s.push(...t.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),t.addresses!=null&&s.push(...t.addresses),t.protocols!=null&&(i=new Set([...i,...t.protocols])),t.metadata!=null){let d=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(let[m,p]of d)p==null?a.delete(m):a.set(m,p);a=vs([...a.entries()],{validate:Pd})}if(t.tags!=null){let d=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),m=new Map(c);for(let[p,g]of d)g==null?m.delete(p):m.set(p,g);c=vs([...m.entries()],{validate:Ld,map:Dd})}t.peerRecordEnvelope!=null&&(u=t.peerRecordEnvelope)}let l;o?.id.publicKey!=null?l=oe(o.id.publicKey):t.publicKey!=null?l=oe(t.publicKey):r.publicKey!=null&&(l=oe(r.publicKey));let f={addresses:await Td(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((d,m)=>d.localeCompare(m)),metadata:a,tags:c,publicKey:l,peerRecordEnvelope:u};return r.type!=="RSA"&&delete f.publicKey,f}function vs(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 Pd(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 Ld(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 Dd(r,t){let e;return t.expiry!=null&&(e=t.expiry),t.ttl!=null&&(e=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:e}}function Ss(r,t){let e=r.toString().split("/")[2],n=ht.parse(e,Ut),o=Zo(n);return Qr(o,t)}function F0(r){return r==null?{}:{prefix:Yc,filters:(r.filters??[]).map(t=>({key:e,value:n})=>t(Ss(e,n))),orders:(r.orders??[]).map(t=>(e,n)=>t(Ss(e.key,e.value),Ss(n.key,n.value)))}}var As=class{peerId;datastore;lock;addressFilter;log;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=e.addressFilter,this.lock=Zc({name:"peer-store",singleProcess:!0})}async has(t){return this.datastore.has(Jr(t))}async delete(t){if(this.peerId.equals(t))throw new R("Cannot delete self peer");await this.datastore.delete(Jr(t))}async load(t){let e=await this.datastore.get(Jr(t));return Qr(t,e)}async save(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Es(t,e,"patch",{addressFilter:this.addressFilter});return this.#e(t,s,n,o)}async patch(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Es(t,e,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async merge(t,e){let{existingBuf:n,existingPeer:o}=await this.#t(t),s=await Es(t,e,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#e(t,s,n,o)}async*all(t){for await(let{key:e,value:n}of this.datastore.query(F0(t??{}))){let o=Ss(e,n);o.id.equals(this.peerId)||(yield o)}}async#t(t){try{let e=await this.datastore.get(Jr(t)),n=Qr(t,e);return{existingBuf:e,existingPeer:n}}catch(e){e.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",e)}return{}}async#e(t,e,n,o){let s=Yr.encode(e);return n!=null&&at(s,n)?{peer:Qr(t,s),previous:o,updated:!1}:(await this.datastore.put(Jr(t),s),{peer:Qr(t,s),previous:o,updated:!0})}};var Qc=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 As(t,e)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(t,e){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(e))t(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(t){this.log.trace("all await read lock");let e=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await jn(this.store.all(t))}finally{this.log.trace("all release read lock"),e()}}async delete(t){this.log.trace("delete await write lock");let e=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(t)}finally{this.log.trace("delete release write lock"),e()}}async has(t){this.log.trace("has await read lock");let e=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(t)}finally{this.log.trace("has release read lock"),e()}}async get(t){this.log.trace("get await read lock");let e=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(t)}finally{this.log.trace("get release read lock"),e()}}async save(t,e){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(t,e){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(t,e){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(t,e);return this.#t(t,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(t,e){let n=await jr.openAndCertify(t,cr.DOMAIN),o=Zo(n.publicKey.toCID());if(e?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",e,o),!1;let s=cr.createFromProtobuf(n.payload),i;try{i=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(i?.peerRecordEnvelope!=null){let a=await jr.createFromProtobuf(i.peerRecordEnvelope),c=cr.createFromProtobuf(a.payload);if(c.seqNumber>=s.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return await this.patch(s.peerId,{peerRecordEnvelope:t,addresses:s.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!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 kd(r,t={}){return new Qc(r,t)}var _s=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 U0(r){return r[Symbol.asyncIterator]!=null}function K0(r){if(U0(r))return(async()=>{for await(let t of r);})();for(let t of r);}var Jc=K0;function q0(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 Rd=q0;function z0(r){return r[Symbol.asyncIterator]!=null}function V0(r,t){let e=0;if(z0(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Rd(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 await(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 fr=V0;function $0(r){return r[Symbol.asyncIterator]!=null}function H0(r,t){return $0(r)?async function*(){yield*(await jn(r)).sort(t)}():function*(){yield*jn(r).sort(t)}()}var tl=H0;function G0(r){return r[Symbol.asyncIterator]!=null}function W0(r,t){return G0(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 el=W0;var Is=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 Jc(this.putMany(t,n)),t=[],await Jc(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=fr(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>fr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>tl(o,s),n)),t.offset!=null){let o=0,s=t.offset;n=fr(n,()=>o++>=s)}return t.limit!=null&&(n=el(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=fr(n,s=>s.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,s)=>fr(o,s),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,s)=>tl(o,s),n)),t.offset!=null){let o=t.offset,s=0;n=fr(n,()=>s++>=o)}return t.limit!=null&&(n=el(n,t.limit)),n}};var Cs=class extends Is{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new _s;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new ur(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new ur(t)}};function Md(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 Bd=un(Nd(),1),X0=["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"],j0=X0.map(r=>new Bd.Netmask(r));function rl(r){for(let t of j0)if(t.contains(r))return!0;return!1}function Z0(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Y0(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 rl(o)}function Q0(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function J0(r){let t=r.split(":"),e=t[t.length-1];return rl(e)}function ty(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 Ke(r){return Jt(r)?rl(r):Z0(r)?Y0(r):Q0(r)?J0(r):$r(r)?ty(r):void 0}var ey=r=>r.toString().split("/").slice(1),tn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>tn(e=>e===r).match(t),pattern:r}),dr=()=>({match:r=>tn(t=>typeof t=="string").match(r),pattern:"{string}"}),Yn=()=>({match:r=>tn(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),J=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{G.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Qn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ma.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),X=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),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},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),V=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function st(...r){function t(o){let s=ey(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var Ps=V(z("dns4"),dr()),Ls=V(z("dns6"),dr()),Ds=V(z("dnsaddr"),dr()),ol=V(z("dns"),dr()),e3=st(Ps,X(J())),r3=st(Ls,X(J())),n3=st(Ds,X(J())),o3=st(Ct(ol,Ds,Ps,Ls),X(J())),Od=V(z("ip4"),tn(Jt)),Fd=V(z("ip6"),tn($r)),sl=Ct(Od,Fd),xe=Ct(sl,ol,Ps,Ls,Ds),s3=st(Ct(sl,V(Ct(ol,Ds,Ps,Ls),X(J())))),il=st(Od),al=st(Fd),i3=st(sl),cl=V(xe,z("tcp"),Yn()),Jn=V(xe,z("udp"),Yn()),to=st(V(cl,X(J()))),a3=st(Jn),ll=V(Jn,z("quic"),X(J())),ks=V(Jn,z("quic-v1"),X(J())),ry=Ct(ll,ks),c3=st(ll),Ud=st(ks),nl=Ct(xe,cl,Jn,ll,ks),Kd=Ct(V(nl,z("ws"),X(J()))),hr=st(Kd),qd=Ct(V(nl,z("wss"),X(J())),V(nl,z("tls"),X(V(z("sni"),dr())),z("ws"),X(J()))),eo=st(qd),zd=V(Jn,z("webrtc-direct"),X(Qn()),X(Qn()),X(J())),ul=st(zd),Vd=V(ks,z("webtransport"),X(Qn()),X(Qn()),X(J())),fl=st(Vd),Ts=Ct(Kd,qd,V(cl,X(J())),V(ry,X(J())),V(xe,X(J())),zd,Vd,J()),l3=st(Ts),ny=V(Ts,z("p2p-circuit"),J()),ro=st(ny),oy=Ct(V(Ts,z("p2p-circuit"),z("webrtc"),X(J())),V(Ts,z("webrtc"),X(J())),V(z("webrtc"),X(J()))),dl=st(oy),sy=Ct(V(xe,z("tcp"),Yn(),z("http"),X(J())),V(xe,z("http"),X(J()))),u3=st(sy),iy=Ct(V(xe,z("tcp"),Ct(V(z("443"),z("http")),V(Yn(),z("https"))),X(J())),V(xe,z("tls"),z("http"),X(J())),V(xe,z("https"),X(J()))),f3=st(iy),ay=Ct(V(z("memory"),dr(),X(J()))),d3=st(ay);var $d=864e13;var cy=448,hl=449,ly=53,uy=54,fy=55,dy=56,Rs=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}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=Ke(n)===!0;this.mappings.set(n,{domain:t,verified:o,expires:o?$d-Date.now():0,lastVerified:o?$d-Date.now():void 0})})}remove(t){let e=this.findHost(t),n=!1;for(let[o,s]of this.mappings.entries())s.domain===e&&(this.log("removing %s to %s DNS mapping %e",o,s.domain,new Error("where")),this.mappings.delete(o),n=n||s.verified);return n}getAll(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n].multiaddr.stringTuples(),i=s[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(s,c.domain)&&(t.splice(n,1),n--,e.push({multiaddr:W(`/${s.map(l=>[$(l[0]).name,l[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return e}maybeAddSNITuple(t,e){for(let n=0;n<t.length;n++)if(t[n][0]===cy&&t[n+1]?.[0]!==hl)return t.splice(n+1,0,[hl,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]===hl||e[0]===ly||e[0]===uy||e[0]===fy||e[0]===dy)return e[1]}};var pl=4,ml=41,gl=6,hy=273,Ms=class{log;mappings;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}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:Jt(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]===gl?"tcp":"udp",s=parseInt(e[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let u=0;u<c.length;u++){let l=c[u];l.externalIp===n&&l.externalPort===s&&l.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",l.externalIp,l.externalPort,n,s,o),i=i||l.verified,c.splice(u,1),u--)}c.length===0&&this.mappings.delete(a)}return i}getAll(t){let e=[];for(let{multiaddr:n}of t){let o=n.stringTuples(),s;if((o[0][0]===pl||o[0][0]===ml)&&o[1][0]===gl?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===pl||o[0][0]===ml)&&o[1][0]===hy&&(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?pl:ml,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,e.push({multiaddr:W(`/${o.map(c=>[$(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]===gl?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let u=0;u<c.length;u++){let l=c[u];l.externalIp===o&&l.externalPort===i&&l.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",l.externalIp,l.externalPort,o,i,s),a=a||l.verified,l.verified=!1,l.expires=Date.now()+e)}return a}};function Hd(r){try{let[[t,e]]=r.stringTuples();if(e==null)return!1;if(t===4)return e.startsWith("169.254.");if(t===41)return e.toLowerCase().startsWith("fe80")}catch{}return!1}function Ns(r){try{let[[t]]=r.stringTuples();return t===4||t===41}catch{}return!1}function pr(r){try{if(!Ns(r))return!1;let[[,t]]=r.stringTuples();return t==null?!1:Ke(t)??!1}catch{}return!0}var py={maxObservedAddresses:10},Bs=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=e.maxObservedAddresses??py.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&&(pr(t)||Hd(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:W(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 my=[4,41,53,54,55,56];function yl(r){try{let[[t]]=r.stringTuples();return my.includes(t)}catch{}return!1}var gy={maxObservedAddresses:10},Os=class{log;addresses;maxObservedAddresses;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=e.maxObservedAddresses??gy.maxObservedAddresses}get(t,e){if(pr(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:!yl(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(yl(t)){let e=t.toOptions();return`${e.host}-${e.port}-${e.transport}`}return t.toString()}};var Gd=6e4,Wd={maxObservedAddresses:10,addressVerificationTTL:Gd*10,addressVerificationRetry:Gd*5},yy=r=>r;function bl(r,t){let e=r.getPeerId();return e!=null&&ie(e).equals(t)&&(r=r.decapsulate(W(`/p2p/${t.toString()}`))),r}var Fs=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 Bs(t,e),this.dnsMappings=new Rs(t,e),this.ipMappings=new Ms(t,e),this.transportAddresses=new Os(t,e),this.announceFilter=e.announceFilter??yy,this.observedAddressFilter=Gn(1024),this.addressVerificationTTL=e.addressVerificationTTL??Wd.addressVerificationTTL,this.addressVerificationRetry=e.addressVerificationRetry??Wd.addressVerificationRetry,this._updatePeerStoreAddresses=Md(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=>W(t))}getAnnounceAddrs(){return Array.from(this.announce).map(t=>W(t))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(t=>W(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=bl(t,this.components.peerId),!this.ipMappings.has(t)&&(this.dnsMappings.has(t)||this.observed.add(t)))}confirmObservedAddr(t,e){t=bl(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=bl(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=W(n);return o.protos().pop()?.path===!0||o.getPeerId()===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(n=>{n.updateAnnounceAddrs(t)}),t.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let e=[];return e=e.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL))),e=e.concat(this.getAppendAnnounceAddrs().map(n=>({multiaddr:n,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(W(`/dns/${t}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.add(t,e,n,o,s),this.observed.removePrefixed(`/ip${Jt(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(t,e,n,o=e,s="tcp"){this.ipMappings.remove(W(`/ip${Jt(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"||Ke(e.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>hr.exactMatch(s)||eo.exactMatch(s),s=>to.exactMatch(s),s=>Ud.exactMatch(s)];for(let s of o){if(!s(t))continue;let i=n.filter(u=>u.getAddrs().filter(l=>l.toOptions().family===4&&s(l)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(u=>u.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(t),this.ipMappings.add(c.host,c.port,e.host,e.port,e.transport),!0}return!1}};var Xd;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Xd||(Xd={}));var Us=class extends Error{constructor(t="Missing service"){super(t),this.name="MissingServiceError"}},Ks=class extends Error{constructor(t="Unmet service dependencies"){super(t),this.name="UnmetServiceDependenciesError"}},en=class extends Error{constructor(t="No content routers available"){super(t),this.name="NoContentRoutersError"}},no=class extends Error{constructor(t="No peer routers available"){super(t),this.name="NoPeerRoutersError"}},qs=class extends Error{constructor(t="Should not try to find self"){super(t),this.name="QueriedForSelfError"}},zs=class extends Error{constructor(t="Unhandled protocol error"){super(t),this.name="UnhandledProtocolError"}},Vs=class extends Error{constructor(t="Duplicate protocol handler error"){super(t),this.name="DuplicateProtocolHandlerError"}},oo=class extends Error{constructor(t="Dial denied error"){super(t),this.name="DialDeniedError"}},$s=class extends Error{constructor(t="No transport was configured to listen on this address"){super(t),this.name="UnsupportedListenAddressError"}},Hs=class extends Error{constructor(t="Configured listen addresses could not be listened on"){super(t),this.name="UnsupportedListenAddressesError"}},Gs=class extends Error{constructor(t="No valid addresses"){super(t),this.name="NoValidAddressesError"}},Ws=class extends Error{constructor(t="Connection intercepted"){super(t),this.name="ConnectionInterceptedError"}},Xs=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"}},gr=class extends Error{constructor(t="Encryption failed"){super(t),this.name="EncryptionFailedError"}},js=class extends Error{constructor(t="Transport unavailable"){super(t),this.name="TransportUnavailableError"}};var wl=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=ps())}isStarted(){return this._started}async _invokeStartableMethod(t){await Promise.all(Object.values(this.components).filter(e=>So(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")}},wy=["metrics","connectionProtector","dns"],xy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function jd(r={}){let t=new wl(r);return new Proxy(t,{get(n,o,s){if(typeof o=="string"&&!xy.includes(o)){let i=t.components[o];if(i==null&&!wy.includes(o))throw new Us(`${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 Zd(r){let t={};for(let e of Object.values(r.components))for(let n of vy(e))t[n]=!0;for(let e of Object.values(r.components))for(let n of Ey(e))if(t[n]!==!0)throw new Ks(`Service "${Sy(e)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function vy(r){return Array.isArray(r?.[hn])?r[hn]:[]}function Ey(r){return Array.isArray(r?.[zi])?r[zi]:[]}function Sy(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var Ay=4,_y=41;function Yd(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async t=>{if(hr.matches(t))return!1;let e=t.stringTuples();return e[0][0]===Ay||e[0][0]===_y?!!Ke(`${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 Qd=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Iy=new WeakMap;function Cy({clearTimeout:r,setTimeout:t}={}){return(e,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Qd());let s,i,a,c=r??clearTimeout,u=()=>{c(s),a(Qd())},l=()=>{o&&o.removeEventListener("abort",u)},f=new Promise((d,m)=>{i=()=>{l(),d(n)},a=m,s=(t??setTimeout)(i,e)});return o&&o.addEventListener("abort",u,{once:!0}),Iy.set(f,()=>{c(s),s=null,i()}),f}}var Ty=Cy(),Jd=Ty;var Zs=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}},Ys=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Qs=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 xl}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 Zs("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 Jd(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)}},xl=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 Js(r){if(po(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let t;if(r.length>0){let e=r[0].getPeerId();t=e==null?void 0:ie(e),r.forEach(n=>{if(!Oe(n))throw new Se("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(t!=null)throw new R("Multiaddrs must all have the same peer id or have no peer id")}else{let s=ie(o);if(t?.equals(s)!==!0)throw new R("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:t,multiaddrs:r}}var Py=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function th(r,t){let e=r?.streams?.map(o=>o.protocol)??[],n=t?.closableProtocols??Py;if(!(e.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(t)}catch(o){r?.abort(o)}}var eh="last-dial-failure",rh="last-dial-success";var ti=100,ei=50;async function nh(r,t){let e=!1;for(let o of Gr.keys())if(e=r.protoNames().includes(o),e)break;if(!e)return[r];let n=await r.resolve(t);return t.log("resolved %s to",r,n.map(o=>o.toString())),n}function so(r){try{let t;if(typeof r=="string"?t=W(r):t=r,!t.protoNames().includes("ipcidr")){let n=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(n)}return Lc(t)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var Ly={maxConnections:ti,allow:[]},ri=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(t,e={}){this.maxConnections=e.maxConnections??Ly.maxConnections,this.allow=(e.allow??[]).map(n=>so(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;if(this.log("checking max connections limit %d/%d",e,this.maxConnections),e<=this.maxConnections)return;let n=new be;for(let a of t){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let u=await this.peerStore.get(c);n.set(c,[...u.tags.values()].reduce((l,f)=>l+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(t,n),s=Math.max(e-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(u=>u.contains(a.remoteAddr.nodeAddress().address))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await th(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}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})}};function lt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ni=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}},rn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ni(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 ni(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 vl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function oi(r={}){return Dy(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 Dy(r,t){t=t??{};let e=t.onEnd,n=new rn,o,s,i,a=lt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(y){b(y)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=lt()})}},u=h=>s!=null?s(h):(n.push(h),o),l=h=>(n=new rn,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?l(h):u({done:!0})),m=()=>(n=new rn,d(),{done:!0}),p=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let x,y;b!=null&&(x=new Promise((E,_)=>{y=()=>{_(new vl)},b.addEventListener("abort",y)}));try{await Promise.race([a.promise,x])}finally{y!=null&&b!=null&&b?.removeEventListener("abort",y)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return g.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},o}var El=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function nn(r,t,e,n){let o=new El(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",l),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,u)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},u=f=>{a(),i(f.detail)},l=()=>{a(),i(o)};e?.addEventListener("abort",l),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,u)})}var si=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 qe(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new si(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new si(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 ii=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 Gt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ky(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ai=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=ky(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Gt),this.cleanup())}async join(t={}){let e=new ii(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 qe(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 sn=class extends le{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=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!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 Ys;let n=new ai(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Gt)}),this.clear()}async onEmpty(t){this.size!==0&&await nn(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await nn(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await nn(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=oi({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new Gt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};var ci=class extends sn{constructor(t={}){super({...t,sort:(e,n)=>e.options.priority>n.options.priority?-1:e.options.priority<n.options.priority?1:0})}};function ve(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 oh(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Sl(r){if(!Ns(r))return!1;let{address:t}=r.nodeAddress();return oh(t)}function Ry(r,t){let e=to.exactMatch(r.multiaddr),n=to.exactMatch(t.multiaddr);if(e&&!n)return-1;if(!e&&n)return 1;let o=eo.exactMatch(r.multiaddr),s=eo.exactMatch(t.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=hr.exactMatch(r.multiaddr),a=hr.exactMatch(t.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=dl.exactMatch(r.multiaddr),u=dl.exactMatch(t.multiaddr);if(c&&!u)return-1;if(!c&&u)return 1;let l=ul.exactMatch(r.multiaddr),f=ul.exactMatch(t.multiaddr);if(l&&!f)return-1;if(!l&&f)return 1;let d=fl.exactMatch(r.multiaddr),m=fl.exactMatch(t.multiaddr);return d&&!m?-1:!d&&m?1:0}function My(r,t){let e=Sl(r.multiaddr),n=Sl(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function Ny(r,t){let e=pr(r.multiaddr),n=pr(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function By(r,t){return r.isCertified&&!t.isCertified?-1:!r.isCertified&&t.isCertified?1:0}function Oy(r,t){let e=ro.exactMatch(r.multiaddr),n=ro.exactMatch(t.multiaddr);return e&&!n?1:!e&&n?-1:0}function sh(r){return r.sort(Ry).sort(By).sort(Oy).sort(Ny).sort(My)}var li={maxParallelDials:ei,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:nr}},ui=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(t,e={}){this.addressSorter=e.addressSorter,this.maxPeerAddrsToDial=e.maxPeerAddrsToDial??li.maxPeerAddrsToDial,this.maxDialQueueLength=e.maxDialQueueLength??li.maxDialQueueLength,this.dialTimeout=e.dialTimeout??li.dialTimeout,this.connections=e.connections??new be,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,this.shutDownController.signal;for(let[n,o]of Object.entries(e.resolvers??{}))Gr.set(n,o);this.queue=new ci({concurrency:e.maxParallelDials??li.maxParallelDials,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==Gt.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(t,e={}){let{peerId:n,multiaddrs:o}=Js(t),s=Array.from(this.connections.values()).flat().find(a=>e.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),e.onProgress?.(new ut("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let u of o)if(c.has(u.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return e.onProgress?.(new ut("dial-queue:already-in-dial-queue")),i.join(e)}if(this.queue.size>=this.maxDialQueueLength)throw new Sr("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),e.onProgress?.(new ut("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new ut("dial-queue:start-dial"));let c=ve([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:e.priority??Cl,multiaddrs:new Set(o.map(a=>a.toString())),signal:e.signal??AbortSignal.timeout(this.dialTimeout),onProgress:e.onProgress})}async dialPeer(t,e){let n=t.peerId,o=t.multiaddrs,s=new Set,i=t.multiaddrs.size===0,a=0,c=0,u=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let l=[],f=new Set(t.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...t,signal:e});for(let m of d){if(s.has(m.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",m.multiaddr,n);continue}l.push(m)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,l.map(m=>m.multiaddr.toString())),t?.onProgress?.(new ut("dial-queue:calculated-addresses",l));for(let m of l){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,t.peerId),new Sr("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(m.multiaddr,{...t,signal:e});this.log("dial to %a succeeded",m.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[rh]:k(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",m.multiaddr,p),s.add(m.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[eh]:k(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(e.aborted)throw new xo(p.message);u.push(p)}}}throw u.length===1?u[0]:new AggregateError(u,"All multiaddr dials failed")}async calculateMultiaddrs(t,e=new Set,n={}){let o=[...e].map(f=>({multiaddr:W(f),isCertified:!1}));if(t!=null){if(this.components.peerId.equals(t))throw new Sr("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(t)===!0)throw new oo("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",t);try{let f=await this.components.peerStore.get(t);o.push(...f.addresses),this.log("loaded multiaddrs for %p",t,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",t);try{let f=await this.components.peerRouting.findPeer(t,n);this.log("found multiaddrs for %p in the peer routing",t,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",t):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",t,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await nh(f.multiaddr,{dns:this.components.dns,...n,log:this.log});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(m=>({multiaddr:m,isCertified:!1}))}))).flat();if(t!=null){let f=`/p2p/${t.toString()}`;s=s.map(d=>d.multiaddr.protos().pop()?.path===!0?d:d.multiaddr.getPeerId()==null?{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(),m=a.get(d);if(m!=null){m.isCertified=m.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new Gs("The dial request has no valid addresses");let u=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||u.push(f);let l=this.addressSorter==null?sh(u):u.sort(this.addressSorter);if(l.length===0)throw new oo("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",t??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",t??"unknown peer",l.map(({multiaddr:f})=>f.toString())),l}async isDialable(t,e={}){Array.isArray(t)||(t=[t]);try{let n=await this.calculateMultiaddrs(void 0,new Set(t.map(o=>o.toString())),e);return e.runOnLimitedConnection===!1?n.find(o=>!ro.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var fi=class extends sn{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var dh=un(uh(),1);var Uy=Object.prototype.toString,Ky=r=>Uy.call(r)==="[object Error]",qy=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 Tl(r){return r&&Ky(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:qy.has(r.message):!1}var Pl=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}},fh=(r,t,e)=>{let n=e.retries-(t-1);return r.attemptNumber=t,r.retriesLeft=n,r};async function Ll(r,t){return new Promise((e,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;let o=dh.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 Pl)throw c.originalError;if(c instanceof TypeError&&!Tl(c))throw c;if(fh(c,a,t),await t.shouldRetry(c)||(o.stop(),n(c)),await t.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(u){fh(u,a,t),i(),n(u)}}})})}var di=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 fi({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);hh(e)&&(this.queue.has(t)||this.queue.add(async n=>{await Ll(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(qi)&&(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=>hh(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 hh(r){for(let t of r.tags.keys())if(t.startsWith(qi))return!0;return!1}var Cl=50,Dl={maxConnections:ti,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},hi=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??Dl.maxConnections,this.maxConnections<1)throw new R("Connection Manager maxConnections must be greater than 0");this.connections=new be,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=>so(n)),this.deny=(e.deny??[]).map(n=>so(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=e.maxIncomingPendingConnections??Dl.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Qs({points:e.inboundConnectionThreshold??Dl.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ri({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:e.allow?.map(n=>W(n))}),this.dialQueue=new ui(t,{addressSorter:e.addressSorter,maxParallelDials:e.maxParallelDials??ei,maxDialQueueLength:e.maxDialQueueLength??500,maxPeerAddrsToDial:e.maxPeerAddrsToDial??25,dialTimeout:e.dialTimeout??1e4,resolvers:e.resolvers??{dnsaddr:nr},connections:this.connections}),this.reconnectQueue=new di({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 Ql(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 Jl(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}onConnect(t){this._onConnect(t).catch(e=>{this.log.error(e)})}async _onConnect(t){let{detail:e}=t;if(!this.started){await e.close();return}if(e.status!=="open")return;let n=e.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(e),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:e.remotePeer})}onDisconnect(t){let{detail:e}=t,n=e.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==e.id);this.connections.set(n,s),s.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:e.remotePeer}))}getConnections(t){if(t!=null)return this.connections.get(t)??[];let e=[];for(let n of this.connections.values())e=e.concat(n);return e}getConnectionsMap(){return this.connections}async openConnection(t,e={}){if(!this.started)throw new ce("Not started");this.outboundPendingConnections++;try{e.signal?.throwIfAborted();let{peerId:n}=Js(t);if(this.peerId.equals(n))throw new Er("Can not dial self");if(n!=null&&e.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),e.onProgress?.(new ut("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(t,{...e,priority:e.priority??Cl});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 Se("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=>W(n))}))}async isDialable(t,e={}){return this.dialQueue.isDialable(t,e)}};var an=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 $y=1.2,Hy=2,Gy=2e3,pi=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(t={}){this.success=new an(t.interval??5e3),this.failure=new an(t.interval??5e3),this.next=new an(t.interval??5e3),this.failureMultiplier=t.failureMultiplier??Hy,this.timeoutMultiplier=t.timeoutMultiplier??$y,this.minTimeout=t.minTimeout??Gy,t.metricName!=null&&(this.metric=t.metrics?.registerMetricGroup(t.metricName))}getTimeoutSignal(t={}){let e=Math.max(Math.round(this.next.movingAverage*(t.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(e),o=ve([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 kl=class{readNext;haveNext;ended;nextResult;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,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 await this._push(void 0),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 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 qe(this.readNext.promise,e?.signal,e)}};function ph(){return new kl}var mi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Rl=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ml=class extends Rl{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function gi(r,t){let e=ph();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 Q;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((l,f)=>{c=()=>{f(new Ml("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),u]);return f===!0?new Q:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new mi("unexpected end of input");o.append(f)}let l=o.sublist(0,i);return o.consume(i),l}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},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 Wy=1e4,Xy="1.0.0",jy="ping",Zy="ipfs",mh=32,Yy=!0,yi=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(t,e={}){this.components=t,this.protocol=`/${e.protocolPrefix??Zy}/${jy}/${Xy}`,this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=e.pingInterval??Wy,this.abortConnectionOnPingFailure=e.abortConnectionOnPingFailure??Yy,this.timeout=new pi({...e.pingTimeout??{},metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[hn]=["@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=gi(o);e=Date.now(),await Promise.all([s.write(Fr(mh),{signal:n}),s.read(mh,{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 Qy(r){return r[Symbol.asyncIterator]!=null}function Jy(...r){let t=[];for(let e of r)Qy(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=oi({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var io=Jy;var bi=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:B(n,"base36")})})??this.put,this.get=t.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:B(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 en("No content routers available");let n=this,o=new sr;for await(let s of io(...n.routers.map(i=>i.findProviders(t,e))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(t,e={}){if(this.routers.length===0)throw new en("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(t,e)}))}async cancelReprovide(t,e={}){if(this.routers.length===0)throw new en("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(t,e)}))}async put(t,e,n){if(!this.isStarted())throw new ce;await Promise.all(this.routers.map(async o=>{await o.put(t,e,n)}))}async get(t,e){if(!this.isStarted())throw new ce;return Promise.any(this.routers.map(async n=>n.get(t,e)))}};var wi=globalThis.CustomEvent??Event;async function*Nl(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered==null?!1:t.ordered,o=new EventTarget,s=[],i=lt(),a=lt(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===e&&(i=lt(),await i.promise),l)break;let g={done:!1};s.push(g),p().then(h=>{g.done=!0,g.ok=!0,g.value=h,o.dispatchEvent(new wi("task-complete"))},h=>{g.done=!0,g.err=h,o.dispatchEvent(new wi("task-complete"))})}c=!0,o.dispatchEvent(new wi("task-complete"))}catch(p){u=p,o.dispatchEvent(new wi("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw l=!0,i.resolve(),p.err;i.resolve()}}function*m(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let g=s[p];if(s.splice(p,1),p--,g.ok)yield g.value;else throw l=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=lt(),await a.promise),u!=null)throw u;if(n?yield*d():yield*m(),c&&s.length===0)break}}var xi=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:B(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 no("No peer routers available");if(t.toString()===this.peerId.toString())throw new qs("Should not try to find self");let n=this,o=io(...this.routers.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}),s;throw new go}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new no("No peer routers available");let n=this,o=Gn(1024);for await(let s of Nl(async function*(){let i=io(...n.routers.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}),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var vi=class extends le{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=ve([this.shutdownController.signal,t?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=lt(),yield(await nn(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=ve([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=Fr(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 qe(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 Bl=32,Ol=64,Ei=class{log;topologies;handlers;components;constructor(t){this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,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 zs(`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 Vs(`Handler already registered for protocol ${t}`);let o=us.bind({ignoreUndefined:!0})({maxInboundStreams:Bl,maxOutboundStreams:Ol},n);this.handlers.set(t,{handler:e,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[t]})}async unhandle(t){(Array.isArray(t)?t:[t]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}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;this.components.peerStore.get(e).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(e)!==!1&&(i.filter?.remove(e),i.onDisconnect?.(e))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",e,n)})}_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 Fl=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 gh(r){let{name:t,metrics:e}=r,n;return e!=null?n=new Fl({name:t,metrics:e}):n=new Map,n}var Si=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=new Map,this.listeners=gh({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=e.faultTolerance??Ve.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 js(`No transport available for address ${String(t)}`);return e?.onProgress?.(new ut("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 ce("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 $s)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(t);for(let c of a){this.log("creating listener for %s on %a",s,c);let u=i.createListener({upgrader:this.components.upgrader}),l=this.listeners.get(s)??[];l==null&&(l=[],this.listeners.set(s,l)),l.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let f=l.findIndex(d=>d===u);l.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),il.matches(c)?e.ipv4.attempts++:al.matches(c)&&e.ipv6.attempts++,n.push(u.listen(c).then(()=>{e.errors.delete(c.toString()),il.matches(c)&&e.ipv4.success++,al.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===Ve.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Hs(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
3
+ ${[...e.errors.entries()].map(([s,i])=>`
4
+ ${s}: ${`${i.stack??i}`.split(`
9
5
  `).join(`
10
6
  `)}
11
- `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let s=t.pop();s!=null&&n.push(s.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Se="/multistream/1.0.0";var qa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},za=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ga=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Fs(r,e={}){let t=Ma(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??st,s=e?.lengthEncoder??Be;return{read:async i=>{let a=-1,c=new ye;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new qa("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ga("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new za("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new ye(s(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ye(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var lx=N(`
12
- `);async function Ur(r,e,t){await r.write(e,t)}async function Am(r,e,t){await r.writeV(e,t)}async function ux(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==lx[0])throw e.log.error("Invalid mss message - missing newline",t),new Xs("Missing newline");return t.sublist(0,-1)}async function ar(r,e){let t=await ux(r,e);return z(t.subarray())}async function Vs(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return fx(r,e[0],t);let n=Fs(r,{...t,maxDataLength:1024}),s=e.shift();if(s==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Se,s);let o=N(`${Se}
13
- `),i=N(`${s}
14
- `);await Am(n,[o,i],t),t.log.trace("select: reading multistream-select header");let a=await ar(n,t);if(t.log.trace('select: read "%s"',a),a===Se&&(t.log.trace("select: reading protocol response"),a=await ar(n,t),t.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(let c of e){t.log.trace('select: write "%s"',c),await Ur(n,N(`${c}
15
- `),t),t.log.trace("select: reading protocol response");let l=await ar(n,t);if(t.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:n.unwrap(),protocol:c}}throw new On("protocol selection failed")}function fx(r,e,t){let n=r.sink.bind(r),s=r.source,o=!1,i=!1,a=ue(),c=!1,l=!1,u=ue(),f=!1,d=!1,m=ue(),p=Fs({sink:n,source:s},{...t,maxDataLength:1024});r.sink=async x=>{let{sink:y}=p.unwrap();await y(async function*(){let E=!1;for await(let _ of x){if(l&&await u.promise,c)yield _;else{l=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Se,e,_.byteLength);let L=`${e}
16
- `;yield new ye(Uint8Array.from([19]),N(`${Se}
17
- `),Be(L.length),N(L),_).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Se,e,_.byteLength),c=!0,l=!1,u.resolve(),g().catch(I=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,I)})}E=!0}E||await g()}())};async function g(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await h()),f||(t.log.trace("optimistic: doing read protocol for %s stream",e),await w())}finally{i=!1,o=!0,a.resolve()}}async function h(){if(l){await u.promise;return}l=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Se,e),await p.writeV([N(`${Se}
18
- `),N(`${e}
19
- `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Se,e)}finally{c=!0,l=!1,u.resolve()}}async function w(){if(d){await m.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let x=await ar(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',x),x===Se&&(x=await ar(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',x,e),x!==e)throw new On("protocol selection failed")}finally{f=!0,d=!1,m.resolve()}}if(r.source=async function*(){await g(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source}(),r.closeRead!=null){let x=r.closeRead.bind(r);r.closeRead=async y=>{o||await g().catch(E=>{t.log.error("could not negotiate protocol before close read",E)}),await x(y)}}if(r.closeWrite!=null){let x=r.closeWrite.bind(r);r.closeWrite=async y=>{o||await g().catch(E=>{t.log.error("could not negotiate protocol before close write",E)}),await x(y)}}if(r.close!=null){let x=r.close.bind(r);r.close=async y=>{let E=[];l&&E.push(u.promise),d&&E.push(m.promise),E.length>0?await ir(Promise.all(E),y?.signal):(o=!0,i=!1,a.resolve()),await x(y)}}return{stream:r,protocol:e}}var Wa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Dn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ja=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Hs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Za(r){return r[Symbol.asyncIterator]!=null}function _m(r,e){if(r.byteLength>e)throw new Dn("Message length too long")}var Ya=r=>{let e=de(r),t=Ce(e);return Be(r,t),Ya.bytes=e,t};Ya.bytes=0;function Ja(r,e){e=e??{};let t=e.lengthEncoder??Ya,n=e?.maxDataLength??4194304;function*s(o){_m(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Za(r)?async function*(){for await(let o of r)yield*s(o)}():function*(){for(let o of r)yield*s(o)}()}Ja.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Ya,n=e?.maxDataLength??4194304;return _m(r,n),new ye(t(r.byteLength),r)};var Fr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Fr||(Fr={}));var uf=r=>{let e=st(r);return uf.bytes=de(e),e};uf.bytes=0;function lf(r,e){let t=new ye,n=Fr.LENGTH,s=-1,o=e?.lengthDecoder??uf,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Fr.LENGTH)try{if(s=o(t),s<0)throw new Wa("Invalid message length");if(s>a)throw new Dn("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Fr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new ja("Message length length too long");break}throw l}if(n===Fr.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Fr.LENGTH}}}return Za(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Hs("Unexpected end of input")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Hs("Unexpected end of input")}()}lf.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}}();return lf(n,{...e??{},onLength:o=>{t=o}})};async function Ks(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Fs(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let s=await ar(n,t);if(t.log.trace('handle: read "%s"',s),s===Se){t.log.trace('handle: respond with "%s" for "%s"',Se,s),await Ur(n,N(`${Se}
20
- `),t),t.log.trace('handle: responded with "%s" for "%s"',Se,s);continue}if(e.includes(s))return t.log.trace('handle: respond with "%s" for "%s"',s,s),await Ur(n,N(`${s}
21
- `),t),t.log.trace('handle: responded with "%s" for "%s"',s,s),{stream:n.unwrap(),protocol:s};if(s==="ls"){let o=new ye(...e.map(i=>Ja.single(N(`${i}
22
- `))),N(`
23
- `));t.log.trace('handle: respond with "%s" for %s',e,s),await Ur(n,o,t),t.log.trace('handle: responded with "%s" for %s',e,s);continue}t.log.trace('handle: respond with "na" for "%s"',s),await Ur(n,N(`na
24
- `),t),t.log('handle: responded with "na" for "%s"',s)}}var px=500,ff=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:s,close:o,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=s,this._close=o,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[xf]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Gs("the connection is being closed");if(this.status==="closed")throw new Kr("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new zr("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(px);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function Cm(r){return new ff(r)}function gx(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return sf}function yx(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??of}function Im(r,e,t){let n=0;return t.streams.forEach(s=>{s.direction===e&&s.protocol===r&&n++}),n}var Qa=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new ha(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Ft([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,s=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new pa("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",{...t,signal:s})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),o}finally{s.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),s;n!=null&&(s=gt(n),await this.shouldBlockConnection("denyOutboundConnection",s,e));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let s,o,i,a,c;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),l=await u.protect(e,n))}try{if(s=l,n?.skipEncryption!==!0){n?.onProgress?.(new fe(`upgrader:encrypt-${t}-connection`)),{conn:s,remotePeer:o,protocol:c}=await(t==="inbound"?this._encryptInbound(l,n):this._encryptOutbound(l,n));let u={...l,...s};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,u)}else{let u=e.remoteAddr.getPeerId();if(u==null)throw new Vt(`${t} connection that skipped encryption must have a peer id`);let f=gt(u);c="native",o=f}if(o.equals(this.components.peerId)){let u=new $r("Can not dial self");throw e.abort(u),u}if(i=s,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new fe(`upgrader:multiplex-${t}-connection`));let u=await(t==="inbound"?this._multiplexInbound({...l,...s},this.streamMuxers,n):this._multiplexOutbound({...l,...s},this.streamMuxers,n));a=u.muxerFactory,i=u.stream}}catch(u){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,u),u}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:o,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:s,upgradedConn:o,remotePeer:i,muxerFactory:a,limits:c}=e,l,u,f;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{f!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),h=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:w,protocol:x}=await Ks(p,g,{signal:h,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",x);let y=gx(x,this.components.registrar);if(Im(x,"inbound",f)===y){let _=new Js(`Too many inbound protocol streams for protocol "${x}" - limit ${y}`);throw p.abort(_),_}p.source=w.source,p.sink=w.sink,p.protocol=x,w.closeWrite!=null&&(p.closeWrite=w.closeWrite),w.closeRead!=null&&(p.closeRead=w.closeRead),w.close!=null&&(p.close=w.close),await this.components.peerStore.merge(i,{protocols:[x]}),this.components.metrics?.trackProtocolStream(p,f),this._onStream({connection:f,stream:p,protocol:x})}).catch(async g=>{f.log.error("error handling incoming stream id %s - %e",p.id,g),p.timeline.close==null&&await p.close()})}}),u=async(p,g={})=>{if(l==null)throw new Rr("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",p);let h=await l.newStream();f.log.trace("started new stream %s for protocols %s",h.id,p);try{if(g.signal==null){h.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let _=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:_}}h.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:x}=await Vs(h,p,{...g,log:h.log,yieldBytes:!0});h.log.trace("selected protocol %s",x);let y=yx(x,this.components.registrar,g),E=Im(x,"outbound",f);if(E>=y){let _=new Qs(`Too many outbound protocol streams for protocol "${x}" - ${E}/${y}`);throw h.abort(_),_}return await this.components.peerStore.merge(i,{protocols:[x]}),h.source=w.source,h.sink=w.sink,h.protocol=x,w.closeWrite!=null&&(h.closeWrite=w.closeWrite),w.closeRead!=null&&(h.closeRead=w.closeRead),w.close!=null&&(h.close=w.close),this.components.metrics?.trackProtocolStream(h,f),h}catch(w){throw f.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,w),h.timeline.close==null&&h.abort(w),w}},Promise.all([l.sink(o.source),o.sink(l.source)]).catch(p=>{f.log.error("error piping data through muxer - %e",p)}));let d=s.timeline;s.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(g){f.log.error("error closing connection after timeline close %e",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(g=>{f.log.error("error thrown while dispatching connection:close event %e",g)}),Reflect.set(...p))}),s.timeline.upgraded=Date.now();let m=()=>{throw new Rr("Connection is not multiplexed")};return f=Cm({remoteAddr:s.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:s.timeline,multiplexer:l?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:u??m,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await s.close(p)},abort:p=>{s.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f.__maConnTimeline=d,f}_onStream(e){let{connection:t,stream:n,protocol:s}=e,{handler:o,options:i}=this.components.registrar.getHandler(s);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new zr("Cannot open protocol stream on limited connection");o({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:s,protocol:o}=await Ks(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(o);if(i==null)throw new Mr(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await i.secureInbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,s),new Mr(s.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:s,protocol:o}=await Vs(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(o);if(i==null)throw new Mr(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await i.secureOutbound(s,t),protocol:o}}catch(s){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,s),new Mr(s.message)}}async _multiplexOutbound(e,t,n){let s=Array.from(t.keys());e.log("outbound selecting muxer %s",s);try{e.log.trace("selecting stream muxer from %s",s);let{stream:o,protocol:i}=await Vs(e,s,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new Rr(String(o))}}async _multiplexInbound(e,t,n){let s=Array.from(t.keys());e.log("inbound handling muxers %s",s);try{let{stream:o,protocol:i}=await Ks(e,s,{...n,log:e.log}),a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new Rr(String(o))}}};var ec="2.7.4",tc="js-libp2p";function km(r,e){return`${r??tc}/${e??ec} browser/${globalThis.navigator.userAgent}`}var rc=class extends xt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new xt,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??Ni(),this.log=this.logger.forComponent("libp2p"),this.services={};let s=e.nodeInfo?.name??tc,o=e.nodeInfo?.version??ec,i=this.components=tm({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:s,version:o,userAgent:e.nodeInfo?.userAgent??km(s,o)},logger:this.logger,events:t,datastore:e.datastore??new Wi,connectionGater:nm(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",Up(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new Qa(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new $a(this.components,e.transportManager)),this.configureComponent("connectionManager",new Na(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Oa(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Ka(this.components)),this.configureComponent("addressManager",new sa(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Va(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Ua(this.components,{routers:c})),this.configureComponent("randomWalk",new Ha(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[sc]!=null&&(this.log("registering service %s for content routing",l),c.push(f[sc])),f[ic]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[ic])),f[oc]!=null&&(this.log("registering service %s for peer discovery",l),f[oc].addEventListener?.("peer",d=>{this.#e(d)}))}rm(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new _r;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new D("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new D("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){rr(e)&&(e=gt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Fe([N("/pk/"),e.toMultihash().bytes]),s=await this.contentRouting.get(n,t),o=hn(s);return await this.peerStore.patch(e,{publicKey:o}),o}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.handle(s,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function wx(r={}){r.privateKey??=await Dh("Ed25519");let e=new rc({...await yp(r),peerId:Uh(r.privateKey)});return r.start!==!1&&await e.start(),e}return $m(bx);})();
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 Ai=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},_i=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ii=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ao(r,t={}){let e=gi(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ft(t.maxDataLength));let n=t?.lengthDecoder??Yt,o=t?.lengthEncoder??At;return{read:async i=>{let a=-1,c=new Q;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Ai("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ii("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new _i("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new Q(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new Q(...i.flatMap(u=>[o(u.byteLength),u]));await e.write(c,a)},unwrap:()=>e.unwrap()}}var tb=k(`
8
+ `);async function br(r,t,e){await r.write(t,e)}async function yh(r,t,e){await r.writeV(t,e)}async function eb(r,t){let e=await r.read(t);if(e.byteLength===0||e.get(e.byteLength-1)!==tb[0])throw t.log.error("Invalid mss message - missing newline",e),new wo("Missing newline");return e.sublist(0,-1)}async function ze(r,t){let e=await eb(r,t);return B(e.subarray())}async function co(r,t,e){if(t=Array.isArray(t)?[...t]:[t],t.length===1&&e.negotiateFully===!1)return rb(r,t[0],e);let n=ao(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=k(`${xt}
9
+ `),i=k(`${o}
10
+ `);await yh(n,[s,i],e),e.log.trace("select: reading multistream-select header");let a=await ze(n,e);if(e.log.trace('select: read "%s"',a),a===xt&&(e.log.trace("select: reading protocol response"),a=await ze(n,e),e.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of t){e.log.trace('select: write "%s"',c),await br(n,k(`${c}
11
+ `),e),e.log.trace("select: reading protocol response");let u=await ze(n,e);if(e.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:n.unwrap(),protocol:c}}throw new dn("protocol selection failed")}function rb(r,t,e){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=lt(),c=!1,u=!1,l=lt(),f=!1,d=!1,m=lt(),p=ao({sink:n,source:o},{...e,maxDataLength:1024});r.sink=async x=>{let{sink:y}=p.unwrap();await y(async function*(){let E=!1;for await(let _ of x){if(u&&await l.promise,c)yield _;else{u=!0,e.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',xt,t,_.byteLength);let L=`${t}
12
+ `;yield new Q(Uint8Array.from([19]),k(`${xt}
13
+ `),At(L.length),k(L),_).subarray(),e.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',xt,t,_.byteLength),c=!0,u=!1,l.resolve(),g().catch(I=>{e.log.error("could not finish optimistic protocol negotiation of %s",t,I)})}E=!0}E||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 h()),f||(e.log.trace("optimistic: doing read protocol for %s stream",t),await b())}finally{i=!1,s=!0,a.resolve()}}async function h(){if(u){await l.promise;return}u=!0;try{e.log.trace('optimistic: write ["%s", "%s", data] in source',xt,t),await p.writeV([k(`${xt}
14
+ `),k(`${t}
15
+ `)]),e.log.trace('optimistic: wrote ["%s", "%s", data] in source',xt,t)}finally{c=!0,u=!1,l.resolve()}}async function b(){if(d){await m.promise;return}d=!0;try{e.log.trace("optimistic: reading multistream select header");let x=await ze(p,e);if(e.log.trace('optimistic: read multistream select header "%s"',x),x===xt&&(x=await ze(p,e)),e.log.trace('optimistic: read protocol "%s", expecting "%s"',x,t),x!==t)throw new dn("protocol selection failed")}finally{f=!0,d=!1,m.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 x=r.closeRead.bind(r);r.closeRead=async y=>{s||await g().catch(E=>{e.log.error("could not negotiate protocol before close read",E)}),await x(y)}}if(r.closeWrite!=null){let x=r.closeWrite.bind(r);r.closeWrite=async y=>{s||await g().catch(E=>{e.log.error("could not negotiate protocol before close write",E)}),await x(y)}}if(r.close!=null){let x=r.close.bind(r);r.close=async y=>{let E=[];u&&E.push(l.promise),d&&E.push(m.promise),E.length>0?await qe(Promise.all(E),y?.signal):(s=!0,i=!1,a.resolve()),await x(y)}}return{stream:r,protocol:t}}var Ci=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},cn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ti=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},lo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Pi(r){return r[Symbol.asyncIterator]!=null}function wh(r,t){if(r.byteLength>t)throw new cn("Message length too long")}var Di=r=>{let t=ft(r),e=Et(t);return At(r,e),Di.bytes=t,e};Di.bytes=0;function ki(r,t){t=t??{};let e=t.lengthEncoder??Di,n=t?.maxDataLength??4194304;function*o(s){wh(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Pi(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}ki.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Di,n=t?.maxDataLength??4194304;return wh(r,n),new Q(e(r.byteLength),r)};var wr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(wr||(wr={}));var ql=r=>{let t=Yt(r);return ql.bytes=ft(t),t};ql.bytes=0;function Kl(r,t){let e=new Q,n=wr.LENGTH,o=-1,s=t?.lengthDecoder??ql,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===wr.LENGTH)try{if(o=s(e),o<0)throw new Ci("Invalid message length");if(o>a)throw new cn("Message length too long");let u=s.bytes;e.consume(u),t?.onLength!=null&&t.onLength(o),n=wr.DATA}catch(u){if(u instanceof RangeError){if(e.byteLength>i)throw new Ti("Message length length too long");break}throw u}if(n===wr.DATA){if(e.byteLength<o)break;let u=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(u),yield u,n=wr.LENGTH}}}return Pi(r)?async function*(){for await(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new lo("Unexpected end of input")}():function*(){for(let u of r)e.append(u),yield*c();if(e.byteLength>0)throw new lo("Unexpected end of input")}()}Kl.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 Kl(n,{...t??{},onLength:s=>{e=s}})};async function uo(r,t,e){t=Array.isArray(t)?t:[t],e.log.trace("handle: available protocols %s",t);let n=ao(r,{...e,maxDataLength:1024,maxLengthLength:2});for(;;){e.log.trace("handle: reading incoming string");let o=await ze(n,e);if(e.log.trace('handle: read "%s"',o),o===xt){e.log.trace('handle: respond with "%s" for "%s"',xt,o),await br(n,k(`${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 br(n,k(`${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 Q(...t.map(i=>ki.single(k(`${i}
18
+ `))),k(`
19
+ `));e.log.trace('handle: respond with "%s" for %s',t,o),await br(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 br(n,k(`na
20
+ `),e),e.log('handle: responded with "na" for "%s"',o)}}var sb=500,zl=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(t){let{remoteAddr:e,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=t;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=e,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[Yl]=!0;get streams(){return this._getStreams()}async newStream(t,e){if(this.status==="closing")throw new mo("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 Ar("Cannot open protocol stream on limited connection");let n=await this._newStream(t,e);return n.direction="outbound",n}async close(t={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",t.signal==null){let e=AbortSignal.timeout(sb);t={...t,signal:e}}try{this.log.trace("closing underlying transport"),await this._close(t),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(t){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,t),this.status="closing",this._abort(t),this.status="closed",this.timeline.close=Date.now())}};function xh(r){return new zl(r)}function ab(r,t){try{let{options:e}=t.getHandler(r);return e.maxInboundStreams}catch(e){if(e.name!=="UnhandledProtocolError")throw e}return Bl}function cb(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??Ol}function vh(r,t,e){let n=0;return e.streams.forEach(o=>{o.direction===t&&o.protocol===r&&n++}),n}var Ri=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(t,e){this.components=t,this.connectionEncrypters=new Map,e.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,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")}}[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 Ws(`The multiaddr connection is blocked by gater.${t}`)}createInboundAbortSignal(t){let e=ve([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 this.components.connectionManager.acceptIncomingConnection(t),!n)throw new Xs("Connection denied");await this.shouldBlockConnection("denyInboundConnection",t),await this._performUpgrade(t,"inbound",{...e,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!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=ie(n),await this.shouldBlockConnection("denyOutboundConnection",o,t));let s="outbound";return e.initiator===!1&&(s="inbound"),await this._performUpgrade(t,s,e)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(t,e,n){let o,s,i,a,c;this.components.metrics?.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",e);let u=t;if(n?.skipProtection!==!0){let l=this.components.connectionProtector;l!=null&&(t.log("protecting the %s connection",e),u=await l.protect(t,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new ut(`upgrader:encrypt-${e}-connection`)),{conn:o,remotePeer:s,protocol:c}=await(e==="inbound"?this._encryptInbound(u,n):this._encryptOutbound(u,n));let l={...u,...o};await this.shouldBlockConnection(e==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,l)}else{let l=t.remoteAddr.getPeerId();if(l==null)throw new Se(`${e} connection that skipped encryption must have a peer id`);let f=ie(l);c="native",s=f}if(s.equals(this.components.peerId)){let l=new Er("Can not dial self");throw t.abort(l),l}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new ut(`upgrader:multiplex-${e}-connection`));let l=await(e==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=l.muxerFactory,i=l.stream}}catch(l){throw t.log.error("failed to upgrade inbound connection %s %a - %e",e==="inbound"?"from":"to",t.remoteAddr,l),l}return await this.shouldBlockConnection(e==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",e),this._createConnection({cryptoProtocol:c,direction:e,maConn:t,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(t){let{cryptoProtocol:e,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=t,u,l,f;a!=null&&(u=a.createStreamMuxer({direction:n,onIncomingStream:p=>{f!=null&&Promise.resolve().then(async()=>{let g=this.components.registrar.getProtocols(),h=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);let{stream:b,protocol:x}=await uo(p,g,{signal:h,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",x);let y=ab(x,this.components.registrar);if(vh(x,"inbound",f)===y){let _=new vo(`Too many inbound protocol streams for protocol "${x}" - limit ${y}`);throw p.abort(_),_}p.source=b.source,p.sink=b.sink,p.protocol=x,b.closeWrite!=null&&(p.closeWrite=b.closeWrite),b.closeRead!=null&&(p.closeRead=b.closeRead),b.close!=null&&(p.close=b.close),await this.components.peerStore.merge(i,{protocols:[x]}),this.components.metrics?.trackProtocolStream(p,f),this._onStream({connection:f,stream:p,protocol:x})}).catch(async g=>{f.log.error("error handling incoming stream id %s - %e",p.id,g),p.timeline.close==null&&await p.close()})}}),l=async(p,g={})=>{if(u==null)throw new mr("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",p);let h=await u.newStream();f.log.trace("started new stream %s for protocols %s",h.id,p);try{if(g.signal==null){h.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let _=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);g={...g,signal:_}}h.log.trace("selecting protocol from protocols %s",p);let{stream:b,protocol:x}=await co(h,p,{...g,log:h.log,yieldBytes:!0});h.log.trace("selected protocol %s",x);let y=cb(x,this.components.registrar,g),E=vh(x,"outbound",f);if(E>=y){let _=new Eo(`Too many outbound protocol streams for protocol "${x}" - ${E}/${y}`);throw h.abort(_),_}return await this.components.peerStore.merge(i,{protocols:[x]}),h.source=b.source,h.sink=b.sink,h.protocol=x,b.closeWrite!=null&&(h.closeWrite=b.closeWrite),b.closeRead!=null&&(h.closeRead=b.closeRead),b.close!=null&&(h.close=b.close),this.components.metrics?.trackProtocolStream(h,f),h}catch(b){throw f.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",t.maConn.remoteAddr,p,b),h.timeline.close==null&&h.abort(b),b}},Promise.all([u.sink(s.source),s.sink(u.source)]).catch(p=>{f.log.error("error piping data through muxer - %e",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(g){f.log.error("error closing connection after timeline close %e",g)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(g=>{f.log.error("error thrown while dispatching connection:close event %e",g)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let m=()=>{throw new mr("Connection is not multiplexed")};return f=xh({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:u?.protocol,encryption:e,limits:c,logger:this.components.logger,newStream:l??m,getStreams:()=>u?.streams??[],close:async p=>{await u?.close(p),await o.close(p)},abort:p=>{o.abort(p),u?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f.__maConnTimeline=d,f}_onStream(t){let{connection:e,stream:n,protocol:o}=t,{handler:s,options:i}=this.components.registrar.getHandler(o);if(e.limits!=null&&i.runOnLimitedConnection!==!0)throw new Ar("Cannot open protocol stream on limited connection");s({connection:e,stream:n})}async _encryptInbound(t,e){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await uo(t,n,{...e,log:t.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new gr(`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 gr(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 co(t,n,{...e,log:t.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new gr(`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 gr(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 co(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 uo(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))}}};var Mi="2.7.5",Ni="js-libp2p";function Sh(r,t){return`${r??Ni}/${t??Mi} browser/${globalThis.navigator.userAgent}`}var Bi=class extends le{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(t){super(),this.status="stopped";let e=new le,n=e.dispatchEvent.bind(e);e.dispatchEvent=u=>{let l=n(u),f=this.dispatchEvent(new CustomEvent(u.type,{detail:u.detail}));return l||f},this.peerId=t.peerId,this.logger=t.logger??ps(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=t.nodeInfo?.name??Ni,s=t.nodeInfo?.version??Mi,i=this.components=jd({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:o,version:s,userAgent:t.nodeInfo?.userAgent??Sh(o,s)},logger:this.logger,events:e,datastore:t.datastore??new Cs,connectionGater:Yd(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",kd(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...t.peerStore})),t.metrics!=null&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),i.events.addEventListener("peer:update",u=>{if(u.detail.previous==null){let l={id:u.detail.peer.id,multiaddrs:u.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:l})}}),t.connectionProtector!=null&&this.configureComponent("connectionProtector",t.connectionProtector(i)),this.components.upgrader=new Ri(this.components,{connectionEncrypters:(t.connectionEncrypters??[]).map((u,l)=>this.configureComponent(`connection-encryption-${l}`,u(this.components))),streamMuxers:(t.streamMuxers??[]).map((u,l)=>this.configureComponent(`stream-muxers-${l}`,u(this.components))),inboundUpgradeTimeout:t.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:t.connectionManager?.inboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:t.connectionManager?.outboundStreamProtocolNegotiationTimeout??t.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Si(this.components,t.transportManager)),this.configureComponent("connectionManager",new hi(this.components,t.connectionManager)),t.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new yi(this.components,t.connectionMonitor)),this.configureComponent("registrar",new Ei(this.components)),this.configureComponent("addressManager",new Fs(this.components,t.addresses));let a=(t.peerRouters??[]).map((u,l)=>this.configureComponent(`peer-router-${l}`,u(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new xi(this.components,{routers:a}));let c=(t.contentRouters??[]).map((u,l)=>this.configureComponent(`content-router-${l}`,u(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new bi(this.components,{routers:c})),this.configureComponent("randomWalk",new vi(this.components)),(t.peerDiscovery??[]).forEach((u,l)=>{this.configureComponent(`peer-discovery-${l}`,u(this.components)).addEventListener("peer",d=>{this.#t(d)})}),t.transports?.forEach((u,l)=>{this.components.transportManager.add(this.configureComponent(`transport-${l}`,u(this.components)))}),t.services!=null)for(let u of Object.keys(t.services)){let l=t.services[u],f=l(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",u);continue}this.services[u]=f,this.configureComponent(u,f),f[Fi]!=null&&(this.log("registering service %s for content routing",u),c.push(f[Fi])),f[Ki]!=null&&(this.log("registering service %s for peer routing",u),a.push(f[Ki])),f[Ui]!=null&&(this.log("registering service %s for peer discovery",u),f[Ui].addEventListener?.("peer",d=>{this.#t(d)}))}Zd(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 sr;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={}){Oe(t)&&(t=ie(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);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Rt([k("/pk/"),t.toMultihash().bytes]),o=await this.contentRouting.get(n,e),s=Kr(o);return await this.peerStore.patch(t,{publicKey:s}),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){Array.isArray(t)||(t=[t]),await Promise.all(t.map(async e=>{await this.components.registrar.unhandle(e)}))}async register(t,e){return this.components.registrar.register(t,e)}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 lb(r={}){r.privateKey??=await Lf("Ed25519");let t=new Bi({...await hd(r),peerId:Mf(r.privateKey)});return r.start!==!1&&await t.start(),t}return Oh(ub);})();
25
21
  /*! Bundled license information:
26
22
 
27
- pvtsutils/build/index.js:
28
- (*!
29
- * MIT License
30
- *
31
- * Copyright (c) 2017-2024 Peculiar Ventures, LLC
32
- *
33
- * Permission is hereby granted, free of charge, to any person obtaining a copy
34
- * of this software and associated documentation files (the "Software"), to deal
35
- * in the Software without restriction, including without limitation the rights
36
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
37
- * copies of the Software, and to permit persons to whom the Software is
38
- * furnished to do so, subject to the following conditions:
39
- *
40
- * The above copyright notice and this permission notice shall be included in all
41
- * copies or substantial portions of the Software.
42
- *
43
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
44
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
45
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
46
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
47
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
48
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
49
- * SOFTWARE.
50
- *
51
- *)
52
-
53
23
  @noble/hashes/esm/utils.js:
54
24
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
55
25
 
@@ -68,46 +38,6 @@ pvtsutils/build/index.js:
68
38
  @noble/curves/esm/ed25519.js:
69
39
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
70
40
 
71
- pvutils/build/utils.es.js:
72
- (*!
73
- Copyright (c) Peculiar Ventures, LLC
74
- *)
75
-
76
- asn1js/build/index.es.js:
77
- (*!
78
- * Copyright (c) 2014, GMO GlobalSign
79
- * Copyright (c) 2015-2022, Peculiar Ventures
80
- * All rights reserved.
81
- *
82
- * Author 2014-2019, Yury Strozhevsky
83
- *
84
- * Redistribution and use in source and binary forms, with or without modification,
85
- * are permitted provided that the following conditions are met:
86
- *
87
- * * Redistributions of source code must retain the above copyright notice, this
88
- * list of conditions and the following disclaimer.
89
- *
90
- * * Redistributions in binary form must reproduce the above copyright notice, this
91
- * list of conditions and the following disclaimer in the documentation and/or
92
- * other materials provided with the distribution.
93
- *
94
- * * Neither the name of the copyright holder nor the names of its
95
- * contributors may be used to endorse or promote products derived from
96
- * this software without specific prior written permission.
97
- *
98
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
99
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
100
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
101
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
102
- * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
103
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
104
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
105
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
106
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
107
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
108
- *
109
- *)
110
-
111
41
  @noble/curves/esm/abstract/weierstrass.js:
112
42
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
113
43