helia 6.1.2 → 6.1.3

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,6 +1,6 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Helia = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
2
  "use strict";var Helia=(()=>{var nP=Object.create;var sh=Object.defineProperty;var oP=Object.getOwnPropertyDescriptor;var iP=Object.getOwnPropertyNames;var sP=Object.getPrototypeOf,aP=Object.prototype.hasOwnProperty;var un=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),wt=(r,e)=>{for(var t in e)sh(r,t,{get:e[t],enumerable:!0})},X7=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of iP(e))!aP.call(r,o)&&o!==t&&sh(r,o,{get:()=>e[o],enumerable:!(n=oP(e,o))||n.enumerable});return r};var Fo=(r,e,t)=>(t=r!=null?nP(sP(r)):{},X7(e||!r||!r.__esModule?sh(t,"default",{value:r,enumerable:!0}):t,r)),cP=r=>X7(sh({},"__esModule",{value:!0}),r);var J7=un((nz,b3)=>{"use strict";var dP=Object.prototype.hasOwnProperty,hr="~";function eu(){}Object.create&&(eu.prototype=Object.create(null),new eu().__proto__||(hr=!1));function fP(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Z7(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new fP(t,n||r,o),s=hr?hr+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function yh(r,e){--r._eventsCount===0?r._events=new eu:delete r._events[e]}function rr(){this._events=new eu,this._eventsCount=0}rr.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)dP.call(t,n)&&e.push(hr?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};rr.prototype.listeners=function(e){var t=hr?hr+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};rr.prototype.listenerCount=function(e){var t=hr?hr+e:e,n=this._events[t];return n?n.fn?1:n.length:0};rr.prototype.emit=function(e,t,n,o,i,s){var a=hr?hr+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,i),!0;case 6:return c.fn.call(c.context,t,n,o,i,s),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,h;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[d].fn.apply(c[d].context,u)}}return!0};rr.prototype.on=function(e,t,n){return Z7(this,e,t,n,!1)};rr.prototype.once=function(e,t,n){return Z7(this,e,t,n,!0)};rr.prototype.removeListener=function(e,t,n,o){var i=hr?hr+e:e;if(!this._events[i])return this;if(!t)return yh(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&yh(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:yh(this,i)}return this};rr.prototype.removeAllListeners=function(e){var t;return e?(t=hr?hr+e:e,this._events[t]&&yh(this,t)):(this._events=new eu,this._eventsCount=0),this};rr.prototype.off=rr.prototype.removeListener;rr.prototype.addListener=rr.prototype.on;rr.prefixed=hr;rr.EventEmitter=rr;typeof b3<"u"&&(b3.exports=rr)});var v9=un((yW,E9)=>{E9.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var p6=un(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.Netmask4Impl=void 0;kc.ip2long=Ic;kc.long2ip=yo;function yo(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var iD=48,sD=97,aD=65;function cD(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let i=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-iD)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-sD)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-aD)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===i)throw new Error("empty octet");return[e,o]}function Ic(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=cD(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var h6=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=Ic(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(Ic(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=yo(this.netLong),this.mask=yo(this.maskLong),this.hostmask=yo(~this.maskLong),this.first=this.bitmask<=30?yo(this.netLong+1):this.base,this.last=this.bitmask<=30?yo(this.netLong+this.size-2):yo(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?yo(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(Ic(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(yo(this.netLong+this.size*e),this.mask)}forEach(e){let t=Ic(this.first),n=Ic(this.last),o=0;for(;t<=n;)e(yo(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};kc.Netmask4Impl=h6});var Ob=un(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});Cc.Netmask6Impl=void 0;Cc.ip6bigint=g6;Cc.bigint2ip6=da;var lD=p6(),m6=(1n<<128n)-1n;function g6(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,lD.ip2long)(n),i=r.substring(0,t+1)+"0:0";return Db(i)&~0xffffffffn|BigInt(o)}return Db(r)}function Db(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),i=r.substring(e+2),s=o===""?[]:o.split(":"),a=i===""?[]:i.split(":"),c=8-s.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...s,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let i=t[o];if(i.length===0||i.length>4)throw new Error('Invalid IPv6: bad group "'+i+'"');let s=parseInt(i,16);if(isNaN(s)||s<0||s>65535)throw new Error('Invalid IPv6: bad group "'+i+'"');n=n<<16n|BigInt(s)}return n}function da(r){if(r<0n||r>m6)throw new Error("Invalid IPv6 address value");let e=[];for(let s=0;s<8;s++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,i=0;for(let s=0;s<8;s++)e[s]===0?o===-1?(o=s,i=1):i++:(i>n&&i>=2&&(t=o,n=i),o=-1,i=0);if(i>n&&i>=2&&(t=o,n=i),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let s=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return s.join(":")+"::"+a.join(":")}else return e.map(s=>s.toString(16)).join(":")}var y6=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=m6>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=g6(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=da(this.netBigint),this.mask=da(this.maskBigint),this.hostmask=da(~this.maskBigint&m6),this.first=this.base,this.last=da(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(g6(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(da(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,i=0;for(;t<=o;)e(da(t),Number(t),i),i++,t++}toString(){return this.base+"/"+this.bitmask}};Cc.Netmask6Impl=y6});var Bb=un(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.long2ip=Hi.ip2long=Hi.Netmask=void 0;var s1=p6();Object.defineProperty(Hi,"ip2long",{enumerable:!0,get:function(){return s1.ip2long}});Object.defineProperty(Hi,"long2ip",{enumerable:!0,get:function(){return s1.long2ip}});var uD=Ob(),w6=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new uD.Netmask6Impl(e,t):this._impl=new s1.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof s1.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};Hi.Netmask=w6});var E0=un((eue,C8)=>{var Jle=(function(){typeof C8<"u"&&(C8.exports=y);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(C){var B=C-C%1;return B==0&&(C<0||C===0&&1/C!=1/0)?-0:B},u=y.prototype,d=(y.fromDate=function(C){return new y(+C)},y.fromInt64BE=O(0,1,2,3,0,4),y.fromInt64LE=O(3,2,1,0,4,0),y.fromString=function($){var B,q=new y,$=($+="").replace(/^\s*[+\-]?\d+/,function(S){var S=+S,A=1970+(S-1970)%400;return q.year=S-A,A}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(b,S,A){return S<0&&(A*=-1),B=6e4*(60*+S+ +A),""}).replace(/\.\d+$/,function(b){return q.nano=+(b+c).substr(1,9),""}).split(/\D+/);if(1<$.length?$[1]--:$[1]=0,q.time=B=Date.UTC.apply(Date,$)-(B||0),isNaN(B))throw new TypeError("Invalid Date");return m(q)},y.fromTimeT=function(C){return x(C,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(C){return this.nano+=+C||0,this},u.getNano=function(){var C=m(this);return(C.time%1e3*a+ +C.nano+1e9)%1e9},u.getTimeT=function(){var B=m(this),C=Math.floor(B.time/1e3),B=B.year;return B&&(C+=B*t*r/e),C},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return g(m(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(C){var B=this,q=B.toDate(),$={H:function(){return V(q.getUTCHours())},L:function(){return H(q.getUTCMilliseconds(),3)},M:function(){return V(q.getUTCMinutes())},N:function(){return H(B.getNano(),9)},S:function(){return V(q.getUTCSeconds())},Y:function(){var b=B.getYear();return 999999<b?"+"+b:9999<b?"+"+H(b,6):0<=b?H(b,4):-999999<=b?"-"+H(-b,6):b},a:function(){return h[q.getUTCDay()]},b:function(){return f[q.getUTCMonth()]},d:function(){return V(q.getUTCDate())},e:function(){return(function(b){return(9<b?"":" ")+(0|b)})(q.getUTCDate())},m:function(){return V(q.getUTCMonth()+1)}};return(function b(S){return S.replace(/%./g,function(A){var v=A[1],E=p[v],v=$[v];return E?b(E):v?v():A})})(C||d)},u.writeInt64BE=P(0,1,2,3,0,4),u.writeInt64LE=P(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),f=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p={"%":"%",F:"%Y-%m-%d",n:`
3
- `,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return y;function y(C,B,q){var $=this;if(!($ instanceof y))return new y(C,B,q);$.time=+C||0,$.nano=+B||0,$.year=+q||0,m($)}function m(C){var B,q,$,b=C.year,S=C.time,A=C.nano,E=((A<0||a<=A)&&(A-=(q=Math.floor(A/a))*a,S+=q,q=1),b%e);return(S<-i||i<S||E)&&((B=l(S/o))&&(b+=B*e,S-=B*o),($=g(S)).setUTCFullYear(E+$.getUTCFullYear()),$=(S=+$)+(B=l((b-=E)/e))*o,B&&-i<=$&&$<=i&&(b-=B*e,S=$),q=1),q&&(C.year=b,C.time=S,C.nano=A),C}function g(C){var B=new Date(0);return B.setTime(C),B}function x(b,$){b=+b||0;var q=l(($=($|0)*s)/n)+l(b/n),$=$%n+b%n,b=l($/n);return b&&(q+=b,$-=b*n),new y(1e3*$,0,q*e)}function P(C,B,q,$,b,S){return function(E,v){var M=m(this);E=E||new Array(8),F(E,v|=0);var R=Math.floor(M.time/1e3),M=M.year*(t*r/e),N=l(M/s)+l(R/s),M=M%s+R%s,R=Math.floor(M/s);return R&&(N+=R,M-=R*s),A(E,v+b,N),A(E,v+S,M),E};function A(E,v,N){E[v+C]=N>>24&255,E[v+B]=N>>16&255,E[v+q]=N>>8&255,E[v+$]=255&N}}function O(C,B,q,$,b,S){return function(E,v){F(E,v|=0);var N=A(E,v+b);return x(A(E,v+S),N)};function A(E,v){return 16777216*E[v+C]+(E[v+B]<<16|E[v+q]<<8|E[v+$])}}function F(C,B){if(C=C&&C.length,C==null)throw new TypeError("Invalid Buffer");if(C<B+8)throw new RangeError("Out of range")}function V(C){return(9<C?"":"0")+(0|C)}function H(C,B){return(c+(0|C)).substr(-B)}})()});var M_=un((pge,B_)=>{"use strict";function lV(r){return r>=55296&&r<=56319}function uV(r){return r>=56320&&r<=57343}B_.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var o=t.length,i=0,s,a,c=0;c<o;c+=1){if(s=t.charCodeAt(c),a=t[c],lV(s)&&uV(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),i+=e(a),i===n)return t.slice(0,c+1);if(i>n)return t.slice(0,c-a.length+1)}return t}});var F_=un((mge,U_)=>{"use strict";function dV(r){return r>=55296&&r<=56319}function fV(r){return r>=56320&&r<=57343}U_.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,o=null,i=null,s=0;s<t;s++)o=e.charCodeAt(s),fV(o)?i!=null&&dV(i)?n+=1:n+=3:o<=127?n+=1:o>=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),i=o;return n}});var V_=un((gge,$_)=>{"use strict";var hV=M_(),pV=F_();$_.exports=hV.bind(null,pV)});var q_=un((yge,H_)=>{"use strict";var mV=V_(),gV=/[\/\?<>\\:\*\|"]/g,yV=/[\x00-\x1f\x80-\x9f]/g,wV=/^\.+$/,bV=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function xV(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function K_(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(gV,e).replace(yV,e).replace(wV,e).replace(bV,e);return t=xV(t,e),mV(t,255)}H_.exports=function(r,e){var t=e&&e.replacement||"",n=K_(r,t);return t===""?n:K_(n,"")}});var z_=un(kl=>{"use strict";var vV="[object ArrayBuffer]",gi=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===vV}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),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let i=0;i<n.length;i++)if(n[i]!==o[i])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 s of t)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of t){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},h5="string",SV=/^[0-9a-f\s]+$/i,AV=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,TV=/^[a-zA-Z0-9-_]+$/,Om=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=gi.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},In=class{static toString(e,t=!1){let n=gi.toArrayBuffer(e),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let i=0;i<e.length;i++)o.setUint16(i*2,e.charCodeAt(i),t);return n}},Bm=class r{static isHex(e){return typeof e===h5&&SV.test(e)}static isBase64(e){return typeof e===h5&&AV.test(e)}static isBase64Url(e){return typeof e===h5&&TV.test(e)}static ToString(e,t="utf8"){let n=gi.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 In.toString(n,!0);case"utf16":case"utf16be":return In.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 In.fromString(e,!0);case"utf16":case"utf16be":return In.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=gi.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 Om.fromString(e);case"utf16":case"utf16be":return In.fromString(e);case"utf16le":case"usc2":return In.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 Om.toString(e);case"utf16":case"utf16be":return In.toString(e);case"utf16le":case"usc2":return In.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 o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=gi.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=gi.toUint8Array(e),n="",o=t.length;for(let i=0;i<o;i++){let s=t[i];s<16&&(n+="0"),n+=s.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 o=0;o<t.length;o=o+2){let i=t.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(e,t=!1){return In.toString(e,t)}static FromUtf16String(e,t=!1){return In.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,"")||""}};Bm.DEFAULT_UTF8_ENCODING="utf8";function _V(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)t[i]=o[i]}return t}function IV(...r){let e=r.map(o=>o.byteLength).reduce((o,i)=>o+i),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)t[n++]=i}),t.buffer}function kV(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}kl.BufferSourceConverter=gi;kl.Convert=Bm;kl.assign=_V;kl.combine=IV;kl.isEqual=kV});var mC=un(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.parseCookie=hC;Mo.parse=hC;Mo.stringifyCookie=eH;Mo.stringifySetCookie=pg;Mo.serialize=pg;Mo.parseSetCookie=tH;Mo.stringifySetCookie=pg;Mo.serialize=pg;var dC=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,fC=/^[\u0021-\u003A\u003C-\u007E]*$/,YK=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,XK=/^[\u0020-\u003A\u003D-\u007E]*$/,QK=/^-?\d+$/,ZK=Object.prototype.toString,JK=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function hC(r,e){let t=new JK,n=r.length;if(n<2)return t;let o=e?.decode||pC,i=0;do{let s=y7(r,i,n);if(s===-1)break;let a=g7(r,i,n);if(s>a){i=r.lastIndexOf(";",s-1)+1;continue}let c=Es(r,i,s);t[c]===void 0&&(t[c]=o(Es(r,s+1,a))),i=a+1}while(i<n);return t}function eH(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let o of Object.keys(r)){let i=r[o];if(i===void 0)continue;if(!dC.test(o))throw new TypeError(`cookie name is invalid: ${o}`);let s=t(i);if(!fC.test(s))throw new TypeError(`cookie val is invalid: ${i}`);n.push(`${o}=${s}`)}return n.join("; ")}function pg(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},i=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!dC.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let s=n.value?i(n.value):"";if(!fC.test(s))throw new TypeError(`argument val is invalid: ${n.value}`);let a=n.name+"="+s;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);a+="; Max-Age="+n.maxAge}if(n.domain){if(!YK.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!XK.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!rH(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.partitioned&&(a+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return a}function tH(r,e){let t=e?.decode||pC,n=r.length,o=g7(r,0,n),i=y7(r,0,o),s=i===-1?{name:"",value:t(Es(r,0,o))}:{name:Es(r,0,i),value:t(Es(r,i+1,o))},a=o+1;for(;a<n;){let c=g7(r,a,n),l=y7(r,a,c),u=l===-1?Es(r,a,c):Es(r,a,l),d=l===-1?void 0:Es(r,l+1,c);switch(u.toLowerCase()){case"httponly":s.httpOnly=!0;break;case"secure":s.secure=!0;break;case"partitioned":s.partitioned=!0;break;case"domain":s.domain=d;break;case"path":s.path=d;break;case"max-age":d&&QK.test(d)&&(s.maxAge=Number(d));break;case"expires":if(!d)break;let f=new Date(d);Number.isFinite(f.valueOf())&&(s.expires=f);break;case"priority":if(!d)break;let h=d.toLowerCase();(h==="low"||h==="medium"||h==="high")&&(s.priority=h);break;case"samesite":if(!d)break;let p=d.toLowerCase();(p==="lax"||p==="strict"||p==="none")&&(s.sameSite=p);break}a=c+1}return s}function g7(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function y7(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Es(r,e,t){let n=e,o=t;do{let i=r.charCodeAt(n);if(i!==32&&i!==9)break}while(++n<o);for(;o>n;){let i=r.charCodeAt(o-1);if(i!==32&&i!==9)break;o--}return r.slice(n,o)}function pC(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function rH(r){return ZK.call(r)==="[object Date]"}});var yq={};wt(yq,{DEFAULT_CID_PEER_FILTER_SIZE:()=>ay,DEFAULT_SESSION_MAX_PROVIDERS:()=>sy,DEFAULT_SESSION_MIN_PROVIDERS:()=>iy,InsufficientProvidersError:()=>cd,InvalidCodecError:()=>cy,NoRoutersAvailableError:()=>Ji,UnknownCodecError:()=>ud,UnknownHashAlgorithmError:()=>ld,createHelia:()=>gq,heliaDefaults:()=>G7,libp2pDefaults:()=>w3});var Q7=Symbol.for("@libp2p/connection");var $o=Symbol.for("@libp2p/content-routing");var fr=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},ah=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},ch=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},T=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Vo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Yl=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},Xl=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var Ns=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},Za=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Cn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Ja=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var lo=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Ql=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},je=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},ec=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},uo=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},lh=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},_i=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},tc=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Te=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Ds=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},fo=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Rn=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Ii=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Os=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Zl=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},uh=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},rc=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Pn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var dh=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},ki=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},fh=class extends ki{constructor(e,t){super(!0,e,t)}},hh=class extends ki{constructor(e,t){super(!1,e,t)}};var Bs=Symbol.for("@libp2p/peer-discovery");var ph=Symbol.for("@libp2p/peer-id");function Rt(r){return!!r?.[ph]}var Ko=Symbol.for("@libp2p/peer-routing");var Ms="keep-alive";function mh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Tt(...r){let e=[];for(let t of r)mh(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 Pt(...r){let e=[];for(let t of r)mh(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 Ci=Symbol.for("@libp2p/transport");var Jl;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Jl||(Jl={}));function lP(r){return typeof r?.handleEvent=="function"}function uP(r){return(r!==!0&&r!==!1&&r?.once)??!1}var we=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=uP(n);super.addEventListener(e,s=>{if(o){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(s.type,a))}lP(t)?t.handleEvent(s):t(s)},n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Ce=Symbol.for("@libp2p/service-capabilities"),Nr=Symbol.for("@libp2p/service-dependencies");var U=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var gh=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var x3=Fo(J7(),1);var E3=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},e9=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function pr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=e,a,c,u=new Promise((d,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){f(e9(s));return}if(s&&(c=()=>{f(e9(s))},s.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new E3;a=i.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&s&&s.removeEventListener("abort",c)});return u.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},u}function v3(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var nc=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},i={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(i);return}let s=v3(this.#e,i,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,i)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex(n=>typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}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 Us=class extends x3.default{#e;#t;#r=0;#a;#c=!1;#m=!1;#u;#I=0;#x=0;#d;#f;#l;#s=[];#i=0;#n;#k;#o=0;#y;#h;#N=1n;#w=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:nc,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#u=e.interval,this.#l=e.strict,this.#n=new e.queueClass,this.#k=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#h=e.autoStart===!1,this.#V()}#v(e){for(;this.#i<this.#s.length;){let n=this.#s[this.#i];if(n!==void 0&&e-n>=this.#u)this.#i++;else break}(this.#i>100&&this.#i>this.#s.length/2||this.#i===this.#s.length)&&(this.#s=this.#s.slice(this.#i),this.#i=0)}#D(e){this.#l?this.#s.push(e):this.#r++}#O(){this.#l?this.#s.length>this.#i&&this.#s.pop():this.#r>0&&this.#r--}#S(){return this.#s.length-this.#i}get#B(){return this.#t?!0:this.#l?this.#S()<this.#a:this.#r<this.#a}get#M(){return this.#o<this.#y}#U(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#F(){this.#f=void 0,this.#P(),this.#R()}#$(e){if(this.#l){if(this.#v(e),this.#S()>=this.#a){let n=this.#s[this.#i],o=this.#u-(e-n);return this.#A(o),!0}return!1}if(this.#d===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#u)return this.#A(this.#u-n),!0}this.#r=this.#e?this.#o:0}else return this.#A(t),!0}return!1}#A(e){this.#f===void 0&&(this.#f=setTimeout(()=>{this.#F()},e))}#T(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}#C(){this.#f&&(clearTimeout(this.#f),this.#f=void 0)}#b(){if(this.#n.size===0){if(this.#T(),this.emit("empty"),this.#o===0){if(this.#C(),this.#l&&this.#i>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#h){let t=Date.now(),n=!this.#$(t);if(this.#B&&this.#M){let o=this.#n.dequeue();this.#t||(this.#D(t),this.#g()),this.emit("active"),o(),n&&this.#R(),e=!0}}return e}#R(){this.#t||this.#d!==void 0||this.#l||(this.#d=setInterval(()=>{this.#P()},this.#u),this.#I=Date.now()+this.#u)}#P(){this.#l||(this.#r===0&&this.#o===0&&this.#d&&this.#T(),this.#r=this.#e?this.#o:0),this.#_(),this.#g()}#_(){for(;this.#b(););}get concurrency(){return this.#y}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.#y=e,this.#_()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#n.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#N++).toString()},new Promise((n,o)=>{let i=Symbol(`task-${t.id}`),s=()=>{},a=async()=>{s(),this.#o++,this.#w.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(f){throw this.#K(),this.#w.delete(i),f}this.#x=Date.now();let u=e({signal:t.signal});if(t.timeout&&(u=pr(Promise.resolve(u),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#n.size} waiting)`})),t.signal){let{signal:f}=t;u=Promise.race([u,new Promise((h,p)=>{l=()=>{p(f.reason)},f.addEventListener("abort",l,{once:!0})})])}let d=await u;n(d),this.emit("completed",d)}catch(u){o(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#w.delete(i),queueMicrotask(()=>{this.#U()})}};this.#n.enqueue(a,t);let c=()=>{if(this.#n instanceof nc){this.#n.remove(a);return}this.#n.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{s(),c(),o(l.reason),this.#b(),this.emit("next")};if(s=()=>{l.removeEventListener("abort",u),this.#E.delete(s)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#E.add(s)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#h?(this.#h=!1,this.#_(),this):this}pause(){this.#h=!0}clear(){for(let e of this.#E)e();this.#n=new this.#k,this.#T(),this.#L(),this.emit("empty"),this.#o===0&&(this.#C(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#o===0&&this.#n.size===0||await this.#p("idle")}async onPendingZero(){this.#o!==0&&await this.#p("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#p("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#p("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#h}#V(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#g()}),this.on("next",()=>{this.#g()}))}#g(){this.#t||this.#m||(this.#m=!0,queueMicrotask(()=>{this.#m=!1,this.#L()}))}#K(){this.#t||(this.#O(),this.#g())}#L(){let e=this.#c;if(this.#t||this.#n.size===0){e&&(this.#c=!1,this.emit("rateLimitCleared"));return}let t;if(this.#l){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#r;let n=t>=this.#a;n!==e&&(this.#c=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#c}get isSaturated(){return this.#o===this.#y&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#w.values()].map(e=>({...e}))}};function wh(r){let e=[Dr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var k3={};wt(k3,{base10:()=>bP});var mz=new Uint8Array(0);function t9(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 Ln(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 r9(r){return new TextEncoder().encode(r)}function n9(r){return new TextDecoder().decode(r)}function hP(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(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 y=0,m=0,g=0,x=p.length;g!==x&&p[g]===0;)g++,y++;for(var P=(x-g)*u+1>>>0,O=new Uint8Array(P);g!==x;){for(var F=p[g],V=0,H=P-1;(F!==0||V<m)&&H!==-1;H--,V++)F+=256*O[H]>>>0,O[H]=F%a>>>0,F=F/a>>>0;if(F!==0)throw new Error("Non-zero carry");m=V,g++}for(var C=P-m;C!==P&&O[C]===0;)C++;for(var B=c.repeat(y);C<P;++C)B+=r.charAt(O[C]);return B}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var m=0,g=0;p[y]===c;)m++,y++;for(var x=(p.length-y)*l+1>>>0,P=new Uint8Array(x);p[y];){var O=t[p.charCodeAt(y)];if(O===255)return;for(var F=0,V=x-1;(O!==0||F<g)&&V!==-1;V--,F++)O+=a*P[V]>>>0,P[V]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");g=F,y++}if(p[y]!==" "){for(var H=x-g;H!==x&&P[H]===0;)H++;for(var C=new Uint8Array(m+(x-H)),B=m;H!==x;)C[B++]=P[H++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var pP=hP,mP=pP,o9=mP;var A3=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")}},T3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return i9(this,e)}},_3=class{decoders;constructor(e){this.decoders=e}or(e){return i9(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 i9(r,e){return new _3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var I3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new A3(e,t,n),this.decoder=new T3(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function oc({name:r,prefix:e,encode:t,decode:n}){return new I3(r,e,t,n)}function Ri({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=o9(t,r);return oc({prefix:e,name:r,encode:n,decode:i=>Ln(o(i))})}function gP(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function yP(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function wP(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function pt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=wP(n);return oc({prefix:e,name:r,encode(i){return yP(i,n,t)},decode(i){return gP(i,o,t,r)}})}var bP=Ri({prefix:"9",name:"base10",alphabet:"0123456789"});var C3={};wt(C3,{base16:()=>xP,base16upper:()=>EP});var xP=pt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),EP=pt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var R3={};wt(R3,{base2:()=>vP});var vP=pt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var P3={};wt(P3,{base256emoji:()=>IP});var s9=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}"),SP=s9.reduce((r,e,t)=>(r[t]=e,r),[]),AP=s9.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function TP(r){return r.reduce((e,t)=>(e+=SP[t],e),"")}function _P(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=AP[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var IP=oc({prefix:"\u{1F680}",name:"base256emoji",encode:TP,decode:_P});var L3={};wt(L3,{base32:()=>Lt,base32hex:()=>PP,base32hexpad:()=>NP,base32hexpadupper:()=>DP,base32hexupper:()=>LP,base32pad:()=>CP,base32padupper:()=>RP,base32upper:()=>kP,base32z:()=>OP});var Lt=pt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kP=pt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),CP=pt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),RP=pt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),PP=pt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),LP=pt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),NP=pt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DP=pt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),OP=pt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var N3={};wt(N3,{base36:()=>dn,base36upper:()=>BP});var dn=Ri({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),BP=Ri({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var D3={};wt(D3,{base58btc:()=>Ye,base58flickr:()=>MP});var Ye=Ri({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),MP=Ri({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var O3={};wt(O3,{base64:()=>xt,base64pad:()=>tu,base64url:()=>ru,base64urlpad:()=>UP});var xt=pt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tu=pt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ru=pt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),UP=pt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var B3={};wt(B3,{base8:()=>FP});var FP=pt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var M3={};wt(M3,{identity:()=>$P});var $P=oc({prefix:"\0",name:"identity",encode:r=>n9(r),decode:r=>r9(r)});var bh={};wt(bh,{code:()=>U3,decode:()=>zP,encode:()=>qP,name:()=>HP});var VP=new TextEncoder,KP=new TextDecoder,HP="json",U3=512;function qP(r){return VP.encode(JSON.stringify(r))}function zP(r){return JSON.parse(KP.decode(r))}var Fs={};wt(Fs,{code:()=>Ho,decode:()=>jP,encode:()=>GP,name:()=>WP});var WP="raw",Ho=85;function GP(r){return Ln(r)}function jP(r){return Ln(r)}var V3={};wt(V3,{identity:()=>Et});var ct={};wt(ct,{Digest:()=>$s,create:()=>mr,decode:()=>Ge,equals:()=>$3,hasCode:()=>hL});var YP=l9,a9=128,XP=127,QP=~XP,ZP=Math.pow(2,31);function l9(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ZP;)e[t++]=r&255|a9,r/=128;for(;r&QP;)e[t++]=r&255|a9,r>>>=7;return e[t]=r|0,l9.bytes=t-n+1,e}var JP=F3,eL=128,c9=127;function F3(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw F3.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&c9)<<o:(s&c9)*Math.pow(2,o),o+=7}while(s>=eL);return F3.bytes=i-n,t}var tL=Math.pow(2,7),rL=Math.pow(2,14),nL=Math.pow(2,21),oL=Math.pow(2,28),iL=Math.pow(2,35),sL=Math.pow(2,42),aL=Math.pow(2,49),cL=Math.pow(2,56),lL=Math.pow(2,63),uL=function(r){return r<tL?1:r<rL?2:r<nL?3:r<oL?4:r<iL?5:r<sL?6:r<aL?7:r<cL?8:r<lL?9:10},dL={encode:YP,decode:JP,encodingLength:uL},fL=dL,nu=fL;function ou(r,e=0){return[nu.decode(r,e),nu.decode.bytes]}function ic(r,e,t=0){return nu.encode(r,e,t),e}function sc(r){return nu.encodingLength(r)}function mr(r,e){let t=e.byteLength,n=sc(r),o=n+sc(t),i=new Uint8Array(o+t);return ic(r,i,0),ic(t,i,n),i.set(e,o),new $s(r,t,e,i)}function Ge(r){let e=Ln(r),[t,n]=ou(e),[o,i]=ou(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new $s(t,o,s,e)}function $3(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&t9(r.bytes,t.bytes)}}var $s=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function hL(r,e){return r.code===e}var u9=0,pL="identity",d9=Ln;function mL(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return mr(u9,d9(r))}var Et={code:u9,name:pL,encode:d9,digest:mL};var H3={};wt(H3,{sha256:()=>ft,sha512:()=>Eh});var gL=20;function iu({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new K3(r,e,t,n,o)}var K3=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??gL,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?f9(n,this.code,t?.truncate):n.then(o=>f9(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function f9(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return mr(e,r)}function p9(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ft=iu({name:"sha2-256",code:18,encode:p9("SHA-256")}),Eh=iu({name:"sha2-512",code:19,encode:p9("SHA-512")});function m9(r,e){let{bytes:t,version:n}=r;return n===0?wL(t,q3(r),e??Ye.encoder):bL(t,q3(r),e??Lt.encoder)}var g9=new WeakMap;function q3(r){let e=g9.get(r);if(e==null){let t=new Map;return g9.set(r,t),t}return e}var J=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==su)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xL)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=mr(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&&$3(e.multihash,n.multihash)}toString(e){return m9(this,e)}toJSON(){return{"/":m9(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??y9(n,o,i.bytes))}else if(t[EL]===!0){let{version:n,multihash:o,code:i}=t,s=Ge(o);return r.create(n,i,s)}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!==su)throw new Error(`Version 0 CID must use dag-pb (code: ${su}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=y9(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,su,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Ln(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new $s(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=ou(e.subarray(t));return t+=f,d},o=n(),i=su;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=yL(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return q3(i).set(n,e),i}};function yL(r,e){switch(r[0]){case"Q":{let t=e??Ye;return[Ye.prefix,t.decode(`${Ye.prefix}${r}`)]}case Ye.prefix:{let t=e??Ye;return[Ye.prefix,t.decode(r)]}case Lt.prefix:{let t=e??Lt;return[Lt.prefix,t.decode(r)]}case dn.prefix:{let t=e??dn;return[dn.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 wL(r,e,t){let{prefix:n}=t;if(n!==Ye.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function bL(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var su=112,xL=18;function y9(r,e,t){let n=sc(r),o=n+sc(e),i=new Uint8Array(o+t.byteLength);return ic(r,i,0),ic(e,i,n),i.set(t,o),i}var EL=Symbol.for("@ipld/js-cid/CID");var Vs={...M3,...R3,...B3,...k3,...C3,...L3,...N3,...D3,...O3,...P3},Zz={...H3,...V3};function be(r=0){return new Uint8Array(r)}function Xe(r=0){return new Uint8Array(r)}function b9(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var w9=b9("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),z3=b9("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=Xe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),vL={utf8:w9,"utf-8":w9,hex:Vs.base16,latin1:z3,ascii:z3,binary:z3,...Vs},vh=vL;function D(r,e="utf8"){let t=vh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var W3=60;function Sh(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:Dr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Dr[e.type],TTL:e.TTL??e.ttl??W3,data:e.data instanceof Uint8Array?D(e.data):e.data}))}}var SL=4;function G3(r,e={}){let t=new Us({concurrency:e.queryConcurrency??SL});return async(n,o={})=>{let i=o?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),wh(o.types).forEach(c=>{s.append("type",Dr[c])}),o.onProgress?.(new U("dns:query",n)),i?.("GET %s",`${r}?${s}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(i?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=Sh(await c.json());return o.onProgress?.(new U("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function x9(){return[G3("https://cloudflare-dns.com/dns-query"),G3("https://dns.google/resolve")]}var S9=Fo(v9(),1);var j3=class{lru;constructor(e){this.lru=(0,S9.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return Sh({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:Dr[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??W3)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function A9(r){return new j3(r)}var AL=1e3,Ah=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=A9(e.cacheSize??AL),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=x9())}async query(e,t={}){let n=wh(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new U("dns:cache",o)),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new U("dns:error",l))}}throw new gh(a,`DNS lookup of ${e} ${n} failed`)}};var Dr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Dr||(Dr={}));function Th(r={}){return new Ah(r)}function TL(r){return r[Symbol.asyncIterator]!=null}function _L(r){if(TL(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Sr=_L;var au=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},cu=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},_h=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var T9={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new _h("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 vt=T9;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 Je(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Xe(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var I9=Symbol.for("@achingbrain/uint8arraylist");function _9(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function ac(r){return!!r?.[I9]}var ie=class r{bufs;length;[I9]=!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(ac(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(ac(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=_9(this.bufs,e);return t.buf[t.index]}set(e,t){let n=_9(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(ac(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Je(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Je(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(s);break}let d=e-a;n.push(s.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(u){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ac(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let d=0;d<i;d++)s[d]=-1;for(let d=0;d<o;d++)s[n[d]]=d;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}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=Xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=be(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=be(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!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((o,i)=>o+i.byteLength,0)),n.length=t,n}};function L(r,e="utf8"){let t=vh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var kL=parseInt("11111",2),Y3=parseInt("10000000",2),CL=parseInt("01111111",2),k9={0:lu,1:lu,2:RL,3:NL,4:DL,5:LL,6:PL,16:lu,22:lu,48:lu};function fn(r,e={offset:0}){let t=r[e.offset]&kL;if(e.offset++,k9[t]!=null)return k9[t](r,e);throw new Error("No decoder for tag "+t)}function uu(r,e){let t=0;if((r[e.offset]&Y3)===Y3){let n=r[e.offset]&CL,o="0x";e.offset++;for(let i=0;i<n;i++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function lu(r,e){uu(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=fn(r,e);if(n===null)break;t.push(n)}return t}function RL(r,e){let t=uu(r,e),n=e.offset,o=e.offset+t,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return e.offset+=t,Uint8Array.from(i)}function PL(r,e){let t=uu(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function LL(r,e){return e.offset++,null}function NL(r,e){let t=uu(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function DL(r,e){let t=uu(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function OL(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ie;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Ih(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=OL(r.byteLength);return new ie(Uint8Array.from([e.byteLength|Y3]),e)}function gr(r){let e=new ie,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ie(Uint8Array.from([2]),Ih(e),e)}function du(r){let e=Uint8Array.from([0]),t=new ie(e,r);return new ie(Uint8Array.from([3]),Ih(t),t)}function C9(r){return new ie(Uint8Array.from([4]),Ih(r),r)}function Nn(r,e=48){let t=new ie;for(let n of r)t.append(n);return new ie(Uint8Array.from([e]),Ih(t),t)}var R9="1.2.840.10045.3.1.7",P9="1.3.132.0.34",L9="1.3.132.0.35";async function N9(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function D9(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function O9(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),i}var BL=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ML=Uint8Array.from([6,5,43,129,4,0,34]),UL=Uint8Array.from([6,5,43,129,4,0,35]),B9={ext:!0,kty:"EC",crv:"P-256"},M9={ext:!0,kty:"EC",crv:"P-384"},U9={ext:!0,kty:"EC",crv:"P-521"},cc=32,lc=48,uc=66;function F9(r){let e=fn(r);return X3(e)}function X3(r){let e=r[1],t=D(e,"base64url"),n=r[2][1][0],o=1,i,s;if(e.byteLength===cc)return i=D(n.subarray(o,o+cc),"base64url"),s=D(n.subarray(o+cc),"base64url"),new Hs({...B9,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===lc)return i=D(n.subarray(o,o+lc),"base64url"),s=D(n.subarray(o+lc),"base64url"),new Hs({...M9,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===uc)return i=D(n.subarray(o,o+uc),"base64url"),s=D(n.subarray(o+uc),"base64url"),new Hs({...U9,key_ops:["sign"],d:t,x:i,y:s});throw new T(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Q3(r){let e=fn(r);return $9(e)}function $9(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===cc*2+1)return n=D(e.subarray(t,t+cc),"base64url"),o=D(e.subarray(t+cc),"base64url"),new Ks({...B9,key_ops:["verify"],x:n,y:o});if(e.byteLength===lc*2+1)return n=D(e.subarray(t,t+lc),"base64url"),o=D(e.subarray(t+lc),"base64url"),new Ks({...M9,key_ops:["verify"],x:n,y:o});if(e.byteLength===uc*2+1)return n=D(e.subarray(t,t+uc),"base64url"),o=D(e.subarray(t+uc),"base64url"),new Ks({...U9,key_ops:["verify"],x:n,y:o});throw new T(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function V9(r){return Nn([gr(Uint8Array.from([1])),C9(L(r.d??"","base64url")),Nn([H9(r.crv)],160),Nn([du(new ie(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function K9(r){return Nn([gr(Uint8Array.from([1])),Nn([H9(r.crv)],160),Nn([du(new ie(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function H9(r){if(r==="P-256")return BL;if(r==="P-384")return ML;if(r==="P-521")return UL;throw new T(`Invalid curve ${r}`)}async function q9(r="P-256"){let e=await N9(r);return new Hs(e.privateKey)}var Ks=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=K9(this.jwk)),this._raw}toMultihash(){return Et.digest(Nt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}async verify(e,t,n){return O9(this.jwk,t,e,n)}},Hs=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Ks({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=V9(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}async sign(e,t){return D9(this.jwk,e,t)}};function Z3(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Ar(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Ht(r,e,t=""){let n=Z3(r),o=r?.length,i=e!==void 0;if(!n||i&&o!==e){let s=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function zo(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Ar(r.outputLen),Ar(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function dc(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 kh(r,e){Ht(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function nr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function qs(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Dn(r,e){return r<<32-e|r>>>e}function Ch(r,e){return r<<e|r>>>32-e>>>0}var W9=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",FL=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Rh(r){if(Ht(r),W9)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=FL[r[t]];return e}var qo={_0:48,_9:57,A:65,F:70,a:97,f:102};function z9(r){if(r>=qo._0&&r<=qo._9)return r-qo._0;if(r>=qo.A&&r<=qo.F)return r-(qo.A-10);if(r>=qo.a&&r<=qo.f)return r-(qo.a-10)}function fu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(W9)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,i=0;o<t;o++,i+=2){let s=z9(r.charCodeAt(i)),a=z9(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}var $L=async()=>{};async function G9(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-n;i>=0&&i<e||(await $L(),n+=i)}}function VL(r){if(typeof r!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(r))}function J3(r,e=""){return typeof r=="string"?VL(r):Ht(r,void 0,e)}function e4(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ht(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function j9(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new TypeError("options must be object or undefined");return Object.assign(r,e)}function hu(r,e={}){let t=(o,i)=>r(i).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Ph(r=32){Ar(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var t4=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Lh(r,e,t){return r&e^~r&t}function Nh(r,e,t){return r&e^r&t^e&t}var zs=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=qs(this.buffer)}update(e){dc(this),Ht(e);let{view:t,buffer:n,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=qs(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){dc(this),kh(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[s++]=128,nr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let d=s;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),i),this.process(n,0);let a=qs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Wo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Dh=BigInt(4294967295),Y9=BigInt(32);function KL(r,e=!1){return e?{h:Number(r&Dh),l:Number(r>>Y9&Dh)}:{h:Number(r>>Y9&Dh)|0,l:Number(r&Dh)|0}}function X9(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let i=0;i<t;i++){let{h:s,l:a}=KL(r[i],e);[n[i],o[i]]=[s,a]}return[n,o]}var r4=(r,e,t)=>r>>>t,n4=(r,e,t)=>r<<32-t|e>>>t,Ws=(r,e,t)=>r>>>t|e<<32-t,Gs=(r,e,t)=>r<<32-t|e>>>t,pu=(r,e,t)=>r<<64-t|e>>>t-32,mu=(r,e,t)=>r>>>t-32|e<<64-t;function ho(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Q9=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Z9=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,J9=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),ew=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,tw=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),rw=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var qL=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pi=new Uint32Array(64),o4=class extends zs{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)Pi[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Pi[d-15],h=Pi[d-2],p=Dn(f,7)^Dn(f,18)^f>>>3,y=Dn(h,17)^Dn(h,19)^h>>>10;Pi[d]=y+Pi[d-7]+p+Pi[d-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=Dn(a,6)^Dn(a,11)^Dn(a,25),h=u+f+Lh(a,c,l)+qL[d]+Pi[d]|0,y=(Dn(n,2)^Dn(n,13)^Dn(n,22))+Nh(n,o,i)|0;u=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,l,u)}roundClean(){nr(Pi)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),nr(this.buffer)}},i4=class extends o4{A=Wo[0]|0;B=Wo[1]|0;C=Wo[2]|0;D=Wo[3]|0;E=Wo[4]|0;F=Wo[5]|0;G=Wo[6]|0;H=Wo[7]|0;constructor(){super(32)}};var nw=X9(["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))),zL=nw[0],WL=nw[1],Li=new Uint32Array(80),Ni=new Uint32Array(80),s4=class extends zs{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:y,Hl:m}=this;return[e,t,n,o,i,s,a,c,l,u,d,f,h,p,y,m]}set(e,t,n,o,i,s,a,c,l,u,d,f,h,p,y,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=h|0,this.Gl=p|0,this.Hh=y|0,this.Hl=m|0}process(e,t){for(let P=0;P<16;P++,t+=4)Li[P]=e.getUint32(t),Ni[P]=e.getUint32(t+=4);for(let P=16;P<80;P++){let O=Li[P-15]|0,F=Ni[P-15]|0,V=Ws(O,F,1)^Ws(O,F,8)^r4(O,F,7),H=Gs(O,F,1)^Gs(O,F,8)^n4(O,F,7),C=Li[P-2]|0,B=Ni[P-2]|0,q=Ws(C,B,19)^pu(C,B,61)^r4(C,B,6),$=Gs(C,B,19)^mu(C,B,61)^n4(C,B,6),b=J9(H,$,Ni[P-7],Ni[P-16]),S=ew(b,V,q,Li[P-7],Li[P-16]);Li[P]=S|0,Ni[P]=b|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:y,Gl:m,Hh:g,Hl:x}=this;for(let P=0;P<80;P++){let O=Ws(d,f,14)^Ws(d,f,18)^pu(d,f,41),F=Gs(d,f,14)^Gs(d,f,18)^mu(d,f,41),V=d&h^~d&y,H=f&p^~f&m,C=tw(x,F,H,WL[P],Ni[P]),B=rw(C,g,O,V,zL[P],Li[P]),q=C|0,$=Ws(n,o,28)^pu(n,o,34)^pu(n,o,39),b=Gs(n,o,28)^mu(n,o,34)^mu(n,o,39),S=n&i^n&a^i&a,A=o&s^o&c^s&c;g=y|0,x=m|0,y=h|0,m=p|0,h=d|0,p=f|0,{h:d,l:f}=ho(l|0,u|0,B|0,q|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let E=Q9(q,b,A);n=Z9(E,B,$,S),o=E|0}({h:n,l:o}=ho(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=ho(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=ho(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ho(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=ho(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=ho(this.Fh|0,this.Fl|0,h|0,p|0),{h:y,l:m}=ho(this.Gh|0,this.Gl|0,y|0,m|0),{h:g,l:x}=ho(this.Hh|0,this.Hl|0,g|0,x|0),this.set(n,o,i,s,a,c,l,u,d,f,h,p,y,m,g,x)}roundClean(){nr(Li,Ni)}destroy(){this.destroyed=!0,nr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},a4=class extends s4{Ah=qt[0]|0;Al=qt[1]|0;Bh=qt[2]|0;Bl=qt[3]|0;Ch=qt[4]|0;Cl=qt[5]|0;Dh=qt[6]|0;Dl=qt[7]|0;Eh=qt[8]|0;El=qt[9]|0;Fh=qt[10]|0;Fl=qt[11]|0;Gh=qt[12]|0;Gl=qt[13]|0;Hh=qt[14]|0;Hl=qt[15]|0;constructor(){super(64)}};var hn=hu(()=>new i4,t4(1));var po=hu(()=>new a4,t4(3));var _e=(r,e,t)=>Ht(r,e,t),l4=Ar,fc=Rh,_t=(...r)=>e4(...r),hc=r=>fu(r),js=Z3,Ys=r=>Ph(r),Bh=BigInt(0),c4=BigInt(1);function On(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Mh(r){if(typeof r=="bigint"){if(!Oh(r))throw new RangeError("positive bigint expected, got "+r)}else l4(r);return r}function Bn(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function gu(r){let e=Mh(r).toString(16);return e.length&1?"0"+e:e}function ow(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Bh:BigInt("0x"+r)}function Xs(r){return ow(Rh(r))}function Or(r){return ow(Rh(Di(Ht(r)).reverse()))}function Uh(r,e){if(Ar(e),e===0)throw new RangeError("zero length");r=Mh(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return fu(t.padStart(e*2,"0"))}function yu(r,e){return Uh(r,e).reverse()}function iw(r,e){if(r=_e(r),e=_e(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Di(r){return Uint8Array.from(_e(r))}function Fh(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Oh=r=>typeof r=="bigint"&&Bh<=r;function GL(r,e,t){return Oh(r)&&Oh(e)&&Oh(t)&&e<=r&&r<t}function Go(r,e,t,n){if(!GL(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function pc(r){if(r<Bh)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Bh;r>>=c4,e+=1);return e}var wu=r=>(c4<<BigInt(r))-c4;function sw(r,e,t){if(Ar(r,"hashLen"),Ar(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},f=(...m)=>t(l,_t(c,...m)),h=(m=o)=>{l=f(i,m),c=f(),m.length!==0&&(l=f(s,m),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=f();let x=c.slice();g.push(x),m+=c.length}return _t(...g)};return(m,g)=>{d(),h(m);let x;for(;(x=g(p()))===void 0;)h();return d(),x}}function Br(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(r,i))throw new TypeError(`param "${i}" is invalid: expected own property`);let c=r[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>n(a,c,s));o(e,!1),o(t,!0)}var u4=()=>{throw new Error("not implemented")};var zt=BigInt(0),mt=BigInt(1),Qs=BigInt(2),uw=BigInt(3),dw=BigInt(4),fw=BigInt(5),jL=BigInt(7),hw=BigInt(8),YL=BigInt(9),pw=BigInt(16);function lt(r,e){if(e<=zt)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=zt?t:e+t}function nt(r,e,t){if(e<zt)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >zt;)n*=n,n%=t;return n}function aw(r,e){if(r===zt)throw new Error("invert: expected non-zero number");if(e<=zt)throw new Error("invert: expected positive modulus, got "+e);let t=lt(r,e),n=e,o=zt,i=mt,s=mt,a=zt;for(;t!==zt;){let l=n/t,u=n-t*l,d=o-s*l,f=i-a*l;n=t,t=u,o=s,i=a,s=d,a=f}if(n!==mt)throw new Error("invert: does not exist");return lt(o,e)}function d4(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function mw(r,e){let t=r,n=(t.ORDER+mt)/dw,o=t.pow(e,n);return d4(t,o,e),o}function XL(r,e){let t=r,n=(t.ORDER-fw)/hw,o=t.mul(e,Qs),i=t.pow(o,n),s=t.mul(e,i),a=t.mul(t.mul(s,Qs),i),c=t.mul(s,t.sub(a,t.ONE));return d4(t,c,e),c}function QL(r){let e=mc(r),t=gw(r),n=t(e,e.neg(e.ONE)),o=t(e,n),i=t(e,e.neg(n)),s=(r+jL)/pw;return((a,c)=>{let l=a,u=l.pow(c,s),d=l.mul(u,n),f=l.mul(u,o),h=l.mul(u,i),p=l.eql(l.sqr(d),c),y=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,y);let m=l.eql(l.sqr(d),c),g=l.cmov(u,d,m);return d4(l,g,c),g})}function gw(r){if(r<uw)throw new Error("sqrt is not defined for small field");let e=r-mt,t=0;for(;e%Qs===zt;)e/=Qs,t++;let n=Qs,o=mc(r);for(;cw(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return mw;let i=o.pow(n,e),s=(e+mt)/Qs;return function(c,l){let u=c;if(u.is0(l))return l;if(cw(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,i),h=u.pow(l,e),p=u.pow(l,s);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let y=1,m=u.sqr(h);for(;!u.eql(m,u.ONE);)if(y++,m=u.sqr(m),y===d)throw new Error("Cannot find square root");let g=mt<<BigInt(d-y-1),x=u.pow(f,g);d=y,f=u.sqr(x),h=u.mul(h,f),p=u.mul(p,x)}return p}}function ZL(r){return r%dw===uw?mw:r%hw===fw?XL:r%pw===YL?QL(r):gw(r)}var jo=(r,e)=>(lt(r,e)&mt)===mt,JL=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function f4(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=JL.reduce((n,o)=>(n[o]="function",n),e);if(Br(r,t),Bn(r.BYTES,"BYTES"),Bn(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=mt)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function eN(r,e,t){let n=r;if(t<zt)throw new Error("invalid exponent, negatives unsupported");if(t===zt)return n.ONE;if(t===mt)return e;let o=n.ONE,i=e;for(;t>zt;)t&mt&&(o=n.mul(o,i)),i=n.sqr(i),t>>=mt;return o}function bu(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),i=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),s=n.inv(i);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),s),o}function cw(r,e){let t=r,n=(t.ORDER-mt)/Qs,o=t.pow(e,n),i=t.eql(o,t.ONE),s=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function tN(r,e){if(e!==void 0&&l4(e),r<=zt)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=pc(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var lw=new WeakMap,$h=class{ORDER;BITS;BYTES;isLE;ZERO=zt;ONE=mt;_lengths;_mod;constructor(e,t={}){if(e<=mt)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:i}=tN(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(e){return lt(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return zt<=e&&e<this.ORDER}is0(e){return e===zt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&mt)===mt}neg(e){return lt(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return lt(e*e,this.ORDER)}add(e,t){return lt(e+t,this.ORDER)}sub(e,t){return lt(e-t,this.ORDER)}mul(e,t){return lt(e*t,this.ORDER)}pow(e,t){return eN(this,e,t)}div(e,t){return lt(e*aw(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return aw(e,this.ORDER)}sqrt(e){let t=lw.get(this);return t||lw.set(this,t=ZL(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?yu(e,this.BYTES):Uh(e,this.BYTES)}fromBytes(e,t=!1){_e(e);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Or(e):Xs(e);if(a&&(c=lt(c,s)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return bu(this,e)}cmov(e,t,n){return On(n,"condition"),n?t:e}};Object.freeze($h.prototype);function mc(r,e={}){return new $h(r,e)}function yw(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=mt)throw new Error("field order must be greater than 1");let e=pc(r-mt);return Math.ceil(e/8)}function h4(r){let e=yw(r);return e+Math.ceil(e/2)}function p4(r,e,t=!1){_e(r);let n=r.length,o=yw(e),i=Math.max(h4(e),16);if(n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=t?Or(r):Xs(r),a=lt(s,e-mt)+mt;return t?yu(a,o):Uh(a,o)}var gc=BigInt(0),Zs=BigInt(1);function xu(r,e){let t=e.negate();return r?t:e}function Js(r,e){let t=bu(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Ew(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function m4(r,e){Ew(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,i=wu(r),s=BigInt(r);return{windows:t,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function ww(r,e,t){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=t,a=Number(r&o),c=r>>s;a>n&&(a-=i,c+=Zs);let l=e*n,u=l+Math.abs(a)-1,d=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:l}}var g4=new WeakMap,vw=new WeakMap;function y4(r){return vw.get(r)||1}function bw(r){if(r!==gc)throw new Error("invalid wNAF")}var yc=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>gc;)t&Zs&&(n=n.add(o)),o=o.double(),t>>=Zs;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=m4(t,this.bits),i=[],s=e,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=m4(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:h}=ww(n,a,s);n=c,u?i=i.add(xu(f,t[h])):o=o.add(xu(d,t[l]))}return bw(n),{p:o,f:i}}wNAFUnsafe(e,t,n,o=this.ZERO){let i=m4(e,this.bits);for(let s=0;s<i.windows&&n!==gc;s++){let{nextN:a,offset:c,isZero:l,isNeg:u}=ww(n,s,i);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return bw(n),o}getPrecomputes(e,t,n){let o=g4.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),g4.set(t,o))),o}cached(e,t,n){let o=y4(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let i=y4(e);return i===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,o)}createCache(e,t){Ew(t,this.bits),vw.set(e,t),g4.delete(e)}hasCache(e){return y4(e)!==1}};function Sw(r,e,t,n){let o=e,i=r.ZERO,s=r.ZERO;for(;t>gc||n>gc;)t&Zs&&(i=i.add(o)),n&Zs&&(s=s.add(o)),o=o.double(),t>>=Zs,n>>=Zs;return{p1:i,p2:s}}function xw(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return f4(e),e}else return mc(r,{isLE:t})}function Vh(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>gc))throw new Error(`CURVE.${c} must be positive bigint`)}let o=xw(e.p,t.Fp,n),i=xw(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function wc(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Oi=BigInt(0),Dt=BigInt(1),w4=BigInt(2),rN=BigInt(8);function nN(r,e,t,n){let o=r.sqr(t),i=r.sqr(n),s=r.add(r.mul(e.a,o),i),a=r.add(r.ONE,r.mul(e.d,r.mul(o,i)));return r.eql(s,a)}function Aw(r,e={}){let t=e,n=Vh("edwards",r,t,t.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;Br(t,{},{uvRatio:"function"});let c=w4<<BigInt(i.BYTES*8)-Dt,l=y=>o.create(y),u=t.uvRatio===void 0?(y,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(y,m))}}catch{return{isValid:!1,value:Oi}}}:t.uvRatio;if(!nN(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(y,m,g=!1){let x=g?Dt:Oi;return Go("coordinate "+y,m,x,c),m}function f(y){if(!(y instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,Dt,l(s.Gx*s.Gy));static ZERO=new h(Oi,Dt,Dt,Oi);static Fp=o;static Fn=i;X;Y;Z;T;constructor(m,g,x,P){this.X=d("x",m),this.Y=d("y",g),this.Z=d("z",x,!0),this.T=d("t",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:g,y:x}=m||{};return d("x",g),d("y",x),new h(g,x,Dt,l(g*x))}static fromBytes(m,g=!1){let x=o.BYTES,{a:P,d:O}=s;m=Di(_e(m,x,"point")),On(g,"zip215");let F=Di(m),V=m[x-1];F[x-1]=V&-129;let H=Or(F),C=g?c:o.ORDER;Go("point.y",H,Oi,C);let B=l(H*H),q=l(B-Dt),$=l(O*B-P),{isValid:b,value:S}=u(q,$);if(!b)throw new Error("bad point: invalid y coordinate");let A=(S&Dt)===Dt,E=(V&128)!==0;if(!g&&S===Oi&&E)throw new Error("bad point: x=0 and x_0=1");return E!==A&&(S=l(-S)),h.fromAffine({x:S,y:H})}static fromHex(m,g=!1){return h.fromBytes(hc(m),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,g=!0){return p.createCache(this,m),g||this.multiply(w4),this}assertValidity(){let m=this,{a:g,d:x}=s;if(m.is0())throw new Error("bad point: ZERO");let{X:P,Y:O,Z:F,T:V}=m,H=l(P*P),C=l(O*O),B=l(F*F),q=l(B*B),$=l(H*g),b=l(B*l($+C)),S=l(q+l(x*l(H*C)));if(b!==S)throw new Error("bad point: equation left != right (1)");let A=l(P*O),E=l(F*V);if(A!==E)throw new Error("bad point: equation left != right (2)")}equals(m){f(m);let{X:g,Y:x,Z:P}=this,{X:O,Y:F,Z:V}=m,H=l(g*V),C=l(O*P),B=l(x*V),q=l(F*P);return H===C&&B===q}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:m}=s,{X:g,Y:x,Z:P}=this,O=l(g*g),F=l(x*x),V=l(w4*l(P*P)),H=l(m*O),C=g+x,B=l(l(C*C)-O-F),q=H+F,$=q-V,b=H-F,S=l(B*$),A=l(q*b),E=l(B*b),v=l($*q);return new h(S,A,v,E)}add(m){f(m);let{a:g,d:x}=s,{X:P,Y:O,Z:F,T:V}=this,{X:H,Y:C,Z:B,T:q}=m,$=l(P*H),b=l(O*C),S=l(V*x*q),A=l(F*B),E=l((P+O)*(H+C)-$-b),v=A-S,N=A+S,M=l(b-g*$),R=l(E*v),z=l(N*M),W=l(E*M),ae=l(v*N);return new h(R,z,ae,W)}subtract(m){return f(m),this.add(m.negate())}multiply(m){if(!i.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:x}=p.cached(this,m,P=>Js(h,P));return Js(h,[g,x])[0]}multiplyUnsafe(m){if(!i.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===Oi?h.ZERO:this.is0()||m===Dt?this:p.unsafe(this,m,g=>Js(h,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,s.n).is0()}toAffine(m){let g=this,x=m,{X:P,Y:O,Z:F}=g,V=g.is0();x==null&&(x=V?rN:o.inv(F));let H=l(P*x),C=l(O*x),B=o.mul(F,x);if(V)return{x:Oi,y:Dt};if(B!==Dt)throw new Error("invZ was invalid");return{x:H,y:C}}clearCofactor(){return a===Dt?this:this.multiplyUnsafe(a)}toBytes(){let{x:m,y:g}=this.toAffine(),x=o.toBytes(g);return x[x.length-1]|=m&Dt?128:0,x}toHex(){return fc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new yc(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Kh=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){u4()}static fromHex(e){u4()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return fc(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function Tw(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Br(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(Bn(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?Ys:o.randomBytes,f=o.adjustScalarBytes===void 0?b=>b:o.adjustScalarBytes,h=o.domain===void 0?(b,S,A)=>{if(On(A,"phflag"),S.length||A)throw new Error("Contexts/pre-hash are not supported");return b}:o.domain;function p(b){return c.create(Or(b))}function y(b){let S=H.secretKey;_e(b,H.secretKey,"secretKey");let A=_e(n(b),2*S,"hashedSecretKey"),E=f(A.slice(0,S)),v=A.slice(S,2*S),N=p(E);return{head:E,prefix:v,scalar:N}}function m(b){let{head:S,prefix:A,scalar:E}=y(b),v=s.multiply(E),N=v.toBytes();return{head:S,prefix:A,scalar:E,point:v,pointBytes:N}}function g(b){return m(b).pointBytes}function x(b=Uint8Array.of(),...S){let A=_t(...S);return p(n(h(A,_e(b,void 0,"context"),!!i)))}function P(b,S,A={}){b=_e(b,void 0,"message"),i&&(b=i(b));let{prefix:E,scalar:v,pointBytes:N}=m(S),M=x(A.context,E,b),R=s.multiply(M).toBytes(),z=x(A.context,R,N,b),W=c.create(M+z*v);if(!c.isValid(W))throw new Error("sign failed: invalid s");let ae=_t(R,c.toBytes(W));return _e(ae,H.signature,"result")}let O={zip215:o.zip215};function F(b,S,A,E=O){let{context:v}=E,N=E.zip215===void 0?!!O.zip215:E.zip215,M=H.signature;b=_e(b,M,"signature"),S=_e(S,void 0,"message"),A=_e(A,H.publicKey,"publicKey"),N!==void 0&&On(N,"zip215"),i&&(S=i(S));let R=M/2,z=b.subarray(0,R),W=Or(b.subarray(R,M)),ae,ve,xe;try{ae=r.fromBytes(A,N),ve=r.fromBytes(z,N),xe=s.multiplyUnsafe(W)}catch{return!1}if(!N&&ae.isSmallOrder())return!1;let qe=x(v,z,A,S);return ve.add(ae.multiplyUnsafe(qe)).subtract(xe).clearCofactor().is0()}let V=a.BYTES,H={secretKey:V,publicKey:V,signature:2*V,seed:V};function C(b){return b=b===void 0?d(H.seed):b,_e(b,H.seed,"seed")}function B(b){return js(b)&&b.length===H.secretKey}function q(b,S){try{return!!r.fromBytes(b,S===void 0?O.zip215:S)}catch{return!1}}let $={getExtendedPublicKey:m,randomSecretKey:C,isValidSecretKey:B,isValidPublicKey:q,toMontgomery(b){let{y:S}=r.fromBytes(b),A=H.publicKey,E=A===32;if(!E&&A!==57)throw new Error("only defined for 25519 and 448");let v=E?a.div(Dt+S,Dt-S):a.div(S-Dt,S+Dt);return a.toBytes(v)},toMontgomerySecret(b){let S=H.secretKey;_e(b,S);let A=n(b.subarray(0,S));return f(A).subarray(0,S)}};return Object.freeze(H),Object.freeze($),Object.freeze({keygen:wc(C,g),getPublicKey:g,sign:P,verify:F,utils:$,Point:r,lengths:H})}function Eu(r,e){if(Bn(r),Bn(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function oN(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function iN(r){if(!js(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Fh(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function b4(r,e,t,n){_e(r),Bn(t),e=iN(e),e.length>255&&(e=n(_t(Fh("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(t/o);if(t>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=_t(e,Eu(e.length,1)),c=new Uint8Array(i),l=Eu(t,2),u=new Array(s),d=n(_t(c,r,l,Eu(0,1),a));u[0]=n(_t(d,Eu(1,1),a));for(let h=1;h<s;h++){let p=[oN(d,u[h-1]),Eu(h+1,1),a];u[h]=n(_t(...p))}return _t(...u).slice(0,t)}var _w="HashToScalar-";var vu=BigInt(0),bc=BigInt(1),Hh=BigInt(2);function sN(r){return Br(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...r})}function Iw(r){let e=sN(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:i,randomBytes:s}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=s===void 0?Ys:s,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),f=BigInt(a?121665:39081),h=a?Hh**BigInt(254):Hh**BigInt(447),p=a?BigInt(8)*Hh**BigInt(251)-bc:BigInt(4)*Hh**BigInt(445)-bc,y=h+p+bc,m=A=>lt(A,t),g=x(d);function x(A){return yu(m(A),u)}function P(A){let E=Di(_e(A,u,"uCoordinate"));return a&&(E[31]&=127),m(Or(E))}function O(A){return Or(o(Di(_e(A,u,"scalar"))))}function F(A,E){let v=q(P(E),O(A));if(v===vu)throw new Error("invalid private or public key received");return x(v)}function V(A){return F(A,g)}let H=V,C=F;function B(A,E,v){let N=m(A*(E-v));return E=m(E-N),v=m(v+N),{x_2:E,x_3:v}}function q(A,E){Go("u",A,vu,t),Go("scalar",E,h,y);let v=E,N=A,M=bc,R=vu,z=A,W=bc,ae=vu;for(let xe=BigInt(l-1);xe>=vu;xe--){let qe=v>>xe&bc;ae^=qe,{x_2:M,x_3:z}=B(ae,M,z),{x_2:R,x_3:W}=B(ae,R,W),ae=qe;let ze=M+R,We=m(ze*ze),Ne=M-R,at=m(Ne*Ne),Uo=We-at,Ls=z+W,Qa=z-W,Gl=m(Qa*ze),jl=m(Ls*Ne),j7=Gl+jl,Y7=Gl-jl;z=m(j7*j7),W=m(N*m(Y7*Y7)),M=m(We*at),R=m(Uo*(We+m(f*Uo)))}({x_2:M,x_3:z}=B(ae,M,z)),{x_2:R,x_3:W}=B(ae,R,W);let ve=i(R);return m(M*ve)}let $={secretKey:u,publicKey:u,seed:u},b=A=>(A=A===void 0?c(u):A,_e(A,$.seed,"seed"),A),S={randomSecretKey:b};return Object.freeze($),Object.freeze(S),Object.freeze({keygen:wc(b,H),getSharedSecret:C,getPublicKey:H,scalarMult:F,scalarMultBase:V,utils:S,GuBytes:g.slice(),lengths:$})}var aN=BigInt(0),Yo=BigInt(1),kw=BigInt(2),cN=BigInt(3),lN=BigInt(5),uN=BigInt(8),ea=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),S4={p:ea,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:uN,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Pw(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),i=ea,a=r*r%i*r%i,c=nt(a,kw,i)*a%i,l=nt(c,Yo,i)*r%i,u=nt(l,lN,i)*l%i,d=nt(u,e,i)*u%i,f=nt(d,t,i)*d%i,h=nt(f,n,i)*f%i,p=nt(h,o,i)*h%i,y=nt(p,o,i)*h%i,m=nt(y,e,i)*u%i;return{pow_p_5_8:nt(m,kw,i)*r%i,b2:a}}function Lw(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var x4=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function A4(r,e){let t=ea,n=lt(e*e*e,t),o=lt(n*n*e,t),i=Pw(r*o).pow_p_5_8,s=lt(r*n*i,t),a=lt(e*s*s,t),c=s,l=lt(s*x4,t),u=a===r,d=a===lt(-r,t),f=a===lt(-r*x4,t);return u&&(s=c),(d||f)&&(s=l),jo(s,t)&&(s=lt(-s,t)),{isValid:u||d,value:s}}var Mi=Aw(S4,{uvRatio:A4}),Bi=Mi.Fp,Nw=Mi.Fn;function dN(r){return Tw(Mi,po,Object.assign({adjustScalarBytes:Lw,zip215:!0},r))}var Su=dN({});var Au=(()=>{let r=ea;return Iw({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=Pw(e);return lt(nt(t,cN,r)*n,r)},adjustScalarBytes:Lw})})();var E4=x4,fN=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),hN=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),pN=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),mN=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Cw=r=>A4(Yo,r),gN=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),v4=r=>Bi.create(Or(r)&gN);function Rw(r){let{d:e}=S4,t=ea,n=g=>Bi.create(g),o=n(E4*r*r),i=n((o+Yo)*pN),s=BigInt(-1),a=n((s-e*o)*n(o+e)),{isValid:c,value:l}=A4(i,a),u=n(l*r);jo(u,t)||(u=n(-u)),c||(l=u),c||(s=o);let d=n(s*(o-Yo)*mN-a),f=l*l,h=n((l+l)*a),p=n(d*fN),y=n(Yo-f),m=n(Yo+f);return new Mi(n(h*m),n(y*p),n(p*m),n(h*y))}var Ui=class r extends Kh{static BASE=new r(Mi.BASE);static ZERO=new r(Mi.ZERO);static Fp=Bi;static Fn=Nw;constructor(e){super(e)}static fromAffine(e){return new r(Mi.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Ht(e,32);let{a:t,d:n}=S4,o=ea,i=O=>Bi.create(O),s=v4(e);if(!iw(Bi.toBytes(s),e)||jo(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(Yo+t*a),l=i(Yo-t*a),u=i(c*c),d=i(l*l),f=i(t*n*u-d),{isValid:h,value:p}=Cw(i(f*d)),y=i(p*l),m=i(p*y*f),g=i((s+s)*y);jo(g,o)&&(g=i(-g));let x=i(c*m),P=i(g*x);if(!h||jo(P,o)||x===aN)throw new Error("invalid ristretto255 encoding 2");return new r(new Mi(g,x,Yo,P))}static fromHex(e){return r.fromBytes(fu(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,i=ea,s=m=>Bi.create(m),a=s(s(n+t)*s(n-t)),c=s(e*t),l=s(c*c),{value:u}=Cw(s(a*l)),d=s(u*a),f=s(u*c),h=s(d*f*o),p;if(jo(o*h,i)){let m=s(t*E4),g=s(e*E4);e=m,t=g,p=s(d*hN)}else p=f;jo(e*h,i)&&(t=s(-t));let y=s((n-t)*p);return jo(y,i)&&(y=s(-y)),Bi.toBytes(y)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:i}=e.ep,s=l=>Bi.create(l),a=s(t*i)===s(n*o),c=s(n*i)===s(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Ui.BASE);Object.freeze(Ui.ZERO);Object.freeze(Ui.prototype);Object.freeze(Ui);var yN=Object.freeze({Point:Ui,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=b4(r,t,64,po);return yN.deriveToCurve(n)},hashToScalar(r,e={DST:_w}){let t=b4(r,e.DST,64,po);return Nw.create(Or(t))},deriveToCurve(r){Ht(r,64);let e=v4(r.subarray(0,32)),t=Rw(e),n=v4(r.subarray(32,64)),o=Rw(n);return new Ui(t.add(o))}});var ta=32,Mr=64,T4=32;var xc,Dw=(async()=>{try{return await vt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Ow(){let r=Su.utils.randomSecretKey(),e=Su.getPublicKey(r);return{privateKey:vN(r,e),publicKey:e}}async function wN(r,e){let t;r.length===Mr?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:D(r.subarray(32),"base64url"),d:D(t,"base64url"),ext:!0,key_ops:["sign"]},o=await vt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await vt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(i,0,i.byteLength)}function bN(r,e){let t=r.subarray(0,T4);return Su.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function Bw(r,e){return xc==null&&(xc=await Dw),xc?wN(r,e):bN(r,e)}async function xN(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await vt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await vt.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function EN(r,e,t){return Su.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Mw(r,e,t){return xc==null&&(xc=await Dw),xc?xN(r,e,t):EN(r,e,t)}function vN(r,e){let t=new Uint8Array(Mr);for(let n=0;n<T4;n++)t[n]=r[n],t[T4+n]=e[n];return t}function Ec(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Tu=class{type="Ed25519";raw;constructor(e){this.raw=Sc(e,ta)}toMultihash(){return Et.digest(Nt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Mw(this.raw,t,e);return Ec(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}},vc=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Sc(e,Mr),this.publicKey=new Tu(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=Bw(this.raw,e);return Ec(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function _4(r){if(r.length>Mr){r=Sc(r,Mr+ta);let n=r.subarray(0,Mr),o=r.subarray(Mr,r.length);return new vc(n,o)}r=Sc(r,Mr);let e=r.subarray(0,Mr),t=r.subarray(ta);return new vc(e,t)}function I4(r){return r=Sc(r,ta),new Tu(r)}async function Fw(){let{privateKey:r,publicKey:e}=Ow();return new vc(r,e)}function Sc(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new T(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var SN=Math.pow(2,7),AN=Math.pow(2,14),TN=Math.pow(2,21),k4=Math.pow(2,28),C4=Math.pow(2,35),R4=Math.pow(2,42),P4=Math.pow(2,49),Ve=128,or=127;function Ae(r){if(r<SN)return 1;if(r<AN)return 2;if(r<TN)return 3;if(r<k4)return 4;if(r<C4)return 5;if(r<R4)return 6;if(r<P4)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Fi(r,e,t=0){switch(Ae(r)){case 8:e[t++]=r&255|Ve,r/=128;case 7:e[t++]=r&255|Ve,r/=128;case 6:e[t++]=r&255|Ve,r/=128;case 5:e[t++]=r&255|Ve,r/=128;case 4:e[t++]=r&255|Ve,r>>>=7;case 3:e[t++]=r&255|Ve,r>>>=7;case 2:e[t++]=r&255|Ve,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function _N(r,e,t=0){switch(Ae(r)){case 8:e.set(t++,r&255|Ve),r/=128;case 7:e.set(t++,r&255|Ve),r/=128;case 6:e.set(t++,r&255|Ve),r/=128;case 5:e.set(t++,r&255|Ve),r/=128;case 4:e.set(t++,r&255|Ve),r>>>=7;case 3:e.set(t++,r&255|Ve),r>>>=7;case 2:e.set(t++,r&255|Ve),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function _u(r,e){let t=r[e],n=0;if(n+=t&or,t<Ve||(t=r[e+1],n+=(t&or)<<7,t<Ve)||(t=r[e+2],n+=(t&or)<<14,t<Ve)||(t=r[e+3],n+=(t&or)<<21,t<Ve)||(t=r[e+4],n+=(t&or)*k4,t<Ve)||(t=r[e+5],n+=(t&or)*C4,t<Ve)||(t=r[e+6],n+=(t&or)*R4,t<Ve)||(t=r[e+7],n+=(t&or)*P4,t<Ve))return n;throw new RangeError("Could not decode varint")}function IN(r,e){let t=r.get(e),n=0;if(n+=t&or,t<Ve||(t=r.get(e+1),n+=(t&or)<<7,t<Ve)||(t=r.get(e+2),n+=(t&or)<<14,t<Ve)||(t=r.get(e+3),n+=(t&or)<<21,t<Ve)||(t=r.get(e+4),n+=(t&or)*k4,t<Ve)||(t=r.get(e+5),n+=(t&or)*C4,t<Ve)||(t=r.get(e+6),n+=(t&or)*R4,t<Ve)||(t=r.get(e+7),n+=(t&or)*P4,t<Ve))return n;throw new RangeError("Could not decode varint")}function ir(r,e,t=0){return e==null&&(e=Xe(Ae(r))),e instanceof Uint8Array?Fi(r,e,t):_N(r,e,t)}function Ur(r,e=0){return r instanceof Uint8Array?_u(r,e):IN(r,e)}var L4=new Float32Array([-0]),$i=new Uint8Array(L4.buffer);function $w(r,e,t){L4[0]=r,e[t]=$i[0],e[t+1]=$i[1],e[t+2]=$i[2],e[t+3]=$i[3]}function Vw(r,e){return $i[0]=r[e],$i[1]=r[e+1],$i[2]=r[e+2],$i[3]=r[e+3],L4[0]}var N4=new Float64Array([-0]),sr=new Uint8Array(N4.buffer);function Kw(r,e,t){N4[0]=r,e[t]=sr[0],e[t+1]=sr[1],e[t+2]=sr[2],e[t+3]=sr[3],e[t+4]=sr[4],e[t+5]=sr[5],e[t+6]=sr[6],e[t+7]=sr[7]}function Hw(r,e){return sr[0]=r[e],sr[1]=r[e+1],sr[2]=r[e+2],sr[3]=r[e+3],sr[4]=r[e+4],sr[5]=r[e+5],sr[6]=r[e+6],sr[7]=r[e+7],N4[0]}var kN=BigInt(Number.MAX_SAFE_INTEGER),CN=BigInt(Number.MIN_SAFE_INTEGER),Fr=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 ra;if(e<kN&&e>CN)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>qw&&(o=0n,++n>qw&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ra;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ra}},ra=new Fr(0,0);ra.toBigInt=function(){return 0n};ra.zzEncode=ra.zzDecode=function(){return this};ra.length=function(){return 1};var qw=4294967296n;function zw(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 Ww(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(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,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function D4(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Mn(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function qh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var O4=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,Mn(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 Mn(this,4);return qh(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Mn(this,4);return qh(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Mn(this,4);let e=Vw(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Mn(this,4);let e=Hw(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 Mn(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Ww(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Mn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Mn(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 Fr(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 Mn(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 Mn(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 Mn(this,8);let e=qh(this.buf,this.pos+=4),t=qh(this.buf,this.pos+=4);return new Fr(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=_u(this.buf,this.pos);return this.pos+=Ae(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 Iu(r){return new O4(r instanceof Uint8Array?r:r.subarray())}function pe(r,e,t){let n=Iu(r);return e.decode(n,void 0,t)}function B4(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return Xe(s);o+s>e&&(n=Xe(e),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var na=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function M4(){}var F4=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},RN=B4();function PN(r){return globalThis.Buffer!=null?Xe(r):RN(r)}var Cu=class{len;head;tail;states;constructor(){this.len=0,this.head=new na(M4,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new na(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new $4((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(zh,10,Fr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Fr.fromBigInt(e);return this._push(zh,t.length(),t)}uint64Number(e){return this._push(Fi,Ae(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=Fr.fromBigInt(e).zzEncode();return this._push(zh,t.length(),t)}sint64Number(e){let t=Fr.fromNumber(e).zzEncode();return this._push(zh,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(U4,1,e?1:0)}fixed32(e){return this._push(ku,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Fr.fromBigInt(e);return this._push(ku,4,t.lo)._push(ku,4,t.hi)}fixed64Number(e){let t=Fr.fromNumber(e);return this._push(ku,4,t.lo)._push(ku,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($w,4,e)}double(e){return this._push(Kw,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(U4,1,0):this.uint32(t)._push(NN,t,e)}string(e){let t=zw(e);return t!==0?this.uint32(t)._push(D4,t,e):this._push(U4,1,0)}fork(){return this.states=new F4(this),this.head=this.tail=new na(M4,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 na(M4,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=PN(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function U4(r,e,t){e[t]=r&255}function LN(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var $4=class extends na{next;constructor(e,t){super(LN,e,t),this.next=void 0}};function zh(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 ku(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 NN(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Cu.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(DN,e,r),this},Cu.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(ON,e,r),this});function DN(r,e,t){e.set(r,t)}function ON(r,e,t){r.length<40?D4(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function V4(){return new Cu}function me(r,e){let t=V4();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ge(r,e,t){let n=Iu(r);yield*e.stream(n,void 0,"$",t)}var Wh={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Gh(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function ut(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(s,a){let c=e(s);a.int32(c)},n=function(s){let a=s.int32();return e(a)},o=function*(s){let a=s.int32();yield e(a)};return Gh("enum",Wh.VARINT,t,n,o)}function ye(r,e,t){return Gh("message",Wh.LENGTH_DELIMITED,r,e,t)}var Se=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Ru=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var Qe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Qe||(Qe={}));var K4;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(K4||(K4={}));(function(r){r.codec=()=>ut(K4)})(Qe||(Qe={}));var mo;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),Qe.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=Qe.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Qe.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(mo||(mo={}));var Pu;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),Qe.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=Qe.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Qe.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Pu||(Pu={}));function yr(r){if(isNaN(r)||r<=0)throw new T("random bytes length must be a Number bigger than 0");return Ph(r)}var Nu={};wt(Nu,{MAX_RSA_KEY_SIZE:()=>H4,generateRSAKeyPair:()=>Z4,jwkToJWKKeyPair:()=>Qw,jwkToPkcs1:()=>FN,jwkToPkix:()=>G4,jwkToRSAPrivateKey:()=>Q4,pkcs1MessageToJwk:()=>z4,pkcs1MessageToRSAPrivateKey:()=>jh,pkcs1ToJwk:()=>UN,pkcs1ToRSAPrivateKey:()=>j4,pkixMessageToJwk:()=>W4,pkixMessageToRSAPublicKey:()=>X4,pkixToJwk:()=>$N,pkixToRSAPublicKey:()=>Y4});var Ac=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Nu.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return J.createV1(114,this._multihash)}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){return Xw(this.jwk,t,e,n)}},Lu=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Nu.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e,t){return Yw(this.jwk,e,t)}};var H4=8192,q4=18,BN=1062,MN=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function UN(r){let e=fn(r);return z4(e)}function z4(r){return{n:D(r[1],"base64url"),e:D(r[2],"base64url"),d:D(r[3],"base64url"),p:D(r[4],"base64url"),q:D(r[5],"base64url"),dp:D(r[6],"base64url"),dq:D(r[7],"base64url"),qi:D(r[8],"base64url"),kty:"RSA"}}function FN(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 T("JWK was missing components");return Nn([gr(Uint8Array.from([0])),gr(L(r.n,"base64url")),gr(L(r.e,"base64url")),gr(L(r.d,"base64url")),gr(L(r.p,"base64url")),gr(L(r.q,"base64url")),gr(L(r.dp,"base64url")),gr(L(r.dq,"base64url")),gr(L(r.qi,"base64url"))]).subarray()}function $N(r){let e=fn(r,{offset:0});return W4(e)}function W4(r){let e=fn(r[1],{offset:0});return{kty:"RSA",n:D(e[0],"base64url"),e:D(e[1],"base64url")}}function G4(r){if(r.n==null||r.e==null)throw new T("JWK was missing components");return Nn([MN,du(Nn([gr(L(r.n,"base64url")),gr(L(r.e,"base64url"))]))]).subarray()}function j4(r){let e=fn(r);return jh(e)}function jh(r){let e=z4(r);return Q4(e)}function Y4(r,e){if(r.byteLength>=BN)throw new Vo("Key size is too large");let t=fn(r,{offset:0});return X4(t,r,e)}function X4(r,e,t){let n=W4(r);if(t==null){let o=hn(mo.encode({Type:Qe.RSA,Data:e}));t=mr(q4,o)}return new Ac(n,t)}function Q4(r){if(Jw(r)>H4)throw new T("Key size is too large");let e=Qw(r),t=hn(mo.encode({Type:Qe.RSA,Data:G4(e.publicKey)})),n=mr(q4,t);return new Lu(e.privateKey,new Ac(e.publicKey,n))}async function Z4(r){if(r>H4)throw new T("Key size is too large");let e=await Zw(r),t=hn(mo.encode({Type:Qe.RSA,Data:G4(e.publicKey)})),n=mr(q4,t);return new Lu(e.privateKey,new Ac(e.publicKey,n))}function Qw(r){if(r==null)throw new T("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Zw(r,e){let t=await vt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await VN(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Yw(r,e,t){let n=await vt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await vt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Xw(r,e,t,n){let o=await vt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await vt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),i}async function VN(r,e){if(r.privateKey==null||r.publicKey==null)throw new T("Private and public key are required");let t=await Promise.all([vt.get().subtle.exportKey("jwk",r.privateKey),vt.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Jw(r){if(r.kty!=="RSA")throw new T("invalid key type");if(r.n==null)throw new T("invalid key modulus");return L(r.n,"base64url").length*8}var Yh=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(zo(e),Ht(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let 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),nr(o)}update(e){return dc(this),this.iHash.update(e),this}digestInto(e){dc(this),kh(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},oa=(()=>{let r=((e,t,n)=>new Yh(e,t).update(n).digest());return r.create=(e,t)=>new Yh(e,t),r})();var eb=(r,e)=>(r+(r>=0?e:-e)/tb)/e;function KN(r,e,t){Go("scalar",r,go,t);let[[n,o],[i,s]]=e,a=eb(s*r,t),c=eb(-o*r,t),l=r-a*n-c*i,u=-a*o-c*s,d=l<go,f=u<go;d&&(l=-l),f&&(u=-u);let h=wu(Math.ceil(pc(t)/2))+Vi;if(l<go||l>=h||u<go||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function e6(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function J4(r,e){Br(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return On(t.lowS,"lowS"),On(t.prehash,"prehash"),t.format!==void 0&&e6(t.format),t}var t6=class extends Error{constructor(e=""){super(e)}},Un={Err:t6,_tlv:{encode:(r,e)=>{let{Err:t}=Un;if(Bn(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=gu(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?gu(o.length/2|128):"";return gu(r)+i+o+e},decode(r,e){let{Err:t}=Un;e=_e(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=Un;if(Mh(r),r<go)throw new e("integer: negative integers are not allowed");let t=gu(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}=Un;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Xs(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Un,o=_e(r,void 0,"signature"),{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{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}=Un,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),i=n+o;return e.encode(48,i)}};Object.freeze(Un._tlv);Object.freeze(Un._int);Object.freeze(Un);var go=BigInt(0),Vi=BigInt(1),tb=BigInt(2),Xh=BigInt(3),HN=BigInt(4);function rb(r,e={}){let t=Vh("weierstrass",r,e),n=t.Fp,o=t.Fn,i=t.CURVE,{h:s,n:a}=i;Br(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=ob(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f($,b,S){if(l&&b.is0())return Uint8Array.of(0);let{x:A,y:E}=b.toAffine(),v=n.toBytes(A);if(On(S,"isCompressed"),S){d();let N=!n.isOdd(E);return _t(nb(N),v)}else return _t(Uint8Array.of(4),v,n.toBytes(E))}function h($){_e($,void 0,"Point");let{publicKey:b,publicKeyUncompressed:S}=u,A=$.length,E=$[0],v=$.subarray(1);if(l&&A===1&&E===0)return{x:n.ZERO,y:n.ZERO};if(A===b&&(E===2||E===3)){let N=n.fromBytes(v);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let M=m(N),R;try{R=n.sqrt(M)}catch(ae){let ve=ae instanceof Error?": "+ae.message:"";throw new Error("bad point: is not on curve, sqrt error"+ve)}d();let z=n.isOdd(R);return(E&1)===1!==z&&(R=n.neg(R)),{x:N,y:R}}else if(A===S&&E===4){let N=n.BYTES,M=n.fromBytes(v.subarray(0,N)),R=n.fromBytes(v.subarray(N,N*2));if(!g(M,R))throw new Error("bad point: is not on curve");return{x:M,y:R}}else throw new Error(`bad point: got length ${A}, expected compressed=${b} or uncompressed=${S}`)}let p=e.toBytes===void 0?f:e.toBytes,y=e.fromBytes===void 0?h:e.fromBytes;function m($){let b=n.sqr($),S=n.mul(b,$);return n.add(n.add(S,n.mul($,i.a)),i.b)}function g($,b){let S=n.sqr(b),A=m($);return n.eql(S,A)}if(!g(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let x=n.mul(n.pow(i.a,Xh),HN),P=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(x,P)))throw new Error("bad curve params: a or b");function O($,b,S=!1){if(!n.isValid(b)||S&&n.is0(b))throw new Error(`bad point coordinate ${$}`);return b}function F($){if(!($ instanceof C))throw new Error("Weierstrass Point expected")}function V($){if(!c||!c.basises)throw new Error("no endo");return KN($,c.basises,o.ORDER)}function H($,b,S,A,E){return S=new C(n.mul(S.X,$),S.Y,S.Z),b=xu(A,b),S=xu(E,S),b.add(S)}class C{static BASE=new C(i.Gx,i.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,S,A){this.X=O("x",b),this.Y=O("y",S,!0),this.Z=O("z",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){let{x:S,y:A}=b||{};if(!b||!n.isValid(S)||!n.isValid(A))throw new Error("invalid affine point");if(b instanceof C)throw new Error("projective point not allowed");return n.is0(S)&&n.is0(A)?C.ZERO:new C(S,A,n.ONE)}static fromBytes(b){let S=C.fromAffine(y(_e(b,void 0,"point")));return S.assertValidity(),S}static fromHex(b){return C.fromBytes(hc(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,S=!0){return q.createCache(this,b),S||this.multiply(Xh),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x:S,y:A}=b.toAffine();if(!n.isValid(S)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!g(S,A))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){F(b);let{X:S,Y:A,Z:E}=this,{X:v,Y:N,Z:M}=b,R=n.eql(n.mul(S,M),n.mul(v,E)),z=n.eql(n.mul(A,M),n.mul(N,E));return R&&z}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:S}=i,A=n.mul(S,Xh),{X:E,Y:v,Z:N}=this,M=n.ZERO,R=n.ZERO,z=n.ZERO,W=n.mul(E,E),ae=n.mul(v,v),ve=n.mul(N,N),xe=n.mul(E,v);return xe=n.add(xe,xe),z=n.mul(E,N),z=n.add(z,z),M=n.mul(b,z),R=n.mul(A,ve),R=n.add(M,R),M=n.sub(ae,R),R=n.add(ae,R),R=n.mul(M,R),M=n.mul(xe,M),z=n.mul(A,z),ve=n.mul(b,ve),xe=n.sub(W,ve),xe=n.mul(b,xe),xe=n.add(xe,z),z=n.add(W,W),W=n.add(z,W),W=n.add(W,ve),W=n.mul(W,xe),R=n.add(R,W),ve=n.mul(v,N),ve=n.add(ve,ve),W=n.mul(ve,xe),M=n.sub(M,W),z=n.mul(ve,ae),z=n.add(z,z),z=n.add(z,z),new C(M,R,z)}add(b){F(b);let{X:S,Y:A,Z:E}=this,{X:v,Y:N,Z:M}=b,R=n.ZERO,z=n.ZERO,W=n.ZERO,ae=i.a,ve=n.mul(i.b,Xh),xe=n.mul(S,v),qe=n.mul(A,N),ze=n.mul(E,M),We=n.add(S,A),Ne=n.add(v,N);We=n.mul(We,Ne),Ne=n.add(xe,qe),We=n.sub(We,Ne),Ne=n.add(S,E);let at=n.add(v,M);return Ne=n.mul(Ne,at),at=n.add(xe,ze),Ne=n.sub(Ne,at),at=n.add(A,E),R=n.add(N,M),at=n.mul(at,R),R=n.add(qe,ze),at=n.sub(at,R),W=n.mul(ae,Ne),R=n.mul(ve,ze),W=n.add(R,W),R=n.sub(qe,W),W=n.add(qe,W),z=n.mul(R,W),qe=n.add(xe,xe),qe=n.add(qe,xe),ze=n.mul(ae,ze),Ne=n.mul(ve,Ne),qe=n.add(qe,ze),ze=n.sub(xe,ze),ze=n.mul(ae,ze),Ne=n.add(Ne,ze),xe=n.mul(qe,Ne),z=n.add(z,xe),xe=n.mul(at,Ne),R=n.mul(We,R),R=n.sub(R,xe),xe=n.mul(We,qe),W=n.mul(at,W),W=n.add(W,xe),new C(R,z,W)}subtract(b){return F(b),this.add(b.negate())}is0(){return this.equals(C.ZERO)}multiply(b){let{endo:S}=e;if(!o.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let A,E,v=N=>q.cached(this,N,M=>Js(C,M));if(S){let{k1neg:N,k1:M,k2neg:R,k2:z}=V(b),{p:W,f:ae}=v(M),{p:ve,f:xe}=v(z);E=ae.add(xe),A=H(S.beta,W,ve,N,R)}else{let{p:N,f:M}=v(b);A=N,E=M}return Js(C,[A,E])[0]}multiplyUnsafe(b){let{endo:S}=e,A=this,E=b;if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(E===go||A.is0())return C.ZERO;if(E===Vi)return A;if(q.hasCache(this))return this.multiply(E);if(S){let{k1neg:v,k1:N,k2neg:M,k2:R}=V(E),{p1:z,p2:W}=Sw(C,A,N,R);return H(S.beta,z,W,v,M)}else return q.unsafe(A,E)}toAffine(b){let S=this,A=b,{X:E,Y:v,Z:N}=S;if(n.eql(N,n.ONE))return{x:E,y:v};let M=S.is0();A==null&&(A=M?n.ONE:n.inv(N));let R=n.mul(E,A),z=n.mul(v,A),W=n.mul(N,A);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(W,n.ONE))throw new Error("invZ was invalid");return{x:R,y:z}}isTorsionFree(){let{isTorsionFree:b}=e;return s===Vi?!0:b?b(C,this):q.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return s===Vi?this:b?b(C,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===Vi?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return On(b,"isCompressed"),this.assertValidity(),p(C,this,b)}toHex(b=!0){return fc(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let B=o.BITS,q=new yc(C,e.endo?Math.ceil(B/2):B);return B>=8&&C.BASE.precompute(8),Object.freeze(C.prototype),Object.freeze(C),C}function nb(r){return Uint8Array.of(r?2:3)}function ob(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function qN(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Ys:e.randomBytes,o=Object.assign(ob(r.Fp,t),{seed:Math.max(h4(t.ORDER),16)});function i(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function s(h,p){let{publicKey:y,publicKeyUncompressed:m}=o;try{let g=h.length;return p===!0&&g!==y||p===!1&&g!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,p4(_e(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:y,publicKeyUncompressed:m}=o,g=t._lengths;if(!js(h))return;let x=_e(h,void 0,"key").length,P=x===y||x===m,O=x===p||!!g?.includes(x);if(!(P&&O))return P}function u(h,p,y=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(p).multiply(m).toBytes(y)}let d={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},f=wc(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:o})}function ib(r,e,t={}){let n=e;zo(n),Br(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Ys:t.randomBytes,i=t.hmac===void 0?(E,v)=>oa(n,E,v):t.hmac,{Fp:s,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=qN(r,t),y={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*tb+Vi<s.ORDER;function g(E){let v=c>>Vi;return E>v}function x(E,v){if(!a.isValidNot0(v))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return v}function P(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(E,v){e6(v);let N=p.signature,M=v==="compact"?N:v==="recovered"?N+1:void 0;return _e(E,M)}class F{r;s;recovery;constructor(v,N,M){if(this.r=x("r",v),this.s=x("s",N),M!=null){if(P(),![0,1,2,3].includes(M))throw new Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(v,N=y.format){O(v,N);let M;if(N==="der"){let{r:ae,s:ve}=Un.toSig(_e(v));return new F(ae,ve)}N==="recovered"&&(M=v[0],N="compact",v=v.subarray(1));let R=p.signature/2,z=v.subarray(0,R),W=v.subarray(R,R*2);return new F(a.fromBytes(z),a.fromBytes(W),M)}static fromHex(v,N){return this.fromBytes(hc(v),N)}assertRecovery(){let{recovery:v}=this;if(v==null)throw new Error("invalid recovery id: must be present");return v}addRecoveryBit(v){return new F(this.r,this.s,v)}recoverPublicKey(v){let{r:N,s:M}=this,R=this.assertRecovery(),z=R===2||R===3?N+c:N;if(!s.isValid(z))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let W=s.toBytes(z),ae=r.fromBytes(_t(nb((R&1)===0),W)),ve=a.inv(z),xe=H(_e(v,void 0,"msgHash")),qe=a.create(-xe*ve),ze=a.create(M*ve),We=r.BASE.multiplyUnsafe(qe).add(ae.multiplyUnsafe(ze));if(We.is0())throw new Error("invalid recovery: point at infinify");return We.assertValidity(),We}hasHighS(){return g(this.s)}toBytes(v=y.format){if(e6(v),v==="der")return hc(Un.hexFromSig(this));let{r:N,s:M}=this,R=a.toBytes(N),z=a.toBytes(M);return v==="recovered"?(P(),_t(Uint8Array.of(this.assertRecovery()),R,z)):_t(R,z)}toHex(v){return fc(this.toBytes(v))}}Object.freeze(F.prototype),Object.freeze(F);let V=t.bits2int===void 0?function(v){if(v.length>8192)throw new Error("input is too large");let N=Xs(v),M=v.length*8-l;return M>0?N>>BigInt(M):N}:t.bits2int,H=t.bits2int_modN===void 0?function(v){return a.create(V(v))}:t.bits2int_modN,C=wu(l);function B(E){return Go("num < 2^"+l,E,go,C),a.toBytes(E)}function q(E,v){return _e(E,void 0,"message"),v?_e(n(E),void 0,"prehashed message"):E}function $(E,v,N){let{lowS:M,prehash:R,extraEntropy:z}=J4(N,y);E=q(E,R);let W=H(E),ae=a.fromBytes(v);if(!a.isValidNot0(ae))throw new Error("invalid private key");let ve=[B(ae),B(W)];if(z!=null&&z!==!1){let We=z===!0?o(p.secretKey):z;ve.push(_e(We,void 0,"extraEntropy"))}let xe=_t(...ve),qe=W;function ze(We){let Ne=V(We);if(!a.isValidNot0(Ne))return;let at=a.inv(Ne),Uo=r.BASE.multiply(Ne).toAffine(),Ls=a.create(Uo.x);if(Ls===go)return;let Qa=a.create(at*a.create(qe+Ls*ae));if(Qa===go)return;let Gl=(Uo.x===Ls?0:2)|Number(Uo.y&Vi),jl=Qa;return M&&g(Qa)&&(jl=a.neg(Qa),Gl^=1),new F(Ls,jl,m?void 0:Gl)}return{seed:xe,k2sig:ze}}function b(E,v,N={}){let{seed:M,k2sig:R}=$(E,v,N);return sw(n.outputLen,a.BYTES,i)(M,R).toBytes(N.format)}function S(E,v,N,M={}){let{lowS:R,prehash:z,format:W}=J4(M,y);if(N=_e(N,void 0,"publicKey"),v=q(v,z),!js(E)){let ae=E instanceof F?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+ae)}O(E,W);try{let ae=F.fromBytes(E,W),ve=r.fromBytes(N);if(R&&ae.hasHighS())return!1;let{r:xe,s:qe}=ae,ze=H(v),We=a.inv(qe),Ne=a.create(ze*We),at=a.create(xe*We),Uo=r.BASE.multiplyUnsafe(Ne).add(ve.multiplyUnsafe(at));return Uo.is0()?!1:a.create(Uo.x)===xe}catch{return!1}}function A(E,v,N={}){let{prehash:M}=J4(N,y);return v=q(v,M),F.fromBytes(E,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:r,sign:b,verify:S,recoverPublicKey:A,Signature:F,hash:n})}var n6={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zN={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var sb=BigInt(2);function WN(r){let e=n6.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=nt(u,t,e)*u%e,f=nt(d,t,e)*u%e,h=nt(f,sb,e)*l%e,p=nt(h,o,e)*h%e,y=nt(p,i,e)*p%e,m=nt(y,a,e)*y%e,g=nt(m,c,e)*m%e,x=nt(g,a,e)*y%e,P=nt(x,t,e)*u%e,O=nt(P,s,e)*p%e,F=nt(O,n,e)*l%e,V=nt(F,sb,e);if(!r6.eql(r6.sqr(V),r))throw new Error("Cannot find square root");return V}var r6=mc(n6.p,{sqrt:WN}),GN=rb(n6,{Fp:r6,endo:zN}),Fn=ib(GN,hn);var ab=32;function cb(r,e,t){let n=ft.digest(e instanceof Uint8Array?e:e.subarray());if(Ec(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),Fn.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new au(String(o))});try{return Fn.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new au(String(o))}}function lb(r,e,t,n){let o=ft.digest(t instanceof Uint8Array?t:t.subarray());if(Ec(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),Fn.verify(e,i,r,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new cu(String(i))});try{return n?.signal?.throwIfAborted(),Fn.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(i){throw new cu(String(i))}}var Du=class{type="secp256k1";raw;_key;constructor(e){this._key=fb(e),this.raw=ub(this._key)}toMultihash(){return Et.digest(Nt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){return lb(this._key,t,e,n)}},Ou=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=db(e),this.publicKey=new Du(t??hb(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e,t){return cb(this.raw,e,t)}};function o6(r){return new Ou(r)}function i6(r){return new Du(r)}async function pb(){let r=jN();return new Ou(r)}function ub(r){return Fn.Point.fromBytes(r).toBytes()}function db(r){try{return Fn.getPublicKey(r,!0),r}catch(e){throw new Yl(String(e))}}function fb(r){try{return Fn.Point.fromBytes(r),r}catch(e){throw new Vo(String(e))}}function hb(r){try{return Fn.getPublicKey(r,!0)}catch(e){throw new Yl(String(e))}}function jN(){return Fn.utils.randomSecretKey()}async function Qh(r,e){if(r==="Ed25519")return Fw();if(r==="secp256k1")return pb();if(r==="RSA")return Z4(YN(e));if(r==="ECDSA")return q9(XN(e));throw new Pn}function bt(r,e){let{Type:t,Data:n}=mo.decode(r),o=n??new Uint8Array;switch(t){case Qe.RSA:return Y4(o,e);case Qe.Ed25519:return I4(o);case Qe.secp256k1:return i6(o);case Qe.ECDSA:return Q3(o);default:throw new Pn}}function Zh(r){let{Type:e,Data:t}=mo.decode(r.digest),n=t??new Uint8Array;switch(e){case Qe.Ed25519:return I4(n);case Qe.secp256k1:return i6(n);case Qe.ECDSA:return Q3(n);default:throw new Pn}}function Nt(r){return mo.encode({Type:Qe[r.type],Data:r.raw})}function mb(r){let e=Pu.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Qe.RSA:return j4(t);case Qe.Ed25519:return _4(t);case Qe.secp256k1:return o6(t);case Qe.ECDSA:return F9(t);default:throw new Pn}}function gb(r){if(r.byteLength===Mr)return _4(r);if(r.byteLength===ab)return o6(r);let e=fn(r),t=e[2]?.[0];if(t===R9||t===P9||t===L9)return X3(e);if(e.length>8)return jh(e);throw new T("Could not extract private key from raw bytes")}function ia(r){return Pu.encode({Type:Qe[r.type],Data:r.raw})}function YN(r){return r==null?2048:parseInt(r,10)}function XN(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new T("Unsupported curve, should be P-256, P-384 or P-521")}var Bu=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ki=new Uint32Array(80),s6=class extends zs{A=Bu[0]|0;B=Bu[1]|0;C=Bu[2]|0;D=Bu[3]|0;E=Bu[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ki[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ki[c]=Ch(Ki[c-3]^Ki[c-8]^Ki[c-14]^Ki[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Lh(o,i,s),u=1518500249):c<40?(l=o^i^s,u=1859775393):c<60?(l=Nh(o,i,s),u=2400959708):(l=o^i^s,u=3395469782);let d=Ch(n,5)+l+a+u+Ki[c]|0;a=s,s=i,i=Ch(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){nr(Ki)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),nr(this.buffer)}},yb=hu(()=>new s6);function wb(r,e,t,n){zo(r);let o=j9({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(Ar(i,"c"),Ar(s,"dkLen"),Ar(a,"asyncTick"),i<1)throw new Error("iterations (c) must be >= 1");if(s<1)throw new Error('"dkLen" must be >= 1');if(s>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=J3(e,"password"),l=J3(t,"salt"),u=new Uint8Array(s),d=oa.create(r,c),f=d._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:u,PRF:d,PRFSalt:f}}function bb(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),nr(o),t}function xb(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=wb(r,e,t,n),l,u=new Uint8Array(4),d=qs(u),f=new Uint8Array(a.outputLen);for(let h=1,p=0;p<i;h++,p+=a.outputLen){let y=s.subarray(p,p+a.outputLen);d.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(f),y.set(f.subarray(0,y.length));for(let m=1;m<o;m++){a._cloneInto(l).update(f).digestInto(f);for(let g=0;g<y.length;g++)y[g]^=f[g]}}return bb(a,c,s,l,f)}async function Jh(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=wb(r,e,t,n),u,d=new Uint8Array(4),f=qs(d),h=new Uint8Array(c.outputLen);for(let p=1,y=0;y<i;p++,y+=c.outputLen){let m=a.subarray(y,y+c.outputLen);f.setInt32(0,p,!1),(u=l._cloneInto(u)).update(d).digestInto(h),m.set(h.subarray(0,m.length)),await G9(o-1,s,()=>{c._cloneInto(u).update(h).digestInto(h);for(let g=0;g<m.length;g++)m[g]^=h[g]})}return bb(c,l,a,u,h)}var Eb={sha1:yb,"sha2-256":hn,"sha2-512":po};function Mu(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(Eb).join(" / ");throw new T(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=Eb[o],s=xb(i,r,e,{c:t,dkLen:n});return xt.encode(s).substring(1)}var a6={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},vb={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Sb=new globalThis.TextEncoder;function QN(r,e){let t=a6[e],n=vb[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function ZN(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=a6[e],o=vb[e],i=r;for(;i.length>0;){let s=Sb.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function c6(r,{size:e=32,utf8Buffer:t}={}){if(!a6[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 ZN(r,e,t);r=Sb.encode(r)}return QN(r,e)}var Uu={hash:r=>Number(c6(r,{size:32})),hashV:(r,e)=>JN(Uu.hash(r,e))};function JN(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var l6=64,$n=class{fp;h;seed;constructor(e,t,n,o=2){if(o>l6)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=be(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,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 sa(r,e){return Math.floor(Math.random()*(e-r))+r}var aa=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof $n))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof $n))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 $n))throw new TypeError("Invalid Fingerprint");let t=sa(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof $n))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var eD=500,Fu=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??Uu,this.seed=e.seed??sa(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new $n(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new aa(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new aa(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[sa(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new aa(this.bucketSize));for(let a=0;a<eD;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new aa(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new $n(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new $n(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},tD={1:.5,2:.84,4:.95,8:.98};function rD(r=.001){return r>.002?2:r>1e-5?4:8}function Ab(r,e=.001){let t=rD(e),n=tD[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),l6);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var e1=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??Uu,this.seed=e.seed??sa(0,Math.pow(2,10)),this.filterSeries=[new Fu({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(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 Fu({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=L(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=L(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 Wt(r,e=.001,t){return new e1({...Ab(r,e),...t??{}})}function he(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new T(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var t1=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(i*=e,i+=u,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Tb=45,nD=15,Tc=new t1;function r1(r){if(!(r.length>nD))return Tc.new(r).parseWith(()=>Tc.readIPv4Addr())}function n1(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Tb))return Tc.new(r).parseWith(()=>Tc.readIPv6Addr())}function _c(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Tb)return;let t=Tc.new(r).parseWith(()=>Tc.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 _b(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function Ib(r,e,t,n){let o=0;for(let i of r)if(!(o<t)){if(o>n)break;if(i!==e[o])return!1;o++}return!0}function u6(r){switch(r.length){case ca:return r.join(".");case la:{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 kb(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function Cb(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var ca=4,la=16,jX=parseInt("0xFFFF",16),oD=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function $u(r,e){e.length===la&&r.length===ca&&_b(e,0,11)&&(e=e.slice(12)),e.length===ca&&r.length===la&&Ib(r,oD,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function Rb(r,e){if(typeof e=="string"&&(e=_c(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 d6(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=ca,o=r1(e);if(o==null&&(n=la,o=n1(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=f6(i,8*n);return{network:$u(o,s),mask:s}}function f6(r,e){if(e!==8*ca&&e!==8*la)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var ua=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=d6(e));else{let n=_c(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let i=_c(t);if(i==null)throw new Error("Failed to parse mask");this.mask=i}else this.mask=f6(o,8*n.length);this.network=$u(n,this.mask)}}contains(e){return Rb({network:this.network,mask:this.mask},e)}toString(){let e=kb(this.mask),t=e!==-1?String(e):Cb(this.mask);return u6(this.network)+"/"+t}};function Pb(r,e){return new ua(r).contains(e)}function o1(r){try{let e=he(r);return e.type==="ip6"?Pb("2000::/3",e.host):!1}catch{return!1}}function Lb(r){try{let e=he(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Nb(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Vu(r){try{let e=he(r);switch(e.type){case"ip4":case"ip6":return Nb(e.host);default:return!1}}catch{return!1}}function Gt(r){try{return he(r),!0}catch{return!1}}function Vn(r){return!!r1(r)}function i1(r){return!!n1(r)}var Mb=Fo(Bb(),1),dD=["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"],fD=dD.map(r=>new Mb.Netmask(r));function b6(r){for(let e of fD)if(e.contains(r))return!0;return!1}function hD(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function pD(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return b6(o)}function mD(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function gD(r){let e=r.split(":"),t=e[e.length-1];return b6(t)}function yD(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 Rc(r){if(Vn(r))return b6(r);if(hD(r))return pD(r);if(mD(r))return gD(r);if(i1(r))return yD(r)}function gt(r){try{let e=he(r);switch(e.type){case"ip4":case"ip6":return Rc(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function Ie(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var a1=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}},Pc=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new a1(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 a1(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 x6=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function jt(r={}){return wD(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 wD(r,e){e=e??{};let t=e.onEnd,n=new Pc,o,i,s,a=Ie(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((m,g)=>{i=x=>{i=null,n.push(x);try{m(r(n))}catch(P){g(P)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ie()})}},l=m=>i!=null?i(m):(n.push(m),o),u=m=>(n=new Pc,i!=null?i({error:m}):(n.push({error:m}),o)),d=m=>{if(s)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},f=m=>s?o:(s=!0,m!=null?u(m):l({done:!0})),h=()=>(n=new Pc,f(),{done:!0}),p=m=>(f(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,P;g!=null&&(x=new Promise((O,F)=>{P=()=>{F(new x6)},g.addEventListener("abort",P)}));try{await Promise.race([a.promise,x])}finally{P!=null&&g!=null&&g?.removeEventListener("abort",P)}}},t==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(m){return y.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(m){return y.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return y.readableLength},onEmpty:m=>y.onEmpty(m)},o}var bD=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function xD(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=bD(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=pr(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function pn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=xD(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function Qo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var c1=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}},l1=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},fa=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},u1=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},d1=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function ED(r){return r.reason}async function Ze(r,e,t){if(e==null)return r;let n=t?.translateError??ED;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var f1=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Ie(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new fr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function vD(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var h1=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=vD(),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 fr),this.cleanup())}async join(e={}){let t=new f1(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 Ze(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 Yt=class extends we{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Qo(this.emitEmpty.bind(this),1),this.emitIdle=Qo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new l1;let n=new h1(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new fr)}),this.clear()}async onEmpty(e){this.size!==0&&await pn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await pn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await pn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=jt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new fr("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var SD=Math.pow(2,20)*4,qi=class extends we{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??SD,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ie,this.writeBuffer=new ie,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new d1)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Ze(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=jt(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let n=i=>{e.end(i.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new lo(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new fh(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new lo("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new lo("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new lo(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new lo(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Ja;this.dispatchEvent(new hh(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new ki))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let i=this.writeBuffer.sublist(0,o),s=new ie(i);this.writeBuffer.consume(i.byteLength);let a=this.sendData(i);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==s.byteLength&&(s.consume(a.sentBytes),this.writeBuffer.prepend(s)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new dh(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Ql(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Ql(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var zi=class extends qi{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await pn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await pn(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function p1(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Wi=class extends we{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=s=>{try{this.onData(s.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Ze(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Cn;let t=this.onCreateStream({...this.streamOptions,...e});return p1(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new u1(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let o=this.streams.findIndex(i=>i===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var Gi=class extends qi{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await pn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await pn(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function Ee(r){let e=new globalThis.AbortController;function t(){let i=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Lc=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,i=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var AD=1.2,TD=2,_D=5e3,ID=6e4,kD=5e3,Kn=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??kD;this.success=new Lc(t),this.failure=new Lc(t),this.next=new Lc(t),this.failureMultiplier=e.failureMultiplier??TD,this.timeoutMultiplier=e.timeoutMultiplier??AD,this.minTimeout=e.minTimeout??_D,this.maxTimeout=e.maxTimeout??ID,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=Ee([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Xt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Zo=class extends Error{static name="ValidationError";name="ValidationError"},m1=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},g1=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function v6(r){return e=>D(e,r)}function S6(r){return e=>L(e,r)}function Nc(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function ha(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ub(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=L(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ha(n);return Je([t,o],t.length+o.length)}function Fb(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=Lt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ha(n);return Je([t,o],t.length+o.length)}function A6(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=D(e,"base32"),o=Nc(t);return`${n}:${o}`}var T6=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Xt("Invalid byte value in IP address");e[n]=o}),e},$b=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=Vn(t[n]),s;i&&(s=T6(t[n]),t[n]=D(s.subarray(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,D(s.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let i=parseInt(t[n],16);if(isNaN(i)||i<0||i>65535)throw new Xt("Invalid byte value in IP address");o[e++]=i>>8&255,o[e++]=i&255}return o},Vb=function(r){if(r.byteLength!==4)throw new Xt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Kb=function(r){if(r.byteLength!==16)throw new Xt("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],i=r[n+1],s=`${o.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;e.push(s)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Xt(`Invalid IPv6 address "${t}"`)}};function Hb(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Xt(`Invalid IPv6 address "${r}"`)}}var E6=Object.values(Vs).map(r=>r.decoder),CD=(function(){let r=E6[0].or(E6[1]);return E6.slice(2).forEach(e=>r=r.or(e)),r})();function qb(r){return CD.decode(r)}function zb(r){return e=>r.encoder.encode(e)}function RD(r){if(parseInt(r).toString()!==r)throw new Zo("Value must be an integer")}function PD(r){if(r<0)throw new Zo("Value must be a positive integer, or zero")}function LD(r){return e=>{if(e>r)throw new Zo(`Value must be smaller than or equal to ${r}`)}}function ND(...r){return e=>{for(let t of r)t(e)}}var Ku=ND(RD,PD,LD(65535));var Ot=-1,_6=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new g1(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},ei=new _6,GD=[{code:4,name:"ip4",size:32,valueToBytes:T6,bytesToValue:Vb,validate:r=>{if(!Vn(r))throw new Zo(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ha,bytesToValue:Nc,validate:Ku},{code:273,name:"udp",size:16,valueToBytes:ha,bytesToValue:Nc,validate:Ku},{code:33,name:"dccp",size:16,valueToBytes:ha,bytesToValue:Nc,validate:Ku},{code:41,name:"ip6",size:128,valueToBytes:$b,bytesToValue:Kb,stringToValue:Hb,validate:r=>{if(!i1(r))throw new Zo(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Ot},{code:43,name:"ipcidr",size:8,bytesToValue:v6("base10"),valueToBytes:S6("base10")},{code:53,name:"dns",size:Ot},{code:54,name:"dns4",size:Ot},{code:55,name:"dns6",size:Ot},{code:56,name:"dnsaddr",size:Ot},{code:132,name:"sctp",size:16,valueToBytes:ha,bytesToValue:Nc,validate:Ku},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ot,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Ot,bytesToValue:v6("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?S6("base58btc")(r):J.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:A6,valueToBytes:Ub},{code:445,name:"onion3",size:296,bytesToValue:A6,valueToBytes:Fb},{code:446,name:"garlic64",size:Ot},{code:447,name:"garlic32",size:Ot},{code:448,name:"tls"},{code:449,name:"sni",size:Ot},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ot,bytesToValue:zb(ru),valueToBytes:qb},{code:480,name:"http"},{code:481,name:"http-path",size:Ot,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Ot}];GD.forEach(r=>{ei.addProtocol(r)});function Wb(r){let e=[],t=0;for(;t<r.length;){let n=Ur(r,t),o=ei.getProtocol(n),i=Ae(n),s=jD(o,r,t+i),a=0;s>0&&o.size===Ot&&(a=Ae(s));let c=i+a+s,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(s>0){let u=t+i+a,d=r.subarray(u,u+s);l.value=o.bytesToValue?.(d)??D(d)}e.push(l),t+=c}return e}function Gb(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=ei.getProtocol(n.code),i=Ae(n.code),s,a=0,c=0;n.value!=null&&(s=o.valueToBytes?.(n.value)??L(n.value),a=s.byteLength,o.size===Ot&&(c=Ae(a)));let l=new Uint8Array(i+c+a),u=0;Fi(n.code,l,u),u+=i,s!=null&&(o.size===Ot&&(Fi(a,l,u),u+=c),l.set(s,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Je(t,e)}function jb(r){if(r.charAt(0)!=="/")throw new Xt('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let i=1;i<r.length;i++){let s=r.charAt(i);s!=="/"&&(t==="protocol"?o+=r.charAt(i):n+=r.charAt(i));let a=i===r.length-1;if(s==="/"||a){let c=ei.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Xt(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Xt(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Xt("Incomplete multiaddr");return e}function Yb(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ei.getProtocol(e.code);if(t==null)throw new Xt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function jD(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Ur(e,t)}var YD=Symbol.for("nodejs.util.inspect.custom"),O6=Symbol.for("@multiformats/multiaddr");function XD(r){if(r==null&&(r="/"),bo(r))return r.getComponents();if(r instanceof Uint8Array)return Wb(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),jb(r);if(Array.isArray(r))return r;throw new Xt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var E1=class r{[O6]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=XD(e),t.validate!==!1&&QD(this)}get bytes(){return this.#r==null&&(this.#r=Gb(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Yb(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new m1(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return ce(this.bytes,e.bytes)}[YD](){return`Multiaddr(${this.toString()})`}};function QD(r){r.getComponents().forEach(e=>{let t=ei.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function bo(r){return!!r?.[O6]}function Z(r){return new E1(r)}var B6=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ie(),this.haveNext=Ie()}[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=Ie(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ie(),await Ze(this.readNext.promise,t?.signal,t)}};function Xb(){return new B6}function ZD(r){return r[Symbol.asyncIterator]!=null}async function JD(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*eO(r){let e=new AbortController,t=Xb();JD(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*tO(r){for(let e of r)yield*e}function rO(...r){let e=[];for(let t of r)ZD(t)||e.push(t);return e.length===r.length?tO(e):eO(r)}var wr=rO;function Mc(r,...e){if(r==null)throw new Error("Empty pipeline");if(M6(r)){let n=r;r=()=>n.source}else if(Zb(r)||Qb(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&M6(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)M6(t[n])&&(t[n]=oO(t[n]));return nO(...t)}var nO=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Qb=r=>r?.[Symbol.asyncIterator]!=null,Zb=r=>r?.[Symbol.iterator]!=null,M6=r=>r==null?!1:r.sink!=null&&r.source!=null,oO=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=jt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Qb(i))o=async function*(){yield*i,n.end()};else if(Zb(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return wr(n,o())}return r.source};var iO=4194304,v1=class extends Error{static name="UnwrappedError";name="UnwrappedError"},ju=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},F6=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},$6=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function sO(r){return typeof r?.closeRead=="function"}function aO(r){return typeof r?.close=="function"}function U6(r){return sO(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:aO(r)?r.status!=="open":!1}function cO(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function S1(r,e){let t=e?.maxBufferSize??iO,n=new ie,o,i=!1;if(!cO(r))throw new T("Argument should be a Stream or a Multiaddr");let s=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",s);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(i===!0)throw new v1("Stream was unwrapped");if(U6(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new fa(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Ze(o.promise,u?.signal),U6(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let f=u?.bytes??n.byteLength;if(n.byteLength<f){if(U6(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,f),new fa(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(u)}let h=n.sublist(0,f);return n.consume(f),h},async write(u,d){if(i===!0)throw new v1("Stream was unwrapped");r.send(u)||await pn(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return i||(i=!0,r.removeEventListener("message",s),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function Yi(r,e={}){let t=S1(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ae(e.maxDataLength));let n=e?.lengthDecoder??Ur,o=e?.lengthEncoder??ir;return{async read(s){let a=-1,c=new ie;for(;;){let u=await t.read({...s,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new ju("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new $6(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new F6(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...s,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new fa(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new fa(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(s,a){await t.write(new ie(o(s.byteLength),s),a)},async writeV(s,a){let c=new ie(...s.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function tt(r,e){let t=Yi(r,e),n={read:async(o,i)=>{let s=await t.read(i);return o.decode(s)},write:async(o,i,s)=>{await t.write(i.encode(o),s)},writeV:async(o,i,s)=>{await t.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var lO=1024*1024*4,uO=1024*1024*4,A1=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new ie,this.maxBufferSize=e.maxBufferSize??lO,this.maxDataLength=e.maxDataLength??uO,this.lengthDecoder=e.lengthDecoder??Ur,this.encodingLength=e.encodingLength??Ae}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new T(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(i){if(i instanceof RangeError)break;throw i}if(t<0||t>this.maxDataLength)throw new ju("Invalid message length");let n=this.encodingLength(t),o=n+t;if(this.buffer.byteLength>=o){let i=this.buffer.sublist(n,o);this.buffer.consume(o),i.byteLength>0&&(yield i)}else break}}};var T1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Uc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},_1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Yu=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function I1(r){return r[Symbol.asyncIterator]!=null}function Jb(r,e){if(r.byteLength>e)throw new Uc("Message length too long")}var C1=r=>{let e=Ae(r),t=Xe(e);return ir(r,t),C1.bytes=e,t};C1.bytes=0;function ti(r,e){e=e??{};let t=e.lengthEncoder??C1,n=e?.maxDataLength??4194304;function*o(i){Jb(i,n);let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return I1(r)?(async function*(){for await(let i of r)yield*o(i)})():(function*(){for(let i of r)yield*o(i)})()}ti.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??C1,n=e?.maxDataLength??4194304;return Jb(r,n),new ie(t(r.byteLength),r)};var ma;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ma||(ma={}));var V6=r=>{let e=Ur(r);return V6.bytes=Ae(e),e};V6.bytes=0;function ga(r,e){let t=new ie,n=ma.LENGTH,o=-1,i=e?.lengthDecoder??V6,s=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===ma.LENGTH)try{if(o=i(t),o<0)throw new T1("Invalid message length");if(o>a)throw new Uc("Message length too long");let l=i.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=ma.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>s)throw new _1("Message length length too long");break}throw l}if(n===ma.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=ma.LENGTH}}}return I1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Yu("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Yu("Unexpected end of input")})()}ga.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:i,value:s}=await r.next(t);if(i===!0)return;s!=null&&(yield s)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}})();return ga(n,{...e??{},onLength:i=>{t=i}})};function fO(r,e){if(typeof r=="string")return hO(r);if(typeof r=="number")return gO(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var R1=fO;function hO(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),i=n.toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function pO(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function mO(r){let e=Math.abs(r);return e>=315576e5?ya(r,e,315576e5,"year"):e>=26298e5?ya(r,e,26298e5,"month"):e>=6048e5?ya(r,e,6048e5,"week"):e>=864e5?ya(r,e,864e5,"day"):e>=36e5?ya(r,e,36e5,"hour"):e>=6e4?ya(r,e,6e4,"minute"):e>=1e3?ya(r,e,1e3,"second"):`${r} ms`}function gO(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?mO(r):pO(r)}function ya(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function K6(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=R1,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let f,h=null,p,y;function m(...g){if(!m.enabled)return;let x=m,P=Number(new Date),O=P-(f||P);x.diff=O,x.prev=f,x.curr=P,f=P,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let F=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(H,C)=>{if(H==="%%")return"%";F++;let B=t.formatters[C];if(typeof B=="function"){let q=g[F];H=B.call(x,q),g.splice(F,1),F--}return H}),t.formatArgs.call(x,g),d?.onLog!=null&&d.onLog(...g),(x.log||t.log).apply(x,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,y=t.enabled(u)),y),set:g=>{h=g}}),typeof t.init=="function"&&t.init(m),m}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,f=(typeof u=="string"?u:"").split(/[\s,]+/),h=f.length;for(d=0;d<h;d++)f[d]&&(u=f[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let d,f;for(d=0,f=t.skips.length;d<f;d++)if(t.skips[d].test(u))return!1;for(d=0,f=t.names.length;d<f;d++)if(t.names[d].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 P1=SO(),yO=["#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 wO(){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 bO(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+R1(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var xO=console.debug??console.log??(()=>{});function EO(r){try{r?P1?.setItem("debug",r):P1?.removeItem("debug")}catch{}}function vO(){let r;try{r=P1?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function SO(){try{return localStorage}catch{}}function AO(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var tx=K6({formatArgs:bO,save:EO,load:vO,useColors:wO,setupFormatters:AO,colors:yO,storage:P1,log:xO});var Tr=tx;Tr.formatters.b=r=>r==null?"undefined":Ye.baseEncode(r);Tr.formatters.t=r=>r==null?"undefined":Lt.baseEncode(r);Tr.formatters.m=r=>r==null?"undefined":xt.baseEncode(r);Tr.formatters.p=r=>r==null?"undefined":r.toString();Tr.formatters.c=r=>r==null?"undefined":r.toString();Tr.formatters.k=r=>r==null?"undefined":r.toString();Tr.formatters.a=r=>r==null?"undefined":r.toString();function rx(r,e=""){let t=nx(r.message),n=nx(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
3
+ `,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return y;function y(C,B,q){var $=this;if(!($ instanceof y))return new y(C,B,q);$.time=+C||0,$.nano=+B||0,$.year=+q||0,m($)}function m(C){var B,q,$,b=C.year,S=C.time,A=C.nano,E=((A<0||a<=A)&&(A-=(q=Math.floor(A/a))*a,S+=q,q=1),b%e);return(S<-i||i<S||E)&&((B=l(S/o))&&(b+=B*e,S-=B*o),($=g(S)).setUTCFullYear(E+$.getUTCFullYear()),$=(S=+$)+(B=l((b-=E)/e))*o,B&&-i<=$&&$<=i&&(b-=B*e,S=$),q=1),q&&(C.year=b,C.time=S,C.nano=A),C}function g(C){var B=new Date(0);return B.setTime(C),B}function x(b,$){b=+b||0;var q=l(($=($|0)*s)/n)+l(b/n),$=$%n+b%n,b=l($/n);return b&&(q+=b,$-=b*n),new y(1e3*$,0,q*e)}function P(C,B,q,$,b,S){return function(E,v){var M=m(this);E=E||new Array(8),F(E,v|=0);var R=Math.floor(M.time/1e3),M=M.year*(t*r/e),N=l(M/s)+l(R/s),M=M%s+R%s,R=Math.floor(M/s);return R&&(N+=R,M-=R*s),A(E,v+b,N),A(E,v+S,M),E};function A(E,v,N){E[v+C]=N>>24&255,E[v+B]=N>>16&255,E[v+q]=N>>8&255,E[v+$]=255&N}}function O(C,B,q,$,b,S){return function(E,v){F(E,v|=0);var N=A(E,v+b);return x(A(E,v+S),N)};function A(E,v){return 16777216*E[v+C]+(E[v+B]<<16|E[v+q]<<8|E[v+$])}}function F(C,B){if(C=C&&C.length,C==null)throw new TypeError("Invalid Buffer");if(C<B+8)throw new RangeError("Out of range")}function V(C){return(9<C?"":"0")+(0|C)}function H(C,B){return(c+(0|C)).substr(-B)}})()});var M_=un((pge,B_)=>{"use strict";function lV(r){return r>=55296&&r<=56319}function uV(r){return r>=56320&&r<=57343}B_.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var o=t.length,i=0,s,a,c=0;c<o;c+=1){if(s=t.charCodeAt(c),a=t[c],lV(s)&&uV(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),i+=e(a),i===n)return t.slice(0,c+1);if(i>n)return t.slice(0,c-a.length+1)}return t}});var F_=un((mge,U_)=>{"use strict";function dV(r){return r>=55296&&r<=56319}function fV(r){return r>=56320&&r<=57343}U_.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,o=null,i=null,s=0;s<t;s++)o=e.charCodeAt(s),fV(o)?i!=null&&dV(i)?n+=1:n+=3:o<=127?n+=1:o>=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),i=o;return n}});var V_=un((gge,$_)=>{"use strict";var hV=M_(),pV=F_();$_.exports=hV.bind(null,pV)});var q_=un((yge,H_)=>{"use strict";var mV=V_(),gV=/[\/\?<>\\:\*\|"]/g,yV=/[\x00-\x1f\x80-\x9f]/g,wV=/^\.+$/,bV=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function xV(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function K_(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(gV,e).replace(yV,e).replace(wV,e).replace(bV,e);return t=xV(t,e),mV(t,255)}H_.exports=function(r,e){var t=e&&e.replacement||"",n=K_(r,t);return t===""?n:K_(n,"")}});var z_=un(kl=>{"use strict";var vV="[object ArrayBuffer]",gi=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===vV}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),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let i=0;i<n.length;i++)if(n[i]!==o[i])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 s of t)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of t){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},h5="string",SV=/^[0-9a-f\s]+$/i,AV=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,TV=/^[a-zA-Z0-9-_]+$/,Om=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=gi.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},In=class{static toString(e,t=!1){let n=gi.toArrayBuffer(e),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let i=0;i<e.length;i++)o.setUint16(i*2,e.charCodeAt(i),t);return n}},Bm=class r{static isHex(e){return typeof e===h5&&SV.test(e)}static isBase64(e){return typeof e===h5&&AV.test(e)}static isBase64Url(e){return typeof e===h5&&TV.test(e)}static ToString(e,t="utf8"){let n=gi.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 In.toString(n,!0);case"utf16":case"utf16be":return In.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 In.fromString(e,!0);case"utf16":case"utf16be":return In.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=gi.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 Om.fromString(e);case"utf16":case"utf16be":return In.fromString(e);case"utf16le":case"usc2":return In.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 Om.toString(e);case"utf16":case"utf16be":return In.toString(e);case"utf16le":case"usc2":return In.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 o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=gi.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=gi.toUint8Array(e),n="",o=t.length;for(let i=0;i<o;i++){let s=t[i];s<16&&(n+="0"),n+=s.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 o=0;o<t.length;o=o+2){let i=t.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(e,t=!1){return In.toString(e,t)}static FromUtf16String(e,t=!1){return In.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,"")||""}};Bm.DEFAULT_UTF8_ENCODING="utf8";function _V(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)t[i]=o[i]}return t}function IV(...r){let e=r.map(o=>o.byteLength).reduce((o,i)=>o+i),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)t[n++]=i}),t.buffer}function kV(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}kl.BufferSourceConverter=gi;kl.Convert=Bm;kl.assign=_V;kl.combine=IV;kl.isEqual=kV});var mC=un(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.parseCookie=hC;Mo.parse=hC;Mo.stringifyCookie=eH;Mo.stringifySetCookie=pg;Mo.serialize=pg;Mo.parseSetCookie=tH;Mo.stringifySetCookie=pg;Mo.serialize=pg;var dC=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,fC=/^[\u0021-\u003A\u003C-\u007E]*$/,YK=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,XK=/^[\u0020-\u003A\u003D-\u007E]*$/,QK=/^-?\d+$/,ZK=Object.prototype.toString,JK=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function hC(r,e){let t=new JK,n=r.length;if(n<2)return t;let o=e?.decode||pC,i=0;do{let s=y7(r,i,n);if(s===-1)break;let a=g7(r,i,n);if(s>a){i=r.lastIndexOf(";",s-1)+1;continue}let c=Es(r,i,s);t[c]===void 0&&(t[c]=o(Es(r,s+1,a))),i=a+1}while(i<n);return t}function eH(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let o of Object.keys(r)){let i=r[o];if(i===void 0)continue;if(!dC.test(o))throw new TypeError(`cookie name is invalid: ${o}`);let s=t(i);if(!fC.test(s))throw new TypeError(`cookie val is invalid: ${i}`);n.push(`${o}=${s}`)}return n.join("; ")}function pg(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},i=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!dC.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let s=n.value?i(n.value):"";if(!fC.test(s))throw new TypeError(`argument val is invalid: ${n.value}`);let a=n.name+"="+s;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);a+="; Max-Age="+n.maxAge}if(n.domain){if(!YK.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!XK.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!rH(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.partitioned&&(a+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return a}function tH(r,e){let t=e?.decode||pC,n=r.length,o=g7(r,0,n),i=y7(r,0,o),s=i===-1?{name:"",value:t(Es(r,0,o))}:{name:Es(r,0,i),value:t(Es(r,i+1,o))},a=o+1;for(;a<n;){let c=g7(r,a,n),l=y7(r,a,c),u=l===-1?Es(r,a,c):Es(r,a,l),d=l===-1?void 0:Es(r,l+1,c);switch(u.toLowerCase()){case"httponly":s.httpOnly=!0;break;case"secure":s.secure=!0;break;case"partitioned":s.partitioned=!0;break;case"domain":s.domain=d;break;case"path":s.path=d;break;case"max-age":d&&QK.test(d)&&(s.maxAge=Number(d));break;case"expires":if(!d)break;let f=new Date(d);Number.isFinite(f.valueOf())&&(s.expires=f);break;case"priority":if(!d)break;let h=d.toLowerCase();(h==="low"||h==="medium"||h==="high")&&(s.priority=h);break;case"samesite":if(!d)break;let p=d.toLowerCase();(p==="lax"||p==="strict"||p==="none")&&(s.sameSite=p);break}a=c+1}return s}function g7(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function y7(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Es(r,e,t){let n=e,o=t;do{let i=r.charCodeAt(n);if(i!==32&&i!==9)break}while(++n<o);for(;o>n;){let i=r.charCodeAt(o-1);if(i!==32&&i!==9)break;o--}return r.slice(n,o)}function pC(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function rH(r){return ZK.call(r)==="[object Date]"}});var yq={};wt(yq,{DEFAULT_CID_PEER_FILTER_SIZE:()=>ay,DEFAULT_SESSION_MAX_PROVIDERS:()=>sy,DEFAULT_SESSION_MIN_PROVIDERS:()=>iy,InsufficientProvidersError:()=>cd,InvalidCodecError:()=>cy,NoRoutersAvailableError:()=>Ji,UnknownCodecError:()=>ud,UnknownHashAlgorithmError:()=>ld,createHelia:()=>gq,heliaDefaults:()=>G7,libp2pDefaults:()=>w3});var Q7=Symbol.for("@libp2p/connection");var $o=Symbol.for("@libp2p/content-routing");var fr=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},ah=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},ch=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},T=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Vo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Yl=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},Xl=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var Ns=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},Za=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Cn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Ja=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var lo=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Ql=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},je=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},ec=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},uo=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},lh=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},_i=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},tc=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Te=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Ds=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},fo=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Rn=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Ii=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Os=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Zl=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},uh=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},rc=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Pn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var dh=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},ki=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},fh=class extends ki{constructor(e,t){super(!0,e,t)}},hh=class extends ki{constructor(e,t){super(!1,e,t)}};var Bs=Symbol.for("@libp2p/peer-discovery");var ph=Symbol.for("@libp2p/peer-id");function Rt(r){return!!r?.[ph]}var Ko=Symbol.for("@libp2p/peer-routing");var Ms="keep-alive";function mh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Tt(...r){let e=[];for(let t of r)mh(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 Pt(...r){let e=[];for(let t of r)mh(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 Ci=Symbol.for("@libp2p/transport");var Jl;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Jl||(Jl={}));function lP(r){return typeof r?.handleEvent=="function"}function uP(r){return(r!==!0&&r!==!1&&r?.once)??!1}var we=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=uP(n);super.addEventListener(e,s=>{if(o){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(s.type,a))}lP(t)?t.handleEvent(s):t(s)},n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Ce=Symbol.for("@libp2p/service-capabilities"),Nr=Symbol.for("@libp2p/service-dependencies");var U=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var gh=class extends AggregateError{static name="DNSQueryFailedError";name="DNSQueryFailedError"};var x3=Fo(J7(),1);var E3=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},e9=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function pr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=e,a,c,u=new Promise((d,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){f(e9(s));return}if(s&&(c=()=>{f(e9(s))},s.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new E3;a=i.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&s&&s.removeEventListener("abort",c)});return u.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},u}function v3(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var nc=class{#e=[];enqueue(e,t){let{priority:n=0,id:o}=t??{},i={priority:n,id:o,run:e};if(this.size===0||this.#e[this.size-1].priority>=n){this.#e.push(i);return}let s=v3(this.#e,i,(a,c)=>c.priority-a.priority);this.#e.splice(s,0,i)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex(n=>typeof e=="string"?n.id===e:n.run===e);t!==-1&&this.#e.splice(t,1)}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 Us=class extends x3.default{#e;#t;#r=0;#a;#c=!1;#m=!1;#u;#I=0;#x=0;#d;#f;#l;#s=[];#i=0;#n;#k;#o=0;#y;#h;#N=1n;#w=new Map;#E=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:nc,strict:!1,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#u=e.interval,this.#l=e.strict,this.#n=new e.queueClass,this.#k=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#h=e.autoStart===!1,this.#V()}#v(e){for(;this.#i<this.#s.length;){let n=this.#s[this.#i];if(n!==void 0&&e-n>=this.#u)this.#i++;else break}(this.#i>100&&this.#i>this.#s.length/2||this.#i===this.#s.length)&&(this.#s=this.#s.slice(this.#i),this.#i=0)}#D(e){this.#l?this.#s.push(e):this.#r++}#O(){this.#l?this.#s.length>this.#i&&this.#s.pop():this.#r>0&&this.#r--}#S(){return this.#s.length-this.#i}get#B(){return this.#t?!0:this.#l?this.#S()<this.#a:this.#r<this.#a}get#M(){return this.#o<this.#y}#U(){this.#o--,this.#o===0&&this.emit("pendingZero"),this.#b(),this.emit("next")}#F(){this.#f=void 0,this.#P(),this.#R()}#$(e){if(this.#l){if(this.#v(e),this.#S()>=this.#a){let n=this.#s[this.#i],o=this.#u-(e-n);return this.#A(o),!0}return!1}if(this.#d===void 0){let t=this.#I-e;if(t<0){if(this.#x>0){let n=e-this.#x;if(n<this.#u)return this.#A(this.#u-n),!0}this.#r=this.#e?this.#o:0}else return this.#A(t),!0}return!1}#A(e){this.#f===void 0&&(this.#f=setTimeout(()=>{this.#F()},e))}#T(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}#C(){this.#f&&(clearTimeout(this.#f),this.#f=void 0)}#b(){if(this.#n.size===0){if(this.#T(),this.emit("empty"),this.#o===0){if(this.#C(),this.#l&&this.#i>0){let t=Date.now();this.#v(t)}this.emit("idle")}return!1}let e=!1;if(!this.#h){let t=Date.now(),n=!this.#$(t);if(this.#B&&this.#M){let o=this.#n.dequeue();this.#t||(this.#D(t),this.#g()),this.emit("active"),o(),n&&this.#R(),e=!0}}return e}#R(){this.#t||this.#d!==void 0||this.#l||(this.#d=setInterval(()=>{this.#P()},this.#u),this.#I=Date.now()+this.#u)}#P(){this.#l||(this.#r===0&&this.#o===0&&this.#d&&this.#T(),this.#r=this.#e?this.#o:0),this.#_(),this.#g()}#_(){for(;this.#b(););}get concurrency(){return this.#y}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.#y=e,this.#_()}setPriority(e,t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#n.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#N++).toString()},new Promise((n,o)=>{let i=Symbol(`task-${t.id}`),s=()=>{},a=async()=>{s(),this.#o++,this.#w.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let l;try{try{t.signal?.throwIfAborted()}catch(f){throw this.#K(),this.#w.delete(i),f}this.#x=Date.now();let u=e({signal:t.signal});if(t.timeout&&(u=pr(Promise.resolve(u),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#o} running, ${this.#n.size} waiting)`})),t.signal){let{signal:f}=t;u=Promise.race([u,new Promise((h,p)=>{l=()=>{p(f.reason)},f.addEventListener("abort",l,{once:!0})})])}let d=await u;n(d),this.emit("completed",d)}catch(u){o(u),this.emit("error",u)}finally{l&&t.signal?.removeEventListener("abort",l),this.#w.delete(i),queueMicrotask(()=>{this.#U()})}};this.#n.enqueue(a,t);let c=()=>{if(this.#n instanceof nc){this.#n.remove(a);return}this.#n.remove?.(t.id)};if(t.signal){let{signal:l}=t,u=()=>{s(),c(),o(l.reason),this.#b(),this.emit("next")};if(s=()=>{l.removeEventListener("abort",u),this.#E.delete(s)},l.aborted){u();return}l.addEventListener("abort",u,{once:!0}),this.#E.add(s)}this.emit("add"),this.#b()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#h?(this.#h=!1,this.#_(),this):this}pause(){this.#h=!0}clear(){for(let e of this.#E)e();this.#n=new this.#k,this.#T(),this.#L(),this.emit("empty"),this.#o===0&&(this.#C(),this.emit("idle")),this.emit("next")}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#o===0&&this.#n.size===0||await this.#p("idle")}async onPendingZero(){this.#o!==0&&await this.#p("pendingZero")}async onRateLimit(){this.isRateLimited||await this.#p("rateLimit")}async onRateLimitCleared(){this.isRateLimited&&await this.#p("rateLimitCleared")}onError(){return new Promise((e,t)=>{let n=o=>{this.off("error",n),t(o)};this.on("error",n)})}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#o}get isPaused(){return this.#h}#V(){this.#t||(this.on("add",()=>{this.#n.size>0&&this.#g()}),this.on("next",()=>{this.#g()}))}#g(){this.#t||this.#m||(this.#m=!0,queueMicrotask(()=>{this.#m=!1,this.#L()}))}#K(){this.#t||(this.#O(),this.#g())}#L(){let e=this.#c;if(this.#t||this.#n.size===0){e&&(this.#c=!1,this.emit("rateLimitCleared"));return}let t;if(this.#l){let o=Date.now();this.#v(o),t=this.#S()}else t=this.#r;let n=t>=this.#a;n!==e&&(this.#c=n,this.emit(n?"rateLimit":"rateLimitCleared"))}get isRateLimited(){return this.#c}get isSaturated(){return this.#o===this.#y&&this.#n.size>0||this.isRateLimited&&this.#n.size>0}get runningTasks(){return[...this.#w.values()].map(e=>({...e}))}};function wh(r){let e=[Dr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var k3={};wt(k3,{base10:()=>bP});var mz=new Uint8Array(0);function t9(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 Ln(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 r9(r){return new TextEncoder().encode(r)}function n9(r){return new TextDecoder().decode(r)}function hP(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(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 y=0,m=0,g=0,x=p.length;g!==x&&p[g]===0;)g++,y++;for(var P=(x-g)*u+1>>>0,O=new Uint8Array(P);g!==x;){for(var F=p[g],V=0,H=P-1;(F!==0||V<m)&&H!==-1;H--,V++)F+=256*O[H]>>>0,O[H]=F%a>>>0,F=F/a>>>0;if(F!==0)throw new Error("Non-zero carry");m=V,g++}for(var C=P-m;C!==P&&O[C]===0;)C++;for(var B=c.repeat(y);C<P;++C)B+=r.charAt(O[C]);return B}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var m=0,g=0;p[y]===c;)m++,y++;for(var x=(p.length-y)*l+1>>>0,P=new Uint8Array(x);p[y];){var O=t[p.charCodeAt(y)];if(O===255)return;for(var F=0,V=x-1;(O!==0||F<g)&&V!==-1;V--,F++)O+=a*P[V]>>>0,P[V]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");g=F,y++}if(p[y]!==" "){for(var H=x-g;H!==x&&P[H]===0;)H++;for(var C=new Uint8Array(m+(x-H)),B=m;H!==x;)C[B++]=P[H++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var pP=hP,mP=pP,o9=mP;var A3=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")}},T3=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return i9(this,e)}},_3=class{decoders;constructor(e){this.decoders=e}or(e){return i9(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 i9(r,e){return new _3({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var I3=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new A3(e,t,n),this.decoder=new T3(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function oc({name:r,prefix:e,encode:t,decode:n}){return new I3(r,e,t,n)}function Ri({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=o9(t,r);return oc({prefix:e,name:r,encode:n,decode:i=>Ln(o(i))})}function gP(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function yP(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function wP(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function pt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=wP(n);return oc({prefix:e,name:r,encode(i){return yP(i,n,t)},decode(i){return gP(i,o,t,r)}})}var bP=Ri({prefix:"9",name:"base10",alphabet:"0123456789"});var C3={};wt(C3,{base16:()=>xP,base16upper:()=>EP});var xP=pt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),EP=pt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var R3={};wt(R3,{base2:()=>vP});var vP=pt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var P3={};wt(P3,{base256emoji:()=>IP});var s9=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}"),SP=s9.reduce((r,e,t)=>(r[t]=e,r),[]),AP=s9.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function TP(r){return r.reduce((e,t)=>(e+=SP[t],e),"")}function _P(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=AP[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var IP=oc({prefix:"\u{1F680}",name:"base256emoji",encode:TP,decode:_P});var L3={};wt(L3,{base32:()=>Lt,base32hex:()=>PP,base32hexpad:()=>NP,base32hexpadupper:()=>DP,base32hexupper:()=>LP,base32pad:()=>CP,base32padupper:()=>RP,base32upper:()=>kP,base32z:()=>OP});var Lt=pt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kP=pt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),CP=pt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),RP=pt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),PP=pt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),LP=pt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),NP=pt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DP=pt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),OP=pt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var N3={};wt(N3,{base36:()=>dn,base36upper:()=>BP});var dn=Ri({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),BP=Ri({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var D3={};wt(D3,{base58btc:()=>Ye,base58flickr:()=>MP});var Ye=Ri({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),MP=Ri({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var O3={};wt(O3,{base64:()=>xt,base64pad:()=>tu,base64url:()=>ru,base64urlpad:()=>UP});var xt=pt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tu=pt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ru=pt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),UP=pt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var B3={};wt(B3,{base8:()=>FP});var FP=pt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var M3={};wt(M3,{identity:()=>$P});var $P=oc({prefix:"\0",name:"identity",encode:r=>n9(r),decode:r=>r9(r)});var bh={};wt(bh,{code:()=>U3,decode:()=>zP,encode:()=>qP,name:()=>HP});var VP=new TextEncoder,KP=new TextDecoder,HP="json",U3=512;function qP(r){return VP.encode(JSON.stringify(r))}function zP(r){return JSON.parse(KP.decode(r))}var Fs={};wt(Fs,{code:()=>Ho,decode:()=>jP,encode:()=>GP,name:()=>WP});var WP="raw",Ho=85;function GP(r){return Ln(r)}function jP(r){return Ln(r)}var V3={};wt(V3,{identity:()=>Et});var ct={};wt(ct,{Digest:()=>$s,create:()=>mr,decode:()=>Ge,equals:()=>$3,hasCode:()=>hL});var YP=l9,a9=128,XP=127,QP=~XP,ZP=Math.pow(2,31);function l9(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ZP;)e[t++]=r&255|a9,r/=128;for(;r&QP;)e[t++]=r&255|a9,r>>>=7;return e[t]=r|0,l9.bytes=t-n+1,e}var JP=F3,eL=128,c9=127;function F3(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw F3.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&c9)<<o:(s&c9)*Math.pow(2,o),o+=7}while(s>=eL);return F3.bytes=i-n,t}var tL=Math.pow(2,7),rL=Math.pow(2,14),nL=Math.pow(2,21),oL=Math.pow(2,28),iL=Math.pow(2,35),sL=Math.pow(2,42),aL=Math.pow(2,49),cL=Math.pow(2,56),lL=Math.pow(2,63),uL=function(r){return r<tL?1:r<rL?2:r<nL?3:r<oL?4:r<iL?5:r<sL?6:r<aL?7:r<cL?8:r<lL?9:10},dL={encode:YP,decode:JP,encodingLength:uL},fL=dL,nu=fL;function ou(r,e=0){return[nu.decode(r,e),nu.decode.bytes]}function ic(r,e,t=0){return nu.encode(r,e,t),e}function sc(r){return nu.encodingLength(r)}function mr(r,e){let t=e.byteLength,n=sc(r),o=n+sc(t),i=new Uint8Array(o+t);return ic(r,i,0),ic(t,i,n),i.set(e,o),new $s(r,t,e,i)}function Ge(r){let e=Ln(r),[t,n]=ou(e),[o,i]=ou(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new $s(t,o,s,e)}function $3(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&t9(r.bytes,t.bytes)}}var $s=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function hL(r,e){return r.code===e}var u9=0,pL="identity",d9=Ln;function mL(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return mr(u9,d9(r))}var Et={code:u9,name:pL,encode:d9,digest:mL};var H3={};wt(H3,{sha256:()=>ft,sha512:()=>Eh});var gL=20;function iu({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new K3(r,e,t,n,o)}var K3=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??gL,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?f9(n,this.code,t?.truncate):n.then(o=>f9(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function f9(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return mr(e,r)}function p9(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ft=iu({name:"sha2-256",code:18,encode:p9("SHA-256")}),Eh=iu({name:"sha2-512",code:19,encode:p9("SHA-512")});function m9(r,e){let{bytes:t,version:n}=r;return n===0?wL(t,q3(r),e??Ye.encoder):bL(t,q3(r),e??Lt.encoder)}var g9=new WeakMap;function q3(r){let e=g9.get(r);if(e==null){let t=new Map;return g9.set(r,t),t}return e}var J=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==su)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xL)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=mr(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&&$3(e.multihash,n.multihash)}toString(e){return m9(this,e)}toJSON(){return{"/":m9(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??y9(n,o,i.bytes))}else if(t[EL]===!0){let{version:n,multihash:o,code:i}=t,s=Ge(o);return r.create(n,i,s)}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!==su)throw new Error(`Version 0 CID must use dag-pb (code: ${su}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=y9(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,su,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Ln(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new $s(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=ou(e.subarray(t));return t+=f,d},o=n(),i=su;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=yL(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return q3(i).set(n,e),i}};function yL(r,e){switch(r[0]){case"Q":{let t=e??Ye;return[Ye.prefix,t.decode(`${Ye.prefix}${r}`)]}case Ye.prefix:{let t=e??Ye;return[Ye.prefix,t.decode(r)]}case Lt.prefix:{let t=e??Lt;return[Lt.prefix,t.decode(r)]}case dn.prefix:{let t=e??dn;return[dn.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 wL(r,e,t){let{prefix:n}=t;if(n!==Ye.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function bL(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var su=112,xL=18;function y9(r,e,t){let n=sc(r),o=n+sc(e),i=new Uint8Array(o+t.byteLength);return ic(r,i,0),ic(e,i,n),i.set(t,o),i}var EL=Symbol.for("@ipld/js-cid/CID");var Vs={...M3,...R3,...B3,...k3,...C3,...L3,...N3,...D3,...O3,...P3},Zz={...H3,...V3};function be(r=0){return new Uint8Array(r)}function Xe(r=0){return new Uint8Array(r)}function b9(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var w9=b9("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),z3=b9("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=Xe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),vL={utf8:w9,"utf-8":w9,hex:Vs.base16,latin1:z3,ascii:z3,binary:z3,...Vs},vh=vL;function D(r,e="utf8"){let t=vh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var W3=60;function Sh(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:Dr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Dr[e.type],TTL:e.TTL??e.ttl??W3,data:e.data instanceof Uint8Array?D(e.data):e.data}))}}var SL=4;function G3(r,e={}){let t=new Us({concurrency:e.queryConcurrency??SL});return async(n,o={})=>{let i=o?.logger?.forComponent("dns:dns-json-over-https"),s=new URLSearchParams;s.set("name",n),wh(o.types).forEach(c=>{s.append("type",Dr[c])}),o.onProgress?.(new U("dns:query",n)),i?.("GET %s",`${r}?${s}`);let a=await t.add(async()=>{let c=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(i?.("GET %s %d",c.url,c.status),c.status!==200)throw new Error(`Unexpected HTTP status: ${c.status} - ${c.statusText}`);let l=Sh(await c.json());return o.onProgress?.(new U("dns:response",l)),l},{signal:o.signal});if(a==null)throw new Error("No DNS response received");return a}}function x9(){return[G3("https://cloudflare-dns.com/dns-query"),G3("https://dns.google/resolve")]}var S9=Fo(v9(),1);var j3=class{lru;constructor(e){this.lru=(0,S9.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return Sh({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:Dr[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??W3)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function A9(r){return new j3(r)}var AL=1e3,Ah=class{resolvers;cache;logger;constructor(e){this.resolvers={},this.cache=A9(e.cacheSize??AL),this.logger=e.logger,Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=x9())}async query(e,t={}){let n=wh(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new U("dns:cache",o)),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,logger:this.logger,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new U("dns:error",l))}}throw new gh(a,`DNS lookup of ${e} ${n} failed`)}};var Dr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Dr||(Dr={}));function Th(r={}){return new Ah(r)}function TL(r){return r[Symbol.asyncIterator]!=null}function _L(r){if(TL(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Sr=_L;var au=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},cu=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},_h=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var T9={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new _h("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 vt=T9;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 Je(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Xe(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var I9=Symbol.for("@achingbrain/uint8arraylist");function _9(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function ac(r){return!!r?.[I9]}var ie=class r{bufs;length;[I9]=!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(ac(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ac(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=_9(this.bufs,e);return t.buf[t.index]}set(e,t){let n=_9(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(ac(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Je(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Je(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=n,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(s);break}let d=e-a;n.push(s.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(u){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ac(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let d=0;d<i;d++)s[d]=-1;for(let d=0;d<o;d++)s[n[d]]=d;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}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=Xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=be(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Xe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=be(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!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((o,i)=>o+i.byteLength,0)),n.length=t,n}};function L(r,e="utf8"){let t=vh[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var kL=parseInt("11111",2),Y3=parseInt("10000000",2),CL=parseInt("01111111",2),k9={0:lu,1:lu,2:RL,3:NL,4:DL,5:LL,6:PL,16:lu,22:lu,48:lu};function fn(r,e={offset:0}){let t=r[e.offset]&kL;if(e.offset++,k9[t]!=null)return k9[t](r,e);throw new Error("No decoder for tag "+t)}function uu(r,e){let t=0;if((r[e.offset]&Y3)===Y3){let n=r[e.offset]&CL,o="0x";e.offset++;for(let i=0;i<n;i++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function lu(r,e){uu(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=fn(r,e);if(n===null)break;t.push(n)}return t}function RL(r,e){let t=uu(r,e),n=e.offset,o=e.offset+t,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return e.offset+=t,Uint8Array.from(i)}function PL(r,e){let t=uu(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function LL(r,e){return e.offset++,null}function NL(r,e){let t=uu(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function DL(r,e){let t=uu(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function OL(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ie;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Ih(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=OL(r.byteLength);return new ie(Uint8Array.from([e.byteLength|Y3]),e)}function gr(r){let e=new ie,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ie(Uint8Array.from([2]),Ih(e),e)}function du(r){let e=Uint8Array.from([0]),t=new ie(e,r);return new ie(Uint8Array.from([3]),Ih(t),t)}function C9(r){return new ie(Uint8Array.from([4]),Ih(r),r)}function Nn(r,e=48){let t=new ie;for(let n of r)t.append(n);return new ie(Uint8Array.from([e]),Ih(t),t)}var R9="1.2.840.10045.3.1.7",P9="1.3.132.0.34",L9="1.3.132.0.35";async function N9(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function D9(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function O9(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),i}var BL=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ML=Uint8Array.from([6,5,43,129,4,0,34]),UL=Uint8Array.from([6,5,43,129,4,0,35]),B9={ext:!0,kty:"EC",crv:"P-256"},M9={ext:!0,kty:"EC",crv:"P-384"},U9={ext:!0,kty:"EC",crv:"P-521"},cc=32,lc=48,uc=66;function F9(r){let e=fn(r);return X3(e)}function X3(r){let e=r[1],t=D(e,"base64url"),n=r[2][1][0],o=1,i,s;if(e.byteLength===cc)return i=D(n.subarray(o,o+cc),"base64url"),s=D(n.subarray(o+cc),"base64url"),new Hs({...B9,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===lc)return i=D(n.subarray(o,o+lc),"base64url"),s=D(n.subarray(o+lc),"base64url"),new Hs({...M9,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===uc)return i=D(n.subarray(o,o+uc),"base64url"),s=D(n.subarray(o+uc),"base64url"),new Hs({...U9,key_ops:["sign"],d:t,x:i,y:s});throw new T(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Q3(r){let e=fn(r);return $9(e)}function $9(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===cc*2+1)return n=D(e.subarray(t,t+cc),"base64url"),o=D(e.subarray(t+cc),"base64url"),new Ks({...B9,key_ops:["verify"],x:n,y:o});if(e.byteLength===lc*2+1)return n=D(e.subarray(t,t+lc),"base64url"),o=D(e.subarray(t+lc),"base64url"),new Ks({...M9,key_ops:["verify"],x:n,y:o});if(e.byteLength===uc*2+1)return n=D(e.subarray(t,t+uc),"base64url"),o=D(e.subarray(t+uc),"base64url"),new Ks({...U9,key_ops:["verify"],x:n,y:o});throw new T(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function V9(r){return Nn([gr(Uint8Array.from([1])),C9(L(r.d??"","base64url")),Nn([H9(r.crv)],160),Nn([du(new ie(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function K9(r){return Nn([gr(Uint8Array.from([1])),Nn([H9(r.crv)],160),Nn([du(new ie(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function H9(r){if(r==="P-256")return BL;if(r==="P-384")return ML;if(r==="P-521")return UL;throw new T(`Invalid curve ${r}`)}async function q9(r="P-256"){let e=await N9(r);return new Hs(e.privateKey)}var Ks=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=K9(this.jwk)),this._raw}toMultihash(){return Et.digest(Nt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}async verify(e,t,n){return O9(this.jwk,t,e,n)}},Hs=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Ks({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=V9(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}async sign(e,t){return D9(this.jwk,e,t)}};function Z3(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Ar(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Ht(r,e,t=""){let n=Z3(r),o=r?.length,i=e!==void 0;if(!n||i&&o!==e){let s=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function zo(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Ar(r.outputLen),Ar(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function dc(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 kh(r,e){Ht(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function nr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function qs(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Dn(r,e){return r<<32-e|r>>>e}function Ch(r,e){return r<<e|r>>>32-e>>>0}var W9=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",FL=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Rh(r){if(Ht(r),W9)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=FL[r[t]];return e}var qo={_0:48,_9:57,A:65,F:70,a:97,f:102};function z9(r){if(r>=qo._0&&r<=qo._9)return r-qo._0;if(r>=qo.A&&r<=qo.F)return r-(qo.A-10);if(r>=qo.a&&r<=qo.f)return r-(qo.a-10)}function fu(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(W9)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,i=0;o<t;o++,i+=2){let s=z9(r.charCodeAt(i)),a=z9(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}var $L=async()=>{};async function G9(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-n;i>=0&&i<e||(await $L(),n+=i)}}function VL(r){if(typeof r!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(r))}function J3(r,e=""){return typeof r=="string"?VL(r):Ht(r,void 0,e)}function e4(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ht(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function j9(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new TypeError("options must be object or undefined");return Object.assign(r,e)}function hu(r,e={}){let t=(o,i)=>r(i).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Ph(r=32){Ar(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var t4=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Lh(r,e,t){return r&e^~r&t}function Nh(r,e,t){return r&e^r&t^e&t}var zs=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=qs(this.buffer)}update(e){dc(this),Ht(e);let{view:t,buffer:n,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=qs(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){dc(this),kh(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[s++]=128,nr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let d=s;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),i),this.process(n,0);let a=qs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Wo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Dh=BigInt(4294967295),Y9=BigInt(32);function KL(r,e=!1){return e?{h:Number(r&Dh),l:Number(r>>Y9&Dh)}:{h:Number(r>>Y9&Dh)|0,l:Number(r&Dh)|0}}function X9(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let i=0;i<t;i++){let{h:s,l:a}=KL(r[i],e);[n[i],o[i]]=[s,a]}return[n,o]}var r4=(r,e,t)=>r>>>t,n4=(r,e,t)=>r<<32-t|e>>>t,Ws=(r,e,t)=>r>>>t|e<<32-t,Gs=(r,e,t)=>r<<32-t|e>>>t,pu=(r,e,t)=>r<<64-t|e>>>t-32,mu=(r,e,t)=>r>>>t-32|e<<64-t;function ho(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Q9=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Z9=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,J9=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),ew=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,tw=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),rw=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var qL=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pi=new Uint32Array(64),o4=class extends zs{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)Pi[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Pi[d-15],h=Pi[d-2],p=Dn(f,7)^Dn(f,18)^f>>>3,y=Dn(h,17)^Dn(h,19)^h>>>10;Pi[d]=y+Pi[d-7]+p+Pi[d-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=Dn(a,6)^Dn(a,11)^Dn(a,25),h=u+f+Lh(a,c,l)+qL[d]+Pi[d]|0,y=(Dn(n,2)^Dn(n,13)^Dn(n,22))+Nh(n,o,i)|0;u=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,l,u)}roundClean(){nr(Pi)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),nr(this.buffer)}},i4=class extends o4{A=Wo[0]|0;B=Wo[1]|0;C=Wo[2]|0;D=Wo[3]|0;E=Wo[4]|0;F=Wo[5]|0;G=Wo[6]|0;H=Wo[7]|0;constructor(){super(32)}};var nw=X9(["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))),zL=nw[0],WL=nw[1],Li=new Uint32Array(80),Ni=new Uint32Array(80),s4=class extends zs{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:y,Hl:m}=this;return[e,t,n,o,i,s,a,c,l,u,d,f,h,p,y,m]}set(e,t,n,o,i,s,a,c,l,u,d,f,h,p,y,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=h|0,this.Gl=p|0,this.Hh=y|0,this.Hl=m|0}process(e,t){for(let P=0;P<16;P++,t+=4)Li[P]=e.getUint32(t),Ni[P]=e.getUint32(t+=4);for(let P=16;P<80;P++){let O=Li[P-15]|0,F=Ni[P-15]|0,V=Ws(O,F,1)^Ws(O,F,8)^r4(O,F,7),H=Gs(O,F,1)^Gs(O,F,8)^n4(O,F,7),C=Li[P-2]|0,B=Ni[P-2]|0,q=Ws(C,B,19)^pu(C,B,61)^r4(C,B,6),$=Gs(C,B,19)^mu(C,B,61)^n4(C,B,6),b=J9(H,$,Ni[P-7],Ni[P-16]),S=ew(b,V,q,Li[P-7],Li[P-16]);Li[P]=S|0,Ni[P]=b|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:y,Gl:m,Hh:g,Hl:x}=this;for(let P=0;P<80;P++){let O=Ws(d,f,14)^Ws(d,f,18)^pu(d,f,41),F=Gs(d,f,14)^Gs(d,f,18)^mu(d,f,41),V=d&h^~d&y,H=f&p^~f&m,C=tw(x,F,H,WL[P],Ni[P]),B=rw(C,g,O,V,zL[P],Li[P]),q=C|0,$=Ws(n,o,28)^pu(n,o,34)^pu(n,o,39),b=Gs(n,o,28)^mu(n,o,34)^mu(n,o,39),S=n&i^n&a^i&a,A=o&s^o&c^s&c;g=y|0,x=m|0,y=h|0,m=p|0,h=d|0,p=f|0,{h:d,l:f}=ho(l|0,u|0,B|0,q|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let E=Q9(q,b,A);n=Z9(E,B,$,S),o=E|0}({h:n,l:o}=ho(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=ho(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=ho(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ho(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=ho(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=ho(this.Fh|0,this.Fl|0,h|0,p|0),{h:y,l:m}=ho(this.Gh|0,this.Gl|0,y|0,m|0),{h:g,l:x}=ho(this.Hh|0,this.Hl|0,g|0,x|0),this.set(n,o,i,s,a,c,l,u,d,f,h,p,y,m,g,x)}roundClean(){nr(Li,Ni)}destroy(){this.destroyed=!0,nr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},a4=class extends s4{Ah=qt[0]|0;Al=qt[1]|0;Bh=qt[2]|0;Bl=qt[3]|0;Ch=qt[4]|0;Cl=qt[5]|0;Dh=qt[6]|0;Dl=qt[7]|0;Eh=qt[8]|0;El=qt[9]|0;Fh=qt[10]|0;Fl=qt[11]|0;Gh=qt[12]|0;Gl=qt[13]|0;Hh=qt[14]|0;Hl=qt[15]|0;constructor(){super(64)}};var hn=hu(()=>new i4,t4(1));var po=hu(()=>new a4,t4(3));var _e=(r,e,t)=>Ht(r,e,t),l4=Ar,fc=Rh,_t=(...r)=>e4(...r),hc=r=>fu(r),js=Z3,Ys=r=>Ph(r),Bh=BigInt(0),c4=BigInt(1);function On(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Mh(r){if(typeof r=="bigint"){if(!Oh(r))throw new RangeError("positive bigint expected, got "+r)}else l4(r);return r}function Bn(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function gu(r){let e=Mh(r).toString(16);return e.length&1?"0"+e:e}function ow(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Bh:BigInt("0x"+r)}function Xs(r){return ow(Rh(r))}function Or(r){return ow(Rh(Di(Ht(r)).reverse()))}function Uh(r,e){if(Ar(e),e===0)throw new RangeError("zero length");r=Mh(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return fu(t.padStart(e*2,"0"))}function yu(r,e){return Uh(r,e).reverse()}function iw(r,e){if(r=_e(r),e=_e(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Di(r){return Uint8Array.from(_e(r))}function Fh(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Oh=r=>typeof r=="bigint"&&Bh<=r;function GL(r,e,t){return Oh(r)&&Oh(e)&&Oh(t)&&e<=r&&r<t}function Go(r,e,t,n){if(!GL(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function pc(r){if(r<Bh)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>Bh;r>>=c4,e+=1);return e}var wu=r=>(c4<<BigInt(r))-c4;function sw(r,e,t){if(Ar(r,"hashLen"),Ar(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},f=(...m)=>t(l,_t(c,...m)),h=(m=o)=>{l=f(i,m),c=f(),m.length!==0&&(l=f(s,m),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=f();let x=c.slice();g.push(x),m+=c.length}return _t(...g)};return(m,g)=>{d(),h(m);let x;for(;(x=g(p()))===void 0;)h();return d(),x}}function Br(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(r,i))throw new TypeError(`param "${i}" is invalid: expected own property`);let c=r[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>n(a,c,s));o(e,!1),o(t,!0)}var u4=()=>{throw new Error("not implemented")};var zt=BigInt(0),mt=BigInt(1),Qs=BigInt(2),uw=BigInt(3),dw=BigInt(4),fw=BigInt(5),jL=BigInt(7),hw=BigInt(8),YL=BigInt(9),pw=BigInt(16);function lt(r,e){if(e<=zt)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=zt?t:e+t}function nt(r,e,t){if(e<zt)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >zt;)n*=n,n%=t;return n}function aw(r,e){if(r===zt)throw new Error("invert: expected non-zero number");if(e<=zt)throw new Error("invert: expected positive modulus, got "+e);let t=lt(r,e),n=e,o=zt,i=mt,s=mt,a=zt;for(;t!==zt;){let l=n/t,u=n-t*l,d=o-s*l,f=i-a*l;n=t,t=u,o=s,i=a,s=d,a=f}if(n!==mt)throw new Error("invert: does not exist");return lt(o,e)}function d4(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function mw(r,e){let t=r,n=(t.ORDER+mt)/dw,o=t.pow(e,n);return d4(t,o,e),o}function XL(r,e){let t=r,n=(t.ORDER-fw)/hw,o=t.mul(e,Qs),i=t.pow(o,n),s=t.mul(e,i),a=t.mul(t.mul(s,Qs),i),c=t.mul(s,t.sub(a,t.ONE));return d4(t,c,e),c}function QL(r){let e=mc(r),t=gw(r),n=t(e,e.neg(e.ONE)),o=t(e,n),i=t(e,e.neg(n)),s=(r+jL)/pw;return((a,c)=>{let l=a,u=l.pow(c,s),d=l.mul(u,n),f=l.mul(u,o),h=l.mul(u,i),p=l.eql(l.sqr(d),c),y=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,y);let m=l.eql(l.sqr(d),c),g=l.cmov(u,d,m);return d4(l,g,c),g})}function gw(r){if(r<uw)throw new Error("sqrt is not defined for small field");let e=r-mt,t=0;for(;e%Qs===zt;)e/=Qs,t++;let n=Qs,o=mc(r);for(;cw(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return mw;let i=o.pow(n,e),s=(e+mt)/Qs;return function(c,l){let u=c;if(u.is0(l))return l;if(cw(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,i),h=u.pow(l,e),p=u.pow(l,s);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let y=1,m=u.sqr(h);for(;!u.eql(m,u.ONE);)if(y++,m=u.sqr(m),y===d)throw new Error("Cannot find square root");let g=mt<<BigInt(d-y-1),x=u.pow(f,g);d=y,f=u.sqr(x),h=u.mul(h,f),p=u.mul(p,x)}return p}}function ZL(r){return r%dw===uw?mw:r%hw===fw?XL:r%pw===YL?QL(r):gw(r)}var jo=(r,e)=>(lt(r,e)&mt)===mt,JL=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function f4(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=JL.reduce((n,o)=>(n[o]="function",n),e);if(Br(r,t),Bn(r.BYTES,"BYTES"),Bn(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=mt)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function eN(r,e,t){let n=r;if(t<zt)throw new Error("invalid exponent, negatives unsupported");if(t===zt)return n.ONE;if(t===mt)return e;let o=n.ONE,i=e;for(;t>zt;)t&mt&&(o=n.mul(o,i)),i=n.sqr(i),t>>=mt;return o}function bu(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),i=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),s=n.inv(i);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),s),o}function cw(r,e){let t=r,n=(t.ORDER-mt)/Qs,o=t.pow(e,n),i=t.eql(o,t.ONE),s=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function tN(r,e){if(e!==void 0&&l4(e),r<=zt)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=pc(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var lw=new WeakMap,$h=class{ORDER;BITS;BYTES;isLE;ZERO=zt;ONE=mt;_lengths;_mod;constructor(e,t={}){if(e<=mt)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:i}=tN(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(e){return lt(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return zt<=e&&e<this.ORDER}is0(e){return e===zt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&mt)===mt}neg(e){return lt(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return lt(e*e,this.ORDER)}add(e,t){return lt(e+t,this.ORDER)}sub(e,t){return lt(e-t,this.ORDER)}mul(e,t){return lt(e*t,this.ORDER)}pow(e,t){return eN(this,e,t)}div(e,t){return lt(e*aw(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return aw(e,this.ORDER)}sqrt(e){let t=lw.get(this);return t||lw.set(this,t=ZL(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?yu(e,this.BYTES):Uh(e,this.BYTES)}fromBytes(e,t=!1){_e(e);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Or(e):Xs(e);if(a&&(c=lt(c,s)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return bu(this,e)}cmov(e,t,n){return On(n,"condition"),n?t:e}};Object.freeze($h.prototype);function mc(r,e={}){return new $h(r,e)}function yw(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=mt)throw new Error("field order must be greater than 1");let e=pc(r-mt);return Math.ceil(e/8)}function h4(r){let e=yw(r);return e+Math.ceil(e/2)}function p4(r,e,t=!1){_e(r);let n=r.length,o=yw(e),i=Math.max(h4(e),16);if(n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=t?Or(r):Xs(r),a=lt(s,e-mt)+mt;return t?yu(a,o):Uh(a,o)}var gc=BigInt(0),Zs=BigInt(1);function xu(r,e){let t=e.negate();return r?t:e}function Js(r,e){let t=bu(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function Ew(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function m4(r,e){Ew(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,i=wu(r),s=BigInt(r);return{windows:t,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function ww(r,e,t){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=t,a=Number(r&o),c=r>>s;a>n&&(a-=i,c+=Zs);let l=e*n,u=l+Math.abs(a)-1,d=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:l}}var g4=new WeakMap,vw=new WeakMap;function y4(r){return vw.get(r)||1}function bw(r){if(r!==gc)throw new Error("invalid wNAF")}var yc=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>gc;)t&Zs&&(n=n.add(o)),o=o.double(),t>>=Zs;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=m4(t,this.bits),i=[],s=e,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=m4(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:h}=ww(n,a,s);n=c,u?i=i.add(xu(f,t[h])):o=o.add(xu(d,t[l]))}return bw(n),{p:o,f:i}}wNAFUnsafe(e,t,n,o=this.ZERO){let i=m4(e,this.bits);for(let s=0;s<i.windows&&n!==gc;s++){let{nextN:a,offset:c,isZero:l,isNeg:u}=ww(n,s,i);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return bw(n),o}getPrecomputes(e,t,n){let o=g4.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),g4.set(t,o))),o}cached(e,t,n){let o=y4(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let i=y4(e);return i===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,o)}createCache(e,t){Ew(t,this.bits),vw.set(e,t),g4.delete(e)}hasCache(e){return y4(e)!==1}};function Sw(r,e,t,n){let o=e,i=r.ZERO,s=r.ZERO;for(;t>gc||n>gc;)t&Zs&&(i=i.add(o)),n&Zs&&(s=s.add(o)),o=o.double(),t>>=Zs,n>>=Zs;return{p1:i,p2:s}}function xw(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return f4(e),e}else return mc(r,{isLE:t})}function Vh(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>gc))throw new Error(`CURVE.${c} must be positive bigint`)}let o=xw(e.p,t.Fp,n),i=xw(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function wc(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Oi=BigInt(0),Dt=BigInt(1),w4=BigInt(2),rN=BigInt(8);function nN(r,e,t,n){let o=r.sqr(t),i=r.sqr(n),s=r.add(r.mul(e.a,o),i),a=r.add(r.ONE,r.mul(e.d,r.mul(o,i)));return r.eql(s,a)}function Aw(r,e={}){let t=e,n=Vh("edwards",r,t,t.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;Br(t,{},{uvRatio:"function"});let c=w4<<BigInt(i.BYTES*8)-Dt,l=y=>o.create(y),u=t.uvRatio===void 0?(y,m)=>{try{return{isValid:!0,value:o.sqrt(o.div(y,m))}}catch{return{isValid:!1,value:Oi}}}:t.uvRatio;if(!nN(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(y,m,g=!1){let x=g?Dt:Oi;return Go("coordinate "+y,m,x,c),m}function f(y){if(!(y instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,Dt,l(s.Gx*s.Gy));static ZERO=new h(Oi,Dt,Dt,Oi);static Fp=o;static Fn=i;X;Y;Z;T;constructor(m,g,x,P){this.X=d("x",m),this.Y=d("y",g),this.Z=d("z",x,!0),this.T=d("t",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:g,y:x}=m||{};return d("x",g),d("y",x),new h(g,x,Dt,l(g*x))}static fromBytes(m,g=!1){let x=o.BYTES,{a:P,d:O}=s;m=Di(_e(m,x,"point")),On(g,"zip215");let F=Di(m),V=m[x-1];F[x-1]=V&-129;let H=Or(F),C=g?c:o.ORDER;Go("point.y",H,Oi,C);let B=l(H*H),q=l(B-Dt),$=l(O*B-P),{isValid:b,value:S}=u(q,$);if(!b)throw new Error("bad point: invalid y coordinate");let A=(S&Dt)===Dt,E=(V&128)!==0;if(!g&&S===Oi&&E)throw new Error("bad point: x=0 and x_0=1");return E!==A&&(S=l(-S)),h.fromAffine({x:S,y:H})}static fromHex(m,g=!1){return h.fromBytes(hc(m),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,g=!0){return p.createCache(this,m),g||this.multiply(w4),this}assertValidity(){let m=this,{a:g,d:x}=s;if(m.is0())throw new Error("bad point: ZERO");let{X:P,Y:O,Z:F,T:V}=m,H=l(P*P),C=l(O*O),B=l(F*F),q=l(B*B),$=l(H*g),b=l(B*l($+C)),S=l(q+l(x*l(H*C)));if(b!==S)throw new Error("bad point: equation left != right (1)");let A=l(P*O),E=l(F*V);if(A!==E)throw new Error("bad point: equation left != right (2)")}equals(m){f(m);let{X:g,Y:x,Z:P}=this,{X:O,Y:F,Z:V}=m,H=l(g*V),C=l(O*P),B=l(x*V),q=l(F*P);return H===C&&B===q}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:m}=s,{X:g,Y:x,Z:P}=this,O=l(g*g),F=l(x*x),V=l(w4*l(P*P)),H=l(m*O),C=g+x,B=l(l(C*C)-O-F),q=H+F,$=q-V,b=H-F,S=l(B*$),A=l(q*b),E=l(B*b),v=l($*q);return new h(S,A,v,E)}add(m){f(m);let{a:g,d:x}=s,{X:P,Y:O,Z:F,T:V}=this,{X:H,Y:C,Z:B,T:q}=m,$=l(P*H),b=l(O*C),S=l(V*x*q),A=l(F*B),E=l((P+O)*(H+C)-$-b),v=A-S,N=A+S,M=l(b-g*$),R=l(E*v),z=l(N*M),W=l(E*M),ae=l(v*N);return new h(R,z,ae,W)}subtract(m){return f(m),this.add(m.negate())}multiply(m){if(!i.isValidNot0(m))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:x}=p.cached(this,m,P=>Js(h,P));return Js(h,[g,x])[0]}multiplyUnsafe(m){if(!i.isValid(m))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return m===Oi?h.ZERO:this.is0()||m===Dt?this:p.unsafe(this,m,g=>Js(h,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,s.n).is0()}toAffine(m){let g=this,x=m,{X:P,Y:O,Z:F}=g,V=g.is0();x==null&&(x=V?rN:o.inv(F));let H=l(P*x),C=l(O*x),B=o.mul(F,x);if(V)return{x:Oi,y:Dt};if(B!==Dt)throw new Error("invZ was invalid");return{x:H,y:C}}clearCofactor(){return a===Dt?this:this.multiplyUnsafe(a)}toBytes(){let{x:m,y:g}=this.toAffine(),x=o.toBytes(g);return x[x.length-1]|=m&Dt?128:0,x}toHex(){return fc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new yc(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var Kh=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){u4()}static fromHex(e){u4()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return fc(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function Tw(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;Br(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(Bn(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?Ys:o.randomBytes,f=o.adjustScalarBytes===void 0?b=>b:o.adjustScalarBytes,h=o.domain===void 0?(b,S,A)=>{if(On(A,"phflag"),S.length||A)throw new Error("Contexts/pre-hash are not supported");return b}:o.domain;function p(b){return c.create(Or(b))}function y(b){let S=H.secretKey;_e(b,H.secretKey,"secretKey");let A=_e(n(b),2*S,"hashedSecretKey"),E=f(A.slice(0,S)),v=A.slice(S,2*S),N=p(E);return{head:E,prefix:v,scalar:N}}function m(b){let{head:S,prefix:A,scalar:E}=y(b),v=s.multiply(E),N=v.toBytes();return{head:S,prefix:A,scalar:E,point:v,pointBytes:N}}function g(b){return m(b).pointBytes}function x(b=Uint8Array.of(),...S){let A=_t(...S);return p(n(h(A,_e(b,void 0,"context"),!!i)))}function P(b,S,A={}){b=_e(b,void 0,"message"),i&&(b=i(b));let{prefix:E,scalar:v,pointBytes:N}=m(S),M=x(A.context,E,b),R=s.multiply(M).toBytes(),z=x(A.context,R,N,b),W=c.create(M+z*v);if(!c.isValid(W))throw new Error("sign failed: invalid s");let ae=_t(R,c.toBytes(W));return _e(ae,H.signature,"result")}let O={zip215:o.zip215};function F(b,S,A,E=O){let{context:v}=E,N=E.zip215===void 0?!!O.zip215:E.zip215,M=H.signature;b=_e(b,M,"signature"),S=_e(S,void 0,"message"),A=_e(A,H.publicKey,"publicKey"),N!==void 0&&On(N,"zip215"),i&&(S=i(S));let R=M/2,z=b.subarray(0,R),W=Or(b.subarray(R,M)),ae,ve,xe;try{ae=r.fromBytes(A,N),ve=r.fromBytes(z,N),xe=s.multiplyUnsafe(W)}catch{return!1}if(!N&&ae.isSmallOrder())return!1;let qe=x(v,z,A,S);return ve.add(ae.multiplyUnsafe(qe)).subtract(xe).clearCofactor().is0()}let V=a.BYTES,H={secretKey:V,publicKey:V,signature:2*V,seed:V};function C(b){return b=b===void 0?d(H.seed):b,_e(b,H.seed,"seed")}function B(b){return js(b)&&b.length===H.secretKey}function q(b,S){try{return!!r.fromBytes(b,S===void 0?O.zip215:S)}catch{return!1}}let $={getExtendedPublicKey:m,randomSecretKey:C,isValidSecretKey:B,isValidPublicKey:q,toMontgomery(b){let{y:S}=r.fromBytes(b),A=H.publicKey,E=A===32;if(!E&&A!==57)throw new Error("only defined for 25519 and 448");let v=E?a.div(Dt+S,Dt-S):a.div(S-Dt,S+Dt);return a.toBytes(v)},toMontgomerySecret(b){let S=H.secretKey;_e(b,S);let A=n(b.subarray(0,S));return f(A).subarray(0,S)}};return Object.freeze(H),Object.freeze($),Object.freeze({keygen:wc(C,g),getPublicKey:g,sign:P,verify:F,utils:$,Point:r,lengths:H})}function Eu(r,e){if(Bn(r),Bn(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function oN(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function iN(r){if(!js(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Fh(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function b4(r,e,t,n){_e(r),Bn(t),e=iN(e),e.length>255&&(e=n(_t(Fh("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(t/o);if(t>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=_t(e,Eu(e.length,1)),c=new Uint8Array(i),l=Eu(t,2),u=new Array(s),d=n(_t(c,r,l,Eu(0,1),a));u[0]=n(_t(d,Eu(1,1),a));for(let h=1;h<s;h++){let p=[oN(d,u[h-1]),Eu(h+1,1),a];u[h]=n(_t(...p))}return _t(...u).slice(0,t)}var _w="HashToScalar-";var vu=BigInt(0),bc=BigInt(1),Hh=BigInt(2);function sN(r){return Br(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...r})}function Iw(r){let e=sN(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:i,randomBytes:s}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=s===void 0?Ys:s,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),f=BigInt(a?121665:39081),h=a?Hh**BigInt(254):Hh**BigInt(447),p=a?BigInt(8)*Hh**BigInt(251)-bc:BigInt(4)*Hh**BigInt(445)-bc,y=h+p+bc,m=A=>lt(A,t),g=x(d);function x(A){return yu(m(A),u)}function P(A){let E=Di(_e(A,u,"uCoordinate"));return a&&(E[31]&=127),m(Or(E))}function O(A){return Or(o(Di(_e(A,u,"scalar"))))}function F(A,E){let v=q(P(E),O(A));if(v===vu)throw new Error("invalid private or public key received");return x(v)}function V(A){return F(A,g)}let H=V,C=F;function B(A,E,v){let N=m(A*(E-v));return E=m(E-N),v=m(v+N),{x_2:E,x_3:v}}function q(A,E){Go("u",A,vu,t),Go("scalar",E,h,y);let v=E,N=A,M=bc,R=vu,z=A,W=bc,ae=vu;for(let xe=BigInt(l-1);xe>=vu;xe--){let qe=v>>xe&bc;ae^=qe,{x_2:M,x_3:z}=B(ae,M,z),{x_2:R,x_3:W}=B(ae,R,W),ae=qe;let ze=M+R,We=m(ze*ze),Ne=M-R,at=m(Ne*Ne),Uo=We-at,Ls=z+W,Qa=z-W,Gl=m(Qa*ze),jl=m(Ls*Ne),j7=Gl+jl,Y7=Gl-jl;z=m(j7*j7),W=m(N*m(Y7*Y7)),M=m(We*at),R=m(Uo*(We+m(f*Uo)))}({x_2:M,x_3:z}=B(ae,M,z)),{x_2:R,x_3:W}=B(ae,R,W);let ve=i(R);return m(M*ve)}let $={secretKey:u,publicKey:u,seed:u},b=A=>(A=A===void 0?c(u):A,_e(A,$.seed,"seed"),A),S={randomSecretKey:b};return Object.freeze($),Object.freeze(S),Object.freeze({keygen:wc(b,H),getSharedSecret:C,getPublicKey:H,scalarMult:F,scalarMultBase:V,utils:S,GuBytes:g.slice(),lengths:$})}var aN=BigInt(0),Yo=BigInt(1),kw=BigInt(2),cN=BigInt(3),lN=BigInt(5),uN=BigInt(8),ea=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),S4={p:ea,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:uN,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Pw(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),i=ea,a=r*r%i*r%i,c=nt(a,kw,i)*a%i,l=nt(c,Yo,i)*r%i,u=nt(l,lN,i)*l%i,d=nt(u,e,i)*u%i,f=nt(d,t,i)*d%i,h=nt(f,n,i)*f%i,p=nt(h,o,i)*h%i,y=nt(p,o,i)*h%i,m=nt(y,e,i)*u%i;return{pow_p_5_8:nt(m,kw,i)*r%i,b2:a}}function Lw(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var x4=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function A4(r,e){let t=ea,n=lt(e*e*e,t),o=lt(n*n*e,t),i=Pw(r*o).pow_p_5_8,s=lt(r*n*i,t),a=lt(e*s*s,t),c=s,l=lt(s*x4,t),u=a===r,d=a===lt(-r,t),f=a===lt(-r*x4,t);return u&&(s=c),(d||f)&&(s=l),jo(s,t)&&(s=lt(-s,t)),{isValid:u||d,value:s}}var Mi=Aw(S4,{uvRatio:A4}),Bi=Mi.Fp,Nw=Mi.Fn;function dN(r){return Tw(Mi,po,Object.assign({adjustScalarBytes:Lw,zip215:!0},r))}var Su=dN({});var Au=(()=>{let r=ea;return Iw({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=Pw(e);return lt(nt(t,cN,r)*n,r)},adjustScalarBytes:Lw})})();var E4=x4,fN=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),hN=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),pN=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),mN=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Cw=r=>A4(Yo,r),gN=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),v4=r=>Bi.create(Or(r)&gN);function Rw(r){let{d:e}=S4,t=ea,n=g=>Bi.create(g),o=n(E4*r*r),i=n((o+Yo)*pN),s=BigInt(-1),a=n((s-e*o)*n(o+e)),{isValid:c,value:l}=A4(i,a),u=n(l*r);jo(u,t)||(u=n(-u)),c||(l=u),c||(s=o);let d=n(s*(o-Yo)*mN-a),f=l*l,h=n((l+l)*a),p=n(d*fN),y=n(Yo-f),m=n(Yo+f);return new Mi(n(h*m),n(y*p),n(p*m),n(h*y))}var Ui=class r extends Kh{static BASE=new r(Mi.BASE);static ZERO=new r(Mi.ZERO);static Fp=Bi;static Fn=Nw;constructor(e){super(e)}static fromAffine(e){return new r(Mi.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Ht(e,32);let{a:t,d:n}=S4,o=ea,i=O=>Bi.create(O),s=v4(e);if(!iw(Bi.toBytes(s),e)||jo(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(Yo+t*a),l=i(Yo-t*a),u=i(c*c),d=i(l*l),f=i(t*n*u-d),{isValid:h,value:p}=Cw(i(f*d)),y=i(p*l),m=i(p*y*f),g=i((s+s)*y);jo(g,o)&&(g=i(-g));let x=i(c*m),P=i(g*x);if(!h||jo(P,o)||x===aN)throw new Error("invalid ristretto255 encoding 2");return new r(new Mi(g,x,Yo,P))}static fromHex(e){return r.fromBytes(fu(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,i=ea,s=m=>Bi.create(m),a=s(s(n+t)*s(n-t)),c=s(e*t),l=s(c*c),{value:u}=Cw(s(a*l)),d=s(u*a),f=s(u*c),h=s(d*f*o),p;if(jo(o*h,i)){let m=s(t*E4),g=s(e*E4);e=m,t=g,p=s(d*hN)}else p=f;jo(e*h,i)&&(t=s(-t));let y=s((n-t)*p);return jo(y,i)&&(y=s(-y)),Bi.toBytes(y)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:i}=e.ep,s=l=>Bi.create(l),a=s(t*i)===s(n*o),c=s(n*i)===s(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Ui.BASE);Object.freeze(Ui.ZERO);Object.freeze(Ui.prototype);Object.freeze(Ui);var yN=Object.freeze({Point:Ui,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=b4(r,t,64,po);return yN.deriveToCurve(n)},hashToScalar(r,e={DST:_w}){let t=b4(r,e.DST,64,po);return Nw.create(Or(t))},deriveToCurve(r){Ht(r,64);let e=v4(r.subarray(0,32)),t=Rw(e),n=v4(r.subarray(32,64)),o=Rw(n);return new Ui(t.add(o))}});var ta=32,Mr=64,T4=32;var xc,Dw=(async()=>{try{return await vt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Ow(){let r=Su.utils.randomSecretKey(),e=Su.getPublicKey(r);return{privateKey:vN(r,e),publicKey:e}}async function wN(r,e){let t;r.length===Mr?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:D(r.subarray(32),"base64url"),d:D(t,"base64url"),ext:!0,key_ops:["sign"]},o=await vt.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await vt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(i,0,i.byteLength)}function bN(r,e){let t=r.subarray(0,T4);return Su.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function Bw(r,e){return xc==null&&(xc=await Dw),xc?wN(r,e):bN(r,e)}async function xN(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await vt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await vt.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function EN(r,e,t){return Su.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Mw(r,e,t){return xc==null&&(xc=await Dw),xc?xN(r,e,t):EN(r,e,t)}function vN(r,e){let t=new Uint8Array(Mr);for(let n=0;n<T4;n++)t[n]=r[n],t[T4+n]=e[n];return t}function Ec(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Tu=class{type="Ed25519";raw;constructor(e){this.raw=Sc(e,ta)}toMultihash(){return Et.digest(Nt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Mw(this.raw,t,e);return Ec(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}},vc=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Sc(e,Mr),this.publicKey=new Tu(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=Bw(this.raw,e);return Ec(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function _4(r){if(r.length>Mr){r=Sc(r,Mr+ta);let n=r.subarray(0,Mr),o=r.subarray(Mr,r.length);return new vc(n,o)}r=Sc(r,Mr);let e=r.subarray(0,Mr),t=r.subarray(ta);return new vc(e,t)}function I4(r){return r=Sc(r,ta),new Tu(r)}async function Fw(){let{privateKey:r,publicKey:e}=Ow();return new vc(r,e)}function Sc(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new T(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var SN=Math.pow(2,7),AN=Math.pow(2,14),TN=Math.pow(2,21),k4=Math.pow(2,28),C4=Math.pow(2,35),R4=Math.pow(2,42),P4=Math.pow(2,49),Ve=128,or=127;function Ae(r){if(r<SN)return 1;if(r<AN)return 2;if(r<TN)return 3;if(r<k4)return 4;if(r<C4)return 5;if(r<R4)return 6;if(r<P4)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Fi(r,e,t=0){switch(Ae(r)){case 8:e[t++]=r&255|Ve,r/=128;case 7:e[t++]=r&255|Ve,r/=128;case 6:e[t++]=r&255|Ve,r/=128;case 5:e[t++]=r&255|Ve,r/=128;case 4:e[t++]=r&255|Ve,r>>>=7;case 3:e[t++]=r&255|Ve,r>>>=7;case 2:e[t++]=r&255|Ve,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function _N(r,e,t=0){switch(Ae(r)){case 8:e.set(t++,r&255|Ve),r/=128;case 7:e.set(t++,r&255|Ve),r/=128;case 6:e.set(t++,r&255|Ve),r/=128;case 5:e.set(t++,r&255|Ve),r/=128;case 4:e.set(t++,r&255|Ve),r>>>=7;case 3:e.set(t++,r&255|Ve),r>>>=7;case 2:e.set(t++,r&255|Ve),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function _u(r,e){let t=r[e],n=0;if(n+=t&or,t<Ve||(t=r[e+1],n+=(t&or)<<7,t<Ve)||(t=r[e+2],n+=(t&or)<<14,t<Ve)||(t=r[e+3],n+=(t&or)<<21,t<Ve)||(t=r[e+4],n+=(t&or)*k4,t<Ve)||(t=r[e+5],n+=(t&or)*C4,t<Ve)||(t=r[e+6],n+=(t&or)*R4,t<Ve)||(t=r[e+7],n+=(t&or)*P4,t<Ve))return n;throw new RangeError("Could not decode varint")}function IN(r,e){let t=r.get(e),n=0;if(n+=t&or,t<Ve||(t=r.get(e+1),n+=(t&or)<<7,t<Ve)||(t=r.get(e+2),n+=(t&or)<<14,t<Ve)||(t=r.get(e+3),n+=(t&or)<<21,t<Ve)||(t=r.get(e+4),n+=(t&or)*k4,t<Ve)||(t=r.get(e+5),n+=(t&or)*C4,t<Ve)||(t=r.get(e+6),n+=(t&or)*R4,t<Ve)||(t=r.get(e+7),n+=(t&or)*P4,t<Ve))return n;throw new RangeError("Could not decode varint")}function ir(r,e,t=0){return e==null&&(e=Xe(Ae(r))),e instanceof Uint8Array?Fi(r,e,t):_N(r,e,t)}function Ur(r,e=0){return r instanceof Uint8Array?_u(r,e):IN(r,e)}var L4=new Float32Array([-0]),$i=new Uint8Array(L4.buffer);function $w(r,e,t){L4[0]=r,e[t]=$i[0],e[t+1]=$i[1],e[t+2]=$i[2],e[t+3]=$i[3]}function Vw(r,e){return $i[0]=r[e],$i[1]=r[e+1],$i[2]=r[e+2],$i[3]=r[e+3],L4[0]}var N4=new Float64Array([-0]),sr=new Uint8Array(N4.buffer);function Kw(r,e,t){N4[0]=r,e[t]=sr[0],e[t+1]=sr[1],e[t+2]=sr[2],e[t+3]=sr[3],e[t+4]=sr[4],e[t+5]=sr[5],e[t+6]=sr[6],e[t+7]=sr[7]}function Hw(r,e){return sr[0]=r[e],sr[1]=r[e+1],sr[2]=r[e+2],sr[3]=r[e+3],sr[4]=r[e+4],sr[5]=r[e+5],sr[6]=r[e+6],sr[7]=r[e+7],N4[0]}var kN=BigInt(Number.MAX_SAFE_INTEGER),CN=BigInt(Number.MIN_SAFE_INTEGER),Fr=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 ra;if(e<kN&&e>CN)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>qw&&(o=0n,++n>qw&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ra;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ra}},ra=new Fr(0,0);ra.toBigInt=function(){return 0n};ra.zzEncode=ra.zzDecode=function(){return this};ra.length=function(){return 1};var qw=4294967296n;function zw(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 Ww(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(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,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function D4(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Mn(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function qh(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var O4=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,Mn(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 Mn(this,4);return qh(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Mn(this,4);return qh(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Mn(this,4);let e=Vw(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Mn(this,4);let e=Hw(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 Mn(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Ww(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Mn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Mn(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 Fr(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 Mn(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 Mn(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 Mn(this,8);let e=qh(this.buf,this.pos+=4),t=qh(this.buf,this.pos+=4);return new Fr(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=_u(this.buf,this.pos);return this.pos+=Ae(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 Iu(r){return new O4(r instanceof Uint8Array?r:r.subarray())}function pe(r,e,t){let n=Iu(r);return e.decode(n,void 0,t)}function B4(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return Xe(s);o+s>e&&(n=Xe(e),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var na=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function M4(){}var F4=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},RN=B4();function PN(r){return globalThis.Buffer!=null?Xe(r):RN(r)}var Cu=class{len;head;tail;states;constructor(){this.len=0,this.head=new na(M4,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new na(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new $4((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(zh,10,Fr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Fr.fromBigInt(e);return this._push(zh,t.length(),t)}uint64Number(e){return this._push(Fi,Ae(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=Fr.fromBigInt(e).zzEncode();return this._push(zh,t.length(),t)}sint64Number(e){let t=Fr.fromNumber(e).zzEncode();return this._push(zh,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(U4,1,e?1:0)}fixed32(e){return this._push(ku,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Fr.fromBigInt(e);return this._push(ku,4,t.lo)._push(ku,4,t.hi)}fixed64Number(e){let t=Fr.fromNumber(e);return this._push(ku,4,t.lo)._push(ku,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($w,4,e)}double(e){return this._push(Kw,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(U4,1,0):this.uint32(t)._push(NN,t,e)}string(e){let t=zw(e);return t!==0?this.uint32(t)._push(D4,t,e):this._push(U4,1,0)}fork(){return this.states=new F4(this),this.head=this.tail=new na(M4,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 na(M4,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=PN(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function U4(r,e,t){e[t]=r&255}function LN(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var $4=class extends na{next;constructor(e,t){super(LN,e,t),this.next=void 0}};function zh(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 ku(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 NN(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Cu.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(DN,e,r),this},Cu.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(ON,e,r),this});function DN(r,e,t){e.set(r,t)}function ON(r,e,t){r.length<40?D4(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function V4(){return new Cu}function me(r,e){let t=V4();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*ge(r,e,t){let n=Iu(r);yield*e.stream(n,void 0,"$",t)}var Wh={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Gh(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function ut(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(s,a){let c=e(s);a.int32(c)},n=function(s){let a=s.int32();return e(a)},o=function*(s){let a=s.int32();yield e(a)};return Gh("enum",Wh.VARINT,t,n,o)}function ye(r,e,t){return Gh("message",Wh.LENGTH_DELIMITED,r,e,t)}var Se=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Ru=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var Qe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Qe||(Qe={}));var K4;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(K4||(K4={}));(function(r){r.codec=()=>ut(K4)})(Qe||(Qe={}));var mo;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),Qe.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=Qe.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Qe.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(mo||(mo={}));var Pu;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),Qe.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=Qe.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Qe.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Pu||(Pu={}));function yr(r){if(isNaN(r)||r<=0)throw new T("random bytes length must be a Number bigger than 0");return Ph(r)}var Nu={};wt(Nu,{MAX_RSA_KEY_SIZE:()=>H4,generateRSAKeyPair:()=>Z4,jwkToJWKKeyPair:()=>Qw,jwkToPkcs1:()=>FN,jwkToPkix:()=>G4,jwkToRSAPrivateKey:()=>Q4,pkcs1MessageToJwk:()=>z4,pkcs1MessageToRSAPrivateKey:()=>jh,pkcs1ToJwk:()=>UN,pkcs1ToRSAPrivateKey:()=>j4,pkixMessageToJwk:()=>W4,pkixMessageToRSAPublicKey:()=>X4,pkixToJwk:()=>$N,pkixToRSAPublicKey:()=>Y4});var Ac=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Nu.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return J.createV1(114,this._multihash)}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){return Xw(this.jwk,t,e,n)}},Lu=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Nu.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e,t){return Yw(this.jwk,e,t)}};var H4=8192,q4=18,BN=1062,MN=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function UN(r){let e=fn(r);return z4(e)}function z4(r){return{n:D(r[1],"base64url"),e:D(r[2],"base64url"),d:D(r[3],"base64url"),p:D(r[4],"base64url"),q:D(r[5],"base64url"),dp:D(r[6],"base64url"),dq:D(r[7],"base64url"),qi:D(r[8],"base64url"),kty:"RSA"}}function FN(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 T("JWK was missing components");return Nn([gr(Uint8Array.from([0])),gr(L(r.n,"base64url")),gr(L(r.e,"base64url")),gr(L(r.d,"base64url")),gr(L(r.p,"base64url")),gr(L(r.q,"base64url")),gr(L(r.dp,"base64url")),gr(L(r.dq,"base64url")),gr(L(r.qi,"base64url"))]).subarray()}function $N(r){let e=fn(r,{offset:0});return W4(e)}function W4(r){let e=fn(r[1],{offset:0});return{kty:"RSA",n:D(e[0],"base64url"),e:D(e[1],"base64url")}}function G4(r){if(r.n==null||r.e==null)throw new T("JWK was missing components");return Nn([MN,du(Nn([gr(L(r.n,"base64url")),gr(L(r.e,"base64url"))]))]).subarray()}function j4(r){let e=fn(r);return jh(e)}function jh(r){let e=z4(r);return Q4(e)}function Y4(r,e){if(r.byteLength>=BN)throw new Vo("Key size is too large");let t=fn(r,{offset:0});return X4(t,r,e)}function X4(r,e,t){let n=W4(r);if(t==null){let o=hn(mo.encode({Type:Qe.RSA,Data:e}));t=mr(q4,o)}return new Ac(n,t)}function Q4(r){if(Jw(r)>H4)throw new T("Key size is too large");let e=Qw(r),t=hn(mo.encode({Type:Qe.RSA,Data:G4(e.publicKey)})),n=mr(q4,t);return new Lu(e.privateKey,new Ac(e.publicKey,n))}async function Z4(r){if(r>H4)throw new T("Key size is too large");let e=await Zw(r),t=hn(mo.encode({Type:Qe.RSA,Data:G4(e.publicKey)})),n=mr(q4,t);return new Lu(e.privateKey,new Ac(e.publicKey,n))}function Qw(r){if(r==null)throw new T("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Zw(r,e){let t=await vt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await VN(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Yw(r,e,t){let n=await vt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await vt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Xw(r,e,t,n){let o=await vt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await vt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),i}async function VN(r,e){if(r.privateKey==null||r.publicKey==null)throw new T("Private and public key are required");let t=await Promise.all([vt.get().subtle.exportKey("jwk",r.privateKey),vt.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Jw(r){if(r.kty!=="RSA")throw new T("invalid key type");if(r.n==null)throw new T("invalid key modulus");return L(r.n,"base64url").length*8}var Yh=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(zo(e),Ht(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let 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),nr(o)}update(e){return dc(this),this.iHash.update(e),this}digestInto(e){dc(this),kh(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},oa=(()=>{let r=((e,t,n)=>new Yh(e,t).update(n).digest());return r.create=(e,t)=>new Yh(e,t),r})();var eb=(r,e)=>(r+(r>=0?e:-e)/tb)/e;function KN(r,e,t){Go("scalar",r,go,t);let[[n,o],[i,s]]=e,a=eb(s*r,t),c=eb(-o*r,t),l=r-a*n-c*i,u=-a*o-c*s,d=l<go,f=u<go;d&&(l=-l),f&&(u=-u);let h=wu(Math.ceil(pc(t)/2))+Vi;if(l<go||l>=h||u<go||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function e6(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function J4(r,e){Br(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return On(t.lowS,"lowS"),On(t.prehash,"prehash"),t.format!==void 0&&e6(t.format),t}var t6=class extends Error{constructor(e=""){super(e)}},Un={Err:t6,_tlv:{encode:(r,e)=>{let{Err:t}=Un;if(Bn(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=gu(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?gu(o.length/2|128):"";return gu(r)+i+o+e},decode(r,e){let{Err:t}=Un;e=_e(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=Un;if(Mh(r),r<go)throw new e("integer: negative integers are not allowed");let t=gu(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}=Un;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Xs(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Un,o=_e(r,void 0,"signature"),{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{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}=Un,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),i=n+o;return e.encode(48,i)}};Object.freeze(Un._tlv);Object.freeze(Un._int);Object.freeze(Un);var go=BigInt(0),Vi=BigInt(1),tb=BigInt(2),Xh=BigInt(3),HN=BigInt(4);function rb(r,e={}){let t=Vh("weierstrass",r,e),n=t.Fp,o=t.Fn,i=t.CURVE,{h:s,n:a}=i;Br(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=ob(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f($,b,S){if(l&&b.is0())return Uint8Array.of(0);let{x:A,y:E}=b.toAffine(),v=n.toBytes(A);if(On(S,"isCompressed"),S){d();let N=!n.isOdd(E);return _t(nb(N),v)}else return _t(Uint8Array.of(4),v,n.toBytes(E))}function h($){_e($,void 0,"Point");let{publicKey:b,publicKeyUncompressed:S}=u,A=$.length,E=$[0],v=$.subarray(1);if(l&&A===1&&E===0)return{x:n.ZERO,y:n.ZERO};if(A===b&&(E===2||E===3)){let N=n.fromBytes(v);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let M=m(N),R;try{R=n.sqrt(M)}catch(ae){let ve=ae instanceof Error?": "+ae.message:"";throw new Error("bad point: is not on curve, sqrt error"+ve)}d();let z=n.isOdd(R);return(E&1)===1!==z&&(R=n.neg(R)),{x:N,y:R}}else if(A===S&&E===4){let N=n.BYTES,M=n.fromBytes(v.subarray(0,N)),R=n.fromBytes(v.subarray(N,N*2));if(!g(M,R))throw new Error("bad point: is not on curve");return{x:M,y:R}}else throw new Error(`bad point: got length ${A}, expected compressed=${b} or uncompressed=${S}`)}let p=e.toBytes===void 0?f:e.toBytes,y=e.fromBytes===void 0?h:e.fromBytes;function m($){let b=n.sqr($),S=n.mul(b,$);return n.add(n.add(S,n.mul($,i.a)),i.b)}function g($,b){let S=n.sqr(b),A=m($);return n.eql(S,A)}if(!g(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let x=n.mul(n.pow(i.a,Xh),HN),P=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(x,P)))throw new Error("bad curve params: a or b");function O($,b,S=!1){if(!n.isValid(b)||S&&n.is0(b))throw new Error(`bad point coordinate ${$}`);return b}function F($){if(!($ instanceof C))throw new Error("Weierstrass Point expected")}function V($){if(!c||!c.basises)throw new Error("no endo");return KN($,c.basises,o.ORDER)}function H($,b,S,A,E){return S=new C(n.mul(S.X,$),S.Y,S.Z),b=xu(A,b),S=xu(E,S),b.add(S)}class C{static BASE=new C(i.Gx,i.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,S,A){this.X=O("x",b),this.Y=O("y",S,!0),this.Z=O("z",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){let{x:S,y:A}=b||{};if(!b||!n.isValid(S)||!n.isValid(A))throw new Error("invalid affine point");if(b instanceof C)throw new Error("projective point not allowed");return n.is0(S)&&n.is0(A)?C.ZERO:new C(S,A,n.ONE)}static fromBytes(b){let S=C.fromAffine(y(_e(b,void 0,"point")));return S.assertValidity(),S}static fromHex(b){return C.fromBytes(hc(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,S=!0){return q.createCache(this,b),S||this.multiply(Xh),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x:S,y:A}=b.toAffine();if(!n.isValid(S)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!g(S,A))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){F(b);let{X:S,Y:A,Z:E}=this,{X:v,Y:N,Z:M}=b,R=n.eql(n.mul(S,M),n.mul(v,E)),z=n.eql(n.mul(A,M),n.mul(N,E));return R&&z}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:S}=i,A=n.mul(S,Xh),{X:E,Y:v,Z:N}=this,M=n.ZERO,R=n.ZERO,z=n.ZERO,W=n.mul(E,E),ae=n.mul(v,v),ve=n.mul(N,N),xe=n.mul(E,v);return xe=n.add(xe,xe),z=n.mul(E,N),z=n.add(z,z),M=n.mul(b,z),R=n.mul(A,ve),R=n.add(M,R),M=n.sub(ae,R),R=n.add(ae,R),R=n.mul(M,R),M=n.mul(xe,M),z=n.mul(A,z),ve=n.mul(b,ve),xe=n.sub(W,ve),xe=n.mul(b,xe),xe=n.add(xe,z),z=n.add(W,W),W=n.add(z,W),W=n.add(W,ve),W=n.mul(W,xe),R=n.add(R,W),ve=n.mul(v,N),ve=n.add(ve,ve),W=n.mul(ve,xe),M=n.sub(M,W),z=n.mul(ve,ae),z=n.add(z,z),z=n.add(z,z),new C(M,R,z)}add(b){F(b);let{X:S,Y:A,Z:E}=this,{X:v,Y:N,Z:M}=b,R=n.ZERO,z=n.ZERO,W=n.ZERO,ae=i.a,ve=n.mul(i.b,Xh),xe=n.mul(S,v),qe=n.mul(A,N),ze=n.mul(E,M),We=n.add(S,A),Ne=n.add(v,N);We=n.mul(We,Ne),Ne=n.add(xe,qe),We=n.sub(We,Ne),Ne=n.add(S,E);let at=n.add(v,M);return Ne=n.mul(Ne,at),at=n.add(xe,ze),Ne=n.sub(Ne,at),at=n.add(A,E),R=n.add(N,M),at=n.mul(at,R),R=n.add(qe,ze),at=n.sub(at,R),W=n.mul(ae,Ne),R=n.mul(ve,ze),W=n.add(R,W),R=n.sub(qe,W),W=n.add(qe,W),z=n.mul(R,W),qe=n.add(xe,xe),qe=n.add(qe,xe),ze=n.mul(ae,ze),Ne=n.mul(ve,Ne),qe=n.add(qe,ze),ze=n.sub(xe,ze),ze=n.mul(ae,ze),Ne=n.add(Ne,ze),xe=n.mul(qe,Ne),z=n.add(z,xe),xe=n.mul(at,Ne),R=n.mul(We,R),R=n.sub(R,xe),xe=n.mul(We,qe),W=n.mul(at,W),W=n.add(W,xe),new C(R,z,W)}subtract(b){return F(b),this.add(b.negate())}is0(){return this.equals(C.ZERO)}multiply(b){let{endo:S}=e;if(!o.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let A,E,v=N=>q.cached(this,N,M=>Js(C,M));if(S){let{k1neg:N,k1:M,k2neg:R,k2:z}=V(b),{p:W,f:ae}=v(M),{p:ve,f:xe}=v(z);E=ae.add(xe),A=H(S.beta,W,ve,N,R)}else{let{p:N,f:M}=v(b);A=N,E=M}return Js(C,[A,E])[0]}multiplyUnsafe(b){let{endo:S}=e,A=this,E=b;if(!o.isValid(E))throw new RangeError("invalid scalar: out of range");if(E===go||A.is0())return C.ZERO;if(E===Vi)return A;if(q.hasCache(this))return this.multiply(E);if(S){let{k1neg:v,k1:N,k2neg:M,k2:R}=V(E),{p1:z,p2:W}=Sw(C,A,N,R);return H(S.beta,z,W,v,M)}else return q.unsafe(A,E)}toAffine(b){let S=this,A=b,{X:E,Y:v,Z:N}=S;if(n.eql(N,n.ONE))return{x:E,y:v};let M=S.is0();A==null&&(A=M?n.ONE:n.inv(N));let R=n.mul(E,A),z=n.mul(v,A),W=n.mul(N,A);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(W,n.ONE))throw new Error("invZ was invalid");return{x:R,y:z}}isTorsionFree(){let{isTorsionFree:b}=e;return s===Vi?!0:b?b(C,this):q.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return s===Vi?this:b?b(C,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===Vi?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return On(b,"isCompressed"),this.assertValidity(),p(C,this,b)}toHex(b=!0){return fc(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let B=o.BITS,q=new yc(C,e.endo?Math.ceil(B/2):B);return B>=8&&C.BASE.precompute(8),Object.freeze(C.prototype),Object.freeze(C),C}function nb(r){return Uint8Array.of(r?2:3)}function ob(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function qN(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?Ys:e.randomBytes,o=Object.assign(ob(r.Fp,t),{seed:Math.max(h4(t.ORDER),16)});function i(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function s(h,p){let{publicKey:y,publicKeyUncompressed:m}=o;try{let g=h.length;return p===!0&&g!==y||p===!1&&g!==m?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,p4(_e(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:y,publicKeyUncompressed:m}=o,g=t._lengths;if(!js(h))return;let x=_e(h,void 0,"key").length,P=x===y||x===m,O=x===p||!!g?.includes(x);if(!(P&&O))return P}function u(h,p,y=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let m=t.fromBytes(h);return r.fromBytes(p).multiply(m).toBytes(y)}let d={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},f=wc(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:o})}function ib(r,e,t={}){let n=e;zo(n),Br(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?Ys:t.randomBytes,i=t.hmac===void 0?(E,v)=>oa(n,E,v):t.hmac,{Fp:s,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=qN(r,t),y={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=c*tb+Vi<s.ORDER;function g(E){let v=c>>Vi;return E>v}function x(E,v){if(!a.isValidNot0(v))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return v}function P(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(E,v){e6(v);let N=p.signature,M=v==="compact"?N:v==="recovered"?N+1:void 0;return _e(E,M)}class F{r;s;recovery;constructor(v,N,M){if(this.r=x("r",v),this.s=x("s",N),M!=null){if(P(),![0,1,2,3].includes(M))throw new Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(v,N=y.format){O(v,N);let M;if(N==="der"){let{r:ae,s:ve}=Un.toSig(_e(v));return new F(ae,ve)}N==="recovered"&&(M=v[0],N="compact",v=v.subarray(1));let R=p.signature/2,z=v.subarray(0,R),W=v.subarray(R,R*2);return new F(a.fromBytes(z),a.fromBytes(W),M)}static fromHex(v,N){return this.fromBytes(hc(v),N)}assertRecovery(){let{recovery:v}=this;if(v==null)throw new Error("invalid recovery id: must be present");return v}addRecoveryBit(v){return new F(this.r,this.s,v)}recoverPublicKey(v){let{r:N,s:M}=this,R=this.assertRecovery(),z=R===2||R===3?N+c:N;if(!s.isValid(z))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let W=s.toBytes(z),ae=r.fromBytes(_t(nb((R&1)===0),W)),ve=a.inv(z),xe=H(_e(v,void 0,"msgHash")),qe=a.create(-xe*ve),ze=a.create(M*ve),We=r.BASE.multiplyUnsafe(qe).add(ae.multiplyUnsafe(ze));if(We.is0())throw new Error("invalid recovery: point at infinify");return We.assertValidity(),We}hasHighS(){return g(this.s)}toBytes(v=y.format){if(e6(v),v==="der")return hc(Un.hexFromSig(this));let{r:N,s:M}=this,R=a.toBytes(N),z=a.toBytes(M);return v==="recovered"?(P(),_t(Uint8Array.of(this.assertRecovery()),R,z)):_t(R,z)}toHex(v){return fc(this.toBytes(v))}}Object.freeze(F.prototype),Object.freeze(F);let V=t.bits2int===void 0?function(v){if(v.length>8192)throw new Error("input is too large");let N=Xs(v),M=v.length*8-l;return M>0?N>>BigInt(M):N}:t.bits2int,H=t.bits2int_modN===void 0?function(v){return a.create(V(v))}:t.bits2int_modN,C=wu(l);function B(E){return Go("num < 2^"+l,E,go,C),a.toBytes(E)}function q(E,v){return _e(E,void 0,"message"),v?_e(n(E),void 0,"prehashed message"):E}function $(E,v,N){let{lowS:M,prehash:R,extraEntropy:z}=J4(N,y);E=q(E,R);let W=H(E),ae=a.fromBytes(v);if(!a.isValidNot0(ae))throw new Error("invalid private key");let ve=[B(ae),B(W)];if(z!=null&&z!==!1){let We=z===!0?o(p.secretKey):z;ve.push(_e(We,void 0,"extraEntropy"))}let xe=_t(...ve),qe=W;function ze(We){let Ne=V(We);if(!a.isValidNot0(Ne))return;let at=a.inv(Ne),Uo=r.BASE.multiply(Ne).toAffine(),Ls=a.create(Uo.x);if(Ls===go)return;let Qa=a.create(at*a.create(qe+Ls*ae));if(Qa===go)return;let Gl=(Uo.x===Ls?0:2)|Number(Uo.y&Vi),jl=Qa;return M&&g(Qa)&&(jl=a.neg(Qa),Gl^=1),new F(Ls,jl,m?void 0:Gl)}return{seed:xe,k2sig:ze}}function b(E,v,N={}){let{seed:M,k2sig:R}=$(E,v,N);return sw(n.outputLen,a.BYTES,i)(M,R).toBytes(N.format)}function S(E,v,N,M={}){let{lowS:R,prehash:z,format:W}=J4(M,y);if(N=_e(N,void 0,"publicKey"),v=q(v,z),!js(E)){let ae=E instanceof F?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+ae)}O(E,W);try{let ae=F.fromBytes(E,W),ve=r.fromBytes(N);if(R&&ae.hasHighS())return!1;let{r:xe,s:qe}=ae,ze=H(v),We=a.inv(qe),Ne=a.create(ze*We),at=a.create(xe*We),Uo=r.BASE.multiplyUnsafe(Ne).add(ve.multiplyUnsafe(at));return Uo.is0()?!1:a.create(Uo.x)===xe}catch{return!1}}function A(E,v,N={}){let{prehash:M}=J4(N,y);return v=q(v,M),F.fromBytes(E,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:r,sign:b,verify:S,recoverPublicKey:A,Signature:F,hash:n})}var n6={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zN={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var sb=BigInt(2);function WN(r){let e=n6.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=nt(u,t,e)*u%e,f=nt(d,t,e)*u%e,h=nt(f,sb,e)*l%e,p=nt(h,o,e)*h%e,y=nt(p,i,e)*p%e,m=nt(y,a,e)*y%e,g=nt(m,c,e)*m%e,x=nt(g,a,e)*y%e,P=nt(x,t,e)*u%e,O=nt(P,s,e)*p%e,F=nt(O,n,e)*l%e,V=nt(F,sb,e);if(!r6.eql(r6.sqr(V),r))throw new Error("Cannot find square root");return V}var r6=mc(n6.p,{sqrt:WN}),GN=rb(n6,{Fp:r6,endo:zN}),Fn=ib(GN,hn);var ab=32;function cb(r,e,t){let n=ft.digest(e instanceof Uint8Array?e:e.subarray());if(Ec(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),Fn.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new au(String(o))});try{return Fn.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new au(String(o))}}function lb(r,e,t,n){let o=ft.digest(t instanceof Uint8Array?t:t.subarray());if(Ec(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),Fn.verify(e,i,r,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new cu(String(i))});try{return n?.signal?.throwIfAborted(),Fn.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(i){throw new cu(String(i))}}var Du=class{type="secp256k1";raw;_key;constructor(e){this._key=fb(e),this.raw=ub(this._key)}toMultihash(){return Et.digest(Nt(this))}toCID(){return J.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}verify(e,t,n){return lb(this._key,t,e,n)}},Ou=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=db(e),this.publicKey=new Du(t??hb(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ce(this.raw,e.raw)}sign(e,t){return cb(this.raw,e,t)}};function o6(r){return new Ou(r)}function i6(r){return new Du(r)}async function pb(){let r=jN();return new Ou(r)}function ub(r){return Fn.Point.fromBytes(r).toBytes()}function db(r){try{return Fn.getPublicKey(r,!0),r}catch(e){throw new Yl(String(e))}}function fb(r){try{return Fn.Point.fromBytes(r),r}catch(e){throw new Vo(String(e))}}function hb(r){try{return Fn.getPublicKey(r,!0)}catch(e){throw new Yl(String(e))}}function jN(){return Fn.utils.randomSecretKey()}async function Qh(r,e){if(r==="Ed25519")return Fw();if(r==="secp256k1")return pb();if(r==="RSA")return Z4(YN(e));if(r==="ECDSA")return q9(XN(e));throw new Pn}function bt(r,e){let{Type:t,Data:n}=mo.decode(r),o=n??new Uint8Array;switch(t){case Qe.RSA:return Y4(o,e);case Qe.Ed25519:return I4(o);case Qe.secp256k1:return i6(o);case Qe.ECDSA:return Q3(o);default:throw new Pn}}function Zh(r){let{Type:e,Data:t}=mo.decode(r.digest),n=t??new Uint8Array;switch(e){case Qe.Ed25519:return I4(n);case Qe.secp256k1:return i6(n);case Qe.ECDSA:return Q3(n);default:throw new Pn}}function Nt(r){return mo.encode({Type:Qe[r.type],Data:r.raw})}function mb(r){let e=Pu.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Qe.RSA:return j4(t);case Qe.Ed25519:return _4(t);case Qe.secp256k1:return o6(t);case Qe.ECDSA:return F9(t);default:throw new Pn}}function gb(r){if(r.byteLength===Mr)return _4(r);if(r.byteLength===ab)return o6(r);let e=fn(r),t=e[2]?.[0];if(t===R9||t===P9||t===L9)return X3(e);if(e.length>8)return jh(e);throw new T("Could not extract private key from raw bytes")}function ia(r){return Pu.encode({Type:Qe[r.type],Data:r.raw})}function YN(r){return r==null?2048:parseInt(r,10)}function XN(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new T("Unsupported curve, should be P-256, P-384 or P-521")}var Bu=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ki=new Uint32Array(80),s6=class extends zs{A=Bu[0]|0;B=Bu[1]|0;C=Bu[2]|0;D=Bu[3]|0;E=Bu[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ki[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ki[c]=Ch(Ki[c-3]^Ki[c-8]^Ki[c-14]^Ki[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Lh(o,i,s),u=1518500249):c<40?(l=o^i^s,u=1859775393):c<60?(l=Nh(o,i,s),u=2400959708):(l=o^i^s,u=3395469782);let d=Ch(n,5)+l+a+u+Ki[c]|0;a=s,s=i,i=Ch(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){nr(Ki)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),nr(this.buffer)}},yb=hu(()=>new s6);function wb(r,e,t,n){zo(r);let o=j9({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(Ar(i,"c"),Ar(s,"dkLen"),Ar(a,"asyncTick"),i<1)throw new Error("iterations (c) must be >= 1");if(s<1)throw new Error('"dkLen" must be >= 1');if(s>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=J3(e,"password"),l=J3(t,"salt"),u=new Uint8Array(s),d=oa.create(r,c),f=d._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:u,PRF:d,PRFSalt:f}}function bb(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),nr(o),t}function xb(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=wb(r,e,t,n),l,u=new Uint8Array(4),d=qs(u),f=new Uint8Array(a.outputLen);for(let h=1,p=0;p<i;h++,p+=a.outputLen){let y=s.subarray(p,p+a.outputLen);d.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(f),y.set(f.subarray(0,y.length));for(let m=1;m<o;m++){a._cloneInto(l).update(f).digestInto(f);for(let g=0;g<y.length;g++)y[g]^=f[g]}}return bb(a,c,s,l,f)}async function Jh(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=wb(r,e,t,n),u,d=new Uint8Array(4),f=qs(d),h=new Uint8Array(c.outputLen);for(let p=1,y=0;y<i;p++,y+=c.outputLen){let m=a.subarray(y,y+c.outputLen);f.setInt32(0,p,!1),(u=l._cloneInto(u)).update(d).digestInto(h),m.set(h.subarray(0,m.length)),await G9(o-1,s,()=>{c._cloneInto(u).update(h).digestInto(h);for(let g=0;g<m.length;g++)m[g]^=h[g]})}return bb(c,l,a,u,h)}var Eb={sha1:yb,"sha2-256":hn,"sha2-512":po};function Mu(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(Eb).join(" / ");throw new T(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=Eb[o],s=xb(i,r,e,{c:t,dkLen:n});return xt.encode(s).substring(1)}var a6={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},vb={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Sb=new globalThis.TextEncoder;function QN(r,e){let t=a6[e],n=vb[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function ZN(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=a6[e],o=vb[e],i=r;for(;i.length>0;){let s=Sb.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function c6(r,{size:e=32,utf8Buffer:t}={}){if(!a6[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 ZN(r,e,t);r=Sb.encode(r)}return QN(r,e)}var Uu={hash:r=>Number(c6(r,{size:32})),hashV:(r,e)=>JN(Uu.hash(r,e))};function JN(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}var l6=64,$n=class{fp;h;seed;constructor(e,t,n,o=2){if(o>l6)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=be(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,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 sa(r,e){return Math.floor(Math.random()*(e-r))+r}var aa=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof $n))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof $n))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 $n))throw new TypeError("Invalid Fingerprint");let t=sa(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof $n))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var eD=500,Fu=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??Uu,this.seed=e.seed??sa(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new $n(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new aa(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new aa(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[sa(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new aa(this.bucketSize));for(let a=0;a<eD;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new aa(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new $n(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new $n(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},tD={1:.5,2:.84,4:.95,8:.98};function rD(r=.001){return r>.002?2:r>1e-5?4:8}function Ab(r,e=.001){let t=rD(e),n=tD[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),l6);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var e1=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??Uu,this.seed=e.seed??sa(0,Math.pow(2,10)),this.filterSeries=[new Fu({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(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 Fu({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=L(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=L(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 Wt(r,e=.001,t){return new e1({...Ab(r,e),...t??{}})}function he(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new T(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var t1=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(i*=e,i+=u,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Tb=45,nD=15,Tc=new t1;function r1(r){if(!(r.length>nD))return Tc.new(r).parseWith(()=>Tc.readIPv4Addr())}function n1(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Tb))return Tc.new(r).parseWith(()=>Tc.readIPv6Addr())}function _c(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Tb)return;let t=Tc.new(r).parseWith(()=>Tc.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 _b(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function Ib(r,e,t,n){let o=0;for(let i of r)if(!(o<t)){if(o>n)break;if(i!==e[o])return!1;o++}return!0}function u6(r){switch(r.length){case ca:return r.join(".");case la:{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 kb(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function Cb(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var ca=4,la=16,jX=parseInt("0xFFFF",16),oD=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function $u(r,e){e.length===la&&r.length===ca&&_b(e,0,11)&&(e=e.slice(12)),e.length===ca&&r.length===la&&Ib(r,oD,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function Rb(r,e){if(typeof e=="string"&&(e=_c(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 d6(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=ca,o=r1(e);if(o==null&&(n=la,o=n1(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=f6(i,8*n);return{network:$u(o,s),mask:s}}function f6(r,e){if(e!==8*ca&&e!==8*la)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var ua=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=d6(e));else{let n=_c(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let i=_c(t);if(i==null)throw new Error("Failed to parse mask");this.mask=i}else this.mask=f6(o,8*n.length);this.network=$u(n,this.mask)}}contains(e){return Rb({network:this.network,mask:this.mask},e)}toString(){let e=kb(this.mask),t=e!==-1?String(e):Cb(this.mask);return u6(this.network)+"/"+t}};function Pb(r,e){return new ua(r).contains(e)}function o1(r){try{let e=he(r);return e.type==="ip6"?Pb("2000::/3",e.host):!1}catch{return!1}}function Lb(r){try{let e=he(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Nb(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Vu(r){try{let e=he(r);switch(e.type){case"ip4":case"ip6":return Nb(e.host);default:return!1}}catch{return!1}}function Gt(r){try{return he(r),!0}catch{return!1}}function Vn(r){return!!r1(r)}function i1(r){return!!n1(r)}var Mb=Fo(Bb(),1),dD=["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"],fD=dD.map(r=>new Mb.Netmask(r));function b6(r){for(let e of fD)if(e.contains(r))return!0;return!1}function hD(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function pD(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return b6(o)}function mD(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function gD(r){let e=r.split(":"),t=e[e.length-1];return b6(t)}function yD(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 Rc(r){if(Vn(r))return b6(r);if(hD(r))return pD(r);if(mD(r))return gD(r);if(i1(r))return yD(r)}function gt(r){try{let e=he(r);switch(e.type){case"ip4":case"ip6":return Rc(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function Ie(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var a1=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}},Pc=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new a1(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 a1(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 x6=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function jt(r={}){return wD(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 wD(r,e){e=e??{};let t=e.onEnd,n=new Pc,o,i,s,a=Ie(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((m,g)=>{i=x=>{i=null,n.push(x);try{m(r(n))}catch(P){g(P)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ie()})}},l=m=>i!=null?i(m):(n.push(m),o),u=m=>(n=new Pc,i!=null?i({error:m}):(n.push({error:m}),o)),d=m=>{if(s)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:m})},f=m=>s?o:(s=!0,m!=null?u(m):l({done:!0})),h=()=>(n=new Pc,f(),{done:!0}),p=m=>(f(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,P;g!=null&&(x=new Promise((O,F)=>{P=()=>{F(new x6)},g.addEventListener("abort",P)}));try{await Promise.race([a.promise,x])}finally{P!=null&&g!=null&&g?.removeEventListener("abort",P)}}},t==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(m){return y.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(m){return y.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return y.readableLength},onEmpty:m=>y.onEmpty(m)},o}var bD=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function xD(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=bD(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=pr(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function pn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=xD(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function Qo(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var c1=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}},l1=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},fa=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},u1=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},d1=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function ED(r){return r.reason}async function Ze(r,e,t){if(e==null)return r;let n=t?.translateError??ED;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var f1=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Ie(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new fr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function vD(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var h1=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=vD(),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 fr),this.cleanup())}async join(e={}){let t=new f1(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 Ze(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 Yt=class extends we{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Qo(this.emitEmpty.bind(this),1),this.emitIdle=Qo(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new l1;let n=new h1(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new fr)}),this.clear()}async onEmpty(e){this.size!==0&&await pn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await pn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await pn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=jt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new fr("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var SD=Math.pow(2,20)*4,qi=class extends we{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??SD,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ie,this.writeBuffer=new ie,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new d1)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Ze(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=jt(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let n=i=>{e.end(i.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new lo(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new fh(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new lo("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new lo("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new lo(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new lo(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Ja;this.dispatchEvent(new hh(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new ki))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let i=this.writeBuffer.sublist(0,o),s=new ie(i);this.writeBuffer.consume(i.byteLength);let a=this.sendData(i);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==s.byteLength&&(s.consume(a.sentBytes),this.writeBuffer.prepend(s)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new dh(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Ql(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Ql(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var zi=class extends qi{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await pn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await pn(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function p1(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Wi=class extends we{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=s=>{try{this.onData(s.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Ze(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Cn;let t=this.onCreateStream({...this.streamOptions,...e});return p1(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new u1(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let o=this.streams.findIndex(i=>i===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var Gi=class extends qi{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await pn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await pn(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};function Ee(r){let e=new globalThis.AbortController;function t(){let i=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Lc=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,i=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var AD=1.2,TD=2,_D=5e3,ID=6e4,kD=5e3,Kn=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??kD;this.success=new Lc(t),this.failure=new Lc(t),this.next=new Lc(t),this.failureMultiplier=e.failureMultiplier??TD,this.timeoutMultiplier=e.timeoutMultiplier??AD,this.minTimeout=e.minTimeout??_D,this.maxTimeout=e.maxTimeout??ID,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=Ee([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Xt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Zo=class extends Error{static name="ValidationError";name="ValidationError"},m1=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},g1=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function v6(r){return e=>D(e,r)}function S6(r){return e=>L(e,r)}function Nc(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function ha(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ub(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=L(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ha(n);return Je([t,o],t.length+o.length)}function Fb(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=Lt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=ha(n);return Je([t,o],t.length+o.length)}function A6(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=D(e,"base32"),o=Nc(t);return`${n}:${o}`}var T6=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Xt("Invalid byte value in IP address");e[n]=o}),e},$b=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=Vn(t[n]),s;i&&(s=T6(t[n]),t[n]=D(s.subarray(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,D(s.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let i=parseInt(t[n],16);if(isNaN(i)||i<0||i>65535)throw new Xt("Invalid byte value in IP address");o[e++]=i>>8&255,o[e++]=i&255}return o},Vb=function(r){if(r.byteLength!==4)throw new Xt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Kb=function(r){if(r.byteLength!==16)throw new Xt("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],i=r[n+1],s=`${o.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;e.push(s)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Xt(`Invalid IPv6 address "${t}"`)}};function Hb(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Xt(`Invalid IPv6 address "${r}"`)}}var E6=Object.values(Vs).map(r=>r.decoder),CD=(function(){let r=E6[0].or(E6[1]);return E6.slice(2).forEach(e=>r=r.or(e)),r})();function qb(r){return CD.decode(r)}function zb(r){return e=>r.encoder.encode(e)}function RD(r){if(parseInt(r).toString()!==r)throw new Zo("Value must be an integer")}function PD(r){if(r<0)throw new Zo("Value must be a positive integer, or zero")}function LD(r){return e=>{if(e>r)throw new Zo(`Value must be smaller than or equal to ${r}`)}}function ND(...r){return e=>{for(let t of r)t(e)}}var Ku=ND(RD,PD,LD(65535));var Ot=-1,_6=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new g1(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},ei=new _6,GD=[{code:4,name:"ip4",size:32,valueToBytes:T6,bytesToValue:Vb,validate:r=>{if(!Vn(r))throw new Zo(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ha,bytesToValue:Nc,validate:Ku},{code:273,name:"udp",size:16,valueToBytes:ha,bytesToValue:Nc,validate:Ku},{code:33,name:"dccp",size:16,valueToBytes:ha,bytesToValue:Nc,validate:Ku},{code:41,name:"ip6",size:128,valueToBytes:$b,bytesToValue:Kb,stringToValue:Hb,validate:r=>{if(!i1(r))throw new Zo(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Ot},{code:43,name:"ipcidr",size:8,bytesToValue:v6("base10"),valueToBytes:S6("base10")},{code:53,name:"dns",size:Ot},{code:54,name:"dns4",size:Ot},{code:55,name:"dns6",size:Ot},{code:56,name:"dnsaddr",size:Ot},{code:132,name:"sctp",size:16,valueToBytes:ha,bytesToValue:Nc,validate:Ku},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ot,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Ot,bytesToValue:v6("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?S6("base58btc")(r):J.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:A6,valueToBytes:Ub},{code:445,name:"onion3",size:296,bytesToValue:A6,valueToBytes:Fb},{code:446,name:"garlic64",size:Ot},{code:447,name:"garlic32",size:Ot},{code:448,name:"tls"},{code:449,name:"sni",size:Ot},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ot,bytesToValue:zb(ru),valueToBytes:qb},{code:480,name:"http"},{code:481,name:"http-path",size:Ot,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Ot}];GD.forEach(r=>{ei.addProtocol(r)});function Wb(r){let e=[],t=0;for(;t<r.length;){let n=Ur(r,t),o=ei.getProtocol(n),i=Ae(n),s=jD(o,r,t+i),a=0;s>0&&o.size===Ot&&(a=Ae(s));let c=i+a+s,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(s>0){let u=t+i+a,d=r.subarray(u,u+s);l.value=o.bytesToValue?.(d)??D(d)}e.push(l),t+=c}return e}function Gb(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=ei.getProtocol(n.code),i=Ae(n.code),s,a=0,c=0;n.value!=null&&(s=o.valueToBytes?.(n.value)??L(n.value),a=s.byteLength,o.size===Ot&&(c=Ae(a)));let l=new Uint8Array(i+c+a),u=0;Fi(n.code,l,u),u+=i,s!=null&&(o.size===Ot&&(Fi(a,l,u),u+=c),l.set(s,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Je(t,e)}function jb(r){if(r.charAt(0)!=="/")throw new Xt('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let i=1;i<r.length;i++){let s=r.charAt(i);s!=="/"&&(t==="protocol"?o+=r.charAt(i):n+=r.charAt(i));let a=i===r.length-1;if(s==="/"||a){let c=ei.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Xt(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Xt(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Xt("Incomplete multiaddr");return e}function Yb(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ei.getProtocol(e.code);if(t==null)throw new Xt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function jD(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Ur(e,t)}var YD=Symbol.for("nodejs.util.inspect.custom"),O6=Symbol.for("@multiformats/multiaddr");function XD(r){if(r==null&&(r="/"),bo(r))return r.getComponents();if(r instanceof Uint8Array)return Wb(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),jb(r);if(Array.isArray(r))return r;throw new Xt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var E1=class r{[O6]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=XD(e),t.validate!==!1&&QD(this)}get bytes(){return this.#r==null&&(this.#r=Gb(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Yb(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new m1(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return ce(this.bytes,e.bytes)}[YD](){return`Multiaddr(${this.toString()})`}};function QD(r){r.getComponents().forEach(e=>{let t=ei.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function bo(r){return!!r?.[O6]}function Z(r){return new E1(r)}var B6=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ie(),this.haveNext=Ie()}[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=Ie(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ie(),await Ze(this.readNext.promise,t?.signal,t)}};function Xb(){return new B6}function ZD(r){return r[Symbol.asyncIterator]!=null}async function JD(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*eO(r){let e=new AbortController,t=Xb();JD(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*tO(r){for(let e of r)yield*e}function rO(...r){let e=[];for(let t of r)ZD(t)||e.push(t);return e.length===r.length?tO(e):eO(r)}var wr=rO;function Mc(r,...e){if(r==null)throw new Error("Empty pipeline");if(M6(r)){let n=r;r=()=>n.source}else if(Zb(r)||Qb(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&M6(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)M6(t[n])&&(t[n]=oO(t[n]));return nO(...t)}var nO=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Qb=r=>r?.[Symbol.asyncIterator]!=null,Zb=r=>r?.[Symbol.iterator]!=null,M6=r=>r==null?!1:r.sink!=null&&r.source!=null,oO=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=jt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Qb(i))o=async function*(){yield*i,n.end()};else if(Zb(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return wr(n,o())}return r.source};var iO=4194304,v1=class extends Error{static name="UnwrappedError";name="UnwrappedError"},ju=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},F6=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},$6=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function sO(r){return typeof r?.closeRead=="function"}function aO(r){return typeof r?.close=="function"}function U6(r){return sO(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:aO(r)?r.status!=="open":!1}function cO(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function S1(r,e){let t=e?.maxBufferSize??iO,n=new ie,o,i=!1;if(!cO(r))throw new T("Argument should be a Stream or a Multiaddr");let s=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",s);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(i===!0)throw new v1("Stream was unwrapped");if(U6(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new fa(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Ze(o.promise,u?.signal),U6(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let f=u?.bytes??n.byteLength;if(n.byteLength<f){if(U6(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,f),new fa(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(u)}let h=n.sublist(0,f);return n.consume(f),h},async write(u,d){if(i===!0)throw new v1("Stream was unwrapped");r.send(u)||await pn(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return i||(i=!0,r.removeEventListener("message",s),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function Yi(r,e={}){let t=S1(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ae(e.maxDataLength));let n=e?.lengthDecoder??Ur,o=e?.lengthEncoder??ir;return{async read(s){let a=-1,c=new ie;for(;;){let u=await t.read({...s,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new ju("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new $6(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new F6(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...s,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new fa(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new fa(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(s,a){await t.write(new ie(o(s.byteLength),s),a)},async writeV(s,a){let c=new ie(...s.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function tt(r,e){let t=Yi(r,e),n={read:async(o,i)=>{let s=await t.read(i);return o.decode(s)},write:async(o,i,s)=>{await t.write(i.encode(o),s)},writeV:async(o,i,s)=>{await t.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var lO=1024*1024*4,uO=1024*1024*4,A1=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new ie,this.maxBufferSize=e.maxBufferSize??lO,this.maxDataLength=e.maxDataLength??uO,this.lengthDecoder=e.lengthDecoder??Ur,this.encodingLength=e.encodingLength??Ae}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new T(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(i){if(i instanceof RangeError)break;throw i}if(t<0||t>this.maxDataLength)throw new ju("Invalid message length");let n=this.encodingLength(t),o=n+t;if(this.buffer.byteLength>=o){let i=this.buffer.sublist(n,o);this.buffer.consume(o),i.byteLength>0&&(yield i)}else break}}};var T1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Uc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},_1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Yu=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function I1(r){return r[Symbol.asyncIterator]!=null}function Jb(r,e){if(r.byteLength>e)throw new Uc("Message length too long")}var C1=r=>{let e=Ae(r),t=Xe(e);return ir(r,t),C1.bytes=e,t};C1.bytes=0;function ti(r,e){e=e??{};let t=e.lengthEncoder??C1,n=e?.maxDataLength??4194304;function*o(i){Jb(i,n);let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return I1(r)?(async function*(){for await(let i of r)yield*o(i)})():(function*(){for(let i of r)yield*o(i)})()}ti.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??C1,n=e?.maxDataLength??4194304;return Jb(r,n),new ie(t(r.byteLength),r)};var ma;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ma||(ma={}));var V6=r=>{let e=Ur(r);return V6.bytes=Ae(e),e};V6.bytes=0;function ga(r,e){let t=new ie,n=ma.LENGTH,o=-1,i=e?.lengthDecoder??V6,s=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===ma.LENGTH)try{if(o=i(t),o<0)throw new T1("Invalid message length");if(o>a)throw new Uc("Message length too long");let l=i.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=ma.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>s)throw new _1("Message length length too long");break}throw l}if(n===ma.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=ma.LENGTH}}}return I1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Yu("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Yu("Unexpected end of input")})()}ga.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:i,value:s}=await r.next(t);if(i===!0)return;s!=null&&(yield s)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}})();return ga(n,{...e??{},onLength:i=>{t=i}})};function fO(r,e){if(typeof r=="string")return hO(r);if(typeof r=="number")return gO(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var R1=fO;function hO(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),i=n.toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function pO(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function mO(r){let e=Math.abs(r);return e>=315576e5?ya(r,e,315576e5,"year"):e>=26298e5?ya(r,e,26298e5,"month"):e>=6048e5?ya(r,e,6048e5,"week"):e>=864e5?ya(r,e,864e5,"day"):e>=36e5?ya(r,e,36e5,"hour"):e>=6e4?ya(r,e,6e4,"minute"):e>=1e3?ya(r,e,1e3,"second"):`${r} ms`}function gO(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?mO(r):pO(r)}function ya(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function K6(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=R1,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let f,h=null,p,y;function m(...g){if(!m.enabled)return;let x=m,P=Number(new Date),O=P-(f||P);x.diff=O,x.prev=f,x.curr=P,f=P,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let F=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(H,C)=>{if(H==="%%")return"%";F++;let B=t.formatters[C];if(typeof B=="function"){let q=g[F];H=B.call(x,q),g.splice(F,1),F--}return H}),t.formatArgs.call(x,g),d?.onLog!=null&&d.onLog(...g),(x.log||t.log).apply(x,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,y=t.enabled(u)),y),set:g=>{h=g}}),typeof t.init=="function"&&t.init(m),m}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,f=(typeof u=="string"?u:"").split(/[\s,]+/),h=f.length;for(d=0;d<h;d++)f[d]&&(u=f[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let d,f;for(d=0,f=t.skips.length;d<f;d++)if(t.skips[d].test(u))return!1;for(d=0,f=t.names.length;d<f;d++)if(t.names[d].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 P1=SO(),yO=["#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 wO(){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 bO(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+R1(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var xO=console.debug??console.log??(()=>{});function EO(r){try{r?P1?.setItem("debug",r):P1?.removeItem("debug")}catch{}}function vO(){let r;try{r=P1?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function SO(){try{return localStorage}catch{}}function AO(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var tx=K6({formatArgs:bO,save:EO,load:vO,useColors:wO,setupFormatters:AO,colors:yO,storage:P1,log:xO});var Tr=tx;Tr.formatters.b=r=>r==null?"undefined":Ye.baseEncode(r);Tr.formatters.t=r=>r==null?"undefined":Lt.baseEncode(r);Tr.formatters.m=r=>r==null?"undefined":xt.baseEncode(r);Tr.formatters.p=r=>r==null?"undefined":r.toString();Tr.formatters.c=r=>r==null?"undefined":r.toString();Tr.formatters.k=r=>r==null?"undefined":r.toString();Tr.formatters.a=r=>r==null?"undefined":r.toString();function rx(r,e=""){let t=nx(r.message),n=nx(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
4
4
  `).join(`
5
5
  ${e}`)}`:`${t}
6
6
  ${e}${n.split(`
@@ -29,7 +29,7 @@ ${e}[Error list was empty]`,t.trim()}return rx(r,e)}Tr.formatters.e=r=>r==null?"
29
29
  HTTP/1.1 %d %s
30
30
  %s
31
31
  `,f.status,f.statusText,[...f.headers.entries()].map(([p,y])=>`${p}: ${y}`).join(`
32
- `)),!f.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, received ${f.status} ${f.statusText}`);t.onProgress?.(new U("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:dl(n.toString()),cid:e})),t.onProgress?.(new U("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:e}));let h=await OA(f,o,{signal:s.signal,log:this.log});return t.onProgress?.(new U("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:e})),this.#a++,h}),this.#c.set(i,c)}return await c}catch(c){throw signal?.aborted===!0?new Error(`Fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`Unable to fetch raw block for CID ${e} - ${c.message}`))}finally{t.signal?.removeEventListener("abort",a),this.#c.delete(i)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#a/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#a,pendingResponses:this.#c.size}}toString(){return`TrustlessGateway(${this.url})`}};var I8=class extends _a{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??w0,this.allowLocal=t.allowLocal??b0,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url),n?.onProgress?.(new U("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}));let o;try{o=await t.getRawBlock(e,n),this.log.trace("got block for %c from %s",e,t.url)}finally{n?.onProgress?.(new U("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}))}return await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*y0(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toFilterKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t,n){if(Rt(e))return;let o=_8(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(o.length===0)return;let i=cs(o[0]);return new pl(i,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:t})}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new U("trustless-gateway:found-provider",{type:"trustless-gateway",cid:e,url:t.url.toJSON(),routing:t.routing}))}};function MA(r,e){return new I8(r,e)}var x0=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??w0,this.allowLocal=t.allowLocal??b0,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of y0(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let i=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s - %e",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return MA({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var w0=!1,b0=!1,BA=2097152;function k8(r={}){return e=>new x0(e,r)}async function*$d(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var n$=Fo(E0(),1);var to=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},v0=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},ml=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},S0=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},A0=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},T0=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Vd=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var Ir;(function(r){let e;(function(a){a.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(a){a[a.EOL=0]="EOL"})(t||(t={})),(function(a){a.codec=()=>ut(t)})(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=ye((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.value!=null&&(c.uint32(10),c.bytes(a.value)),a.signatureV1!=null&&(c.uint32(18),c.bytes(a.signatureV1)),a.validityType!=null&&(c.uint32(24),r.ValidityType.codec().encode(a.validityType,c)),a.validity!=null&&(c.uint32(34),c.bytes(a.validity)),a.sequence!=null&&(c.uint32(40),c.uint64(a.sequence)),a.ttl!=null&&(c.uint32(48),c.uint64(a.ttl)),a.pubKey!=null&&(c.uint32(58),c.bytes(a.pubKey)),a.signatureV2!=null&&(c.uint32(66),c.bytes(a.signatureV2)),a.data!=null&&(c.uint32(74),c.bytes(a.data)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.value=a.bytes();break}case 2:{u.signatureV1=a.bytes();break}case 3:{u.validityType=r.ValidityType.codec().decode(a);break}case 4:{u.validity=a.bytes();break}case 5:{u.sequence=a.uint64();break}case 6:{u.ttl=a.uint64();break}case 7:{u.pubKey=a.bytes();break}case 8:{u.signatureV2=a.bytes();break}case 9:{u.data=a.bytes();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.value`,value:a.bytes()};break}case 2:{yield{field:`${l}.signatureV1`,value:a.bytes()};break}case 3:{yield{field:`${l}.validityType`,value:r.ValidityType.codec().decode(a)};break}case 4:{yield{field:`${l}.validity`,value:a.bytes()};break}case 5:{yield{field:`${l}.sequence`,value:a.uint64()};break}case 6:{yield{field:`${l}.ttl`,value:a.uint64()};break}case 7:{yield{field:`${l}.pubKey`,value:a.bytes()};break}case 8:{yield{field:`${l}.signatureV2`,value:a.bytes()};break}case 9:{yield{field:`${l}.data`,value:a.bytes()};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return me(a,r.codec())}r.encode=o;function i(a,c){return pe(a,r.codec(),c)}r.decode=i;function s(a,c){return ge(a,r.codec(),c)}r.stream=s})(Ir||(Ir={}));var vF=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function UA(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=SF(r);return t||"Object"}function SF(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(vF.includes(e))return e}var k=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};k.uint=new k(0,"uint",!0);k.negint=new k(1,"negint",!0);k.bytes=new k(2,"bytes",!0);k.string=new k(3,"string",!0);k.array=new k(4,"array",!1);k.map=new k(5,"map",!1);k.tag=new k(6,"tag",!1);k.float=new k(7,"float",!0);k.false=new k(7,"false",!0);k.true=new k(7,"true",!0);k.null=new k(7,"null",!0);k.undefined=new k(7,"undefined",!0);k.break=new k(7,"break",!0);var re=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Kd=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",AF=new TextEncoder;function _0(r){return Kd&&globalThis.Buffer.isBuffer(r)}function Hd(r){return r instanceof Uint8Array?_0(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var TF=24,_F=200,R8=Kd?r=>r.length>=TF?globalThis.Buffer.from(r):FA(r):r=>r.length>=_F?AF.encode(r):FA(r),_o=r=>Uint8Array.from(r),$A=Kd?(r,e,t)=>_0(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),VA=Kd?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Hd(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},KA=Kd?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function I0(r,e){if(_0(r)&&_0(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function FA(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}var IF=256,qd=class{constructor(e=IF){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=KA(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=$A(n,0,this.cursor)}else t=VA(this.chunks,this.cursor);return e&&this.reset(),t}},k0=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var de="CBOR decode error:",P8="CBOR encode error:",zd=[];zd[23]=1;zd[24]=2;zd[25]=3;zd[26]=5;zd[27]=9;function di(r,e,t){if(r.length-e<t)throw new Error(`${de} not enough data for type`)}var Vt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function rn(r,e,t){di(r,e,1);let n=r[e];if(t.strict===!0&&n<Vt[0])throw new Error(`${de} integer encoded in more bytes than necessary (strict decode)`);return n}function nn(r,e,t){di(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Vt[1])throw new Error(`${de} integer encoded in more bytes than necessary (strict decode)`);return n}function on(r,e,t){di(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Vt[2])throw new Error(`${de} integer encoded in more bytes than necessary (strict decode)`);return n}function sn(r,e,t){di(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<Vt[3])throw new Error(`${de} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${de} integers outside of the safe integer range are not supported`)}function HA(r,e,t,n){return new re(k.uint,rn(r,e+1,n),2)}function qA(r,e,t,n){return new re(k.uint,nn(r,e+1,n),3)}function zA(r,e,t,n){return new re(k.uint,on(r,e+1,n),5)}function WA(r,e,t,n){return new re(k.uint,sn(r,e+1,n),9)}function An(r,e){return Kt(r,0,e.value)}function Kt(r,e,t){if(t<Vt[0]){let n=Number(t);r.push([e|n])}else if(t<Vt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Vt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Vt[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<Vt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${de} encountered BigInt larger than allowable range`)}}An.encodedSize=function(e){return Kt.encodedSize(e.value)};Kt.encodedSize=function(e){return e<Vt[0]?1:e<Vt[1]?2:e<Vt[2]?3:e<Vt[3]?5:9};An.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function GA(r,e,t,n){return new re(k.negint,-1-rn(r,e+1,n),2)}function jA(r,e,t,n){return new re(k.negint,-1-nn(r,e+1,n),3)}function YA(r,e,t,n){return new re(k.negint,-1-on(r,e+1,n),5)}var L8=BigInt(-1),XA=BigInt(1);function QA(r,e,t,n){let o=sn(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new re(k.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${de} integers outside of the safe integer range are not supported`);return new re(k.negint,L8-BigInt(o),9)}function C0(r,e){let t=e.value,n=typeof t=="bigint"?t*L8-XA:t*-1-1;Kt(r,e.type.majorEncoded,n)}C0.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*L8-XA:t*-1-1;return n<Vt[0]?1:n<Vt[1]?2:n<Vt[2]?3:n<Vt[3]?5:9};C0.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Wd(r,e,t,n){di(r,e,t+n);let o=r.slice(e+t,e+t+n);return new re(k.bytes,o,t+n)}function ZA(r,e,t,n){return Wd(r,e,1,t)}function JA(r,e,t,n){return Wd(r,e,2,rn(r,e+1,n))}function eT(r,e,t,n){return Wd(r,e,3,nn(r,e+1,n))}function tT(r,e,t,n){return Wd(r,e,5,on(r,e+1,n))}function rT(r,e,t,n){let o=sn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${de} 64-bit integer bytes lengths not supported`);return Wd(r,e,9,o)}function R0(r){return r.encodedBytes===void 0&&(r.encodedBytes=k.equals(r.type,k.string)?R8(r.value):r.value),r.encodedBytes}function gl(r,e){let t=R0(e);Kt(r,e.type.majorEncoded,t.length),r.push(t)}gl.encodedSize=function(e){let t=R0(e);return Kt.encodedSize(t.length)+t.length};gl.compareTokens=function(e,t){return CF(R0(e),R0(t))};function CF(r,e){return r.length<e.length?-1:r.length>e.length?1:I0(r,e)}var nT=new TextDecoder,PF=32;function LF(r,e,t){if(t-e<PF){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return nT.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return nT.decode(r.subarray(e,t))}function Gd(r,e,t,n,o){let i=t+n;di(r,e,i);let s=new re(k.string,LF(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function oT(r,e,t,n){return Gd(r,e,1,t,n)}function iT(r,e,t,n){return Gd(r,e,2,rn(r,e+1,n),n)}function sT(r,e,t,n){return Gd(r,e,3,nn(r,e+1,n),n)}function aT(r,e,t,n){return Gd(r,e,5,on(r,e+1,n),n)}function cT(r,e,t,n){let o=sn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${de} 64-bit integer string lengths not supported`);return Gd(r,e,9,o,n)}var lT=gl;function yl(r,e,t,n){return new re(k.array,n,t)}function uT(r,e,t,n){return yl(r,e,1,t)}function dT(r,e,t,n){return yl(r,e,2,rn(r,e+1,n))}function fT(r,e,t,n){return yl(r,e,3,nn(r,e+1,n))}function hT(r,e,t,n){return yl(r,e,5,on(r,e+1,n))}function pT(r,e,t,n){let o=sn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${de} 64-bit integer array lengths not supported`);return yl(r,e,9,o)}function mT(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${de} indefinite length items not allowed`);return yl(r,e,1,1/0)}function P0(r,e){Kt(r,k.array.majorEncoded,e.value)}P0.compareTokens=An.compareTokens;P0.encodedSize=function(e){return Kt.encodedSize(e.value)};function wl(r,e,t,n){return new re(k.map,n,t)}function gT(r,e,t,n){return wl(r,e,1,t)}function yT(r,e,t,n){return wl(r,e,2,rn(r,e+1,n))}function wT(r,e,t,n){return wl(r,e,3,nn(r,e+1,n))}function bT(r,e,t,n){return wl(r,e,5,on(r,e+1,n))}function xT(r,e,t,n){let o=sn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${de} 64-bit integer map lengths not supported`);return wl(r,e,9,o)}function ET(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${de} indefinite length items not allowed`);return wl(r,e,1,1/0)}function L0(r,e){Kt(r,k.map.majorEncoded,e.value)}L0.compareTokens=An.compareTokens;L0.encodedSize=function(e){return Kt.encodedSize(e.value)};function vT(r,e,t,n){return new re(k.tag,t,1)}function ST(r,e,t,n){return new re(k.tag,rn(r,e+1,n),2)}function AT(r,e,t,n){return new re(k.tag,nn(r,e+1,n),3)}function TT(r,e,t,n){return new re(k.tag,on(r,e+1,n),5)}function _T(r,e,t,n){return new re(k.tag,sn(r,e+1,n),9)}function N0(r,e){Kt(r,k.tag.majorEncoded,e.value)}N0.compareTokens=An.compareTokens;N0.encodedSize=function(e){return Kt.encodedSize(e.value)};var N8=20,D8=21,O8=22,B8=23;function IT(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${de} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new re(k.null,null,1):new re(k.undefined,void 0,1)}function kT(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${de} indefinite length items not allowed`);return new re(k.break,void 0,1)}function M8(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${de} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${de} Infinity values are not supported`)}return new re(k.float,r,e)}function CT(r,e,t,n){return M8(U8(r,e+1),3,n)}function RT(r,e,t,n){return M8(F8(r,e+1),5,n)}function PT(r,e,t,n){return M8(OT(r,e+1),9,n)}function D0(r,e,t){let n=e.value;if(n===!1)r.push([k.float.majorEncoded|N8]);else if(n===!0)r.push([k.float.majorEncoded|D8]);else if(n===null)r.push([k.float.majorEncoded|O8]);else if(n===void 0)r.push([k.float.majorEncoded|B8]);else{let o,i=!1;(!t||t.float64!==!0)&&(NT(n),o=U8(ro,1),n===o||Number.isNaN(n)?(ro[0]=249,r.push(ro.slice(0,3)),i=!0):(DT(n),o=F8(ro,1),n===o&&(ro[0]=250,r.push(ro.slice(0,5)),i=!0))),i||(MF(n),o=OT(ro,1),ro[0]=251,r.push(ro.slice(0,9)))}}D0.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){NT(n);let o=U8(ro,1);if(n===o||Number.isNaN(n))return 3;if(DT(n),o=F8(ro,1),n===o)return 5}return 9};var LT=new ArrayBuffer(9),Tn=new DataView(LT,1),ro=new Uint8Array(LT,0);function NT(r){if(r===1/0)Tn.setUint16(0,31744,!1);else if(r===-1/0)Tn.setUint16(0,64512,!1);else if(Number.isNaN(r))Tn.setUint16(0,32256,!1);else{Tn.setFloat32(0,r);let e=Tn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Tn.setUint16(0,31744,!1);else if(t===0)Tn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Tn.setUint16(0,0):o<-14?Tn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Tn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function U8(r,e){if(r.length-e<2)throw new Error(`${de} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function DT(r){Tn.setFloat32(0,r,!1)}function F8(r,e){if(r.length-e<4)throw new Error(`${de} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function MF(r){Tn.setFloat64(0,r,!1)}function OT(r,e){if(r.length-e<8)throw new Error(`${de} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}D0.compareTokens=An.compareTokens;function Me(r,e,t){throw new Error(`${de} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function O0(r){return()=>{throw new Error(`${de} ${r}`)}}var X=[];for(let r=0;r<=23;r++)X[r]=Me;X[24]=HA;X[25]=qA;X[26]=zA;X[27]=WA;X[28]=Me;X[29]=Me;X[30]=Me;X[31]=Me;for(let r=32;r<=55;r++)X[r]=Me;X[56]=GA;X[57]=jA;X[58]=YA;X[59]=QA;X[60]=Me;X[61]=Me;X[62]=Me;X[63]=Me;for(let r=64;r<=87;r++)X[r]=ZA;X[88]=JA;X[89]=eT;X[90]=tT;X[91]=rT;X[92]=Me;X[93]=Me;X[94]=Me;X[95]=O0("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)X[r]=oT;X[120]=iT;X[121]=sT;X[122]=aT;X[123]=cT;X[124]=Me;X[125]=Me;X[126]=Me;X[127]=O0("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)X[r]=uT;X[152]=dT;X[153]=fT;X[154]=hT;X[155]=pT;X[156]=Me;X[157]=Me;X[158]=Me;X[159]=mT;for(let r=160;r<=183;r++)X[r]=gT;X[184]=yT;X[185]=wT;X[186]=bT;X[187]=xT;X[188]=Me;X[189]=Me;X[190]=Me;X[191]=ET;for(let r=192;r<=215;r++)X[r]=vT;X[216]=ST;X[217]=AT;X[218]=TT;X[219]=_T;X[220]=Me;X[221]=Me;X[222]=Me;X[223]=Me;for(let r=224;r<=243;r++)X[r]=O0("simple values are not supported");X[244]=Me;X[245]=Me;X[246]=Me;X[247]=IT;X[248]=O0("simple values are not supported");X[249]=CT;X[250]=RT;X[251]=PT;X[252]=Me;X[253]=Me;X[254]=Me;X[255]=kT;var no=[];for(let r=0;r<24;r++)no[r]=new re(k.uint,r,1);for(let r=-1;r>=-24;r--)no[31-r]=new re(k.negint,r,1);no[64]=new re(k.bytes,new Uint8Array(0),1);no[96]=new re(k.string,"",1);no[128]=new re(k.array,0,1);no[160]=new re(k.map,0,1);no[244]=new re(k.false,!1,1);no[245]=new re(k.true,!0,1);no[246]=new re(k.null,null,1);function BT(r){switch(r.type){case k.false:return _o([244]);case k.true:return _o([245]);case k.null:return _o([246]);case k.bytes:return r.value.length?void 0:_o([64]);case k.string:return r.value===""?_o([96]):void 0;case k.array:return r.value===0?_o([128]):void 0;case k.map:return r.value===0?_o([160]):void 0;case k.uint:return r.value<24?_o([Number(r.value)]):void 0;case k.negint:if(r.value>=-24)return _o([31-Number(r.value)])}}var UT=Object.freeze({float64:!0,mapSorter:HF,quickEncodeToken:BT});function FF(){let r=[];return r[k.uint.major]=An,r[k.negint.major]=C0,r[k.bytes.major]=gl,r[k.string.major]=lT,r[k.array.major]=P0,r[k.map.major]=L0,r[k.tag.major]=N0,r[k.float.major]=D0,r}var $F=FF(),VF=new qd,B0=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${P8} object contains circular references`);return new r(t,e)}},us={null:new re(k.null,null),undefined:new re(k.undefined,void 0),true:new re(k.true,!0),false:new re(k.false,!1),emptyArray:new re(k.array,0),emptyMap:new re(k.map,0)},ds={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new re(k.float,r):r>=0?new re(k.uint,r):new re(k.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new re(k.uint,r):new re(k.negint,r)},Uint8Array(r,e,t,n){return new re(k.bytes,r)},string(r,e,t,n){return new re(k.string,r)},boolean(r,e,t,n){return r?us.true:us.false},null(r,e,t,n){return us.null},undefined(r,e,t,n){return us.undefined},ArrayBuffer(r,e,t,n){return new re(k.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new re(k.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[us.emptyArray,new re(k.break)]:us.emptyArray;n=B0.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=bl(s,t,n);return t.addBreakTokens?[new re(k.array,r.length),o,new re(k.break)]:[new re(k.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length,a;if(s){a=new Array(s),n=B0.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[bl(u,t,n),bl(d,t,n)])}l<s&&(a.length=l)}return a?.length?(KF(a,t),t.addBreakTokens?[new re(k.map,a.length),a,new re(k.break)]:[new re(k.map,a.length),a]):t.addBreakTokens===!0?[us.emptyMap,new re(k.break)]:us.emptyMap},Tagged(r,e,t,n){return[new re(k.tag,r.tag),bl(r.value,t,n)]}};ds.Map=ds.Object;ds.Buffer=ds.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ds[`${r}Array`]=ds.DataView;function bl(r,e={},t){let n=UA(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||ds[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=ds[n];if(!i)throw new Error(`${P8} unsupported type: ${n}`);return i(r,n,e,t)}function KF(r,e){e.mapSorter&&r.sort(e.mapSorter)}function HF(r,e){if(r[0]instanceof re&&e[0]instanceof re){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=MT(t.value)),n._keyBytes||(n._keyBytes=MT(n.value)),I0(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function MT(r){return qF(r,$F,UT)}function FT(r,e,t,n){if(Array.isArray(e))for(let o of e)FT(r,o,t,n);else t[e.type.major](r,e,n)}var Wue=k.uint.majorEncoded,Gue=k.negint.majorEncoded,jue=k.bytes.majorEncoded,Yue=k.string.majorEncoded,Xue=k.array.majorEncoded,Que=k.float.majorEncoded|N8,Zue=k.float.majorEncoded|D8,Jue=k.float.majorEncoded|O8,ede=k.float.majorEncoded|B8,tde=BigInt(-1),rde=BigInt(1);function qF(r,e,t,n){let o=n instanceof Uint8Array,i=o?new k0(n):VF,s=bl(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new qd(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Hd(i.chunks[0])}}return i.reset(),FT(i,s,e,t),i.toBytes(!0)}var zF={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},M0=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=no[e];if(t===void 0){let n=X[e];if(!n)throw new Error(`${de} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},fs=Symbol.for("DONE"),xl=Symbol.for("BREAK");function WF(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=hs(e,t);if(i===xl){if(r.value===1/0)break;throw new Error(`${de} got unexpected break to lengthed array`)}if(i===fs)throw new Error(`${de} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function GF(r,e,t){let n=t.useMaps===!0,o=t.rejectDuplicateMapKeys===!0,i=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=hs(e,t);if(c===xl){if(r.value===1/0)break;throw new Error(`${de} got unexpected break to lengthed map`)}if(c===fs)throw new Error(`${de} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${de} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${de} found repeat map key "${c}"`);let l=hs(e,t);if(l===fs)throw new Error(`${de} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*jF(r,e,t){for(let n=0;n<r.value;n++){let o=hs(e,t);if(o===xl){if(r.value===1/0)break;throw new Error(`${de} got unexpected break to lengthed map`)}if(o===fs)throw new Error(`${de} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=hs(e,t);if(i===fs)throw new Error(`${de} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function YF(r,e){let t=!1,n=function(){if(t)throw new Error(`${de} tag decode() may only be called once`);t=!0;let o=hs(r,e);if(o===fs)throw new Error(`${de} tag content missing`);if(o===xl)throw new Error(`${de} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${de} tag decode() may only be called once`);t=!0;let o=r.next();if(!k.equals(o.type,k.map))throw new Error(`${de} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of jF(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function hs(r,e){if(r.done())return fs;let t=r.next();if(k.equals(t.type,k.break))return xl;if(t.type.terminal)return t.value;if(k.equals(t.type,k.array))return WF(t,r,e);if(k.equals(t.type,k.map))return GF(t,r,e);if(k.equals(t.type,k.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=YF(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${de} tag decoder must call decode() or entries()`);return o}throw new Error(`${de} tag not supported (${t.value})`)}throw new Error("unsupported")}function $T(r,e){if(!(r instanceof Uint8Array))throw new Error(`${de} data to decode must be a Uint8Array`);e=Object.assign({},zF,e);let t=Hd(r),n=e.tokenizer||new M0(t,e),o=hs(n,e);if(o===fs)throw new Error(`${de} did not find any content to decode`);if(o===xl)throw new Error(`${de} got unexpected break`);return[o,r.subarray(n.pos())]}function $8(r,e){let[t,n]=$T(r,e);if(n.length>0)throw new Error(`${de} too many terminals, data makes no sense`);return t}var U0=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(U0.prototype,Symbol.toStringTag,{value:"Tagged"});var ZF=mn("ipns:utils"),VT=L("/ipns/");var JF=0,e$=18;function KT(r){let e;if(r.pubKey!=null)try{e=bt(r.pubKey)}catch(t){throw ZF.error(t),t}if(e!=null)return e}function HT(r){let e=L("ipns-signature:");return Je([e,r])}function jd(r){return"signatureV1"in r?Ir.encode({value:L(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:L(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Ir.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function Io(r){let e=Ir.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new to("Missing data or signatureV2");let t=qT(e.data),n=t$(t.Value),o=D(t.Validity);if(e.value!=null&&e.signatureV1!=null)return r$(e),{value:n,validityType:Ir.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Ir.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function Yd(r){return Je([VT,r.bytes])}function El(r){let e=Ge(r.slice(VT.length));if(!F0(e,JF)&&!F0(e,e$))throw new _i("Multihash in IPNS key was not identity or sha2-256");return e}function qT(r){let e=$8(r);if(e.ValidityType===0)e.ValidityType=Ir.ValidityType.EOL;else throw new ml("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function t$(r){let e=D(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${J.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${J.parse(e).toV1().toString()}`}catch{}throw new A0("Value must be a valid content path starting with /")}function r$(r){if(r.data==null)throw new T0("Record data is missing");let e=qT(r.data);if(!ce(e.Value,r.value??new Uint8Array(0)))throw new to('Field "value" did not match between protobuf and CBOR');if(!ce(e.Validity,r.validity??new Uint8Array(0)))throw new to('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new to('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new to('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new to('Field "ttl" did not match between protobuf and CBOR')}function F0(r,e){return r.code===e}var Cde=mn("ipns"),Rde=300*1e9,o$="/ipns/",Pde=o$.length;var zT=Fo(E0(),1);var $0=mn("ipns:validator"),i$=1024*10;async function s$(r,e){let t=Io(e),n;try{let o=HT(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw $0.error("record signature verification failed"),new to("Record signature verification failed");if(t.validityType===Ir.ValidityType.EOL){if(zT.default.fromString(t.validity).toDate().getTime()<Date.now())throw $0.error("record has expired"),new v0("record has expired")}else if(t.validityType!=null)throw $0.error("the validity type is unsupported"),new ml("The validity type is unsupported");$0("ipns record for %s is valid",t.value)}async function V0(r,e){if(e.byteLength>i$)throw new S0("The record is too large");let t=El(r),n;F0(t,0)&&(n=Zh(t));let o=Io(e),i=KT(o)??n;if(i==null)throw new Vd("Could not extract public key from IPNS record or routing key");let s=Yd(i.toMultihash());if(!ce(s,r))throw new Vd("Embedded public key did not match routing key");await s$(i,e)}var K0=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*vl(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let i of r){if(typeof i=="string"&&(i=new TextEncoder().encode(i)),ac(i)&&(i=i.subarray()),o+=n.decode(i,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new K0("Incoming message too long");let s=o.split(t);o=s.pop()??"";for(let a=0;a<s.length;a++)yield JSON.parse(s[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Oa=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},_n=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function a$(r){return r[Symbol.asyncIterator]!=null}function c$(r){if(a$(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var WT=c$;var GT=L("/ipns/");function jT(r){return ce(r.subarray(0,GT.byteLength),GT)}var H0=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){try{yield*Sn(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof je)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!jT(e))return;let o=El(e),i=J.createV1(114,o),s=Io(t);await this.client.putIPNS(i,s,n)}async get(e,t){if(!jT(e))throw new je("Not found");let n=El(e),o=J.createV1(114,n);try{let i=await this.client.getIPNS(o,t);return jd(i)}catch(i){throw i.name==="BadResponseError"?new je("Not found"):i}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},q0=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await WT(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new je("Not found")}async*getClosestPeers(e,t={}){let n;try{n=J.decode(e)}catch{try{n=yt(ct.decode(e))}catch{n=J.createV1(Ho,Et.digest(e))}}for await(let o of this.client.getClosestPeers(n,t))yield{id:o.ID,multiaddrs:o.Addrs??[]}}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};var z0={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},W0=class{url;started;httpQueue;shutDownController;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new Us({concurrency:t.concurrentRequests??z0.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??z0.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new H0(this),this.peerRouting=new q0(this),this.cacheName=t.cacheName??z0.cacheName,this.cacheTTL=t.cacheTTL??z0.cacheTTL}get[$o](){return this.contentRouting}get[Ko](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ee([this.shutDownController.signal,n,t.signal]);let i=Ie(),s=Ie(),a=0;this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l={headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o},u=await this.#r(c.toString(),l);if(!u.ok){if(u.status===404)return;throw u.status===422?new Oa("Request does not conform to schema or semantic constraints"):new _n(`Unexpected status code: ${u.status}`)}let d=u.headers.get("Content-Type");if(d==null)throw new _n("No Content-Type header received");if(u.body==null){if(d!=="application/x-ndjson")throw new _n("Routing response had no body");return}if(d.startsWith("application/json")){let h=(await u.json()).Providers??[];for(let p of h){let y=this.#e(p);y!=null&&(a++,yield y)}}else if(d.includes("application/x-ndjson"))for await(let f of vl($d(u.body))){let h=this.#e(f);h!=null&&(a++,yield h)}else throw new _n(`Unsupported Content-Type: ${d}`)}finally{o.clear(),s.resolve(),this.log("getProviders finished found %d providers for %c",a,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ee([this.shutDownController.signal,n,t.signal]);let i=Ie(),s=Ie();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.url}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)return;if(l.status===422)throw new Oa("Request does not conform to schema or semantic constraints");if(l.body==null)throw new _n("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let f=(await l.json()).Peers??[];for(let h of f){let p=this.#e(h);p!=null&&(yield p)}}else for await(let d of vl($d(l.body))){let f=this.#e(d);f!=null&&(yield f)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),s.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if(Rt(e))n=e.toCID().toString();else if(J.asCID(e)===e||e instanceof J)n=e.toV1().toString();else throw new T("Key must be CID or PeerId");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),i=Ee([this.shutDownController.signal,o,t.signal]);let s=Ie(),a=Ie();this.httpQueue.add(async()=>(s.resolve(),a.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l={headers:{Accept:"application/x-ndjson"},signal:i},u=await this.#r(c.toString(),l);if(u.status===404)return;if(u.status===422)throw new Oa("Request does not conform to schema or semantic constraints");if(u.body==null)throw new _n("Routing response had no body");if(u.headers.get("Content-Type")?.startsWith("application/json")){let h=(await u.json()).Peers??[];for(let p of h){let y=this.#e(p);y!=null&&(yield y)}}else for await(let f of vl($d(u.body))){let h=this.#e(f);h!=null&&(yield h)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{i.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(e,t={}){this.log("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=Ee([this.shutDownController.signal,n,t.signal]);let i=Ie(),s=Ie();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await i.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o},l=await this.#r(a,c);if(this.log("getIPNS GET %s %d",a,l.status),l.status===404)throw new je("No matching records found");if(l.status===422)throw new Oa("Request does not conform to schema or semantic constraints");if(!l.ok)throw new _n(`Unexpected status code: ${l.status}`);let u=l.headers.get("Content-Type");if(u==null||!u.includes("application/vnd.ipfs.ipns-record"))throw new je("No matching records found");if(l.body==null)throw new _n("GET ipns response had no body");let d=await l.arrayBuffer(),f=new Uint8Array(d,0,d.byteLength);return t.validate!==!1&&await V0(Yd(e.multihash),f),Io(f)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),s.resolve(),this.log("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=Ee([this.shutDownController.signal,o,n.signal]);let s=Ie(),a=Ie();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let l=jd(t),u={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i},d=await this.#r(c,u);if(this.log("putIPNS PUT %s %d",c,d.status),d.status!==200)throw new _n("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{i.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(Z)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:et(e.ID),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let i=this.inFlightRequests.get(o);if(i!=null){let c=await i;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(e,t);let s=fetch(e,t).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let d=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,d)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,s),await s}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,i]of n.entries())this.log("%s: %s",o,i)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function YT(r){return e=>new W0(e,r)}function V8(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var l$=["https://trustless-gateway.link","https://4everland.io"],u$=2336;function d$(r){return r=r.toString(),{id:en(J.createV1(u$,Et.digest(L(r)))),multiaddrs:[dl(r)]}}function f$(r){return new URL(D(r.id.toMultihash().digest))}var K8=class{name="http-gateway-router";gateways;shuffle;constructor(e={}){this.gateways=(e.gateways??l$).map(t=>d$(t)),this.shuffle=e.shuffle??!0}async*findProviders(e,t){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,protocols:["transport-ipfs-gateway-http"],routing:"http-gateway-routing"}))}toString(){return`HTTPGatewayRouter([${this.gateways.map(e=>f$(e)).join(", ")}])`}};function H8(r={}){return new K8(r)}var q8=class{name="libp2p-router";libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*this.libp2p.contentRouting.findProviders(e,t)}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return this.libp2p.contentRouting.get(e,t)}async findPeer(e,t){return this.libp2p.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t){yield*this.libp2p.peerRouting.getClosestPeers(e,t)}toString(){return"Libp2pRouter()"}};function z8(r){return new q8(r)}function h$(r){return r[Symbol.asyncIterator]!=null}function p$(r){if(h$(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 fi=p$;function m$(r){return typeof r?.then=="function"}var Xd=class extends ai{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let o;if(t instanceof Uint8Array)o=[t];else{let i=fi(t);if(m$(i))return i.then(s=>this._put(e,s,n));o=i}return this._put(e,o,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(Lt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(Lt.encode(e.multihash.bytes));if(n==null)throw new vn;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(Lt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(Lt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:J.createV1(Ho,Ge(Lt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var rhe=mn("blockstore:core:tiered");var XT="SHARDING";function y$(r){return r[Symbol.asyncIterator]!=null}function w$(r,e){return y$(r)?(async function*(){yield*(await fi(r)).sort(e)})():(function*(){yield*fi(r).sort(e)})()}var G0=w$;var hi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Sr(this.putMany(e,n)),e=[],await Sr(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Zn(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>Zn(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>G0(o,i),n)),e.offset!=null){let o=0,i=e.offset;n=Zn(n,()=>o++>=i)}return e.limit!=null&&(n=as(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Zn(n,i=>i.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>Zn(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>G0(o,i),n)),e.offset!=null){let o=e.offset,i=0;n=Zn(n,()=>i++>=o)}return e.limit!=null&&(n=as(n,e.limit)),n}};var Ba=class extends hi{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new vn;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new rt(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new rt(n),t?.signal?.throwIfAborted()}};var Dhe=new rt(XT);var jhe=mn("datastore:core:tiered");async function ZT(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new T("Private network is enforced, but no protector was provided");return r}var Qd;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.publicKey!=null&&i.publicKey.byteLength>0&&(s.uint32(10),s.bytes(i.publicKey)),i.payloadType!=null&&i.payloadType.byteLength>0&&(s.uint32(18),s.bytes(i.payloadType)),i.payload!=null&&i.payload.byteLength>0&&(s.uint32(26),s.bytes(i.payload)),i.signature!=null&&i.signature.byteLength>0&&(s.uint32(42),s.bytes(i.signature)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={publicKey:be(0),payloadType:be(0),payload:be(0),signature:be(0)},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.publicKey=i.bytes();break}case 2:{c.payloadType=i.bytes();break}case 3:{c.payload=i.bytes();break}case 5:{c.signature=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:i.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:i.bytes()};break}case 3:{yield{field:`${a}.payload`,value:i.bytes()};break}case 5:{yield{field:`${a}.signature`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Qd||(Qd={}));var j0=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var an=class r{static createFromProtobuf=e=>{let t=Qd.decode(e),n=bt(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,i=e.codec,s=e.marshal(),a=JT(o,i,s),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:i,payload:s,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new j0("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:i}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=i}marshal(){return this.marshaled==null&&(this.marshaled=Qd.encode({publicKey:Nt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:ce(this.marshal(),e.marshal())}async validate(e,t){let n=JT(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},JT=(r,e,t)=>{let n=L(r),o=ir(n.byteLength),i=ir(e.length),s=ir(t.length);return new ie(o,n,i,e,s,t)};var e_="libp2p-peer-record",t_=Uint8Array.from([3,1]);var Zd;(function(r){let e;(function(s){let a;s.codec=()=>(a==null&&(a=ye((d,f,h={})=>{h.lengthDelimited!==!1&&f.fork(),d.multiaddr!=null&&d.multiaddr.byteLength>0&&(f.uint32(10),f.bytes(d.multiaddr)),h.lengthDelimited!==!1&&f.ldelim()},(d,f,h={})=>{let p={multiaddr:be(0)},y=f==null?d.len:d.pos+f;for(;d.pos<y;){let m=d.uint32();m>>>3===1?p.multiaddr=d.bytes():d.skipType(m&7)}return p},function*(d,f,h,p={}){let y=f==null?d.len:d.pos+f;for(;d.pos<y;){let m=d.uint32();m>>>3===1?yield{field:`${h}.multiaddr`,value:d.bytes()}:d.skipType(m&7)}})),a);function c(d){return me(d,s.codec())}s.encode=c;function l(d,f){return pe(d,s.codec(),f)}s.decode=l;function u(d,f){return ge(d,s.codec(),f)}s.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=ye((s,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),s.peerId!=null&&s.peerId.byteLength>0&&(a.uint32(10),a.bytes(s.peerId)),s.seq!=null&&s.seq!==0n&&(a.uint32(16),a.uint64(s.seq)),s.addresses!=null&&s.addresses.length>0)for(let l of s.addresses)a.uint32(26),r.AddressInfo.codec().encode(l,a);c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={peerId:be(0),seq:0n,addresses:[]},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{l.peerId=s.bytes();break}case 2:{l.seq=s.uint64();break}case 3:{if(c.limits?.addresses!=null&&l.addresses.length===c.limits.addresses)throw new Se('Decode error - repeated field "addresses" had too many elements');l.addresses.push(r.AddressInfo.codec().decode(s,s.uint32(),{limits:c.limits?.addresses$}));break}default:{s.skipType(d&7);break}}}return l},function*(s,a,c,l={}){let u={addresses:0},d=a==null?s.len:s.pos+a;for(;s.pos<d;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${c}.peerId`,value:s.bytes()};break}case 2:{yield{field:`${c}.seq`,value:s.uint64()};break}case 3:{if(l.limits?.addresses!=null&&u.addresses===l.limits.addresses)throw new Se('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(s,s.uint32(),`${c}.addresses[]`,{limits:l.limits?.addresses$}))yield{...h,index:u.addresses};u.addresses++;break}default:{s.skipType(f&7);break}}}})),t);function n(s){return me(s,r.codec())}r.encode=n;function o(s,a){return pe(s,r.codec(),a)}r.decode=o;function i(s,a){return ge(s,r.codec(),a)}r.stream=i})(Zd||(Zd={}));function r_(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var xr=class r{static createFromProtobuf=e=>{let t=Zd.decode(e),n=yt(Ge(t.peerId)),o=(t.addresses??[]).map(s=>Z(s.multiaddr)),i=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:i})};static DOMAIN=e_;static CODEC=t_;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Zd.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||!r_(this.multiaddrs,e.multiaddrs))}};var pi;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=ye((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&f.value.byteLength>0&&(h.uint32(18),h.bytes(f.value)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={key:"",value:be(0)},m=h==null?f.len:f.pos+h;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:{y.key=f.string();break}case 2:{y.value=f.bytes();break}default:{f.skipType(g&7);break}}}return y},function*(f,h,p,y={}){let m=h==null?f.len:f.pos+h;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield{field:`${p}.value`,value:f.bytes()};break}default:{f.skipType(g&7);break}}}})),c);function l(f){return me(f,a.codec())}a.encode=l;function u(f,h){return pe(f,a.codec(),h)}a.decode=u;function d(f,h){return ge(f,a.codec(),h)}a.stream=d})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=ye((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&(h.uint32(18),ef.codec().encode(f.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={key:""},m=h==null?f.len:f.pos+h;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:{y.key=f.string();break}case 2:{y.value=ef.codec().decode(f,f.uint32(),{limits:p.limits?.value});break}default:{f.skipType(g&7);break}}}return y},function*(f,h,p,y={}){let m=h==null?f.len:f.pos+h;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield*ef.codec().stream(f,f.uint32(),`${p}.value`,{limits:y.limits?.value});break}default:{f.skipType(g&7);break}}}})),c);function l(f){return me(f,a.codec())}a.encode=l;function u(f,h){return pe(f,a.codec(),h)}a.decode=u;function d(f,h){return ge(f,a.codec(),h)}a.stream=d})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ye((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let u of a.addresses)c.uint32(10),Jd.codec().encode(u,c);if(a.protocols!=null&&a.protocols.length>0)for(let u of a.protocols)c.uint32(18),c.string(u);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[u,d]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:d},c);if(a.tags!=null&&a.tags.size>0)for(let[u,d]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:d},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={addresses:[],protocols:[],metadata:new Map,tags:new Map},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new Se('Decode error - repeated field "addresses" had too many elements');u.addresses.push(Jd.codec().decode(a,a.uint32(),{limits:l.limits?.addresses$}));break}case 2:{if(l.limits?.protocols!=null&&u.protocols.length===l.limits.protocols)throw new Se('Decode error - repeated field "protocols" had too many elements');u.protocols.push(a.string());break}case 4:{u.publicKey=a.bytes();break}case 5:{u.peerRecordEnvelope=a.bytes();break}case 6:{if(l.limits?.metadata!=null&&u.metadata.size===l.limits.metadata)throw new Ru('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.metadata$value}});u.metadata.set(h.key,h.value);break}case 7:{if(l.limits?.tags!=null&&u.tags.size===l.limits.tags)throw new Ru('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.tags$value}});u.tags.set(h.key,h.value);break}case 8:{u.updated=a.uint64Number();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={addresses:0,protocols:0,metadata:0,tags:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&d.addresses===u.limits.addresses)throw new Se('Streaming decode error - repeated field "addresses" had too many elements');for(let p of Jd.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...p,index:d.addresses};d.addresses++;break}case 2:{if(u.limits?.protocols!=null&&d.protocols===u.limits.protocols)throw new Se('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:d.protocols,value:a.string()},d.protocols++;break}case 4:{yield{field:`${l}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${l}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(u.limits?.metadata!=null&&d.metadata===u.limits.metadata)throw new Se('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${l}.metadata{}`,{limits:{value:u.limits?.metadata$value}}),d.metadata++;break}case 7:{if(u.limits?.tags!=null&&d.tags===u.limits.tags)throw new Se('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${l}.tags{}`,{limits:{value:u.limits?.tags$value}}),d.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return me(a,r.codec())}r.encode=o;function i(a,c){return pe(a,r.codec(),c)}r.decode=i;function s(a,c){return ge(a,r.codec(),c)}r.stream=s})(pi||(pi={}));var Jd;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.multiaddr!=null&&i.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(i.multiaddr)),i.isCertified!=null&&(s.uint32(16),s.bool(i.isCertified)),i.observed!=null&&(s.uint32(24),s.uint64Number(i.observed)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={multiaddr:be(0)},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.multiaddr=i.bytes();break}case 2:{c.isCertified=i.bool();break}case 3:{c.observed=i.uint64Number();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:i.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:i.bool()};break}case 3:{yield{field:`${a}.observed`,value:i.uint64Number()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Jd||(Jd={}));var ef;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.value!=null&&i.value!==0&&(s.uint32(8),s.uint32(i.value)),i.expiry!=null&&(s.uint32(16),s.uint64(i.expiry)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={value:0},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.value=i.uint32();break}case 2:{c.expiry=i.uint64();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:i.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:i.uint64()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(ef||(ef={}));function b$(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=bt(e.publicKey,t);return To(n)}function n_(r,e,t){let n=pi.decode(e);return Sl(r,n,t)}function Sl(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[i,s]of e.tags.entries())s.expiry!=null&&s.expiry<o||n.set(i,s);return{...e,id:b$(r,e),addresses:e.addresses.filter(({observed:i})=>i!=null&&i>Date.now()-t).map(({multiaddr:i,isCertified:s})=>({multiaddr:Z(i),isCertified:s??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function o_(r,e){return x$(r.addresses,e.addresses)&&E$(r.protocols,e.protocols)&&v$(r.publicKey,e.publicKey)&&S$(r.peerRecordEnvelope,e.peerRecordEnvelope)&&A$(r.metadata,e.metadata)&&T$(r.tags,e.tags)}function x$(r,e){return s_(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!ce(t.multiaddr,n.multiaddr)))}function E$(r,e){return s_(r,e,(t,n)=>t===n)}function v$(r,e){return i_(r,e)}function S$(r,e){return i_(r,e)}function A$(r,e){return a_(r,e,(t,n)=>ce(t,n))}function T$(r,e){return a_(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function i_(r,e){return r==null&&e==null?!0:r!=null&&e!=null?ce(r,e):!1}function s_(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function a_(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let i=e.get(n);if(i==null||!t(o,i))return!1}return!0}var W8="/peers/";function tf(r){if(!Rt(r)||r.type==null)throw new T("Invalid PeerId");let e=r.toCID().toString();return new rt(`${W8}${e}`)}async function c_(r,e,t,n,o){let i=new Map;for(let s of t){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=Z(s.multiaddr)),!bo(s.multiaddr))throw new T("Multiaddr was invalid");if(!await e(r,s.multiaddr,o))continue;let a=s.isCertified??!1,c=s.multiaddr.toString(),l=i.get(c);l!=null?s.isCertified=l.isCertified||a:i.set(c,{multiaddr:s.multiaddr,isCertified:a})}return[...i.values()].sort((s,a)=>s.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:s,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(Z(`/p2p/${r}`))),{isCertified:s,multiaddr:a.bytes}})}async function X0(r,e,t,n){if(e==null)throw new T("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new T("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new T("peer id did not match existing peer id");let i=o?.addresses??[],s=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(i=[],e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Y0(f,{validate:l_})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Y0(f,{validate:u_,map:d_})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=Y0([...a.entries()],{validate:l_})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,y]of f)y==null?h.delete(p):h.set(p,y);c=Y0([...h.entries()],{validate:u_,map:d_})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Nt(o.id.publicKey):e.publicKey!=null?u=Nt(e.publicKey):r.publicKey!=null&&(u=Nt(r.publicKey));let d={addresses:await c_(r,n.addressFilter??(async()=>!0),i,n.existingPeer?.peerPB.addresses,n),protocols:[...s.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return d.addresses.forEach(f=>{f.observed=n.existingPeer?.peerPB.addresses?.find(h=>ce(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete d.publicKey,d}function Y0(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([i],[s])=>i.localeCompare(s)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function l_(r,e){if(typeof r!="string")throw new T("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new T("Metadata value must be a Uint8Array")}function u_(r,e){if(typeof r!="string")throw new T("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new T("Tag value must be an integer");if(e.value<0||e.value>100)throw new T("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new T("Tag ttl must be an integer");if(e.ttl<0)throw new T("Tag ttl must be between greater than 0")}}function d_(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function f_(r){let e=r.toString().split("/")[2],t=J.parse(e,Lt);return en(t)}function G8(r,e,t){let n=f_(r);return n_(n,e,t)}function _$(r,e){return{prefix:W8,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(G8(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(G8(n.key,n.value,e),G8(o.key,o.value,e)))}}var Q0=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=ci({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:hd({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(tf(e),t)}async load(e,t){let n=tf(e),o=await this.datastore.get(n,t),i=pi.decode(o);if(this.#r(e,i))throw await this.datastore.delete(n,t),new je;return Sl(e,i,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),i=await X0(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,i,o)}async patch(e,t,n){let o=await this.#e(e,n),i=await X0(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,o)}async merge(e,t,n){let o=await this.#e(e,n),i=await X0(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(_$(e??{},this.maxAddressAge),e)){let o=f_(t);if(o.equals(this.peerId))continue;let i=pi.decode(n);if(this.#r(o,i)){await this.datastore.delete(t,e);continue}yield Sl(o,i,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=tf(e),o=await this.datastore.get(n,t),i=pi.decode(o);if(this.#r(e,i))throw await this.datastore.delete(n,t),new je;return{peerPB:i,peer:Sl(e,i,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let i=pi.encode(t);return await this.datastore.put(tf(e),i,o),{peer:Sl(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!o_(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,i=t.addresses.filter(s=>s.observed!=null&&s.observed>o);return n&&i.length===0}};var j8=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 Q0(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return fi(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let i=await this.store.save(e,t,n);return this.#e(e,i),i.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let i=await this.store.patch(e,t,n);return this.#e(e,i),i.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let i=await this.store.merge(e,t,n);return this.#e(e,i),i.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Rt(t)?t:Rt(t?.expectedPeer)?t.expectedPeer:void 0,i=Rt(t)||t===void 0?n:t,s=await an.openAndCertify(e,xr.DOMAIN,i),a=en(s.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=xr.createFromProtobuf(s.payload),l;try{l=await this.get(a,i)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=an.createFromProtobuf(l.peerRecordEnvelope),d=xr.createFromProtobuf(u.payload);if(d.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},i),!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 h_(r,e={}){return new j8(r,e)}var p_=864e13;var Z0=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=St({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=he(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=Rc(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?p_-Date.now():0,lastVerified:o?p_-Date.now():void 0})})}remove(e){let t=he(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,i]of this.mappings.entries())i.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,i.domain),this.mappings.delete(o),n=n||i.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!Gt(o))continue;let i=he(o);for(let[s,a]of this.mappings.entries()){if(i.host!==s)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),Z(n)}confirm(e,t){let n=he(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let i=!1;for(let[s,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",s,a.domain),i=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return i}unconfirm(e,t){let n=he(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,i=!1;for(let[s,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",s,a.domain),i=i||a.verified,a.verified=!1,a.expires=Date.now()+t);return i}};var J0=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=St({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=he(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,i="tcp"){let s=`${e}-${t}-${i}`,a=this.mappings.get(s)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:Vn(n)?4:6,protocol:i,verified:!1,expires:0};a.push(c),this.mappings.set(s,a)}remove(e){let t=he(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,i]of this.mappings.entries()){for(let s=0;s<i.length;s++){let a=i[s];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,i.splice(s,1),s--)}i.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!Gt(n))continue;let o=he(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let i;if(o.protocol==="tcp"?i=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(i=`${o.host}-${o.port}-udp`),i==null)continue;let s=this.mappings.get(i);if(s!=null)for(let a of s)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,i){let s=e.getComponents(),a=s.findIndex(l=>l.code===4||l.code===41),c=s.findIndex(l=>l.name===o);return a>-1&&c>-1?(s[a].value=t,s[a].code=n===4?4:41,s[c].value=`${i}`,Z(s)):e}confirm(e,t){if(!Gt(e))return!1;let n=he(e),o=!1;for(let i of this.mappings.values())for(let s of i)s.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",s.internalIp,s.externalIp),o=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return o}unconfirm(e,t){if(!Gt(e))return!1;let n=he(e),o=!1;for(let i of this.mappings.values())for(let s=0;s<i.length;s++){let a=i[s];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var I$={maxObservedAddresses:10},em=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=St({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??I$.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&&(gt(e)||Lb(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:Z(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},i=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),i}};var k$={maxObservedAddresses:10},tm=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=St({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??k$.maxObservedAddresses}get(e,t){if(gt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!Gt(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},i=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),i}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},i=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),i}toKey(e){if(!Gt(e))return e.toString();let t=he(e);return`${t.host}-${t.port}-${t.protocol}`}};var m_=6e4,g_={maxObservedAddresses:10,addressVerificationTTL:m_*10,addressVerificationRetry:m_*5},C$=r=>r;function Y8(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&et(t).equals(e)&&(r=r.decapsulate(Z(`/p2p/${e.toString()}`))),r}var rm=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:i=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.appendAnnounce=new Set(i.map(s=>s.toString())),this.observed=new em(e,t),this.dnsMappings=new Z0(e,t),this.ipMappings=new J0(e,t),this.transportAddresses=new tm(e,t),this.announceFilter=t.announceFilter??C$,this.observedAddressFilter=Wt(1024),this.addressVerificationTTL=t.addressVerificationTTL??g_.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??g_.addressVerificationRetry,this._updatePeerStoreAddresses=Qo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>Z(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Z(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Z(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=he(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Y8(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Y8(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=Y8(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=Z(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Z(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,i="tcp"){this.ipMappings.add(e,t,n,o,i),this.observed.removePrefixed(`/ip${Vn(n)?4:6}/${n}/${i}/${o}`)}removePublicAddressMapping(e,t,n,o=t,i="tcp"){this.ipMappings.remove(Z(`/ip${Vn(n)?4:6}/${n}/${i}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Gt(e))return!1;let t=he(e);if(t.type!=="ip4"||Rc(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[i=>ui.exactMatch(i)||Na.exactMatch(i),i=>La.exactMatch(i),i=>kA.exactMatch(i)];for(let i of o){if(!i(e))continue;let s=n.filter(l=>l.getAddrs().filter(u=>he(u).type==="ip4"&&i(u)).length>0);if(s.length!==1)continue;let a=s[0].getAddrs().filter(l=>!Vu(l)).pop();if(a==null)continue;let c=he(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var y_;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(y_||(y_={}));var nm=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},om=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Al=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},rf=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},im=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},sm=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},am=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},nf=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},cm=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},lm=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},um=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},dm=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},fm=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},ps=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Ma=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},hm=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},pm=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var X8=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=Fc())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>mh(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")}},R$=["metrics","connectionProtector","dns"],P$=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function w_(r={}){let e=new X8(r);return new Proxy(e,{get(n,o,i){if(typeof o=="string"&&!P$.includes(o)){let s=e.components[o];if(s==null&&!R$.includes(o))throw new nm(`${o} not set`);return s}return Reflect.get(n,o,i)},set(n,o,i){return typeof o=="string"?e.components[o]=i:Reflect.set(n,o,i),!0}})}function b_(r){let e={};for(let t of Object.values(r.components))for(let n of L$(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of N$(t))if(e[n]!==!0)throw new om(`Service "${D$(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function L$(r){return Array.isArray(r?.[Ce])?r[Ce]:[]}function N$(r){return Array.isArray(r?.[Nr])?r[Nr]:[]}function D$(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function x_(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>ui.matches(e)?!0:gt(e)),r}var O$=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function B$(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=O$(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=pr(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function of(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=B$(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function mm(r){if(Rt(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:et(n),e.forEach(o=>{if(!bo(o))throw new uo("Invalid multiaddr");let i=o.getComponents().findLast(s=>s.code===421)?.value;if(i==null){if(t!=null)throw new T("Multiaddrs must all have the same peer id or have no peer id")}else{let s=et(i);if(t?.equals(s)!==!0)throw new T("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!SA.exactMatch(n)),{peerId:t,multiaddrs:e}}var M$=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function E_(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??M$;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function sf(r){let e=he(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new T(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new T(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new ua(e.host,t)}function Q8(r){return!$t.exactMatch(r)}function gm(r,e,t){if(r==null||e==null)return;let n=e.filter(i=>i.status==="open").sort((i,s)=>i.direct?-1:s.direct?1:0).find(i=>i.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(i=>Q8(i)))return n}var ym=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>sf(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new ar;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((d,f)=>d+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let i=this.sortConnections(e,o),s=Math.max(t-n,0),a=[];for(let c of i)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(Gt(c.remoteAddr)){let d=he(c.remoteAddr);return u.contains(d.host)}return!0})||a.push(c),a.length===s)break;await Promise.all(a.map(async c=>{await E_(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let i=n.timeline.open,s=o.timeline.open;return i<s?1:i>s?-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 i=t.get(n.remotePeer)??0,s=t.get(o.remotePeer)??0;return i>s?1:i<s?-1:0})}};var v_="last-dial-failure",S_="last-dial-success";var A_=100,wm=50;function U$(r,e){let t=La.exactMatch(r.multiaddr),n=La.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=Na.exactMatch(r.multiaddr),i=Na.exactMatch(e.multiaddr);if(o&&!i)return-1;if(!o&&i)return 1;let s=ui.exactMatch(r.multiaddr),a=ui.exactMatch(e.multiaddr);if(s&&!a)return-1;if(!s&&a)return 1;let c=Fd.exactMatch(r.multiaddr),l=Fd.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Ud.exactMatch(r.multiaddr),d=Ud.exactMatch(e.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;let f=T8.exactMatch(r.multiaddr),h=T8.exactMatch(e.multiaddr);return f&&!h?-1:!f&&h?1:0}function F$(r,e){let t=Vu(r.multiaddr),n=Vu(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function $$(r,e){let t=gt(r.multiaddr),n=gt(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function V$(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function K$(r,e){let t=$t.exactMatch(r.multiaddr),n=$t.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function T_(r){return r.sort(U$).sort(V$).sort(K$).sort($$).sort(F$)}var Z8=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let i=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[Dr.TXT]}),s=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of i.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(s!=null&&!l.includes(s)||a.push(Z(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Th()),this.dns)}},af=new Z8;async function J8(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new pm("Max recursive depth reached");let o=!1,i=[];for(let s of Object.values(e))if(s.canResolve(r)){o=!0;let a=await s.resolve(r,t);for(let c of a)i.push(...await J8(c,e,{...t,depth:n+1}))}return o===!1&&i.push(r),i}var cf={maxParallelDials:wm,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:af}},bm=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??cf.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??cf.maxDialQueueLength,this.dialTimeout=t.dialTimeout??cf.dialTimeout,this.connections=t.connections??new ar,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??cf.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new L1({concurrency:t.maxParallelDials??cf.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==fr.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=mm(e);if(n!=null&&t.force!==!0){let s=gm(n,this.connections.get(n),o);if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new U("dial-queue:already-connected",s)),s}let i=this.queue.queue.find(s=>{if(n?.equals(s.options.peerId)===!0)return!0;let a=s.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let s of o)i.options.multiaddrs.add(s.toString());return t.onProgress?.(new U("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Ii("Dial queue is full");return this.log("creating dial target for %p",n,o.map(s=>s.toString())),t.onProgress?.(new U("dial-queue:add-to-dial-queue")),this.queue.add(async s=>{s.onProgress?.(new U("dial-queue:start-dial"));let a=Ee([this.shutDownController.signal,s.signal]);try{return await this.dialPeer(s,a)}finally{a.clear()}},{peerId:n,priority:t.priority??n5,multiaddrs:new Set(o.map(s=>s.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,i=new Set,s=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);s||o.size>0;){c++,s=!1;let u=[],d=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...d]);let f=await this.calculateMultiaddrs(n,d,{...e,signal:t});for(let h of f){if(i.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new U("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Ii("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[S_]:L(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}return p}catch(p){if(this.log.error("dial failed to %a - %e",h.multiaddr,p),i.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[v_]:L(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}if(t.aborted)throw new fo(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(d=>({multiaddr:Z(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Ii("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new nf("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);o.push(...d.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:f})=>f.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:f})=>f.toString())),o.push(...d.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(d){d.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,d)}}}let i=(await Promise.all(o.map(async d=>{let f=await J8(d.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return f.length===1&&f[0].equals(d.multiaddr)?d:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;i=i.map(f=>f.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:f.multiaddr.encapsulate(d),isCertified:f.isCertified}:f)}let s=i.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let f=d.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let d of s){let f=d.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||d.isCertified||!1;continue}a.set(f,d)}let c=[...a.values()];if(c.length===0)throw new um("The dial request has no valid addresses");let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?T_(l):l.sort(this.addressSorter);if(u.length===0)throw new nf("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!$t.matches(o.multiaddr))!=null:!0}catch{}return!1}};var H$=Object.prototype.toString,q$=r=>H$.call(r)==="[object Error]",z$=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function o5(r){if(!(r&&q$(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:z$.has(t)}function W$(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function xm(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var i5=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function G$(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function __(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function j$({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let i=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(i instanceof i5)throw i.originalError;let s=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:s,retriesConsumed:t});if(await o.onFailedAttempt(c),__(n,a)<=0)throw i;let l=await o.shouldConsumeRetry(c),u=__(n,a);if(u<=0||s<=0)throw i;if(i instanceof TypeError&&!o5(i)){if(l)throw i;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(c))throw i;if(!l)return o.signal?.throwIfAborted(),!1;let d=G$(t,o),f=Math.min(d,u);return o.signal?.throwIfAborted(),f>0&&await new Promise((h,p)=>{let y=()=>{clearTimeout(m),o.signal?.removeEventListener("abort",y),p(o.signal.reason)},m=setTimeout(()=>{o.signal?.removeEventListener("abort",y),h()},f);o.unref&&m.unref?.(),o.signal?.addEventListener("abort",y,{once:!0})}),o.signal?.throwIfAborted(),!0}async function s5(r,e={}){if(e={...e},W$(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,xm("factor",e.factor,{min:0,allowInfinity:!1}),xm("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),xm("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),xm("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let i=await r(t);return e.signal?.throwIfAborted(),i}catch(i){await j$({error:i,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Em=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 Qt({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);I_(t)&&(this.queue.has(e)||this.queue.add(async n=>{await s5(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(i){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,i),i}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(i=>{i.startsWith(Ms)&&(o[i]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>I_(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function I_(r){for(let e of r.tags.keys())if(e.startsWith(Ms))return!0;return!1}var n5=50,a5={maxConnections:A_,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},vm=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??a5.maxConnections,this.maxConnections<1)throw new T("Connection Manager maxConnections must be greater than 0");this.connections=new ar,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=>sf(Z(n))),this.deny=(t.deny??[]).map(n=>sf(Z(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??a5.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new $c({points:t.inboundConnectionThreshold??a5.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ym({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>Z(n))}),this.dialQueue=new bm(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??wm,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:af},connections:this.connections}),this.reconnectQueue=new Em({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let i=`${o.direction} ${o.protocol??"unnegotiated"}`;e[i]=(e[i]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let i={};for(let s of o.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;i[a]=(i[a]??0)+1}for(let[s,a]of Object.entries(i))e[s]=e[s]??[],e[s].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((s,a)=>s-a);let i=Math.floor(o.length*.9);t[n]=o[i]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Tt(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 Pt(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([of(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new T("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),i=this.connections.get(n)??[];i.push(t),this.connections.set(n,i),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,i=(this.connections.get(n)??[]).filter(s=>s.id!==t.id);this.connections.set(n,i),i.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Rn("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new U("connection:open",e));let{peerId:n,multiaddrs:o}=mm(e);if(this.peerId.equals(n))throw new ec("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=gm(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new U("dial-queue:already-connected")),t.onProgress?.(new U("connection:opened",c)),c}let i=await this.dialQueue.dial(e,{...t,priority:t.priority??n5});if(i.status!=="open")throw new Ns("Remote closed connection during opening");let s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let a=!1;for(let c of s)if(c.id===i.id&&(a=!0),t.force!==!0&&c.id!==i.id&&c.remoteAddr.equals(i.remoteAddr))return i.abort(new uo("Duplicate multiaddr connection")),c;return a||s.push(i),t.onProgress?.(new U("connection:opened",i)),i}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([of(o,"close",t),o.close(t)])}catch(i){o.abort(i)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Gt(e.remoteAddr)){let i=he(e.remoteAddr);return o.contains(i.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(Gt(e.remoteAddr)){let i=he(e.remoteAddr);return o.contains(i.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(Gt(e.remoteAddr)){let o=he(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>Z(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Q$=1e4,Z$="1.0.0",J$="ping",eV="ipfs",k_=32,tV=!0,Sm=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??eV}/${J$}/${Z$}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Q$,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??tV,this.timeout=new Kn({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ce]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal});try{let o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),i=S1(o);t=Date.now(),await Promise.all([i.write(yr(k_),{signal:n}),i.read({bytes:k_,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(o){if(o.name!=="UnsupportedProtocolError")throw o;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var Am=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:D(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:D(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 Al("No content routers available");let n=this,o=new tn;for await(let i of wr(...n.routers.filter(s=>s.findProviders instanceof Function).map(s=>s.findProviders(e,t))))i!=null&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),!o.has(i.id)&&(o.add(i.id),yield i))}async provide(e,t={}){if(this.routers.length===0)throw new Al("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Al("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Rn;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Rn;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Tm=globalThis.CustomEvent??Event;async function*mi(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,i=[],s=Ie(),a=Ie(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(i.length===t&&(s=Ie(),await s.promise),u)break;let y={done:!1};i.push(y),p().then(m=>{y.done=!0,y.ok=!0,y.value=m,o.dispatchEvent(new Tm("task-complete"))},m=>{y.done=!0,y.err=m,o.dispatchEvent(new Tm("task-complete"))})}c=!0,o.dispatchEvent(new Tm("task-complete"))}catch(p){l=p,o.dispatchEvent(new Tm("task-complete"))}});function d(){return n?i[0]?.done:!!i.find(p=>p.done)}function*f(){for(;i.length>0&&i[0].done;){let p=i[0];if(i.shift(),p.ok)yield p.value;else throw u=!0,s.resolve(),p.err;s.resolve()}}function*h(){for(;d();)for(let p=0;p<i.length;p++)if(i[p].done){let y=i[p];if(i.splice(p,1),p--,y.ok)yield y.value;else throw u=!0,s.resolve(),y.err;s.resolve()}}for(;;){if(d()||(a=Ie(),await a.promise),l!=null||(n?yield*f():yield*h(),l!=null))throw l;if(c&&i.length===0)break}}var _m=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:D(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new rf("No peer routers available");if(e.toString()===this.peerId.toString())throw new im("Should not try to find self");let n=this,o=wr(...this.routers.filter(i=>i.findPeer instanceof Function).map(i=>(async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error("router failed to find peer - %e",s)}})()));for await(let i of o)if(i!=null)return i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),i;throw new je}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new rf("No peer routers available");let n=this,o=Wt(1024);for await(let i of mi((async function*(){let s=wr(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of s)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))i!=null&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),!o.has(i.id.toMultihash().bytes)&&(o.add(i.id.toMultihash().bytes),yield i))}};var Im=class extends we{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=Ee([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Ie(),yield(await of(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Ee([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=yr(32),i=Date.now();for await(let s of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-i,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:s}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ze(this.needNext.promise,e)),i=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var c5=32,l5=64,km=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=St({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new sm(`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 am(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:c5,maxOutboundStreams:l5,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new T("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let i of o.protocols){let s=this.topologies.get(i);s!=null&&await Promise.all([...s.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(i=>!t.protocols.includes(i));try{for(let i of o){let s=this.topologies.get(i);s!=null&&await Promise.all([...s.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(i){this.log.error("could not inform topologies of updated peer %p - %e",t.id,i)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let i of t){let s=this.topologies.get(i);s!=null&&await Promise.all([...s.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(i){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,i)}}};var Cm=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=St({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=St({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Jl.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new T("Transport must have a valid tag");if(this.transports.has(t))throw new T(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new hm(`No transport available for address ${String(e)}`);return t?.onProgress?.(new U("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 Rn("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(i=>{t.errors.set(i.toString(),new cm)});let n=[];for(let[i,s]of this.transports.entries()){let a=s.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",i,c);let l=s.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(i)??[];u==null&&(u=[],this.listeners.set(i,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=u.findIndex(f=>f===l);u.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),E8.matches(c)?t.ipv4.attempts++:v8.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),E8.matches(c)&&t.ipv4.success++,v8.matches(c)&&t.ipv6.success++},d=>{throw this.log.error("transport %s could not listen on address %a - %e",i,c,d),t.errors.set(c.toString(),d),d}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(i=>i.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Jl.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new lm(`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:
32
+ `)),!f.ok)throw this.#t++,new Error(`Unable to fetch raw block for CID ${e} from gateway ${this.url}, received ${f.status} ${f.statusText}`);t.onProgress?.(new U("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:dl(n.toString()),cid:e})),t.onProgress?.(new U("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:e}));let h=await OA(f,o,{signal:s.signal,log:this.log});return t.onProgress?.(new U("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:e})),this.#a++,h}),this.#c.set(i,c)}return await c}catch(c){throw t.signal?.aborted===!0?new Error(`Fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`Unable to fetch raw block for CID ${e} - ${c.message}`))}finally{t.signal?.removeEventListener("abort",a),this.#c.delete(i)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#a/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#a,pendingResponses:this.#c.size}}toString(){return`TrustlessGateway(${this.url})`}};var I8=class extends _a{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??w0,this.allowLocal=t.allowLocal??b0,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url),n?.onProgress?.(new U("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}));let o;try{o=await t.getRawBlock(e,n),this.log.trace("got block for %c from %s",e,t.url)}finally{n?.onProgress?.(new U("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:t.url,transport:"http",cid:e}))}return await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*y0(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toFilterKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t,n){if(Rt(e))return;let o=_8(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(o.length===0)return;let i=cs(o[0]);return new pl(i,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:t})}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new U("trustless-gateway:found-provider",{type:"trustless-gateway",cid:e,url:t.url.toJSON(),routing:t.routing}))}};function MA(r,e){return new I8(r,e)}var x0=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??w0,this.allowLocal=t.allowLocal??b0,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of y0(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let i=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s - %e",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s - %e",e,o.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return MA({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var w0=!1,b0=!1,BA=2097152;function k8(r={}){return e=>new x0(e,r)}async function*$d(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var n$=Fo(E0(),1);var to=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},v0=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},ml=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},S0=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},A0=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},T0=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Vd=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var Ir;(function(r){let e;(function(a){a.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(a){a[a.EOL=0]="EOL"})(t||(t={})),(function(a){a.codec=()=>ut(t)})(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=ye((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.value!=null&&(c.uint32(10),c.bytes(a.value)),a.signatureV1!=null&&(c.uint32(18),c.bytes(a.signatureV1)),a.validityType!=null&&(c.uint32(24),r.ValidityType.codec().encode(a.validityType,c)),a.validity!=null&&(c.uint32(34),c.bytes(a.validity)),a.sequence!=null&&(c.uint32(40),c.uint64(a.sequence)),a.ttl!=null&&(c.uint32(48),c.uint64(a.ttl)),a.pubKey!=null&&(c.uint32(58),c.bytes(a.pubKey)),a.signatureV2!=null&&(c.uint32(66),c.bytes(a.signatureV2)),a.data!=null&&(c.uint32(74),c.bytes(a.data)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.value=a.bytes();break}case 2:{u.signatureV1=a.bytes();break}case 3:{u.validityType=r.ValidityType.codec().decode(a);break}case 4:{u.validity=a.bytes();break}case 5:{u.sequence=a.uint64();break}case 6:{u.ttl=a.uint64();break}case 7:{u.pubKey=a.bytes();break}case 8:{u.signatureV2=a.bytes();break}case 9:{u.data=a.bytes();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.value`,value:a.bytes()};break}case 2:{yield{field:`${l}.signatureV1`,value:a.bytes()};break}case 3:{yield{field:`${l}.validityType`,value:r.ValidityType.codec().decode(a)};break}case 4:{yield{field:`${l}.validity`,value:a.bytes()};break}case 5:{yield{field:`${l}.sequence`,value:a.uint64()};break}case 6:{yield{field:`${l}.ttl`,value:a.uint64()};break}case 7:{yield{field:`${l}.pubKey`,value:a.bytes()};break}case 8:{yield{field:`${l}.signatureV2`,value:a.bytes()};break}case 9:{yield{field:`${l}.data`,value:a.bytes()};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return me(a,r.codec())}r.encode=o;function i(a,c){return pe(a,r.codec(),c)}r.decode=i;function s(a,c){return ge(a,r.codec(),c)}r.stream=s})(Ir||(Ir={}));var vF=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function UA(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=SF(r);return t||"Object"}function SF(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(vF.includes(e))return e}var k=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};k.uint=new k(0,"uint",!0);k.negint=new k(1,"negint",!0);k.bytes=new k(2,"bytes",!0);k.string=new k(3,"string",!0);k.array=new k(4,"array",!1);k.map=new k(5,"map",!1);k.tag=new k(6,"tag",!1);k.float=new k(7,"float",!0);k.false=new k(7,"false",!0);k.true=new k(7,"true",!0);k.null=new k(7,"null",!0);k.undefined=new k(7,"undefined",!0);k.break=new k(7,"break",!0);var re=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Kd=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",AF=new TextEncoder;function _0(r){return Kd&&globalThis.Buffer.isBuffer(r)}function Hd(r){return r instanceof Uint8Array?_0(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var TF=24,_F=200,R8=Kd?r=>r.length>=TF?globalThis.Buffer.from(r):FA(r):r=>r.length>=_F?AF.encode(r):FA(r),_o=r=>Uint8Array.from(r),$A=Kd?(r,e,t)=>_0(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),VA=Kd?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Hd(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},KA=Kd?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function I0(r,e){if(_0(r)&&_0(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function FA(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}var IF=256,qd=class{constructor(e=IF){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=KA(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=$A(n,0,this.cursor)}else t=VA(this.chunks,this.cursor);return e&&this.reset(),t}},k0=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var de="CBOR decode error:",P8="CBOR encode error:",zd=[];zd[23]=1;zd[24]=2;zd[25]=3;zd[26]=5;zd[27]=9;function di(r,e,t){if(r.length-e<t)throw new Error(`${de} not enough data for type`)}var Vt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function rn(r,e,t){di(r,e,1);let n=r[e];if(t.strict===!0&&n<Vt[0])throw new Error(`${de} integer encoded in more bytes than necessary (strict decode)`);return n}function nn(r,e,t){di(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Vt[1])throw new Error(`${de} integer encoded in more bytes than necessary (strict decode)`);return n}function on(r,e,t){di(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Vt[2])throw new Error(`${de} integer encoded in more bytes than necessary (strict decode)`);return n}function sn(r,e,t){di(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<Vt[3])throw new Error(`${de} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${de} integers outside of the safe integer range are not supported`)}function HA(r,e,t,n){return new re(k.uint,rn(r,e+1,n),2)}function qA(r,e,t,n){return new re(k.uint,nn(r,e+1,n),3)}function zA(r,e,t,n){return new re(k.uint,on(r,e+1,n),5)}function WA(r,e,t,n){return new re(k.uint,sn(r,e+1,n),9)}function An(r,e){return Kt(r,0,e.value)}function Kt(r,e,t){if(t<Vt[0]){let n=Number(t);r.push([e|n])}else if(t<Vt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Vt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Vt[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<Vt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${de} encountered BigInt larger than allowable range`)}}An.encodedSize=function(e){return Kt.encodedSize(e.value)};Kt.encodedSize=function(e){return e<Vt[0]?1:e<Vt[1]?2:e<Vt[2]?3:e<Vt[3]?5:9};An.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function GA(r,e,t,n){return new re(k.negint,-1-rn(r,e+1,n),2)}function jA(r,e,t,n){return new re(k.negint,-1-nn(r,e+1,n),3)}function YA(r,e,t,n){return new re(k.negint,-1-on(r,e+1,n),5)}var L8=BigInt(-1),XA=BigInt(1);function QA(r,e,t,n){let o=sn(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new re(k.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${de} integers outside of the safe integer range are not supported`);return new re(k.negint,L8-BigInt(o),9)}function C0(r,e){let t=e.value,n=typeof t=="bigint"?t*L8-XA:t*-1-1;Kt(r,e.type.majorEncoded,n)}C0.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*L8-XA:t*-1-1;return n<Vt[0]?1:n<Vt[1]?2:n<Vt[2]?3:n<Vt[3]?5:9};C0.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Wd(r,e,t,n){di(r,e,t+n);let o=r.slice(e+t,e+t+n);return new re(k.bytes,o,t+n)}function ZA(r,e,t,n){return Wd(r,e,1,t)}function JA(r,e,t,n){return Wd(r,e,2,rn(r,e+1,n))}function eT(r,e,t,n){return Wd(r,e,3,nn(r,e+1,n))}function tT(r,e,t,n){return Wd(r,e,5,on(r,e+1,n))}function rT(r,e,t,n){let o=sn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${de} 64-bit integer bytes lengths not supported`);return Wd(r,e,9,o)}function R0(r){return r.encodedBytes===void 0&&(r.encodedBytes=k.equals(r.type,k.string)?R8(r.value):r.value),r.encodedBytes}function gl(r,e){let t=R0(e);Kt(r,e.type.majorEncoded,t.length),r.push(t)}gl.encodedSize=function(e){let t=R0(e);return Kt.encodedSize(t.length)+t.length};gl.compareTokens=function(e,t){return CF(R0(e),R0(t))};function CF(r,e){return r.length<e.length?-1:r.length>e.length?1:I0(r,e)}var nT=new TextDecoder,PF=32;function LF(r,e,t){if(t-e<PF){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return nT.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return nT.decode(r.subarray(e,t))}function Gd(r,e,t,n,o){let i=t+n;di(r,e,i);let s=new re(k.string,LF(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function oT(r,e,t,n){return Gd(r,e,1,t,n)}function iT(r,e,t,n){return Gd(r,e,2,rn(r,e+1,n),n)}function sT(r,e,t,n){return Gd(r,e,3,nn(r,e+1,n),n)}function aT(r,e,t,n){return Gd(r,e,5,on(r,e+1,n),n)}function cT(r,e,t,n){let o=sn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${de} 64-bit integer string lengths not supported`);return Gd(r,e,9,o,n)}var lT=gl;function yl(r,e,t,n){return new re(k.array,n,t)}function uT(r,e,t,n){return yl(r,e,1,t)}function dT(r,e,t,n){return yl(r,e,2,rn(r,e+1,n))}function fT(r,e,t,n){return yl(r,e,3,nn(r,e+1,n))}function hT(r,e,t,n){return yl(r,e,5,on(r,e+1,n))}function pT(r,e,t,n){let o=sn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${de} 64-bit integer array lengths not supported`);return yl(r,e,9,o)}function mT(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${de} indefinite length items not allowed`);return yl(r,e,1,1/0)}function P0(r,e){Kt(r,k.array.majorEncoded,e.value)}P0.compareTokens=An.compareTokens;P0.encodedSize=function(e){return Kt.encodedSize(e.value)};function wl(r,e,t,n){return new re(k.map,n,t)}function gT(r,e,t,n){return wl(r,e,1,t)}function yT(r,e,t,n){return wl(r,e,2,rn(r,e+1,n))}function wT(r,e,t,n){return wl(r,e,3,nn(r,e+1,n))}function bT(r,e,t,n){return wl(r,e,5,on(r,e+1,n))}function xT(r,e,t,n){let o=sn(r,e+1,n);if(typeof o=="bigint")throw new Error(`${de} 64-bit integer map lengths not supported`);return wl(r,e,9,o)}function ET(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${de} indefinite length items not allowed`);return wl(r,e,1,1/0)}function L0(r,e){Kt(r,k.map.majorEncoded,e.value)}L0.compareTokens=An.compareTokens;L0.encodedSize=function(e){return Kt.encodedSize(e.value)};function vT(r,e,t,n){return new re(k.tag,t,1)}function ST(r,e,t,n){return new re(k.tag,rn(r,e+1,n),2)}function AT(r,e,t,n){return new re(k.tag,nn(r,e+1,n),3)}function TT(r,e,t,n){return new re(k.tag,on(r,e+1,n),5)}function _T(r,e,t,n){return new re(k.tag,sn(r,e+1,n),9)}function N0(r,e){Kt(r,k.tag.majorEncoded,e.value)}N0.compareTokens=An.compareTokens;N0.encodedSize=function(e){return Kt.encodedSize(e.value)};var N8=20,D8=21,O8=22,B8=23;function IT(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${de} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new re(k.null,null,1):new re(k.undefined,void 0,1)}function kT(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${de} indefinite length items not allowed`);return new re(k.break,void 0,1)}function M8(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${de} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${de} Infinity values are not supported`)}return new re(k.float,r,e)}function CT(r,e,t,n){return M8(U8(r,e+1),3,n)}function RT(r,e,t,n){return M8(F8(r,e+1),5,n)}function PT(r,e,t,n){return M8(OT(r,e+1),9,n)}function D0(r,e,t){let n=e.value;if(n===!1)r.push([k.float.majorEncoded|N8]);else if(n===!0)r.push([k.float.majorEncoded|D8]);else if(n===null)r.push([k.float.majorEncoded|O8]);else if(n===void 0)r.push([k.float.majorEncoded|B8]);else{let o,i=!1;(!t||t.float64!==!0)&&(NT(n),o=U8(ro,1),n===o||Number.isNaN(n)?(ro[0]=249,r.push(ro.slice(0,3)),i=!0):(DT(n),o=F8(ro,1),n===o&&(ro[0]=250,r.push(ro.slice(0,5)),i=!0))),i||(MF(n),o=OT(ro,1),ro[0]=251,r.push(ro.slice(0,9)))}}D0.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){NT(n);let o=U8(ro,1);if(n===o||Number.isNaN(n))return 3;if(DT(n),o=F8(ro,1),n===o)return 5}return 9};var LT=new ArrayBuffer(9),Tn=new DataView(LT,1),ro=new Uint8Array(LT,0);function NT(r){if(r===1/0)Tn.setUint16(0,31744,!1);else if(r===-1/0)Tn.setUint16(0,64512,!1);else if(Number.isNaN(r))Tn.setUint16(0,32256,!1);else{Tn.setFloat32(0,r);let e=Tn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Tn.setUint16(0,31744,!1);else if(t===0)Tn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Tn.setUint16(0,0):o<-14?Tn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Tn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function U8(r,e){if(r.length-e<2)throw new Error(`${de} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function DT(r){Tn.setFloat32(0,r,!1)}function F8(r,e){if(r.length-e<4)throw new Error(`${de} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function MF(r){Tn.setFloat64(0,r,!1)}function OT(r,e){if(r.length-e<8)throw new Error(`${de} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}D0.compareTokens=An.compareTokens;function Me(r,e,t){throw new Error(`${de} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function O0(r){return()=>{throw new Error(`${de} ${r}`)}}var X=[];for(let r=0;r<=23;r++)X[r]=Me;X[24]=HA;X[25]=qA;X[26]=zA;X[27]=WA;X[28]=Me;X[29]=Me;X[30]=Me;X[31]=Me;for(let r=32;r<=55;r++)X[r]=Me;X[56]=GA;X[57]=jA;X[58]=YA;X[59]=QA;X[60]=Me;X[61]=Me;X[62]=Me;X[63]=Me;for(let r=64;r<=87;r++)X[r]=ZA;X[88]=JA;X[89]=eT;X[90]=tT;X[91]=rT;X[92]=Me;X[93]=Me;X[94]=Me;X[95]=O0("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)X[r]=oT;X[120]=iT;X[121]=sT;X[122]=aT;X[123]=cT;X[124]=Me;X[125]=Me;X[126]=Me;X[127]=O0("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)X[r]=uT;X[152]=dT;X[153]=fT;X[154]=hT;X[155]=pT;X[156]=Me;X[157]=Me;X[158]=Me;X[159]=mT;for(let r=160;r<=183;r++)X[r]=gT;X[184]=yT;X[185]=wT;X[186]=bT;X[187]=xT;X[188]=Me;X[189]=Me;X[190]=Me;X[191]=ET;for(let r=192;r<=215;r++)X[r]=vT;X[216]=ST;X[217]=AT;X[218]=TT;X[219]=_T;X[220]=Me;X[221]=Me;X[222]=Me;X[223]=Me;for(let r=224;r<=243;r++)X[r]=O0("simple values are not supported");X[244]=Me;X[245]=Me;X[246]=Me;X[247]=IT;X[248]=O0("simple values are not supported");X[249]=CT;X[250]=RT;X[251]=PT;X[252]=Me;X[253]=Me;X[254]=Me;X[255]=kT;var no=[];for(let r=0;r<24;r++)no[r]=new re(k.uint,r,1);for(let r=-1;r>=-24;r--)no[31-r]=new re(k.negint,r,1);no[64]=new re(k.bytes,new Uint8Array(0),1);no[96]=new re(k.string,"",1);no[128]=new re(k.array,0,1);no[160]=new re(k.map,0,1);no[244]=new re(k.false,!1,1);no[245]=new re(k.true,!0,1);no[246]=new re(k.null,null,1);function BT(r){switch(r.type){case k.false:return _o([244]);case k.true:return _o([245]);case k.null:return _o([246]);case k.bytes:return r.value.length?void 0:_o([64]);case k.string:return r.value===""?_o([96]):void 0;case k.array:return r.value===0?_o([128]):void 0;case k.map:return r.value===0?_o([160]):void 0;case k.uint:return r.value<24?_o([Number(r.value)]):void 0;case k.negint:if(r.value>=-24)return _o([31-Number(r.value)])}}var UT=Object.freeze({float64:!0,mapSorter:HF,quickEncodeToken:BT});function FF(){let r=[];return r[k.uint.major]=An,r[k.negint.major]=C0,r[k.bytes.major]=gl,r[k.string.major]=lT,r[k.array.major]=P0,r[k.map.major]=L0,r[k.tag.major]=N0,r[k.float.major]=D0,r}var $F=FF(),VF=new qd,B0=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${P8} object contains circular references`);return new r(t,e)}},us={null:new re(k.null,null),undefined:new re(k.undefined,void 0),true:new re(k.true,!0),false:new re(k.false,!1),emptyArray:new re(k.array,0),emptyMap:new re(k.map,0)},ds={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new re(k.float,r):r>=0?new re(k.uint,r):new re(k.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new re(k.uint,r):new re(k.negint,r)},Uint8Array(r,e,t,n){return new re(k.bytes,r)},string(r,e,t,n){return new re(k.string,r)},boolean(r,e,t,n){return r?us.true:us.false},null(r,e,t,n){return us.null},undefined(r,e,t,n){return us.undefined},ArrayBuffer(r,e,t,n){return new re(k.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new re(k.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[us.emptyArray,new re(k.break)]:us.emptyArray;n=B0.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=bl(s,t,n);return t.addBreakTokens?[new re(k.array,r.length),o,new re(k.break)]:[new re(k.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length,a;if(s){a=new Array(s),n=B0.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[bl(u,t,n),bl(d,t,n)])}l<s&&(a.length=l)}return a?.length?(KF(a,t),t.addBreakTokens?[new re(k.map,a.length),a,new re(k.break)]:[new re(k.map,a.length),a]):t.addBreakTokens===!0?[us.emptyMap,new re(k.break)]:us.emptyMap},Tagged(r,e,t,n){return[new re(k.tag,r.tag),bl(r.value,t,n)]}};ds.Map=ds.Object;ds.Buffer=ds.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ds[`${r}Array`]=ds.DataView;function bl(r,e={},t){let n=UA(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||ds[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=ds[n];if(!i)throw new Error(`${P8} unsupported type: ${n}`);return i(r,n,e,t)}function KF(r,e){e.mapSorter&&r.sort(e.mapSorter)}function HF(r,e){if(r[0]instanceof re&&e[0]instanceof re){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=MT(t.value)),n._keyBytes||(n._keyBytes=MT(n.value)),I0(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function MT(r){return qF(r,$F,UT)}function FT(r,e,t,n){if(Array.isArray(e))for(let o of e)FT(r,o,t,n);else t[e.type.major](r,e,n)}var Wue=k.uint.majorEncoded,Gue=k.negint.majorEncoded,jue=k.bytes.majorEncoded,Yue=k.string.majorEncoded,Xue=k.array.majorEncoded,Que=k.float.majorEncoded|N8,Zue=k.float.majorEncoded|D8,Jue=k.float.majorEncoded|O8,ede=k.float.majorEncoded|B8,tde=BigInt(-1),rde=BigInt(1);function qF(r,e,t,n){let o=n instanceof Uint8Array,i=o?new k0(n):VF,s=bl(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new qd(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Hd(i.chunks[0])}}return i.reset(),FT(i,s,e,t),i.toBytes(!0)}var zF={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},M0=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=no[e];if(t===void 0){let n=X[e];if(!n)throw new Error(`${de} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},fs=Symbol.for("DONE"),xl=Symbol.for("BREAK");function WF(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=hs(e,t);if(i===xl){if(r.value===1/0)break;throw new Error(`${de} got unexpected break to lengthed array`)}if(i===fs)throw new Error(`${de} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function GF(r,e,t){let n=t.useMaps===!0,o=t.rejectDuplicateMapKeys===!0,i=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=hs(e,t);if(c===xl){if(r.value===1/0)break;throw new Error(`${de} got unexpected break to lengthed map`)}if(c===fs)throw new Error(`${de} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${de} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${de} found repeat map key "${c}"`);let l=hs(e,t);if(l===fs)throw new Error(`${de} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*jF(r,e,t){for(let n=0;n<r.value;n++){let o=hs(e,t);if(o===xl){if(r.value===1/0)break;throw new Error(`${de} got unexpected break to lengthed map`)}if(o===fs)throw new Error(`${de} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=hs(e,t);if(i===fs)throw new Error(`${de} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function YF(r,e){let t=!1,n=function(){if(t)throw new Error(`${de} tag decode() may only be called once`);t=!0;let o=hs(r,e);if(o===fs)throw new Error(`${de} tag content missing`);if(o===xl)throw new Error(`${de} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${de} tag decode() may only be called once`);t=!0;let o=r.next();if(!k.equals(o.type,k.map))throw new Error(`${de} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of jF(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function hs(r,e){if(r.done())return fs;let t=r.next();if(k.equals(t.type,k.break))return xl;if(t.type.terminal)return t.value;if(k.equals(t.type,k.array))return WF(t,r,e);if(k.equals(t.type,k.map))return GF(t,r,e);if(k.equals(t.type,k.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=YF(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${de} tag decoder must call decode() or entries()`);return o}throw new Error(`${de} tag not supported (${t.value})`)}throw new Error("unsupported")}function $T(r,e){if(!(r instanceof Uint8Array))throw new Error(`${de} data to decode must be a Uint8Array`);e=Object.assign({},zF,e);let t=Hd(r),n=e.tokenizer||new M0(t,e),o=hs(n,e);if(o===fs)throw new Error(`${de} did not find any content to decode`);if(o===xl)throw new Error(`${de} got unexpected break`);return[o,r.subarray(n.pos())]}function $8(r,e){let[t,n]=$T(r,e);if(n.length>0)throw new Error(`${de} too many terminals, data makes no sense`);return t}var U0=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(U0.prototype,Symbol.toStringTag,{value:"Tagged"});var ZF=mn("ipns:utils"),VT=L("/ipns/");var JF=0,e$=18;function KT(r){let e;if(r.pubKey!=null)try{e=bt(r.pubKey)}catch(t){throw ZF.error(t),t}if(e!=null)return e}function HT(r){let e=L("ipns-signature:");return Je([e,r])}function jd(r){return"signatureV1"in r?Ir.encode({value:L(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:L(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Ir.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function Io(r){let e=Ir.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new to("Missing data or signatureV2");let t=qT(e.data),n=t$(t.Value),o=D(t.Validity);if(e.value!=null&&e.signatureV1!=null)return r$(e),{value:n,validityType:Ir.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Ir.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function Yd(r){return Je([VT,r.bytes])}function El(r){let e=Ge(r.slice(VT.length));if(!F0(e,JF)&&!F0(e,e$))throw new _i("Multihash in IPNS key was not identity or sha2-256");return e}function qT(r){let e=$8(r);if(e.ValidityType===0)e.ValidityType=Ir.ValidityType.EOL;else throw new ml("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function t$(r){let e=D(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${J.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${J.parse(e).toV1().toString()}`}catch{}throw new A0("Value must be a valid content path starting with /")}function r$(r){if(r.data==null)throw new T0("Record data is missing");let e=qT(r.data);if(!ce(e.Value,r.value??new Uint8Array(0)))throw new to('Field "value" did not match between protobuf and CBOR');if(!ce(e.Validity,r.validity??new Uint8Array(0)))throw new to('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new to('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new to('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new to('Field "ttl" did not match between protobuf and CBOR')}function F0(r,e){return r.code===e}var Cde=mn("ipns"),Rde=300*1e9,o$="/ipns/",Pde=o$.length;var zT=Fo(E0(),1);var $0=mn("ipns:validator"),i$=1024*10;async function s$(r,e){let t=Io(e),n;try{let o=HT(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw $0.error("record signature verification failed"),new to("Record signature verification failed");if(t.validityType===Ir.ValidityType.EOL){if(zT.default.fromString(t.validity).toDate().getTime()<Date.now())throw $0.error("record has expired"),new v0("record has expired")}else if(t.validityType!=null)throw $0.error("the validity type is unsupported"),new ml("The validity type is unsupported");$0("ipns record for %s is valid",t.value)}async function V0(r,e){if(e.byteLength>i$)throw new S0("The record is too large");let t=El(r),n;F0(t,0)&&(n=Zh(t));let o=Io(e),i=KT(o)??n;if(i==null)throw new Vd("Could not extract public key from IPNS record or routing key");let s=Yd(i.toMultihash());if(!ce(s,r))throw new Vd("Embedded public key did not match routing key");await s$(i,e)}var K0=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*vl(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let i of r){if(typeof i=="string"&&(i=new TextEncoder().encode(i)),ac(i)&&(i=i.subarray()),o+=n.decode(i,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new K0("Incoming message too long");let s=o.split(t);o=s.pop()??"";for(let a=0;a<s.length;a++)yield JSON.parse(s[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Oa=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},_n=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function a$(r){return r[Symbol.asyncIterator]!=null}function c$(r){if(a$(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var WT=c$;var GT=L("/ipns/");function jT(r){return ce(r.subarray(0,GT.byteLength),GT)}var H0=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){try{yield*Sn(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof je)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!jT(e))return;let o=El(e),i=J.createV1(114,o),s=Io(t);await this.client.putIPNS(i,s,n)}async get(e,t){if(!jT(e))throw new je("Not found");let n=El(e),o=J.createV1(114,n);try{let i=await this.client.getIPNS(o,t);return jd(i)}catch(i){throw i.name==="BadResponseError"?new je("Not found"):i}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},q0=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await WT(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new je("Not found")}async*getClosestPeers(e,t={}){let n;try{n=J.decode(e)}catch{try{n=yt(ct.decode(e))}catch{n=J.createV1(Ho,Et.digest(e))}}for await(let o of this.client.getClosestPeers(n,t))yield{id:o.ID,multiaddrs:o.Addrs??[]}}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};var z0={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},W0=class{url;started;httpQueue;shutDownController;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new Us({concurrency:t.concurrentRequests??z0.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??z0.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new H0(this),this.peerRouting=new q0(this),this.cacheName=t.cacheName??z0.cacheName,this.cacheTTL=t.cacheTTL??z0.cacheTTL}get[$o](){return this.contentRouting}get[Ko](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ee([this.shutDownController.signal,n,t.signal]);let i=Ie(),s=Ie(),a=0;this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l={headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o},u=await this.#r(c.toString(),l);if(!u.ok){if(u.status===404)return;throw u.status===422?new Oa("Request does not conform to schema or semantic constraints"):new _n(`Unexpected status code: ${u.status}`)}let d=u.headers.get("Content-Type");if(d==null)throw new _n("No Content-Type header received");if(u.body==null){if(d!=="application/x-ndjson")throw new _n("Routing response had no body");return}if(d.startsWith("application/json")){let h=(await u.json()).Providers??[];for(let p of h){let y=this.#e(p);y!=null&&(a++,yield y)}}else if(d.includes("application/x-ndjson"))for await(let f of vl($d(u.body))){let h=this.#e(f);h!=null&&(a++,yield h)}else throw new _n(`Unsupported Content-Type: ${d}`)}finally{o.clear(),s.resolve(),this.log("getProviders finished found %d providers for %c",a,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ee([this.shutDownController.signal,n,t.signal]);let i=Ie(),s=Ie();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.url}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)return;if(l.status===422)throw new Oa("Request does not conform to schema or semantic constraints");if(l.body==null)throw new _n("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let f=(await l.json()).Peers??[];for(let h of f){let p=this.#e(h);p!=null&&(yield p)}}else for await(let d of vl($d(l.body))){let f=this.#e(d);f!=null&&(yield f)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),s.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if(Rt(e))n=e.toCID().toString();else if(J.asCID(e)===e||e instanceof J)n=e.toV1().toString();else throw new T("Key must be CID or PeerId");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),i=Ee([this.shutDownController.signal,o,t.signal]);let s=Ie(),a=Ie();this.httpQueue.add(async()=>(s.resolve(),a.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l={headers:{Accept:"application/x-ndjson"},signal:i},u=await this.#r(c.toString(),l);if(u.status===404)return;if(u.status===422)throw new Oa("Request does not conform to schema or semantic constraints");if(u.body==null)throw new _n("Routing response had no body");if(u.headers.get("Content-Type")?.startsWith("application/json")){let h=(await u.json()).Peers??[];for(let p of h){let y=this.#e(p);y!=null&&(yield y)}}else for await(let f of vl($d(u.body))){let h=this.#e(f);h!=null&&(yield h)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{i.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(e,t={}){this.log("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=Ee([this.shutDownController.signal,n,t.signal]);let i=Ie(),s=Ie();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await i.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o},l=await this.#r(a,c);if(this.log("getIPNS GET %s %d",a,l.status),l.status===404)throw new je("No matching records found");if(l.status===422)throw new Oa("Request does not conform to schema or semantic constraints");if(!l.ok)throw new _n(`Unexpected status code: ${l.status}`);let u=l.headers.get("Content-Type");if(u==null||!u.includes("application/vnd.ipfs.ipns-record"))throw new je("No matching records found");if(l.body==null)throw new _n("GET ipns response had no body");let d=await l.arrayBuffer(),f=new Uint8Array(d,0,d.byteLength);return t.validate!==!1&&await V0(Yd(e.multihash),f),Io(f)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),s.resolve(),this.log("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=Ee([this.shutDownController.signal,o,n.signal]);let s=Ie(),a=Ie();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let l=jd(t),u={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i},d=await this.#r(c,u);if(this.log("putIPNS PUT %s %d",c,d.status),d.status!==200)throw new _n("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{i.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(Z)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:et(e.ID),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let i=this.inFlightRequests.get(o);if(i!=null){let c=await i;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(e,t);let s=fetch(e,t).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let d=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,d)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,s),await s}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,i]of n.entries())this.log("%s: %s",o,i)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function YT(r){return e=>new W0(e,r)}function V8(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var l$=["https://trustless-gateway.link","https://4everland.io"],u$=2336;function d$(r){return r=r.toString(),{id:en(J.createV1(u$,Et.digest(L(r)))),multiaddrs:[dl(r)]}}function f$(r){return new URL(D(r.id.toMultihash().digest))}var K8=class{name="http-gateway-router";gateways;shuffle;constructor(e={}){this.gateways=(e.gateways??l$).map(t=>d$(t)),this.shuffle=e.shuffle??!0}async*findProviders(e,t){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,protocols:["transport-ipfs-gateway-http"],routing:"http-gateway-routing"}))}toString(){return`HTTPGatewayRouter([${this.gateways.map(e=>f$(e)).join(", ")}])`}};function H8(r={}){return new K8(r)}var q8=class{name="libp2p-router";libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*this.libp2p.contentRouting.findProviders(e,t)}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return this.libp2p.contentRouting.get(e,t)}async findPeer(e,t){return this.libp2p.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t){yield*this.libp2p.peerRouting.getClosestPeers(e,t)}toString(){return"Libp2pRouter()"}};function z8(r){return new q8(r)}function h$(r){return r[Symbol.asyncIterator]!=null}function p$(r){if(h$(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 fi=p$;function m$(r){return typeof r?.then=="function"}var Xd=class extends ai{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let o;if(t instanceof Uint8Array)o=[t];else{let i=fi(t);if(m$(i))return i.then(s=>this._put(e,s,n));o=i}return this._put(e,o,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(Lt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(Lt.encode(e.multihash.bytes));if(n==null)throw new vn;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(Lt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(Lt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:J.createV1(Ho,Ge(Lt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var rhe=mn("blockstore:core:tiered");var XT="SHARDING";function y$(r){return r[Symbol.asyncIterator]!=null}function w$(r,e){return y$(r)?(async function*(){yield*(await fi(r)).sort(e)})():(function*(){yield*fi(r).sort(e)})()}var G0=w$;var hi=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Sr(this.putMany(e,n)),e=[],await Sr(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Zn(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>Zn(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>G0(o,i),n)),e.offset!=null){let o=0,i=e.offset;n=Zn(n,()=>o++>=i)}return e.limit!=null&&(n=as(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Zn(n,i=>i.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>Zn(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>G0(o,i),n)),e.offset!=null){let o=e.offset,i=0;n=Zn(n,()=>i++>=o)}return e.limit!=null&&(n=as(n,e.limit)),n}};var Ba=class extends hi{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new vn;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new rt(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new rt(n),t?.signal?.throwIfAborted()}};var Dhe=new rt(XT);var jhe=mn("datastore:core:tiered");async function ZT(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new T("Private network is enforced, but no protector was provided");return r}var Qd;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.publicKey!=null&&i.publicKey.byteLength>0&&(s.uint32(10),s.bytes(i.publicKey)),i.payloadType!=null&&i.payloadType.byteLength>0&&(s.uint32(18),s.bytes(i.payloadType)),i.payload!=null&&i.payload.byteLength>0&&(s.uint32(26),s.bytes(i.payload)),i.signature!=null&&i.signature.byteLength>0&&(s.uint32(42),s.bytes(i.signature)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={publicKey:be(0),payloadType:be(0),payload:be(0),signature:be(0)},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.publicKey=i.bytes();break}case 2:{c.payloadType=i.bytes();break}case 3:{c.payload=i.bytes();break}case 5:{c.signature=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:i.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:i.bytes()};break}case 3:{yield{field:`${a}.payload`,value:i.bytes()};break}case 5:{yield{field:`${a}.signature`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Qd||(Qd={}));var j0=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var an=class r{static createFromProtobuf=e=>{let t=Qd.decode(e),n=bt(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,i=e.codec,s=e.marshal(),a=JT(o,i,s),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:i,payload:s,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new j0("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:i}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=i}marshal(){return this.marshaled==null&&(this.marshaled=Qd.encode({publicKey:Nt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:ce(this.marshal(),e.marshal())}async validate(e,t){let n=JT(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},JT=(r,e,t)=>{let n=L(r),o=ir(n.byteLength),i=ir(e.length),s=ir(t.length);return new ie(o,n,i,e,s,t)};var e_="libp2p-peer-record",t_=Uint8Array.from([3,1]);var Zd;(function(r){let e;(function(s){let a;s.codec=()=>(a==null&&(a=ye((d,f,h={})=>{h.lengthDelimited!==!1&&f.fork(),d.multiaddr!=null&&d.multiaddr.byteLength>0&&(f.uint32(10),f.bytes(d.multiaddr)),h.lengthDelimited!==!1&&f.ldelim()},(d,f,h={})=>{let p={multiaddr:be(0)},y=f==null?d.len:d.pos+f;for(;d.pos<y;){let m=d.uint32();m>>>3===1?p.multiaddr=d.bytes():d.skipType(m&7)}return p},function*(d,f,h,p={}){let y=f==null?d.len:d.pos+f;for(;d.pos<y;){let m=d.uint32();m>>>3===1?yield{field:`${h}.multiaddr`,value:d.bytes()}:d.skipType(m&7)}})),a);function c(d){return me(d,s.codec())}s.encode=c;function l(d,f){return pe(d,s.codec(),f)}s.decode=l;function u(d,f){return ge(d,s.codec(),f)}s.stream=u})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=ye((s,a,c={})=>{if(c.lengthDelimited!==!1&&a.fork(),s.peerId!=null&&s.peerId.byteLength>0&&(a.uint32(10),a.bytes(s.peerId)),s.seq!=null&&s.seq!==0n&&(a.uint32(16),a.uint64(s.seq)),s.addresses!=null&&s.addresses.length>0)for(let l of s.addresses)a.uint32(26),r.AddressInfo.codec().encode(l,a);c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={peerId:be(0),seq:0n,addresses:[]},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{l.peerId=s.bytes();break}case 2:{l.seq=s.uint64();break}case 3:{if(c.limits?.addresses!=null&&l.addresses.length===c.limits.addresses)throw new Se('Decode error - repeated field "addresses" had too many elements');l.addresses.push(r.AddressInfo.codec().decode(s,s.uint32(),{limits:c.limits?.addresses$}));break}default:{s.skipType(d&7);break}}}return l},function*(s,a,c,l={}){let u={addresses:0},d=a==null?s.len:s.pos+a;for(;s.pos<d;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${c}.peerId`,value:s.bytes()};break}case 2:{yield{field:`${c}.seq`,value:s.uint64()};break}case 3:{if(l.limits?.addresses!=null&&u.addresses===l.limits.addresses)throw new Se('Streaming decode error - repeated field "addresses" had too many elements');for(let h of r.AddressInfo.codec().stream(s,s.uint32(),`${c}.addresses[]`,{limits:l.limits?.addresses$}))yield{...h,index:u.addresses};u.addresses++;break}default:{s.skipType(f&7);break}}}})),t);function n(s){return me(s,r.codec())}r.encode=n;function o(s,a){return pe(s,r.codec(),a)}r.decode=o;function i(s,a){return ge(s,r.codec(),a)}r.stream=i})(Zd||(Zd={}));function r_(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var xr=class r{static createFromProtobuf=e=>{let t=Zd.decode(e),n=yt(Ge(t.peerId)),o=(t.addresses??[]).map(s=>Z(s.multiaddr)),i=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:i})};static DOMAIN=e_;static CODEC=t_;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=Zd.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||!r_(this.multiaddrs,e.multiaddrs))}};var pi;(function(r){let e;(function(a){let c;a.codec=()=>(c==null&&(c=ye((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&f.value.byteLength>0&&(h.uint32(18),h.bytes(f.value)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={key:"",value:be(0)},m=h==null?f.len:f.pos+h;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:{y.key=f.string();break}case 2:{y.value=f.bytes();break}default:{f.skipType(g&7);break}}}return y},function*(f,h,p,y={}){let m=h==null?f.len:f.pos+h;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield{field:`${p}.value`,value:f.bytes()};break}default:{f.skipType(g&7);break}}}})),c);function l(f){return me(f,a.codec())}a.encode=l;function u(f,h){return pe(f,a.codec(),h)}a.decode=u;function d(f,h){return ge(f,a.codec(),h)}a.stream=d})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(a){let c;a.codec=()=>(c==null&&(c=ye((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.key!=null&&f.key!==""&&(h.uint32(10),h.string(f.key)),f.value!=null&&(h.uint32(18),ef.codec().encode(f.value,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={key:""},m=h==null?f.len:f.pos+h;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:{y.key=f.string();break}case 2:{y.value=ef.codec().decode(f,f.uint32(),{limits:p.limits?.value});break}default:{f.skipType(g&7);break}}}return y},function*(f,h,p,y={}){let m=h==null?f.len:f.pos+h;for(;f.pos<m;){let g=f.uint32();switch(g>>>3){case 1:{yield{field:`${p}.key`,value:f.string()};break}case 2:{yield*ef.codec().stream(f,f.uint32(),`${p}.value`,{limits:y.limits?.value});break}default:{f.skipType(g&7);break}}}})),c);function l(f){return me(f,a.codec())}a.encode=l;function u(f,h){return pe(f,a.codec(),h)}a.decode=u;function d(f,h){return ge(f,a.codec(),h)}a.stream=d})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ye((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.addresses!=null&&a.addresses.length>0)for(let u of a.addresses)c.uint32(10),Jd.codec().encode(u,c);if(a.protocols!=null&&a.protocols.length>0)for(let u of a.protocols)c.uint32(18),c.string(u);if(a.publicKey!=null&&(c.uint32(34),c.bytes(a.publicKey)),a.peerRecordEnvelope!=null&&(c.uint32(42),c.bytes(a.peerRecordEnvelope)),a.metadata!=null&&a.metadata.size>0)for(let[u,d]of a.metadata.entries())c.uint32(50),r.Peer$metadataEntry.codec().encode({key:u,value:d},c);if(a.tags!=null&&a.tags.size>0)for(let[u,d]of a.tags.entries())c.uint32(58),r.Peer$tagsEntry.codec().encode({key:u,value:d},c);a.updated!=null&&(c.uint32(64),c.uint64Number(a.updated)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={addresses:[],protocols:[],metadata:new Map,tags:new Map},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{if(l.limits?.addresses!=null&&u.addresses.length===l.limits.addresses)throw new Se('Decode error - repeated field "addresses" had too many elements');u.addresses.push(Jd.codec().decode(a,a.uint32(),{limits:l.limits?.addresses$}));break}case 2:{if(l.limits?.protocols!=null&&u.protocols.length===l.limits.protocols)throw new Se('Decode error - repeated field "protocols" had too many elements');u.protocols.push(a.string());break}case 4:{u.publicKey=a.bytes();break}case 5:{u.peerRecordEnvelope=a.bytes();break}case 6:{if(l.limits?.metadata!=null&&u.metadata.size===l.limits.metadata)throw new Ru('Decode error - map field "metadata" had too many elements');let h=r.Peer$metadataEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.metadata$value}});u.metadata.set(h.key,h.value);break}case 7:{if(l.limits?.tags!=null&&u.tags.size===l.limits.tags)throw new Ru('Decode error - map field "tags" had too many elements');let h=r.Peer$tagsEntry.codec().decode(a,a.uint32(),{limits:{value:l.limits?.tags$value}});u.tags.set(h.key,h.value);break}case 8:{u.updated=a.uint64Number();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={addresses:0,protocols:0,metadata:0,tags:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{if(u.limits?.addresses!=null&&d.addresses===u.limits.addresses)throw new Se('Streaming decode error - repeated field "addresses" had too many elements');for(let p of Jd.codec().stream(a,a.uint32(),`${l}.addresses[]`,{limits:u.limits?.addresses$}))yield{...p,index:d.addresses};d.addresses++;break}case 2:{if(u.limits?.protocols!=null&&d.protocols===u.limits.protocols)throw new Se('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${l}.protocols[]`,index:d.protocols,value:a.string()},d.protocols++;break}case 4:{yield{field:`${l}.publicKey`,value:a.bytes()};break}case 5:{yield{field:`${l}.peerRecordEnvelope`,value:a.bytes()};break}case 6:{if(u.limits?.metadata!=null&&d.metadata===u.limits.metadata)throw new Se('Decode error - map field "metadata" had too many elements');yield*r.Peer$metadataEntry.codec().stream(a,a.uint32(),`${l}.metadata{}`,{limits:{value:u.limits?.metadata$value}}),d.metadata++;break}case 7:{if(u.limits?.tags!=null&&d.tags===u.limits.tags)throw new Se('Decode error - map field "tags" had too many elements');yield*r.Peer$tagsEntry.codec().stream(a,a.uint32(),`${l}.tags{}`,{limits:{value:u.limits?.tags$value}}),d.tags++;break}case 8:{yield{field:`${l}.updated`,value:a.uint64Number()};break}default:{a.skipType(h&7);break}}}})),n);function o(a){return me(a,r.codec())}r.encode=o;function i(a,c){return pe(a,r.codec(),c)}r.decode=i;function s(a,c){return ge(a,r.codec(),c)}r.stream=s})(pi||(pi={}));var Jd;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.multiaddr!=null&&i.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(i.multiaddr)),i.isCertified!=null&&(s.uint32(16),s.bool(i.isCertified)),i.observed!=null&&(s.uint32(24),s.uint64Number(i.observed)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={multiaddr:be(0)},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.multiaddr=i.bytes();break}case 2:{c.isCertified=i.bool();break}case 3:{c.observed=i.uint64Number();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.multiaddr`,value:i.bytes()};break}case 2:{yield{field:`${a}.isCertified`,value:i.bool()};break}case 3:{yield{field:`${a}.observed`,value:i.uint64Number()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(Jd||(Jd={}));var ef;(function(r){let e;r.codec=()=>(e==null&&(e=ye((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.value!=null&&i.value!==0&&(s.uint32(8),s.uint32(i.value)),i.expiry!=null&&(s.uint32(16),s.uint64(i.expiry)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={value:0},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.value=i.uint32();break}case 2:{c.expiry=i.uint64();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.value`,value:i.uint32()};break}case 2:{yield{field:`${a}.expiry`,value:i.uint64()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return me(i,r.codec())}r.encode=t;function n(i,s){return pe(i,r.codec(),s)}r.decode=n;function o(i,s){return ge(i,r.codec(),s)}r.stream=o})(ef||(ef={}));function b$(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=bt(e.publicKey,t);return To(n)}function n_(r,e,t){let n=pi.decode(e);return Sl(r,n,t)}function Sl(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[i,s]of e.tags.entries())s.expiry!=null&&s.expiry<o||n.set(i,s);return{...e,id:b$(r,e),addresses:e.addresses.filter(({observed:i})=>i!=null&&i>Date.now()-t).map(({multiaddr:i,isCertified:s})=>({multiaddr:Z(i),isCertified:s??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function o_(r,e){return x$(r.addresses,e.addresses)&&E$(r.protocols,e.protocols)&&v$(r.publicKey,e.publicKey)&&S$(r.peerRecordEnvelope,e.peerRecordEnvelope)&&A$(r.metadata,e.metadata)&&T$(r.tags,e.tags)}function x$(r,e){return s_(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!ce(t.multiaddr,n.multiaddr)))}function E$(r,e){return s_(r,e,(t,n)=>t===n)}function v$(r,e){return i_(r,e)}function S$(r,e){return i_(r,e)}function A$(r,e){return a_(r,e,(t,n)=>ce(t,n))}function T$(r,e){return a_(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function i_(r,e){return r==null&&e==null?!0:r!=null&&e!=null?ce(r,e):!1}function s_(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function a_(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let i=e.get(n);if(i==null||!t(o,i))return!1}return!0}var W8="/peers/";function tf(r){if(!Rt(r)||r.type==null)throw new T("Invalid PeerId");let e=r.toCID().toString();return new rt(`${W8}${e}`)}async function c_(r,e,t,n,o){let i=new Map;for(let s of t){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=Z(s.multiaddr)),!bo(s.multiaddr))throw new T("Multiaddr was invalid");if(!await e(r,s.multiaddr,o))continue;let a=s.isCertified??!1,c=s.multiaddr.toString(),l=i.get(c);l!=null?s.isCertified=l.isCertified||a:i.set(c,{multiaddr:s.multiaddr,isCertified:a})}return[...i.values()].sort((s,a)=>s.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:s,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(Z(`/p2p/${r}`))),{isCertified:s,multiaddr:a.bytes}})}async function X0(r,e,t,n){if(e==null)throw new T("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new T("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new T("peer id did not match existing peer id");let i=o?.addresses??[],s=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(i=[],e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Y0(f,{validate:l_})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Y0(f,{validate:u_,map:d_})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&i.push(...e.multiaddrs.map(f=>({isCertified:!1,multiaddr:f}))),e.addresses!=null&&i.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let f=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of f)p==null?a.delete(h):a.set(h,p);a=Y0([...a.entries()],{validate:l_})}if(e.tags!=null){let f=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,y]of f)y==null?h.delete(p):h.set(p,y);c=Y0([...h.entries()],{validate:u_,map:d_})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Nt(o.id.publicKey):e.publicKey!=null?u=Nt(e.publicKey):r.publicKey!=null&&(u=Nt(r.publicKey));let d={addresses:await c_(r,n.addressFilter??(async()=>!0),i,n.existingPeer?.peerPB.addresses,n),protocols:[...s.values()].sort((f,h)=>f.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return d.addresses.forEach(f=>{f.observed=n.existingPeer?.peerPB.addresses?.find(h=>ce(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete d.publicKey,d}function Y0(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([i],[s])=>i.localeCompare(s)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function l_(r,e){if(typeof r!="string")throw new T("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new T("Metadata value must be a Uint8Array")}function u_(r,e){if(typeof r!="string")throw new T("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new T("Tag value must be an integer");if(e.value<0||e.value>100)throw new T("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new T("Tag ttl must be an integer");if(e.ttl<0)throw new T("Tag ttl must be between greater than 0")}}function d_(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function f_(r){let e=r.toString().split("/")[2],t=J.parse(e,Lt);return en(t)}function G8(r,e,t){let n=f_(r);return n_(n,e,t)}function _$(r,e){return{prefix:W8,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(G8(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(G8(n.key,n.value,e),G8(o.key,o.value,e)))}}var Q0=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=ci({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:hd({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(tf(e),t)}async load(e,t){let n=tf(e),o=await this.datastore.get(n,t),i=pi.decode(o);if(this.#r(e,i))throw await this.datastore.delete(n,t),new je;return Sl(e,i,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),i=await X0(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,i,o)}async patch(e,t,n){let o=await this.#e(e,n),i=await X0(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,o)}async merge(e,t,n){let o=await this.#e(e,n),i=await X0(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(_$(e??{},this.maxAddressAge),e)){let o=f_(t);if(o.equals(this.peerId))continue;let i=pi.decode(n);if(this.#r(o,i)){await this.datastore.delete(t,e);continue}yield Sl(o,i,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=tf(e),o=await this.datastore.get(n,t),i=pi.decode(o);if(this.#r(e,i))throw await this.datastore.delete(n,t),new je;return{peerPB:i,peer:Sl(e,i,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let i=pi.encode(t);return await this.datastore.put(tf(e),i,o),{peer:Sl(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!o_(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,i=t.addresses.filter(s=>s.observed!=null&&s.observed>o);return n&&i.length===0}};var j8=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 Q0(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return fi(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let i=await this.store.save(e,t,n);return this.#e(e,i),i.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let i=await this.store.patch(e,t,n);return this.#e(e,i),i.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let i=await this.store.merge(e,t,n);return this.#e(e,i),i.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=Rt(t)?t:Rt(t?.expectedPeer)?t.expectedPeer:void 0,i=Rt(t)||t===void 0?n:t,s=await an.openAndCertify(e,xr.DOMAIN,i),a=en(s.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=xr.createFromProtobuf(s.payload),l;try{l=await this.get(a,i)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=an.createFromProtobuf(l.peerRecordEnvelope),d=xr.createFromProtobuf(u.payload);if(d.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",d.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},i),!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 h_(r,e={}){return new j8(r,e)}var p_=864e13;var Z0=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=St({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=he(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=Rc(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?p_-Date.now():0,lastVerified:o?p_-Date.now():void 0})})}remove(e){let t=he(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,i]of this.mappings.entries())i.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,i.domain),this.mappings.delete(o),n=n||i.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!Gt(o))continue;let i=he(o);for(let[s,a]of this.mappings.entries()){if(i.host!==s)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),Z(n)}confirm(e,t){let n=he(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let i=!1;for(let[s,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",s,a.domain),i=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return i}unconfirm(e,t){let n=he(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,i=!1;for(let[s,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",s,a.domain),i=i||a.verified,a.verified=!1,a.expires=Date.now()+t);return i}};var J0=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=St({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=he(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,i="tcp"){let s=`${e}-${t}-${i}`,a=this.mappings.get(s)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:Vn(n)?4:6,protocol:i,verified:!1,expires:0};a.push(c),this.mappings.set(s,a)}remove(e){let t=he(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,i]of this.mappings.entries()){for(let s=0;s<i.length;s++){let a=i[s];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,i.splice(s,1),s--)}i.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!Gt(n))continue;let o=he(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let i;if(o.protocol==="tcp"?i=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(i=`${o.host}-${o.port}-udp`),i==null)continue;let s=this.mappings.get(i);if(s!=null)for(let a of s)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,i){let s=e.getComponents(),a=s.findIndex(l=>l.code===4||l.code===41),c=s.findIndex(l=>l.name===o);return a>-1&&c>-1?(s[a].value=t,s[a].code=n===4?4:41,s[c].value=`${i}`,Z(s)):e}confirm(e,t){if(!Gt(e))return!1;let n=he(e),o=!1;for(let i of this.mappings.values())for(let s of i)s.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",s.internalIp,s.externalIp),o=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return o}unconfirm(e,t){if(!Gt(e))return!1;let n=he(e),o=!1;for(let i of this.mappings.values())for(let s=0;s<i.length;s++){let a=i[s];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var I$={maxObservedAddresses:10},em=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=St({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??I$.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&&(gt(e)||Lb(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:Z(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},i=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),i}};var k$={maxObservedAddresses:10},tm=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=St({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??k$.maxObservedAddresses}get(e,t){if(gt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!Gt(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},i=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),i}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},i=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),i}toKey(e){if(!Gt(e))return e.toString();let t=he(e);return`${t.host}-${t.port}-${t.protocol}`}};var m_=6e4,g_={maxObservedAddresses:10,addressVerificationTTL:m_*10,addressVerificationRetry:m_*5},C$=r=>r;function Y8(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&et(t).equals(e)&&(r=r.decapsulate(Z(`/p2p/${e.toString()}`))),r}var rm=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:i=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.appendAnnounce=new Set(i.map(s=>s.toString())),this.observed=new em(e,t),this.dnsMappings=new Z0(e,t),this.ipMappings=new J0(e,t),this.transportAddresses=new tm(e,t),this.announceFilter=t.announceFilter??C$,this.observedAddressFilter=Wt(1024),this.addressVerificationTTL=t.addressVerificationTTL??g_.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??g_.addressVerificationRetry,this._updatePeerStoreAddresses=Qo(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>Z(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>Z(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>Z(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=he(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Y8(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Y8(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=Y8(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=Z(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Z(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,i="tcp"){this.ipMappings.add(e,t,n,o,i),this.observed.removePrefixed(`/ip${Vn(n)?4:6}/${n}/${i}/${o}`)}removePublicAddressMapping(e,t,n,o=t,i="tcp"){this.ipMappings.remove(Z(`/ip${Vn(n)?4:6}/${n}/${i}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!Gt(e))return!1;let t=he(e);if(t.type!=="ip4"||Rc(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[i=>ui.exactMatch(i)||Na.exactMatch(i),i=>La.exactMatch(i),i=>kA.exactMatch(i)];for(let i of o){if(!i(e))continue;let s=n.filter(l=>l.getAddrs().filter(u=>he(u).type==="ip4"&&i(u)).length>0);if(s.length!==1)continue;let a=s[0].getAddrs().filter(l=>!Vu(l)).pop();if(a==null)continue;let c=he(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var y_;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(y_||(y_={}));var nm=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},om=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Al=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},rf=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},im=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},sm=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},am=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},nf=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},cm=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},lm=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},um=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},dm=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},fm=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},ps=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Ma=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},hm=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},pm=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var X8=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=Fc())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>mh(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")}},R$=["metrics","connectionProtector","dns"],P$=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function w_(r={}){let e=new X8(r);return new Proxy(e,{get(n,o,i){if(typeof o=="string"&&!P$.includes(o)){let s=e.components[o];if(s==null&&!R$.includes(o))throw new nm(`${o} not set`);return s}return Reflect.get(n,o,i)},set(n,o,i){return typeof o=="string"?e.components[o]=i:Reflect.set(n,o,i),!0}})}function b_(r){let e={};for(let t of Object.values(r.components))for(let n of L$(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of N$(t))if(e[n]!==!0)throw new om(`Service "${D$(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function L$(r){return Array.isArray(r?.[Ce])?r[Ce]:[]}function N$(r){return Array.isArray(r?.[Nr])?r[Nr]:[]}function D$(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function x_(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>ui.matches(e)?!0:gt(e)),r}var O$=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function B$(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=O$(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=pr(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function of(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=B$(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function mm(r){if(Rt(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:et(n),e.forEach(o=>{if(!bo(o))throw new uo("Invalid multiaddr");let i=o.getComponents().findLast(s=>s.code===421)?.value;if(i==null){if(t!=null)throw new T("Multiaddrs must all have the same peer id or have no peer id")}else{let s=et(i);if(t?.equals(s)!==!0)throw new T("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!SA.exactMatch(n)),{peerId:t,multiaddrs:e}}var M$=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function E_(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??M$;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function sf(r){let e=he(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new T(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new T(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new ua(e.host,t)}function Q8(r){return!$t.exactMatch(r)}function gm(r,e,t){if(r==null||e==null)return;let n=e.filter(i=>i.status==="open").sort((i,s)=>i.direct?-1:s.direct?1:0).find(i=>i.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(i=>Q8(i)))return n}var ym=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>sf(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new ar;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((d,f)=>d+f.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let i=this.sortConnections(e,o),s=Math.max(t-n,0),a=[];for(let c of i)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(Gt(c.remoteAddr)){let d=he(c.remoteAddr);return u.contains(d.host)}return!0})||a.push(c),a.length===s)break;await Promise.all(a.map(async c=>{await E_(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let i=n.timeline.open,s=o.timeline.open;return i<s?1:i>s?-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 i=t.get(n.remotePeer)??0,s=t.get(o.remotePeer)??0;return i>s?1:i<s?-1:0})}};var v_="last-dial-failure",S_="last-dial-success";var A_=100,wm=50;function U$(r,e){let t=La.exactMatch(r.multiaddr),n=La.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=Na.exactMatch(r.multiaddr),i=Na.exactMatch(e.multiaddr);if(o&&!i)return-1;if(!o&&i)return 1;let s=ui.exactMatch(r.multiaddr),a=ui.exactMatch(e.multiaddr);if(s&&!a)return-1;if(!s&&a)return 1;let c=Fd.exactMatch(r.multiaddr),l=Fd.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Ud.exactMatch(r.multiaddr),d=Ud.exactMatch(e.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;let f=T8.exactMatch(r.multiaddr),h=T8.exactMatch(e.multiaddr);return f&&!h?-1:!f&&h?1:0}function F$(r,e){let t=Vu(r.multiaddr),n=Vu(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function $$(r,e){let t=gt(r.multiaddr),n=gt(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function V$(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function K$(r,e){let t=$t.exactMatch(r.multiaddr),n=$t.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function T_(r){return r.sort(U$).sort(V$).sort(K$).sort($$).sort(F$)}var Z8=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let i=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[Dr.TXT]}),s=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of i.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(s!=null&&!l.includes(s)||a.push(Z(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Th()),this.dns)}},af=new Z8;async function J8(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new pm("Max recursive depth reached");let o=!1,i=[];for(let s of Object.values(e))if(s.canResolve(r)){o=!0;let a=await s.resolve(r,t);for(let c of a)i.push(...await J8(c,e,{...t,depth:n+1}))}return o===!1&&i.push(r),i}var cf={maxParallelDials:wm,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:af}},bm=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??cf.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??cf.maxDialQueueLength,this.dialTimeout=t.dialTimeout??cf.dialTimeout,this.connections=t.connections??new ar,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??cf.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new L1({concurrency:t.maxParallelDials??cf.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==fr.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=mm(e);if(n!=null&&t.force!==!0){let s=gm(n,this.connections.get(n),o);if(s!=null)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new U("dial-queue:already-connected",s)),s}let i=this.queue.queue.find(s=>{if(n?.equals(s.options.peerId)===!0)return!0;let a=s.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let s of o)i.options.multiaddrs.add(s.toString());return t.onProgress?.(new U("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Ii("Dial queue is full");return this.log("creating dial target for %p",n,o.map(s=>s.toString())),t.onProgress?.(new U("dial-queue:add-to-dial-queue")),this.queue.add(async s=>{s.onProgress?.(new U("dial-queue:start-dial"));let a=Ee([this.shutDownController.signal,s.signal]);try{return await this.dialPeer(s,a)}finally{a.clear()}},{peerId:n,priority:t.priority??n5,multiaddrs:new Set(o.map(s=>s.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,i=new Set,s=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);s||o.size>0;){c++,s=!1;let u=[],d=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...d]);let f=await this.calculateMultiaddrs(n,d,{...e,signal:t});for(let h of f){if(i.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new U("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Ii("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[S_]:L(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}return p}catch(p){if(this.log.error("dial failed to %a - %e",h.multiaddr,p),i.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[v_]:L(Date.now().toString())}})}catch(y){this.log.error("could not update last dial failure key for %p - %e",n,y)}if(t.aborted)throw new fo(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(d=>({multiaddr:Z(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Ii("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new nf("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);o.push(...d.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:f})=>f.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:f})=>f.toString())),o.push(...d.multiaddrs.map(f=>({multiaddr:f,isCertified:!1})))}catch(d){d.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,d)}}}let i=(await Promise.all(o.map(async d=>{let f=await J8(d.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return f.length===1&&f[0].equals(d.multiaddr)?d:f.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;i=i.map(f=>f.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:f.multiaddr.encapsulate(d),isCertified:f.isCertified}:f)}let s=i.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let f=d.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&f!=null?e.equals(f):!0}),a=new Map;for(let d of s){let f=d.multiaddr.toString(),h=a.get(f);if(h!=null){h.isCertified=h.isCertified||d.isCertified||!1;continue}a.set(f,d)}let c=[...a.values()];if(c.length===0)throw new um("The dial request has no valid addresses");let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?T_(l):l.sort(this.addressSorter);if(u.length===0)throw new nf("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!$t.matches(o.multiaddr))!=null:!0}catch{}return!1}};var H$=Object.prototype.toString,q$=r=>H$.call(r)==="[object Error]",z$=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function o5(r){if(!(r&&q$(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:z$.has(t)}function W$(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function xm(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var i5=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function G$(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function __(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function j$({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let i=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(i instanceof i5)throw i.originalError;let s=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:s,retriesConsumed:t});if(await o.onFailedAttempt(c),__(n,a)<=0)throw i;let l=await o.shouldConsumeRetry(c),u=__(n,a);if(u<=0||s<=0)throw i;if(i instanceof TypeError&&!o5(i)){if(l)throw i;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(c))throw i;if(!l)return o.signal?.throwIfAborted(),!1;let d=G$(t,o),f=Math.min(d,u);return o.signal?.throwIfAborted(),f>0&&await new Promise((h,p)=>{let y=()=>{clearTimeout(m),o.signal?.removeEventListener("abort",y),p(o.signal.reason)},m=setTimeout(()=>{o.signal?.removeEventListener("abort",y),h()},f);o.unref&&m.unref?.(),o.signal?.addEventListener("abort",y,{once:!0})}),o.signal?.throwIfAborted(),!0}async function s5(r,e={}){if(e={...e},W$(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,xm("factor",e.factor,{min:0,allowInfinity:!1}),xm("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),xm("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),xm("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let i=await r(t);return e.signal?.throwIfAborted(),i}catch(i){await j$({error:i,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Em=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 Qt({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);I_(t)&&(this.queue.has(e)||this.queue.add(async n=>{await s5(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(i){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,i),i}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(i=>{i.startsWith(Ms)&&(o[i]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>I_(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function I_(r){for(let e of r.tags.keys())if(e.startsWith(Ms))return!0;return!1}var n5=50,a5={maxConnections:A_,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},vm=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??a5.maxConnections,this.maxConnections<1)throw new T("Connection Manager maxConnections must be greater than 0");this.connections=new ar,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=>sf(Z(n))),this.deny=(t.deny??[]).map(n=>sf(Z(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??a5.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new $c({points:t.inboundConnectionThreshold??a5.inboundConnectionThreshold,duration:1}),this.connectionPruner=new ym({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>Z(n))}),this.dialQueue=new bm(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??wm,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:af},connections:this.connections}),this.reconnectQueue=new Em({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let i=`${o.direction} ${o.protocol??"unnegotiated"}`;e[i]=(e[i]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let i={};for(let s of o.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;i[a]=(i[a]??0)+1}for(let[s,a]of Object.entries(i))e[s]=e[s]??[],e[s].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((s,a)=>s-a);let i=Math.floor(o.length*.9);t[n]=o[i]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Tt(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 Pt(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([of(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(e<1)throw new T("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),i=this.connections.get(n)??[];i.push(t),this.connections.set(n,i),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,i=(this.connections.get(n)??[]).filter(s=>s.id!==t.id);this.connections.set(n,i),i.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Rn("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted(),t?.onProgress?.(new U("connection:open",e));let{peerId:n,multiaddrs:o}=mm(e);if(this.peerId.equals(n))throw new ec("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=gm(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new U("dial-queue:already-connected")),t.onProgress?.(new U("connection:opened",c)),c}let i=await this.dialQueue.dial(e,{...t,priority:t.priority??n5});if(i.status!=="open")throw new Ns("Remote closed connection during opening");let s=this.connections.get(i.remotePeer);s==null&&(s=[],this.connections.set(i.remotePeer,s));let a=!1;for(let c of s)if(c.id===i.id&&(a=!0),t.force!==!0&&c.id!==i.id&&c.remoteAddr.equals(i.remoteAddr))return i.abort(new uo("Duplicate multiaddr connection")),c;return a||s.push(i),t.onProgress?.(new U("connection:opened",i)),i}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([of(o,"close",t),o.close(t)])}catch(i){o.abort(i)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(Gt(e.remoteAddr)){let i=he(e.remoteAddr);return o.contains(i.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(Gt(e.remoteAddr)){let i=he(e.remoteAddr);return o.contains(i.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(Gt(e.remoteAddr)){let o=he(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>Z(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Q$=1e4,Z$="1.0.0",J$="ping",eV="ipfs",k_=32,tV=!0,Sm=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??eV}/${J$}/${Z$}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??Q$,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??tV,this.timeout=new Kn({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ce]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now(),n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal});try{let o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),i=S1(o);t=Date.now(),await Promise.all([i.write(yr(k_),{signal:n}),i.read({bytes:k_,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(o){if(o.name!=="UnsupportedProtocolError")throw o;e.rtt=(Date.now()-t)/2}finally{this.timeout.cleanUp(n)}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var Am=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:D(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:D(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 Al("No content routers available");let n=this,o=new tn;for await(let i of wr(...n.routers.filter(s=>s.findProviders instanceof Function).map(s=>s.findProviders(e,t))))i!=null&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),!o.has(i.id)&&(o.add(i.id),yield i))}async provide(e,t={}){if(this.routers.length===0)throw new Al("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Al("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Rn;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Rn;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var Tm=globalThis.CustomEvent??Event;async function*mi(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,i=[],s=Ie(),a=Ie(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(i.length===t&&(s=Ie(),await s.promise),u)break;let y={done:!1};i.push(y),p().then(m=>{y.done=!0,y.ok=!0,y.value=m,o.dispatchEvent(new Tm("task-complete"))},m=>{y.done=!0,y.err=m,o.dispatchEvent(new Tm("task-complete"))})}c=!0,o.dispatchEvent(new Tm("task-complete"))}catch(p){l=p,o.dispatchEvent(new Tm("task-complete"))}});function d(){return n?i[0]?.done:!!i.find(p=>p.done)}function*f(){for(;i.length>0&&i[0].done;){let p=i[0];if(i.shift(),p.ok)yield p.value;else throw u=!0,s.resolve(),p.err;s.resolve()}}function*h(){for(;d();)for(let p=0;p<i.length;p++)if(i[p].done){let y=i[p];if(i.splice(p,1),p--,y.ok)yield y.value;else throw u=!0,s.resolve(),y.err;s.resolve()}}for(;;){if(d()||(a=Ie(),await a.promise),l!=null||(n?yield*f():yield*h(),l!=null))throw l;if(c&&i.length===0)break}}var _m=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:D(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new rf("No peer routers available");if(e.toString()===this.peerId.toString())throw new im("Should not try to find self");let n=this,o=wr(...this.routers.filter(i=>i.findPeer instanceof Function).map(i=>(async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error("router failed to find peer - %e",s)}})()));for await(let i of o)if(i!=null)return i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),i;throw new je}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new rf("No peer routers available");let n=this,o=Wt(1024);for await(let i of mi((async function*(){let s=wr(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of s)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))i!=null&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs},t),!o.has(i.id.toMultihash().bytes)&&(o.add(i.id.toMultihash().bytes),yield i))}};var Im=class extends we{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=Ee([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Ie(),yield(await of(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Ee([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=yr(32),i=Date.now();for await(let s of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-i,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:s}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ze(this.needNext.promise,e)),i=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var c5=32,l5=64,km=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=St({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new sm(`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 am(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:c5,maxOutboundStreams:l5,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new T("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let i of o.protocols){let s=this.topologies.get(i);s!=null&&await Promise.all([...s.values()].map(async a=>{a.filter!=null&&a.filter.has(t)!==!0||(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(i=>!t.protocols.includes(i));try{for(let i of o){let s=this.topologies.get(i);s!=null&&await Promise.all([...s.values()].map(async a=>{a.filter!=null&&a.filter.has(t.id)!==!0||(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(i){this.log.error("could not inform topologies of updated peer %p - %e",t.id,i)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let i of t){let s=this.topologies.get(i);s!=null&&await Promise.all([...s.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(i){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,i)}}};var Cm=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=St({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=St({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Jl.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new T("Transport must have a valid tag");if(this.transports.has(t))throw new T(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new hm(`No transport available for address ${String(e)}`);return t?.onProgress?.(new U("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 Rn("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(i=>{t.errors.set(i.toString(),new cm)});let n=[];for(let[i,s]of this.transports.entries()){let a=s.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",i,c);let l=s.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(i)??[];u==null&&(u=[],this.listeners.set(i,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let d=u.findIndex(f=>f===l);u.splice(d,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),E8.matches(c)?t.ipv4.attempts++:v8.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),E8.matches(c)&&t.ipv4.success++,v8.matches(c)&&t.ipv6.success++},d=>{throw this.log.error("transport %s could not listen on address %a - %e",i,c,d),t.errors.set(c.toString(),d),d}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(i=>i.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Jl.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new lm(`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:
33
33
  ${[...t.errors.entries()].map(([i,s])=>`
34
34
  ${i}: ${`${rV(s)}`.split(`
35
35
  `).join(`
@@ -100,7 +100,7 @@ a=end-of-candidates
100
100
  `:`
101
101
  `;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
102
102
  a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
103
- a=ice-pwd:`+e+t)}catch{}return r}var H7=L("libp2p-webrtc-noise:");function HR(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=L(n,"hex"),i=mr(ft.code,o),s=$7.decode(V7(e)),a=H7.byteLength+i.bytes.byteLength+s.byteLength;return t==="server"?Je([H7,s,i.bytes],a):Je([H7,i.bytes,s],a)}var uq=a3?"iceconnectionstatechange":"connectionstatechange";function dq(r,e){return r.role==="server"}async function qR(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=K7(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=$R(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=VR(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=K7(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Ti(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),dq(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(FR(d))}let i=UR(r.localDescription?.sdp);if(i==null)throw new Ps("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let s=HR(i,n.remoteAddr,n.role),a=M2({prologueBytes:s})(n),c=oh({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=ih({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener(uq,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(i){throw o.close(),r.close(),i}}async function zR(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,i=new RTCPeerConnection({...o??{},certificates:[n]}),s=new Rs({peerConnection:i,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:i,muxerFactory:s}}var y3=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Ci]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ce]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=et(o));let i=LR(),{peerConnection:s,muxerFactory:a}=await zR("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await qR(s,a,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw s.close(),c}}createListener(e){throw new d3("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Ud.exactMatch)}};function WR(r){return e=>new y3(e,r)}function GR(r){return e=>new g3(e,r)}var fq=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function hq(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=fq(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=pr(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function jR(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=hq(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function YR(){throw new Error("WebSocket Servers can not be created in the browser!")}var pq=1024*1024*4,mq=10,q7=class extends zi{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??pq,this.checkBufferedAmountTask=Vc(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??mq),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=L(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(n);let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function XR(r){return new q7(r)}var z7=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Ci]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ce]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=XR({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=cs(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new U("websockets:open-connection")),await jR(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Za(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return YR({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>ui.exactMatch(t)||Na.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function QR(r={}){return e=>new z7(e,r)}var W7=Fo(E0(),1);function ZR(r,e){let t=e.map((n,o)=>({record:Io(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===Ir.ValidityType.EOL&&o.record.validityType===Ir.ValidityType.EOL){let a=W7.default.fromString(n.record.validity).toDate(),c=W7.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var JR="6.1.2",eP="helia";var tP={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function w3(r={}){let e=`${eP}/${JR} ${Nm()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[Ok(),GR(),WR(),QR()],connectionEncrypters:[M2()],streamMuxers:[bk(),pR()],peerDiscovery:[Ak(tP)],services:{autoNAT:Sk(),dcutr:Uk(),delegatedRouting:YT(V8()),dht:lR({clientMode:!0,validators:{ipns:V0},selectors:{ipns:ZR}}),identify:CC(),identifyPush:RC(),keychain:I2(r.keychain),ping:xR(),http:SC()}}}async function rP(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await E5(r.datastore,r.keychain));let t=w3(e);return t.datastore=t.datastore??r.datastore,await D_({...t,...e,start:!1})}async function G7(r={}){let e=r.datastore??new Ba,t=r.blockstore??new Xd,n;return O_(r.libp2p)?n=r.libp2p:n=await rP({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[k8(),u8()],routers:r.routers??[z8(n),H8()],metrics:n.metrics}}async function gq(r={}){let e=await G7(r),t=new Jp(e);return e.start!==!1&&await t.start(),t}return cP(yq);})();
103
+ a=ice-pwd:`+e+t)}catch{}return r}var H7=L("libp2p-webrtc-noise:");function HR(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=L(n,"hex"),i=mr(ft.code,o),s=$7.decode(V7(e)),a=H7.byteLength+i.bytes.byteLength+s.byteLength;return t==="server"?Je([H7,s,i.bytes],a):Je([H7,i.bytes,s],a)}var uq=a3?"iceconnectionstatechange":"connectionstatechange";function dq(r,e){return r.role==="server"}async function qR(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=K7(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=$R(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=VR(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=K7(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Ti(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),dq(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(FR(d))}let i=UR(r.localDescription?.sdp);if(i==null)throw new Ps("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let s=HR(i,n.remoteAddr,n.role),a=M2({prologueBytes:s})(n),c=oh({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=ih({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener(uq,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(i){throw o.close(),r.close(),i}}async function zR(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,i=new RTCPeerConnection({...o??{},certificates:[n]}),s=new Rs({peerConnection:i,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:i,muxerFactory:s}}var y3=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Ci]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ce]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=et(o));let i=LR(),{peerConnection:s,muxerFactory:a}=await zR("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await qR(s,a,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw s.close(),c}}createListener(e){throw new d3("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Ud.exactMatch)}};function WR(r){return e=>new y3(e,r)}function GR(r){return e=>new g3(e,r)}var fq=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function hq(r,e,t){let n,o=new Promise((i,s)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=fq(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=pr(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function jR(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=hq(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function YR(){throw new Error("WebSocket Servers can not be created in the browser!")}var pq=1024*1024*4,mq=10,q7=class extends zi{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??pq,this.checkBufferedAmountTask=Vc(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??mq),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=L(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(n);let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function XR(r){return new q7(r)}var z7=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Ci]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ce]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=XR({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=cs(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new U("websockets:open-connection")),await jR(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new Za(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return YR({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>ui.exactMatch(t)||Na.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function QR(r={}){return e=>new z7(e,r)}var W7=Fo(E0(),1);function ZR(r,e){let t=e.map((n,o)=>({record:Io(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===Ir.ValidityType.EOL&&o.record.validityType===Ir.ValidityType.EOL){let a=W7.default.fromString(n.record.validity).toDate(),c=W7.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var JR="6.1.3",eP="helia";var tP={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function w3(r={}){let e=`${eP}/${JR} ${Nm()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[Ok(),GR(),WR(),QR()],connectionEncrypters:[M2()],streamMuxers:[bk(),pR()],peerDiscovery:[Ak(tP)],services:{autoNAT:Sk(),dcutr:Uk(),delegatedRouting:YT(V8()),dht:lR({clientMode:!0,validators:{ipns:V0},selectors:{ipns:ZR}}),identify:CC(),identifyPush:RC(),keychain:I2(r.keychain),ping:xR(),http:SC()}}}async function rP(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await E5(r.datastore,r.keychain));let t=w3(e);return t.datastore=t.datastore??r.datastore,await D_({...t,...e,start:!1})}async function G7(r={}){let e=r.datastore??new Ba,t=r.blockstore??new Xd,n;return O_(r.libp2p)?n=r.libp2p:n=await rP({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[k8(),u8()],routers:r.routers??[z8(n),H8()],metrics:n.metrics}}async function gq(r={}){let e=await G7(r),t=new Jp(e);return e.start!==!1&&await t.start(),t}return cP(yq);})();
104
104
  /*! Bundled license information:
105
105
 
106
106
  pvtsutils/build/index.js: