@helia/verified-fetch 2.0.1 → 2.1.1
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,24 +1,24 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaVerifiedFetch = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaVerifiedFetch=(()=>{var Ub=Object.create;var ls=Object.defineProperty;var Fb=Object.getOwnPropertyDescriptor;var Mb=Object.getOwnPropertyNames;var Vb=Object.getPrototypeOf,Hb=Object.prototype.hasOwnProperty;var ge=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),vt=(r,t)=>{for(var e in t)ls(r,e,{get:t[e],enumerable:!0})},Td=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Mb(t))!Hb.call(r,o)&&o!==e&&ls(r,o,{get:()=>t[o],enumerable:!(n=Fb(t,o))||n.enumerable});return r};var Ot=(r,t,e)=>(e=r!=null?Ub(Vb(r)):{},Td(t||!r||!r.__esModule?ls(e,"default",{value:r,enumerable:!0}):e,r)),$b=r=>Td(ls({},"__esModule",{value:!0}),r);var Np=ge(co=>{"use strict";var TE="[object ArrayBuffer]",wr=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===TE}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);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(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let s of e)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of e){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},of="string",CE=/^[0-9a-f]+$/i,RE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,NE=/^[a-zA-Z0-9-_]+$/,Rs=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=wr.toUint8Array(t),n="";for(let i=0;i<e.length;i++)n+=String.fromCharCode(e[i]);return decodeURIComponent(escape(n))}},ke=class{static toString(t,e=!1){let n=wr.toArrayBuffer(t),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,e);i+=String.fromCharCode(a)}return i}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let i=0;i<t.length;i++)o.setUint16(i*2,t.charCodeAt(i),e);return n}},Ns=class r{static isHex(t){return typeof t===of&&CE.test(t)}static isBase64(t){return typeof t===of&&RE.test(t)}static isBase64Url(t){return typeof t===of&&NE.test(t)}static ToString(t,e="utf8"){let n=wr.toUint8Array(t);switch(e.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 ke.toString(n,!0);case"utf16":case"utf16be":return ke.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return ke.fromString(t,!0);case"utf16":case"utf16be":return ke.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=wr.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return Rs.fromString(t);case"utf16":case"utf16be":return ke.fromString(t);case"utf16le":case"usc2":return ke.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return Rs.toString(t);case"utf16":case"utf16be":return ke.toString(t);case"utf16le":case"usc2":return ke.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=wr.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=wr.toUint8Array(t),n="",o=e.length;for(let i=0;i<o;i++){let s=e[i];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let i=e.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(t,e=!1){return ke.toString(t,e)}static FromUtf16String(t,e=!1){return ke.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};Ns.DEFAULT_UTF8_ENCODING="utf8";function LE(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)e[i]=o[i]}return e}function PE(...r){let t=r.map(o=>o.byteLength).reduce((o,i)=>o+i),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)e[n++]=i}),e.buffer}function DE(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}co.BufferSourceConverter=wr;co.Convert=Ns;co.assign=LE;co.combine=PE;co.isEqual=DE});var zm=ge((bi,Ca)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function o(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function i(h,m){return h<<m|h>>>32-m}function s(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var p=[0,0,0,0];return p[3]+=h[3]+m[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=h[2]+m[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=h[1]+m[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=h[0]+m[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var p=[0,0,0,0];return p[3]+=h[3]*m[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=h[2]*m[3],p[1]+=p[2]>>>16,p[2]&=65535,p[2]+=h[3]*m[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=h[1]*m[3],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=h[2]*m[2],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=h[3]*m[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function u(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function f(h,m){return[h[0]^m[0],h[1]^m[1]]}function d(h){return h=f(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=f(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=f(h,[0,h[0]>>>1]),h}e.x86.hash32=function(h,m){if(e.inputValidation&&!n(h))return t;m=m||0;for(var p=h.length%4,y=h.length-p,g=m,x=0,b=3432918353,E=461845907,k=0;k<y;k=k+4)x=h[k]|h[k+1]<<8|h[k+2]<<16|h[k+3]<<24,x=o(x,b),x=i(x,15),x=o(x,E),g^=x,g=i(g,13),g=o(g,5)+3864292196;switch(x=0,p){case 3:x^=h[k+2]<<16;case 2:x^=h[k+1]<<8;case 1:x^=h[k],x=o(x,b),x=i(x,15),x=o(x,E),g^=x}return g^=h.length,g=s(g),g>>>0},e.x86.hash128=function(h,m){if(e.inputValidation&&!n(h))return t;m=m||0;for(var p=h.length%16,y=h.length-p,g=m,x=m,b=m,E=m,k=0,T=0,S=0,v=0,_=597399067,z=2869860233,F=951274213,U=2716044179,P=0;P<y;P=P+16)k=h[P]|h[P+1]<<8|h[P+2]<<16|h[P+3]<<24,T=h[P+4]|h[P+5]<<8|h[P+6]<<16|h[P+7]<<24,S=h[P+8]|h[P+9]<<8|h[P+10]<<16|h[P+11]<<24,v=h[P+12]|h[P+13]<<8|h[P+14]<<16|h[P+15]<<24,k=o(k,_),k=i(k,15),k=o(k,z),g^=k,g=i(g,19),g+=x,g=o(g,5)+1444728091,T=o(T,z),T=i(T,16),T=o(T,F),x^=T,x=i(x,17),x+=b,x=o(x,5)+197830471,S=o(S,F),S=i(S,17),S=o(S,U),b^=S,b=i(b,15),b+=E,b=o(b,5)+2530024501,v=o(v,U),v=i(v,18),v=o(v,_),E^=v,E=i(E,13),E+=g,E=o(E,5)+850148119;switch(k=0,T=0,S=0,v=0,p){case 15:v^=h[P+14]<<16;case 14:v^=h[P+13]<<8;case 13:v^=h[P+12],v=o(v,U),v=i(v,18),v=o(v,_),E^=v;case 12:S^=h[P+11]<<24;case 11:S^=h[P+10]<<16;case 10:S^=h[P+9]<<8;case 9:S^=h[P+8],S=o(S,F),S=i(S,17),S=o(S,U),b^=S;case 8:T^=h[P+7]<<24;case 7:T^=h[P+6]<<16;case 6:T^=h[P+5]<<8;case 5:T^=h[P+4],T=o(T,z),T=i(T,16),T=o(T,F),x^=T;case 4:k^=h[P+3]<<24;case 3:k^=h[P+2]<<16;case 2:k^=h[P+1]<<8;case 1:k^=h[P],k=o(k,_),k=i(k,15),k=o(k,z),g^=k}return g^=h.length,x^=h.length,b^=h.length,E^=h.length,g+=x,g+=b,g+=E,x+=g,b+=g,E+=g,g=s(g),x=s(x),b=s(b),E=s(E),g+=x,g+=b,g+=E,x+=g,b+=g,E+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)},e.x64.hash128=function(h,m){if(e.inputValidation&&!n(h))return t;m=m||0;for(var p=h.length%16,y=h.length-p,g=[0,m],x=[0,m],b=[0,0],E=[0,0],k=[2277735313,289559509],T=[1291169091,658871167],S=0;S<y;S=S+16)b=[h[S+4]|h[S+5]<<8|h[S+6]<<16|h[S+7]<<24,h[S]|h[S+1]<<8|h[S+2]<<16|h[S+3]<<24],E=[h[S+12]|h[S+13]<<8|h[S+14]<<16|h[S+15]<<24,h[S+8]|h[S+9]<<8|h[S+10]<<16|h[S+11]<<24],b=c(b,k),b=l(b,31),b=c(b,T),g=f(g,b),g=l(g,27),g=a(g,x),g=a(c(g,[0,5]),[0,1390208809]),E=c(E,T),E=l(E,33),E=c(E,k),x=f(x,E),x=l(x,31),x=a(x,g),x=a(c(x,[0,5]),[0,944331445]);switch(b=[0,0],E=[0,0],p){case 15:E=f(E,u([0,h[S+14]],48));case 14:E=f(E,u([0,h[S+13]],40));case 13:E=f(E,u([0,h[S+12]],32));case 12:E=f(E,u([0,h[S+11]],24));case 11:E=f(E,u([0,h[S+10]],16));case 10:E=f(E,u([0,h[S+9]],8));case 9:E=f(E,[0,h[S+8]]),E=c(E,T),E=l(E,33),E=c(E,k),x=f(x,E);case 8:b=f(b,u([0,h[S+7]],56));case 7:b=f(b,u([0,h[S+6]],48));case 6:b=f(b,u([0,h[S+5]],40));case 5:b=f(b,u([0,h[S+4]],32));case 4:b=f(b,u([0,h[S+3]],24));case 3:b=f(b,u([0,h[S+2]],16));case 2:b=f(b,u([0,h[S+1]],8));case 1:b=f(b,[0,h[S]]),b=c(b,k),b=l(b,31),b=c(b,T),g=f(g,b)}return g=f(g,[0,h.length]),x=f(x,[0,h.length]),g=a(g,x),x=a(x,g),g=d(g),x=d(x),g=a(g,x),x=a(x,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(x[0]>>>0).toString(16)).slice(-8)+("00000000"+(x[1]>>>0).toString(16)).slice(-8)},typeof bi<"u"?(typeof Ca<"u"&&Ca.exports&&(bi=Ca.exports=e),bi.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(bi)});var wf=ge((FC,qm)=>{qm.exports=zm()});var Ym=ge((JC,xf)=>{"use strict";var wv=Object.prototype.hasOwnProperty,Jt="~";function xi(){}Object.create&&(xi.prototype=Object.create(null),new xi().__proto__||(Jt=!1));function bv(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function jm(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var i=new bv(e,n||r,o),s=Jt?Jt+t:t;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 Pa(r,t){--r._eventsCount===0?r._events=new xi:delete r._events[t]}function Wt(){this._events=new xi,this._eventsCount=0}Wt.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)wv.call(e,n)&&t.push(Jt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Wt.prototype.listeners=function(t){var e=Jt?Jt+t:t,n=this._events[e];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};Wt.prototype.listenerCount=function(t){var e=Jt?Jt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Wt.prototype.emit=function(t,e,n,o,i,s){var a=Jt?Jt+t:t;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,i),!0;case 6:return c.fn.call(c.context,e,n,o,i,s),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(t,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};Wt.prototype.on=function(t,e,n){return jm(this,t,e,n,!1)};Wt.prototype.once=function(t,e,n){return jm(this,t,e,n,!0)};Wt.prototype.removeListener=function(t,e,n,o){var i=Jt?Jt+t:t;if(!this._events[i])return this;if(!e)return Pa(this,i),this;var s=this._events[i];if(s.fn)s.fn===e&&(!o||s.once)&&(!n||s.context===n)&&Pa(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==e||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:Pa(this,i)}return this};Wt.prototype.removeAllListeners=function(t){var e;return t?(e=Jt?Jt+t:t,this._events[e]&&Pa(this,e)):(this._events=new xi,this._eventsCount=0),this};Wt.prototype.off=Wt.prototype.removeListener;Wt.prototype.addListener=Wt.prototype.on;Wt.prefixed=Jt;Wt.EventEmitter=Wt;typeof xf<"u"&&(xf.exports=Wt)});var kf=ge((E6,Qm)=>{Qm.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(i,s){e[i]=s,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(i){return e[i]!==void 0||n[i]!==void 0},remove:function(i){e[i]!==void 0&&(e[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=e[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){e[i]!==void 0?e[i]=s:o(i,s)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var N0=ge(Oi=>{(function(){var r,t,e,n,o,i,s,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},s=function(c){var l,u,f,d,h,m;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=t(c),h=m[0],u=m[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),i=e("a"),o=e("A"),t=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(e(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+e(c[f])-i)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,h,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(m=l.split("/",2),l=m[0],u=m[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=s(u)}catch(p){throw f=p,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(l)&this.maskLong)>>>0}catch(p){throw f=p,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(s(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=s(this.first),f=s(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Oi.ip2long=s,Oi.long2ip=a,Oi.Netmask=r}).call(Oi)});var Do=ge((IP,Nh)=>{var AP=function(){typeof Nh<"u"&&(Nh.exports=p);var r=86400,t=3200,e=146097*t/400,n=r*e,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(v){var _=v-v%1;return _==0&&(v<0||v===0&&1/v!=1/0)?-0:_},u=p.prototype,f=(p.fromDate=function(v){return new p(+v)},p.fromInt64BE=E(0,1,2,3,0,4),p.fromInt64LE=E(3,2,1,0,4,0),p.fromString=function(F){var _,z=new p,F=(F+="").replace(/^\s*[+\-]?\d+/,function(P){var P=+P,R=1970+(P-1970)%400;return z.year=P-R,R}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(U,P,R){return P<0&&(R*=-1),_=6e4*(60*+P+ +R),""}).replace(/\.\d+$/,function(U){return z.nano=+(U+c).substr(1,9),""}).split(/\D+/);if(1<F.length?F[1]--:F[1]=0,z.time=_=Date.UTC.apply(Date,F)-(_||0),isNaN(_))throw new TypeError("Invalid Date");return y(z)},p.fromTimeT=function(v){return x(v,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(v){return this.nano+=+v||0,this},u.getNano=function(){var v=y(this);return(v.time%1e3*a+ +v.nano+1e9)%1e9},u.getTimeT=function(){var _=y(this),v=Math.floor(_.time/1e3),_=_.year;return _&&(v+=_*e*r/t),v},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return g(y(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(v){var _=this,z=_.toDate(),F={H:function(){return T(z.getUTCHours())},L:function(){return S(z.getUTCMilliseconds(),3)},M:function(){return T(z.getUTCMinutes())},N:function(){return S(_.getNano(),9)},S:function(){return T(z.getUTCSeconds())},Y:function(){var U=_.getYear();return 999999<U?"+"+U:9999<U?"+"+S(U,6):0<=U?S(U,4):-999999<=U?"-"+S(-U,6):U},a:function(){return h[z.getUTCDay()]},b:function(){return d[z.getUTCMonth()]},d:function(){return T(z.getUTCDate())},e:function(){return function(U){return(9<U?"":" ")+(0|U)}(z.getUTCDate())},m:function(){return T(z.getUTCMonth()+1)}};return function U(P){return P.replace(/%./g,function(R){var I=R[1],N=m[I],I=F[I];return N?U(N):I?I():R})}(v||f)},u.writeInt64BE=b(0,1,2,3,0,4),u.writeInt64LE=b(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m={"%":"%",F:"%Y-%m-%d",n:`
|
|
3
|
-
`,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return p;function p(v,_,z){var F=this;if(!(F instanceof p))return new p(v,_,z);F.time=+v||0,F.nano=+_||0,F.year=+z||0,y(F)}function y(v){var _,z,F,U=v.year,P=v.time,R=v.nano,N=((R<0||a<=R)&&(R-=(z=Math.floor(R/a))*a,P+=z,z=1),U%t);return(P<-i||i<P||N)&&((_=l(P/o))&&(U+=_*t,P-=_*o),(F=g(P)).setUTCFullYear(N+F.getUTCFullYear()),F=(P=+F)+(_=l((U-=N)/t))*o,_&&-i<=F&&F<=i&&(U-=_*t,P=F),z=1),z&&(v.year=U,v.time=P,v.nano=R),v}function g(v){var _=new Date(0);return _.setTime(v),_}function x(U,F){U=+U||0;var z=l((F=(F|0)*s)/n)+l(U/n),F=F%n+U%n,U=l(F/n);return U&&(z+=U,F-=U*n),new p(1e3*F,0,z*t)}function b(v,_,z,F,U,P){return function(N,I){var C=y(this);N=N||new Array(8),k(N,I|=0);var V=Math.floor(C.time/1e3),C=C.year*(e*r/t),A=l(C/s)+l(V/s),C=C%s+V%s,V=Math.floor(C/s);return V&&(A+=V,C-=V*s),R(N,I+U,A),R(N,I+P,C),N};function R(N,I,A){N[I+v]=A>>24&255,N[I+_]=A>>16&255,N[I+z]=A>>8&255,N[I+F]=255&A}}function E(v,_,z,F,U,P){return function(N,I){k(N,I|=0);var A=R(N,I+U);return x(R(N,I+P),A)};function R(N,I){return 16777216*N[I+v]+(N[I+_]<<16|N[I+z]<<8|N[I+F])}}function k(v,_){if(v=v&&v.length,v==null)throw new TypeError("Invalid Buffer");if(v<_+8)throw new RangeError("Out of range")}function T(v){return(9<v?"":"0")+(0|v)}function S(v,_){return(c+(0|v)).substr(-_)}}()});var Py=ge((eU,Ly)=>{Ly.exports=zh;var Ny=128,cA=127,lA=~cA,uA=Math.pow(2,31);function zh(r,t,e){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw zh.bytes=0,new RangeError("Could not encode varint");t=t||[],e=e||0;for(var n=e;r>=uA;)t[e++]=r&255|Ny,r/=128;for(;r&lA;)t[e++]=r&255|Ny,r>>>=7;return t[e]=r|0,zh.bytes=e-n+1,t}});var Uy=ge((rU,Oy)=>{Oy.exports=qh;var fA=128,Dy=127;function qh(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw qh.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&Dy)<<o:(s&Dy)*Math.pow(2,o),o+=7}while(s>=fA);return qh.bytes=i-n,e}});var My=ge((nU,Fy)=>{var hA=Math.pow(2,7),dA=Math.pow(2,14),pA=Math.pow(2,21),mA=Math.pow(2,28),gA=Math.pow(2,35),yA=Math.pow(2,42),wA=Math.pow(2,49),bA=Math.pow(2,56),xA=Math.pow(2,63);Fy.exports=function(r){return r<hA?1:r<dA?2:r<pA?3:r<mA?4:r<gA?5:r<yA?6:r<wA?7:r<bA?8:r<xA?9:10}});var Xc=ge((oU,Vy)=>{Vy.exports={encode:Py(),decode:Uy(),encodingLength:My()}});var Lw=ge((MM,Nw)=>{"use strict";Nw.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(t,e){let n=this._internalPositionFor(t,!1);if(e===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(t),this._changedLength=!0,this._changedData=!0);else{let o=!1;n===-1?(n=this._data.length,this._setBit(t),this._changedData=!0):o=!0,this._setInternalPos(n,t,e,o),this._changedLength=!0}}unset(t){this.set(t,void 0)}get(t){this._sortData();let e=this._internalPositionFor(t,!0);if(e!==-1)return this._data[e][1]}push(t){return this.set(this.length,t),this.length}get length(){if(this._sortData(),this._changedLength){let t=this._data[this._data.length-1];this._length=t?t[0]+1:0,this._changedLength=!1}return this._length}forEach(t){let e=0;for(;e<this.length;)t(this.get(e),e,this),e++}map(t){let e=0,n=new Array(this.length);for(;e<this.length;)n[e]=t(this.get(e),e,this),e++;return n}reduce(t,e){let n=0,o=e;for(;n<this.length;){let i=this.get(n);o=t(o,i,n),n++}return o}find(t){let e=0,n,o;for(;e<this.length&&!n;)o=this.get(e),n=t(o),e++;return n?o:void 0}_internalPositionFor(t,e){let n=this._bytePosFor(t,e);if(n>=this._bitArrays.length)return-1;let o=this._bitArrays[n],i=t-n*7;if(!((o&1<<i)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(yI,0),c=~(4294967295<<i+1),l=Rw(o&c);return a+l-1}_bytePosFor(t,e){let n=Math.floor(t/7),o=n+1;for(;!e&&this._bitArrays.length<o;)this._bitArrays.push(0);return n}_setBit(t){let e=this._bytePosFor(t,!1);this._bitArrays[e]|=1<<t-e*7}_unsetBit(t){let e=this._bytePosFor(t,!1);this._bitArrays[e]&=~(1<<t-e*7)}_setInternalPos(t,e,n,o){let i=this._data,s=[e,n];if(o)this._sortData(),i[t]=s;else{if(i.length)if(i[i.length-1][0]>=e)i.push(s);else if(i[0][0]<=e)i.unshift(s);else{let a=Math.round(i.length/2);this._data=i.slice(0,a).concat(s).concat(i.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(t){this._data.splice(t,1)}_sortData(){this._changedData&&this._data.sort(wI),this._changedData=!1}bitField(){let t=[],e=8,n=0,o=0,i,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(i=s.shift(),n=7);let c=Math.min(n,e),l=~(255<<c),u=i&l;o|=u<<8-e,i=i>>>c,n-=c,e-=c,(!e||!n&&!s.length)&&(t.push(o),o=0,e=8)}for(var a=t.length-1;a>0&&t[a]===0;a--)t.pop();return t}compactArray(){return this._sortData(),this._data.map(bI)}};function yI(r,t){return r+Rw(t)}function Rw(r){let t=r;return t=t-(t>>1&1431655765),t=(t&858993459)+(t>>2&858993459),(t+(t>>4)&252645135)*16843009>>24}function wI(r,t){return r[0]-t[0]}function bI(r){return r[1]}});var db=ge((J9,hb)=>{"use strict";hb.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:256,RTLD_LOCAL:0,RTLD_DEEPBIND:8,E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOPNOTSUPP:95,EOVERFLOW:75,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:17,SIGSTKFLT:16,SIGCONT:18,SIGSTOP:19,SIGTSTP:20,SIGTTIN:21,SIGTTOU:22,SIGURG:23,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:29,SIGPOLL:29,SIGPWR:30,SIGSYS:31,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,EXTENSIONLESS_FORMAT_JAVASCRIPT:0,EXTENSIONLESS_FORMAT_WASM:1,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:64,O_EXCL:128,UV_FS_O_FILEMAP:0,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_DIRECTORY:65536,O_NOATIME:262144,O_NOFOLLOW:131072,O_SYNC:1052672,O_DSYNC:4096,O_DIRECT:16384,O_NONBLOCK:2048,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:805306576,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var Uk={};vt(Uk,{createVerifiedFetch:()=>Ed,verifiedFetch:()=>ql});var Wo=Symbol.for("@libp2p/content-routing");function Cd(r){return r==null?!1:(r.type==="RSA"||r.type==="Ed25519"||r.type==="secp256k1")&&r.raw instanceof Uint8Array&&typeof r.equals=="function"&&typeof r.toMultihash=="function"&&typeof r.toCID=="function"&&typeof r.verify=="function"}var $n=Symbol.for("@libp2p/peer-id");var jo=Symbol.for("@libp2p/peer-routing");var Ne=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var gt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},zn=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var _t=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}};var Yo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Ae=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var pn=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var mt=(r,...t)=>{try{[...t]}catch{}};var qn=class extends EventTarget{#t=new Map;constructor(){super(),mt(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:i})=>i!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Rd(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Vr(...r){let t=[];for(let e of r)Rd(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Hr(...r){let t=[];for(let e of r)Rd(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}function Yt(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function ft(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var us=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Kn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new us(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new us(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Gl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function We(r={}){return zb(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function zb(r,t){t=t??{};let e=t.onEnd,n=new Kn,o,i,s,a=ft(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{i=x=>{i=null,n.push(x);try{y(r(n))}catch(b){g(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ft()})}},l=y=>i!=null?i(y):(n.push(y),o),u=y=>(n=new Kn,i!=null?i({error:y}):(n.push({error:y}),o)),f=y=>{if(s)return o;if(t?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},d=y=>s?o:(s=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new Kn,d(),{done:!0}),m=y=>(d(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:d,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,b;g!=null&&(x=new Promise((E,k)=>{b=()=>{k(new Gl)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},e==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(y){return p.throw(y),e!=null&&(e(y),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(y){return p.end(y),e!=null&&(e(y),e=void 0),o},get readableLength(){return p.readableLength},onEmpty:y=>p.onEmpty(y)},o}var Wl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function fs(r,t,e,n){let o=new Wl(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),s(d);return}a(),i(f)},l=f=>{a(),s(f.detail)},u=()=>{a(),s(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var hs=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Nd(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new hs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new hs(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}function qb(r){return r[Symbol.asyncIterator]!=null}function Kb(r){if(qb(r))return(async()=>{for await(let t of r);})();for(let t of r);}var ur=Kb;function re(r=0){return new Uint8Array(r)}function ne(r=0){return new Uint8Array(r)}var Gb=Math.pow(2,7),Wb=Math.pow(2,14),jb=Math.pow(2,21),jl=Math.pow(2,28),Yl=Math.pow(2,35),Xl=Math.pow(2,42),Zl=Math.pow(2,49),it=128,$t=127;function oe(r){if(r<Gb)return 1;if(r<Wb)return 2;if(r<jb)return 3;if(r<jl)return 4;if(r<Yl)return 5;if(r<Xl)return 6;if(r<Zl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Jl(r,t,e=0){switch(oe(r)){case 8:t[e++]=r&255|it,r/=128;case 7:t[e++]=r&255|it,r/=128;case 6:t[e++]=r&255|it,r/=128;case 5:t[e++]=r&255|it,r/=128;case 4:t[e++]=r&255|it,r>>>=7;case 3:t[e++]=r&255|it,r>>>=7;case 2:t[e++]=r&255|it,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Yb(r,t,e=0){switch(oe(r)){case 8:t.set(e++,r&255|it),r/=128;case 7:t.set(e++,r&255|it),r/=128;case 6:t.set(e++,r&255|it),r/=128;case 5:t.set(e++,r&255|it),r/=128;case 4:t.set(e++,r&255|it),r>>>=7;case 3:t.set(e++,r&255|it),r>>>=7;case 2:t.set(e++,r&255|it),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ql(r,t){let e=r[t],n=0;if(n+=e&$t,e<it||(e=r[t+1],n+=(e&$t)<<7,e<it)||(e=r[t+2],n+=(e&$t)<<14,e<it)||(e=r[t+3],n+=(e&$t)<<21,e<it)||(e=r[t+4],n+=(e&$t)*jl,e<it)||(e=r[t+5],n+=(e&$t)*Yl,e<it)||(e=r[t+6],n+=(e&$t)*Xl,e<it)||(e=r[t+7],n+=(e&$t)*Zl,e<it))return n;throw new RangeError("Could not decode varint")}function Xb(r,t){let e=r.get(t),n=0;if(n+=e&$t,e<it||(e=r.get(t+1),n+=(e&$t)<<7,e<it)||(e=r.get(t+2),n+=(e&$t)<<14,e<it)||(e=r.get(t+3),n+=(e&$t)<<21,e<it)||(e=r.get(t+4),n+=(e&$t)*jl,e<it)||(e=r.get(t+5),n+=(e&$t)*Yl,e<it)||(e=r.get(t+6),n+=(e&$t)*Xl,e<it)||(e=r.get(t+7),n+=(e&$t)*Zl,e<it))return n;throw new RangeError("Could not decode varint")}function Gn(r,t,e=0){return t==null&&(t=ne(oe(r))),t instanceof Uint8Array?Jl(r,t,e):Yb(r,t,e)}function mn(r,t=0){return r instanceof Uint8Array?Ql(r,t):Xb(r,t)}function ct(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=ne(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function Z(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Dd=Symbol.for("@achingbrain/uint8arraylist");function Pd(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function je(r){return!!r?.[Dd]}var fr=class r{bufs;length;[Dd]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(je(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(je(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Pd(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Pd(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(je(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return ct(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:ct(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),i=new r;return i.length=o,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(u){if(e===c){n.push(s);break}n.push(s.subarray(0,e-a));break}n.push(s)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!je(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let f=0;f<i;f++)s[f]=-1;for(let f=0;f<o;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Z(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,i)=>o+i.byteLength,0)),n.length=e,n}};function Zb(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Wn=Zb;function Jb(r){return r[Symbol.asyncIterator]!=null}function Qb(r,t){let e=0;if(Jb(r))return async function*(){for await(let c of r)yield t(c,e++)}();let n=Wn(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=t(o,e++);if(typeof s.then=="function")return async function*(){yield await s;for await(let c of n)yield t(c,e++)}();let a=t;return function*(){yield s;for(let c of n)yield a(c,e++)}()}var zt=Qb;function tx(r){return r[Symbol.asyncIterator]!=null}function ex(...r){let t=[];for(let e of r)tx(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=We({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var $r=ex;function Ye(r,...t){if(r==null)throw new Error("Empty pipeline");if(tu(r)){let n=r;r=()=>n.source}else if(Ud(r)||Od(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&tu(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)tu(e[n])&&(e[n]=nx(e[n]));return rx(...e)}var rx=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Od=r=>r?.[Symbol.asyncIterator]!=null,Ud=r=>r?.[Symbol.iterator]!=null,tu=r=>r==null?!1:r.sink!=null&&r.source!=null,nx=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=We({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Od(i))o=async function*(){yield*i,n.end()};else if(Ud(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return $r(n,o())}return r.source};function ox(r){return r[Symbol.asyncIterator]!=null}function ix(r,t){return ox(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var ds=ix;var H=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var eu=new Float32Array([-0]),zr=new Uint8Array(eu.buffer);function Fd(r,t,e){eu[0]=r,t[e]=zr[0],t[e+1]=zr[1],t[e+2]=zr[2],t[e+3]=zr[3]}function Md(r,t){return zr[0]=r[t],zr[1]=r[t+1],zr[2]=r[t+2],zr[3]=r[t+3],eu[0]}var ru=new Float64Array([-0]),qt=new Uint8Array(ru.buffer);function Vd(r,t,e){ru[0]=r,t[e]=qt[0],t[e+1]=qt[1],t[e+2]=qt[2],t[e+3]=qt[3],t[e+4]=qt[4],t[e+5]=qt[5],t[e+6]=qt[6],t[e+7]=qt[7]}function Hd(r,t){return qt[0]=r[t],qt[1]=r[t+1],qt[2]=r[t+2],qt[3]=r[t+3],qt[4]=r[t+4],qt[5]=r[t+5],qt[6]=r[t+6],qt[7]=r[t+7],ru[0]}var sx=BigInt(Number.MAX_SAFE_INTEGER),ax=BigInt(Number.MIN_SAFE_INTEGER),ye=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return gn;if(t<sx&&t>ax)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>$d&&(o=0n,++n>$d&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return gn;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):gn}},gn=new ye(0,0);gn.toBigInt=function(){return 0n};gn.zzEncode=gn.zzDecode=function(){return this};gn.length=function(){return 1};var $d=4294967296n;function zd(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function qd(r,t,e){if(e-t<1)return"";let o,i=[],s=0,a;for(;t<e;)a=r[t++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&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 nu(r,t,e){let n=e,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Le(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ps(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ou=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Le(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Le(this,4);return ps(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Le(this,4);return ps(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Le(this,4);let t=Md(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Le(this,4);let t=Hd(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Le(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return qd(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Le(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Le(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new ye(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Le(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Le(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Le(this,8);let t=ps(this.buf,this.pos+=4),e=ps(this.buf,this.pos+=4);return new ye(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ql(this.buf,this.pos);return this.pos+=oe(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function iu(r){return new ou(r instanceof Uint8Array?r:r.subarray())}function ie(r,t,e){let n=iu(r);return t.decode(n,void 0,e)}var du={};vt(du,{base10:()=>gx});var yn={};vt(yn,{coerce:()=>Ie,empty:()=>Gd,equals:()=>su,fromHex:()=>lx,fromString:()=>au,isBinary:()=>ux,toHex:()=>cx,toString:()=>cu});var Gd=new Uint8Array(0);function cx(r){return r.reduce((t,e)=>t+e.toString(16).padStart(2,"0"),"")}function lx(r){let t=r.match(/../g);return t!=null?new Uint8Array(t.map(e=>parseInt(e,16))):Gd}function su(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ie(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 ux(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function au(r){return new TextEncoder().encode(r)}function cu(r){return new TextDecoder().decode(r)}function fx(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(e[s]!==255)throw new TypeError(i+" is ambiguous");e[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 f(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var p=0,y=0,g=0,x=m.length;g!==x&&m[g]===0;)g++,p++;for(var b=(x-g)*u+1>>>0,E=new Uint8Array(b);g!==x;){for(var k=m[g],T=0,S=b-1;(k!==0||T<y)&&S!==-1;S--,T++)k+=256*E[S]>>>0,E[S]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");y=T,g++}for(var v=b-y;v!==b&&E[v]===0;)v++;for(var _=c.repeat(p);v<b;++v)_+=r.charAt(E[v]);return _}function d(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var p=0;if(m[p]!==" "){for(var y=0,g=0;m[p]===c;)y++,p++;for(var x=(m.length-p)*l+1>>>0,b=new Uint8Array(x);m[p];){var E=e[m.charCodeAt(p)];if(E===255)return;for(var k=0,T=x-1;(E!==0||k<g)&&T!==-1;T--,k++)E+=a*b[T]>>>0,b[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");g=k,p++}if(m[p]!==" "){for(var S=x-g;S!==x&&b[S]===0;)S++;for(var v=new Uint8Array(y+(x-S)),_=y;S!==x;)v[_++]=b[S++];return v}}}function h(m){var p=d(m);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var hx=fx,dx=hx,Wd=dx;var lu=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},uu=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return jd(this,t)}},fu=class{decoders;constructor(t){this.decoders=t}or(t){return jd(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function jd(r,t){return new fu({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var hu=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new lu(t,e,n),this.decoder=new uu(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function jn({name:r,prefix:t,encode:e,decode:n}){return new hu(r,t,e,n)}function qr({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Wd(e,r);return jn({prefix:t,name:r,encode:n,decode:i=>Ie(o(i))})}function px(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function mx(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>e;)s-=e,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<e-s]),n)for(;i.length*e&7;)i+="=";return i}function yt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return jn({prefix:t,name:r,encode(o){return mx(o,n,e)},decode(o){return px(o,n,e,r)}})}var gx=qr({prefix:"9",name:"base10",alphabet:"0123456789"});var pu={};vt(pu,{base16:()=>yx,base16upper:()=>wx});var yx=yt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wx=yt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var mu={};vt(mu,{base2:()=>bx});var bx=yt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var gu={};vt(gu,{base256emoji:()=>Ax});var Yd=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),xx=Yd.reduce((r,t,e)=>(r[e]=t,r),[]),Ex=Yd.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function vx(r){return r.reduce((t,e)=>(t+=xx[e],t),"")}function Sx(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Ex[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Ax=jn({prefix:"\u{1F680}",name:"base256emoji",encode:vx,decode:Sx});var yu={};vt(yu,{base32:()=>St,base32hex:()=>Bx,base32hexpad:()=>Cx,base32hexpadupper:()=>Rx,base32hexupper:()=>Tx,base32pad:()=>kx,base32padupper:()=>_x,base32upper:()=>Ix,base32z:()=>Nx});var St=yt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ix=yt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kx=yt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),_x=yt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Bx=yt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Tx=yt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cx=yt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Rx=yt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Nx=yt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var wu={};vt(wu,{base36:()=>Kt,base36upper:()=>Lx});var Kt=qr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Lx=qr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var bu={};vt(bu,{base58btc:()=>Y,base58flickr:()=>Px});var Y=qr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Px=qr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Eu={};vt(Eu,{base64:()=>se,base64pad:()=>Dx,base64url:()=>xu,base64urlpad:()=>Ox});var se=yt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Dx=yt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xu=yt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ox=yt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var vu={};vt(vu,{base8:()=>Ux});var Ux=yt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Su={};vt(Su,{identity:()=>Fx});var Fx=jn({prefix:"\0",name:"identity",encode:r=>cu(r),decode:r=>au(r)});var Yn={};vt(Yn,{code:()=>hr,decode:()=>Au,encode:()=>$x,name:()=>Hx});var Mx=new TextEncoder,Vx=new TextDecoder,Hx="json",hr=512;function $x(r){return Mx.encode(JSON.stringify(r))}function Au(r){return JSON.parse(Vx.decode(r))}var wn={};vt(wn,{code:()=>ae,decode:()=>Kx,encode:()=>qx,name:()=>zx});var zx="raw",ae=85;function qx(r){return Ie(r)}function Kx(r){return Ie(r)}var ku={};vt(ku,{identity:()=>bt});var Gx=Jd,Xd=128,Wx=127,jx=~Wx,Yx=Math.pow(2,31);function Jd(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Yx;)t[e++]=r&255|Xd,r/=128;for(;r&jx;)t[e++]=r&255|Xd,r>>>=7;return t[e]=r|0,Jd.bytes=e-n+1,t}var Xx=Iu,Zx=128,Zd=127;function Iu(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Iu.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&Zd)<<o:(s&Zd)*Math.pow(2,o),o+=7}while(s>=Zx);return Iu.bytes=i-n,e}var Jx=Math.pow(2,7),Qx=Math.pow(2,14),t1=Math.pow(2,21),e1=Math.pow(2,28),r1=Math.pow(2,35),n1=Math.pow(2,42),o1=Math.pow(2,49),i1=Math.pow(2,56),s1=Math.pow(2,63),a1=function(r){return r<Jx?1:r<Qx?2:r<t1?3:r<e1?4:r<r1?5:r<n1?6:r<o1?7:r<i1?8:r<s1?9:10},c1={encode:Gx,decode:Xx,encodingLength:a1},l1=c1,Xo=l1;function Zo(r,t=0){return[Xo.decode(r,t),Xo.decode.bytes]}function Xn(r,t,e=0){return Xo.encode(r,t,e),t}function Zn(r){return Xo.encodingLength(r)}function Pe(r,t){let e=t.byteLength,n=Zn(r),o=n+Zn(e),i=new Uint8Array(o+e);return Xn(r,i,0),Xn(e,i,n),i.set(t,o),new Jn(r,e,t,i)}function wt(r){let t=Ie(r),[e,n]=Zo(t),[o,i]=Zo(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Jn(e,o,s,t)}function Qd(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&su(r.bytes,e.bytes)}}var Jn=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var tp=0,u1="identity",ep=Ie;function f1(r){return Pe(tp,ep(r))}var bt={code:tp,name:u1,encode:ep,digest:f1};var Bu={};vt(Bu,{sha256:()=>Xe,sha512:()=>gs});function bn({name:r,code:t,encode:e}){return new _u(r,t,e)}var _u=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Pe(this.code,e):e.then(n=>Pe(this.code,n))}else throw Error("Unknown type, must be binary type")}};function np(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Xe=bn({name:"sha2-256",code:18,encode:np("SHA-256")}),gs=bn({name:"sha2-512",code:19,encode:np("SHA-512")});function op(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return d1(e,Tu(r),t??Y.encoder);default:return p1(e,Tu(r),t??St.encoder)}}var ip=new WeakMap;function Tu(r){let t=ip.get(r);if(t==null){let e=new Map;return ip.set(r,e),e}return t}var L=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Jo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==m1)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Pe(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Qd(t.multihash,n.multihash)}toString(t){return op(this,t)}toJSON(){return{"/":op(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:i,bytes:s}=e;return new r(n,o,i,s??sp(n,o,i.bytes))}else if(e[g1]===!0){let{version:n,multihash:o,code:i}=e,s=wt(o);return r.create(n,i,s)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Jo)throw new Error(`Version 0 CID must use dag-pb (code: ${Jo}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=sp(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Jo,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ie(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new Jn(e.multihashCode,e.digestSize,i,o);return[e.version===0?r.createV0(s):r.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=Zo(t.subarray(e));return e+=d,f},o=n(),i=Jo;if(o===18?(o=0,e=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=e,a=n(),c=n(),l=e+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=h1(t,e),i=r.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Tu(i).set(n,t),i}};function h1(r,t){switch(r[0]){case"Q":{let e=t??Y;return[Y.prefix,e.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let e=t??Y;return[Y.prefix,e.decode(r)]}case St.prefix:{let e=t??St;return[St.prefix,e.decode(r)]}case Kt.prefix:{let e=t??Kt;return[Kt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function d1(r,t,e){let{prefix:n}=e;if(n!==Y.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return o}function p1(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let i=e.encode(r);return t.set(n,i),i}else return o}var Jo=112,m1=18;function sp(r,t,e){let n=Zn(r),o=n+Zn(t),i=new Uint8Array(o+e.byteLength);return Xn(r,i,0),Xn(t,i,n),i.set(e,o),i}var g1=Symbol.for("@ipld/js-cid/CID");var Qo={...Su,...mu,...vu,...du,...pu,...yu,...wu,...bu,...Eu,...gu},m_={...Bu,...ku};function cp(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ap=cp("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Cu=cp("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=ne(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),y1={utf8:ap,"utf-8":ap,hex:Qo.base16,latin1:Cu,ascii:Cu,binary:Cu,...Qo},ys=y1;function D(r,t="utf8"){let e=ys[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Ru(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return ne(s);o+s>t&&(n=ne(t),o=0);let a=n.subarray(o,o+=s);return o&7&&(o=(o|7)+1),a}}var xn=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Nu(){}var Pu=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},w1=Ru();function b1(r){return globalThis.Buffer!=null?ne(r):w1(r)}var ei=class{len;head;tail;states;constructor(){this.len=0,this.head=new xn(Nu,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new xn(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Du((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ws,10,ye.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=ye.fromBigInt(t);return this._push(ws,e.length(),e)}uint64Number(t){return this._push(Jl,oe(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=ye.fromBigInt(t).zzEncode();return this._push(ws,e.length(),e)}sint64Number(t){let e=ye.fromNumber(t).zzEncode();return this._push(ws,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Lu,1,t?1:0)}fixed32(t){return this._push(ti,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=ye.fromBigInt(t);return this._push(ti,4,e.lo)._push(ti,4,e.hi)}fixed64Number(t){let e=ye.fromNumber(t);return this._push(ti,4,e.lo)._push(ti,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Fd,4,t)}double(t){return this._push(Vd,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Lu,1,0):this.uint32(e)._push(E1,e,t)}string(t){let e=zd(t);return e!==0?this.uint32(e)._push(nu,e,t):this._push(Lu,1,0)}fork(){return this.states=new Pu(this),this.head=this.tail=new xn(Nu,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 xn(Nu,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=b1(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Lu(r,t,e){t[e]=r&255}function x1(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Du=class extends xn{next;constructor(t,e){super(x1,t,e),this.next=void 0}};function ws(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function ti(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function E1(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(ei.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(v1,t,r),this},ei.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(S1,t,r),this});function v1(r,t,e){t.set(r,e)}function S1(r,t,e){r.length<40?nu(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(D(r),e)}function Ou(){return new ei}function ce(r,t){let e=Ou();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Qn;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Qn||(Qn={}));function bs(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function dr(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,s){let a=t(i);s.int32(a)},n=function(i){let s=i.int32();return t(s)};return bs("enum",Qn.VARINT,e,n)}function le(r,t){return bs("message",Qn.LENGTH_DELIMITED,r,t)}function lp(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function A1(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function to(r,...t){if(!A1(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function up(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");lp(r.outputLen),lp(r.blockLen)}function eo(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function fp(r,t){to(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var En=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var xs=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),De=(r,t)=>r<<32-t|r>>>t;var Y_=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hp(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function ri(r){return typeof r=="string"&&(r=hp(r)),to(r),r}function Uu(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];to(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}var ro=class{clone(){return this._cloneInto()}},X_={}.toString;function Es(r){let t=n=>r().update(ri(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function no(r=32){if(En&&typeof En.getRandomValues=="function")return En.getRandomValues(new Uint8Array(r));if(En&&typeof En.randomBytes=="function")return En.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function I1(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(e>>o&i),a=Number(e&i),c=n?4:0,l=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+l,a,n)}var dp=(r,t,e)=>r&t^~r&e,pp=(r,t,e)=>r&t^r&e^t&e,oo=class extends ro{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=xs(this.buffer)}update(t){eo(this);let{view:e,buffer:n,blockLen:o}=this;t=ri(t);let i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=xs(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){eo(this),fp(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;I1(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=xs(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.length=o,t.pos=a,t.finished=i,t.destroyed=s,o%e&&t.buffer.set(n),t}};var vs=BigInt(4294967295),Fu=BigInt(32);function mp(r,t=!1){return t?{h:Number(r&vs),l:Number(r>>Fu&vs)}:{h:Number(r>>Fu&vs)|0,l:Number(r&vs)|0}}function k1(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=mp(r[o],t);[e[o],n[o]]=[i,s]}return[e,n]}var _1=(r,t)=>BigInt(r>>>0)<<Fu|BigInt(t>>>0),B1=(r,t,e)=>r>>>e,T1=(r,t,e)=>r<<32-e|t>>>e,C1=(r,t,e)=>r>>>e|t<<32-e,R1=(r,t,e)=>r<<32-e|t>>>e,N1=(r,t,e)=>r<<64-e|t>>>e-32,L1=(r,t,e)=>r>>>e-32|t<<64-e,P1=(r,t)=>t,D1=(r,t)=>r,O1=(r,t,e)=>r<<e|t>>>32-e,U1=(r,t,e)=>t<<e|r>>>32-e,F1=(r,t,e)=>t<<e-32|r>>>64-e,M1=(r,t,e)=>r<<e-32|t>>>64-e;function V1(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var H1=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),$1=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,z1=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),q1=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,K1=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),G1=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var W1={fromBig:mp,split:k1,toBig:_1,shrSH:B1,shrSL:T1,rotrSH:C1,rotrSL:R1,rotrBH:N1,rotrBL:L1,rotr32H:P1,rotr32L:D1,rotlSH:O1,rotlSL:U1,rotlBH:F1,rotlBL:M1,add:V1,add3L:H1,add3H:$1,add4L:z1,add4H:q1,add5H:G1,add5L:K1},j=W1;var[j1,Y1]=j.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Kr=new Uint32Array(80),Gr=new Uint32Array(80),Mu=class extends oo{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:m,Hh:p,Hl:y}=this;return[t,e,n,o,i,s,a,c,l,u,f,d,h,m,p,y]}set(t,e,n,o,i,s,a,c,l,u,f,d,h,m,p,y){this.Ah=t|0,this.Al=e|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=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=p|0,this.Hl=y|0}process(t,e){for(let b=0;b<16;b++,e+=4)Kr[b]=t.getUint32(e),Gr[b]=t.getUint32(e+=4);for(let b=16;b<80;b++){let E=Kr[b-15]|0,k=Gr[b-15]|0,T=j.rotrSH(E,k,1)^j.rotrSH(E,k,8)^j.shrSH(E,k,7),S=j.rotrSL(E,k,1)^j.rotrSL(E,k,8)^j.shrSL(E,k,7),v=Kr[b-2]|0,_=Gr[b-2]|0,z=j.rotrSH(v,_,19)^j.rotrBH(v,_,61)^j.shrSH(v,_,6),F=j.rotrSL(v,_,19)^j.rotrBL(v,_,61)^j.shrSL(v,_,6),U=j.add4L(S,F,Gr[b-7],Gr[b-16]),P=j.add4H(U,T,z,Kr[b-7],Kr[b-16]);Kr[b]=P|0,Gr[b]=U|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:m,Gh:p,Gl:y,Hh:g,Hl:x}=this;for(let b=0;b<80;b++){let E=j.rotrSH(f,d,14)^j.rotrSH(f,d,18)^j.rotrBH(f,d,41),k=j.rotrSL(f,d,14)^j.rotrSL(f,d,18)^j.rotrBL(f,d,41),T=f&h^~f&p,S=d&m^~d&y,v=j.add5L(x,k,S,Y1[b],Gr[b]),_=j.add5H(v,g,E,T,j1[b],Kr[b]),z=v|0,F=j.rotrSH(n,o,28)^j.rotrBH(n,o,34)^j.rotrBH(n,o,39),U=j.rotrSL(n,o,28)^j.rotrBL(n,o,34)^j.rotrBL(n,o,39),P=n&i^n&a^i&a,R=o&s^o&c^s&c;g=p|0,x=y|0,p=h|0,y=m|0,h=f|0,m=d|0,{h:f,l:d}=j.add(l|0,u|0,_|0,z|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let N=j.add3L(z,U,R);n=j.add3H(N,_,F,P),o=N|0}({h:n,l:o}=j.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=j.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=j.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=j.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=j.add(this.Eh|0,this.El|0,f|0,d|0),{h,l:m}=j.add(this.Fh|0,this.Fl|0,h|0,m|0),{h:p,l:y}=j.add(this.Gh|0,this.Gl|0,p|0,y|0),{h:g,l:x}=j.add(this.Hh|0,this.Hl|0,g|0,x|0),this.set(n,o,i,s,a,c,l,u,f,d,h,m,p,y,g,x)}roundClean(){Kr.fill(0),Gr.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var gp=Es(()=>new Mu);var As={};vt(As,{aInRange:()=>ue,abool:()=>Oe,abytes:()=>io,bitGet:()=>eE,bitLen:()=>qu,bitMask:()=>oi,bitSet:()=>rE,bytesToHex:()=>mr,bytesToNumberBE:()=>gr,bytesToNumberLE:()=>jr,concatBytes:()=>yr,createHmacDrbg:()=>Ku,ensureBytes:()=>xt,equalBytes:()=>Q1,hexToBytes:()=>Sn,hexToNumber:()=>zu,inRange:()=>ni,isBytes:()=>Wr,memoized:()=>In,notImplemented:()=>oE,numberToBytesBE:()=>Yr,numberToBytesLE:()=>An,numberToHexUnpadded:()=>vn,numberToVarBytesBE:()=>J1,utf8ToBytes:()=>tE,validateObject:()=>Ze});var $u=BigInt(0),Ss=BigInt(1),X1=BigInt(2);function Wr(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function io(r){if(!Wr(r))throw new Error("Uint8Array expected")}function Oe(r,t){if(typeof t!="boolean")throw new Error(`${r} must be valid boolean, got "${t}".`)}var Z1=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function mr(r){io(r);let t="";for(let e=0;e<r.length;e++)t+=Z1[r[e]];return t}function vn(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function zu(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var pr={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function yp(r){if(r>=pr._0&&r<=pr._9)return r-pr._0;if(r>=pr._A&&r<=pr._F)return r-(pr._A-10);if(r>=pr._a&&r<=pr._f)return r-(pr._a-10)}function Sn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,i=0;o<e;o++,i+=2){let s=yp(r.charCodeAt(i)),a=yp(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function gr(r){return zu(mr(r))}function jr(r){return io(r),zu(mr(Uint8Array.from(r).reverse()))}function Yr(r,t){return Sn(r.toString(16).padStart(t*2,"0"))}function An(r,t){return Yr(r,t).reverse()}function J1(r){return Sn(vn(r))}function xt(r,t,e){let n;if(typeof t=="string")try{n=Sn(t)}catch(i){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${i}`)}else if(Wr(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function yr(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];io(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}function Q1(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function tE(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Vu=r=>typeof r=="bigint"&&$u<=r;function ni(r,t,e){return Vu(r)&&Vu(t)&&Vu(e)&&t<=r&&r<e}function ue(r,t,e,n){if(!ni(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function qu(r){let t;for(t=0;r>$u;r>>=Ss,t+=1);return t}function eE(r,t){return r>>BigInt(t)&Ss}function rE(r,t,e){return r|(e?Ss:$u)<<BigInt(t)}var oi=r=>(X1<<BigInt(r-1))-Ss,Hu=r=>new Uint8Array(r),wp=r=>Uint8Array.from(r);function Ku(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Hu(r),o=Hu(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>e(o,n,...f),c=(f=Hu())=>{o=a(wp([0]),f),n=a(),f.length!==0&&(o=a(wp([1]),f),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let h=n.slice();d.push(h),f+=n.length}return yr(...d)};return(f,d)=>{s(),c(f);let h;for(;!(h=d(l()));)c();return s(),h}}var nE={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Wr(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Ze(r,t,e={}){let n=(o,i,s)=>{let a=nE[i];if(typeof a!="function")throw new Error(`Invalid validator "${i}", expected function`);let c=r[o];if(!(s&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${i}`)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(e))n(o,i,!0);return r}var oE=()=>{throw new Error("not implemented")};function In(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let i=r(e,...n);return t.set(e,i),i}}var Bt=BigInt(0),ht=BigInt(1),kn=BigInt(2),iE=BigInt(3),Gu=BigInt(4),bp=BigInt(5),xp=BigInt(8),sE=BigInt(9),aE=BigInt(16);function at(r,t){let e=r%t;return e>=Bt?e:t+e}function cE(r,t,e){if(e<=Bt||t<Bt)throw new Error("Expected power/modulo > 0");if(e===ht)return Bt;let n=ht;for(;t>Bt;)t&ht&&(n=n*r%e),r=r*r%e,t>>=ht;return n}function dt(r,t,e){let n=r;for(;t-- >Bt;)n*=n,n%=e;return n}function Is(r,t){if(r===Bt||t<=Bt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=at(r,t),n=t,o=Bt,i=ht,s=ht,a=Bt;for(;e!==Bt;){let l=n/e,u=n%e,f=o-s*l,d=i-a*l;n=e,e=u,o=s,i=a,s=f,a=d}if(n!==ht)throw new Error("invert: does not exist");return at(o,t)}function lE(r){let t=(r-ht)/kn,e,n,o;for(e=r-ht,n=0;e%kn===Bt;e/=kn,n++);for(o=kn;o<r&&cE(o,t,r)!==r-ht;o++);if(n===1){let s=(r+ht)/Gu;return function(c,l){let u=c.pow(l,s);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let i=(e+ht)/kn;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,i),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let p=a.sqr(d);h<l&&!a.eql(p,a.ONE);h++)p=a.sqr(p);let m=a.pow(u,ht<<BigInt(l-h-1));u=a.sqr(m),f=a.mul(f,m),d=a.mul(d,u),l=h}return f}}function uE(r){if(r%Gu===iE){let t=(r+ht)/Gu;return function(n,o){let i=n.pow(o,t);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%xp===bp){let t=(r-bp)/xp;return function(n,o){let i=n.mul(o,kn),s=n.pow(i,t),a=n.mul(o,s),c=n.mul(n.mul(a,kn),s),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%aE,lE(r)}var Ep=(r,t)=>(at(r,t)&ht)===ht,fE=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Wu(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=fE.reduce((n,o)=>(n[o]="function",n),t);return Ze(r,e)}function hE(r,t,e){if(e<Bt)throw new Error("Expected power > 0");if(e===Bt)return r.ONE;if(e===ht)return t;let n=r.ONE,o=t;for(;e>Bt;)e&ht&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ht;return n}function dE(r,t){let e=new Array(t.length),n=t.reduce((i,s,a)=>r.is0(s)?i:(e[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return t.reduceRight((i,s,a)=>r.is0(s)?i:(e[a]=r.mul(i,e[a]),r.mul(i,s)),o),e}function ju(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Xr(r,t,e=!1,n={}){if(r<=Bt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:i}=ju(r,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=uE(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:i,MASK:oi(o),ZERO:Bt,ONE:ht,create:c=>at(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Bt<=c&&c<r},is0:c=>c===Bt,isOdd:c=>(c&ht)===ht,neg:c=>at(-c,r),eql:(c,l)=>c===l,sqr:c=>at(c*c,r),add:(c,l)=>at(c+l,r),sub:(c,l)=>at(c-l,r),mul:(c,l)=>at(c*l,r),pow:(c,l)=>hE(a,c,l),div:(c,l)=>at(c*Is(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Is(c,r),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>dE(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?An(c,i):Yr(c,i),fromBytes:c=>{if(c.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);return e?jr(c):gr(c)}});return Object.freeze(a)}function vp(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Yu(r){let t=vp(r);return t+Math.ceil(t/2)}function Sp(r,t,e=!1){let n=r.length,o=vp(t),i=Yu(t);if(n<16||n<i||n>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);let s=e?gr(r):jr(r),a=at(s,t-ht)+ht;return e?An(a,o):Yr(a,o)}var mE=BigInt(0),Xu=BigInt(1),Zu=new WeakMap,Ap=new WeakMap;function ks(r,t){let e=(i,s)=>{let a=s.negate();return i?a:s},n=i=>{if(!Number.isSafeInteger(i)||i<=0||i>t)throw new Error(`Wrong window size=${i}, should be [1..${t}]`)},o=i=>{n(i);let s=Math.ceil(t/i)+1,a=2**(i-1);return{windows:s,windowSize:a}};return{constTimeNegate:e,unsafeLadder(i,s){let a=r.ZERO,c=i;for(;s>mE;)s&Xu&&(a=a.add(c)),c=c.double(),s>>=Xu;return a},precomputeWindow(i,s){let{windows:a,windowSize:c}=o(s),l=[],u=i,f=u;for(let d=0;d<a;d++){f=u,l.push(f);for(let h=1;h<c;h++)f=f.add(u),l.push(f);u=f.double()}return l},wNAF(i,s,a){let{windows:c,windowSize:l}=o(i),u=r.ZERO,f=r.BASE,d=BigInt(2**i-1),h=2**i,m=BigInt(i);for(let p=0;p<c;p++){let y=p*l,g=Number(a&d);a>>=m,g>l&&(g-=h,a+=Xu);let x=y,b=y+Math.abs(g)-1,E=p%2!==0,k=g<0;g===0?f=f.add(e(E,s[x])):u=u.add(e(k,s[b]))}return{p:u,f}},wNAFCached(i,s,a){let c=Ap.get(i)||1,l=Zu.get(i);return l||(l=this.precomputeWindow(i,c),c!==1&&Zu.set(i,a(l))),this.wNAF(c,l,s)},setWindowSize(i,s){n(s),Ap.set(i,s),Zu.delete(i)}}}function _s(r,t,e,n){if(!Array.isArray(e)||!Array.isArray(n)||n.length!==e.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((u,f)=>{if(!t.isValid(u))throw new Error(`wrong scalar at index ${f}`)}),e.forEach((u,f)=>{if(!(u instanceof r))throw new Error(`wrong point at index ${f}`)});let o=qu(BigInt(e.length)),i=o>12?o-3:o>4?o-2:o?2:1,s=(1<<i)-1,a=new Array(s+1).fill(r.ZERO),c=Math.floor((t.BITS-1)/i)*i,l=r.ZERO;for(let u=c;u>=0;u-=i){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],m=Number(h>>BigInt(u)&BigInt(s));a[m]=a[m].add(e[d])}let f=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),f=f.add(h);if(l=l.add(f),u!==0)for(let d=0;d<i;d++)l=l.double()}return l}function ii(r){return Wu(r.Fp),Ze(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ju(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Ue=BigInt(0),fe=BigInt(1),Bs=BigInt(2),gE=BigInt(8),yE={zip215:!0};function wE(r){let t=ii(r);return Ze(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Ip(r){let t=wE(r),{Fp:e,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=Bs<<BigInt(a*8)-fe,u=e.create,f=Xr(t.n,t.nBitLength),d=t.uvRatio||((I,A)=>{try{return{isValid:!0,value:e.sqrt(I*e.inv(A))}}catch{return{isValid:!1,value:Ue}}}),h=t.adjustScalarBytes||(I=>I),m=t.domain||((I,A,C)=>{if(Oe("phflag",C),A.length||C)throw new Error("Contexts/pre-hash are not supported");return I});function p(I,A){ue("coordinate "+I,A,Ue,l)}function y(I){if(!(I instanceof b))throw new Error("ExtendedPoint expected")}let g=In((I,A)=>{let{ex:C,ey:V,ez:K}=I,G=I.is0();A==null&&(A=G?gE:e.inv(K));let J=u(C*A),et=u(V*A),Q=u(K*A);if(G)return{x:Ue,y:fe};if(Q!==fe)throw new Error("invZ was invalid");return{x:J,y:et}}),x=In(I=>{let{a:A,d:C}=t;if(I.is0())throw new Error("bad point: ZERO");let{ex:V,ey:K,ez:G,et:J}=I,et=u(V*V),Q=u(K*K),st=u(G*G),lt=u(st*st),Rt=u(et*A),Nt=u(st*u(Rt+Q)),Dt=u(lt+u(C*u(et*Q)));if(Nt!==Dt)throw new Error("bad point: equation left != right (1)");let jt=u(V*K),kt=u(G*J);if(jt!==kt)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(A,C,V,K){this.ex=A,this.ey=C,this.ez=V,this.et=K,p("x",A),p("y",C),p("z",V),p("t",K),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof b)throw new Error("extended point not allowed");let{x:C,y:V}=A||{};return p("x",C),p("y",V),new b(C,V,fe,u(C*V))}static normalizeZ(A){let C=e.invertBatch(A.map(V=>V.ez));return A.map((V,K)=>V.toAffine(C[K])).map(b.fromAffine)}static msm(A,C){return _s(b,f,A,C)}_setWindowSize(A){T.setWindowSize(this,A)}assertValidity(){x(this)}equals(A){y(A);let{ex:C,ey:V,ez:K}=this,{ex:G,ey:J,ez:et}=A,Q=u(C*et),st=u(G*K),lt=u(V*et),Rt=u(J*K);return Q===st&<===Rt}is0(){return this.equals(b.ZERO)}negate(){return new b(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:A}=t,{ex:C,ey:V,ez:K}=this,G=u(C*C),J=u(V*V),et=u(Bs*u(K*K)),Q=u(A*G),st=C+V,lt=u(u(st*st)-G-J),Rt=Q+J,Nt=Rt-et,Dt=Q-J,jt=u(lt*Nt),kt=u(Rt*Dt),ee=u(lt*Dt),lr=u(Nt*Rt);return new b(jt,kt,lr,ee)}add(A){y(A);let{a:C,d:V}=t,{ex:K,ey:G,ez:J,et}=this,{ex:Q,ey:st,ez:lt,et:Rt}=A;if(C===BigInt(-1)){let vd=u((G-K)*(st+Q)),Sd=u((G+K)*(st-Q)),Kl=u(Sd-vd);if(Kl===Ue)return this.double();let Ad=u(J*Bs*Rt),Id=u(et*Bs*lt),kd=Id+Ad,_d=Sd+vd,Bd=Id-Ad,Lb=u(kd*Kl),Pb=u(_d*Bd),Db=u(kd*Bd),Ob=u(Kl*_d);return new b(Lb,Pb,Ob,Db)}let Nt=u(K*Q),Dt=u(G*st),jt=u(et*V*Rt),kt=u(J*lt),ee=u((K+G)*(Q+st)-Nt-Dt),lr=kt-jt,Ko=kt+jt,Go=u(Dt-C*Nt),Tb=u(ee*lr),Cb=u(Ko*Go),Rb=u(ee*Go),Nb=u(lr*Ko);return new b(Tb,Cb,Nb,Rb)}subtract(A){return this.add(A.negate())}wNAF(A){return T.wNAFCached(this,A,b.normalizeZ)}multiply(A){let C=A;ue("scalar",C,fe,n);let{p:V,f:K}=this.wNAF(C);return b.normalizeZ([V,K])[0]}multiplyUnsafe(A){let C=A;return ue("scalar",C,Ue,n),C===Ue?k:this.equals(k)||C===fe?this:this.equals(E)?this.wNAF(C).p:T.unsafeLadder(this,C)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,n).is0()}toAffine(A){return g(this,A)}clearCofactor(){let{h:A}=t;return A===fe?this:this.multiplyUnsafe(A)}static fromHex(A,C=!1){let{d:V,a:K}=t,G=e.BYTES;A=xt("pointHex",A,G),Oe("zip215",C);let J=A.slice(),et=A[G-1];J[G-1]=et&-129;let Q=jr(J),st=C?l:e.ORDER;ue("pointHex.y",Q,Ue,st);let lt=u(Q*Q),Rt=u(lt-fe),Nt=u(V*lt-K),{isValid:Dt,value:jt}=d(Rt,Nt);if(!Dt)throw new Error("Point.fromHex: invalid y coordinate");let kt=(jt&fe)===fe,ee=(et&128)!==0;if(!C&&jt===Ue&&ee)throw new Error("Point.fromHex: x=0 and x_0=1");return ee!==kt&&(jt=u(-jt)),b.fromAffine({x:jt,y:Q})}static fromPrivateKey(A){return _(A).point}toRawBytes(){let{x:A,y:C}=this.toAffine(),V=An(C,e.BYTES);return V[V.length-1]|=A&fe?128:0,V}toHex(){return mr(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,fe,u(t.Gx*t.Gy)),b.ZERO=new b(Ue,fe,fe,Ue);let{BASE:E,ZERO:k}=b,T=ks(b,a*8);function S(I){return at(I,n)}function v(I){return S(jr(I))}function _(I){let A=a;I=xt("private key",I,A);let C=xt("hashed private key",i(I),2*A),V=h(C.slice(0,A)),K=C.slice(A,2*A),G=v(V),J=E.multiply(G),et=J.toRawBytes();return{head:V,prefix:K,scalar:G,point:J,pointBytes:et}}function z(I){return _(I).pointBytes}function F(I=new Uint8Array,...A){let C=yr(...A);return v(i(m(C,xt("context",I),!!o)))}function U(I,A,C={}){I=xt("message",I),o&&(I=o(I));let{prefix:V,scalar:K,pointBytes:G}=_(A),J=F(C.context,V,I),et=E.multiply(J).toRawBytes(),Q=F(C.context,et,G,I),st=S(J+Q*K);ue("signature.s",st,Ue,n);let lt=yr(et,An(st,e.BYTES));return xt("result",lt,a*2)}let P=yE;function R(I,A,C,V=P){let{context:K,zip215:G}=V,J=e.BYTES;I=xt("signature",I,2*J),A=xt("message",A),G!==void 0&&Oe("zip215",G),o&&(A=o(A));let et=jr(I.slice(J,2*J)),Q,st,lt;try{Q=b.fromHex(C,G),st=b.fromHex(I.slice(0,J),G),lt=E.multiplyUnsafe(et)}catch{return!1}if(!G&&Q.isSmallOrder())return!1;let Rt=F(K,st.toRawBytes(),Q.toRawBytes(),A);return st.add(Q.multiplyUnsafe(Rt)).subtract(lt).clearCofactor().equals(b.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:z,sign:U,verify:R,ExtendedPoint:b,utils:{getExtendedPublicKey:_,randomPrivateKey:()=>s(e.BYTES),precompute(I=8,A=b.BASE){return A._setWindowSize(I),A.multiply(BigInt(3)),A}}}}var Ju=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),kp=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),bB=BigInt(0),bE=BigInt(1),_p=BigInt(2),xB=BigInt(3),xE=BigInt(5),EE=BigInt(8);function vE(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=Ju,a=r*r%i*r%i,c=dt(a,_p,i)*a%i,l=dt(c,bE,i)*r%i,u=dt(l,xE,i)*l%i,f=dt(u,t,i)*u%i,d=dt(f,e,i)*f%i,h=dt(d,n,i)*d%i,m=dt(h,o,i)*h%i,p=dt(m,o,i)*h%i,y=dt(p,t,i)*u%i;return{pow_p_5_8:dt(y,_p,i)*r%i,b2:a}}function SE(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function AE(r,t){let e=Ju,n=at(t*t*t,e),o=at(n*n*t,e),i=vE(r*o).pow_p_5_8,s=at(r*n*i,e),a=at(t*s*s,e),c=s,l=at(s*kp,e),u=a===r,f=a===at(-r,e),d=a===at(-r*kp,e);return u&&(s=c),(f||d)&&(s=l),Ep(s,e)&&(s=at(-s,e)),{isValid:u||f,value:s}}var IE=Xr(Ju,void 0,!0),kE={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:IE,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:EE,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gp,randomBytes:no,adjustScalarBytes:SE,uvRatio:AE},Bp=Ip(kE);var Ts=32;function Tp(r,t,e){return Bp.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var Cs=class{type="Ed25519";raw;constructor(t){this.raw=Qu(t,Ts)}toMultihash(){return bt.digest(so(this))}toCID(){return L.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}verify(t,e){return Tp(this.raw,e,t)}};function tf(r){return r=Qu(r,Ts),new Cs(r)}function Qu(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new gt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Tt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(Tt||(Tt={}));var ef;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(ef||(ef={}));(function(r){r.codec=()=>dr(ef)})(Tt||(Tt={}));var Je;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),Tt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=Tt.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>ce(e,r.codec()),r.decode=(e,n)=>ie(e,r.codec(),n)})(Je||(Je={}));var rf;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),Tt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=Tt.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>ce(e,r.codec()),r.decode=(e,n)=>ie(e,r.codec(),n)})(rf||(rf={}));var mi={};vt(mi,{MAX_RSA_KEY_SIZE:()=>va,generateRSAKeyPair:()=>_m,jwkToJWKKeyPair:()=>Bm,jwkToPkcs1:()=>zE,jwkToPkix:()=>hf,jwkToRSAPrivateKey:()=>km,pkcs1ToJwk:()=>Sm,pkcs1ToRSAPrivateKey:()=>Im,pkixToJwk:()=>Am,pkixToRSAPublicKey:()=>df});var BE=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Zr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jr=new Uint32Array(64),nf=class extends oo{constructor(){super(64,32,8,!1),this.A=Zr[0]|0,this.B=Zr[1]|0,this.C=Zr[2]|0,this.D=Zr[3]|0,this.E=Zr[4]|0,this.F=Zr[5]|0,this.G=Zr[6]|0,this.H=Zr[7]|0}get(){let{A:t,B:e,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,e,n,o,i,s,a,c]}set(t,e,n,o,i,s,a,c){this.A=t|0,this.B=e|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(t,e){for(let f=0;f<16;f++,e+=4)Jr[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Jr[f-15],h=Jr[f-2],m=De(d,7)^De(d,18)^d>>>3,p=De(h,17)^De(h,19)^h>>>10;Jr[f]=p+Jr[f-7]+m+Jr[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=De(a,6)^De(a,11)^De(a,25),h=u+d+dp(a,c,l)+BE[f]+Jr[f]|0,p=(De(n,2)^De(n,13)^De(n,22))+pp(n,o,i)|0;u=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+p|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(){Jr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ao=Es(()=>new nf);var tt=Ot(Np());function _n(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function Qr(r,t,e=-1){let n=e,o=r,i=0,s=Math.pow(2,t);for(let a=1;a<8;a++){if(r<s){let c;if(n<0)c=new ArrayBuffer(a),i=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*t);l[i-u-1]=Math.floor(o/f),o-=l[i-u-1]*f}return c}s*=Math.pow(2,t)}return new ArrayBuffer(0)}function Ls(...r){let t=0,e=0;for(let i of r)t+=i.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let i of r)o.set(i,e),e+=i.length;return o}function sf(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=_n(e,8),o=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=r[a];return i[0]&=127,_n(i,8)-n}function Lp(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let s=e-t,a=Qr(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Qr(t,8,n),i=new Uint8Array(o);if(i[0]&128){let s=o.slice(0),a=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),i=new Uint8Array(o);for(let c=0;c<s.byteLength;c++)i[c+1]=a[c];i[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function Pp(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function he(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(e)}var zB=Math.log(2);function Ps(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function af(r){let t=0,e=0;for(let o=0;o<r.length;o++){let i=r[o];t+=i.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let i=r[o];n.set(new Uint8Array(i),e),e+=i.byteLength}return n.buffer}function vr(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var ai=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return af(this.items)}},si=[new Uint8Array([1])],Dp="0123456789";var ho="",Fe=new ArrayBuffer(0),cf=new Uint8Array(0),ci="EndOfContent",Up="OCTET STRING",Fp="BIT STRING";function Sr(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let i=n[0]||{};this.isHexOnly=(o=i.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=i.valueHex?tt.BufferSourceConverter.toUint8Array(i.valueHex):cf}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,i){let s=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!vr(this,s,o,i))return-1;let a=o+i;return this.valueHexView=s.subarray(o,a),this.valueHexView.length?(this.blockLength=i,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Fe)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:tt.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var br=class{constructor({blockLength:t=0,error:e=ho,warnings:n=[],valueBeforeDecode:o=cf}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=tt.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:tt.Convert.ToHex(this.valueBeforeDecodeView)}}};br.NAME="baseBlock";var Gt=class extends br{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Gt.NAME="valueBlock";var Ds=class extends Sr(br){constructor({idBlock:t={}}={}){var e,n,o,i;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?tt.BufferSourceConverter.toUint8Array(t.valueHex):cf,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(i=t.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",Fe}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let i=this.tagNumber;i&=31,e|=i,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=Qr(this.tagNumber,7),i=new Uint8Array(o),s=o.byteLength,a=new Uint8Array(s+1);if(a[0]=e|31,!t){for(let c=0;c<s-1;c++)a[c+1]=i[c]|128;a[s]=i[s-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let i=0;i<o.length-1;i++)n[i+1]=o[i]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;i[c]&128;){if(l[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let h=0;h<l.length;h++)d[h]=l[h];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=i[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=_n(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Ds.NAME="identificationBlock";var Os=class extends br{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,e+this.blockLength;let s=i[0]&127;if(s>8)return this.error="Too big integer",-1;if(s+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=_n(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=Qr(this.length,8);if(o.byteLength>127)return this.error="Too big length",Fe;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let i=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let s=0;s<o.byteLength;s++)n[s+1]=i[s];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Os.NAME="lengthBlock";var M={},Ut=class extends br{constructor({name:t=ho,optional:e=!1,primitiveSchema:n,...o}={},i){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new Ds(o),this.lenBlock=new Os(o),this.valueBlock=i?new i(o):new Gt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(t,e){let n=e||new ai;e||Mp(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(t);this.lenBlock.length=i.byteLength;let s=this.lenBlock.toBER(t);n.write(s),n.write(i)}return e?Fe:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():tt.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${tt.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return Pp(e,n)}};Ut.NAME="BaseBlock";function Mp(r){if(r instanceof M.Constructed)for(let t of r.valueBlock.value)Mp(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Us=class extends Ut{constructor({value:t=ho,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Us.NAME="BaseStringBlock";var Fs=class extends Sr(Gt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};Fs.NAME="PrimitiveValueBlock";var Vp,Ms=class extends Ut{constructor(t={}){super(t,Fs),this.idBlock.isConstructed=!1}};Vp=Ms;M.Primitive=Vp;Ms.NAME="PRIMITIVE";function UE(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function ba(r,t=0,e=r.length){let n=t,o=new Ut({},Gt),i=new br;if(!vr(i,r,t,e))return o.error=i.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ut;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=M.EndOfContent;break;case 1:c=M.Boolean;break;case 2:c=M.Integer;break;case 3:c=M.BitString;break;case 4:c=M.OctetString;break;case 5:c=M.Null;break;case 6:c=M.ObjectIdentifier;break;case 10:c=M.Enumerated;break;case 12:c=M.Utf8String;break;case 13:c=M.RelativeObjectIdentifier;break;case 14:c=M.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=M.Sequence;break;case 17:c=M.Set;break;case 18:c=M.NumericString;break;case 19:c=M.PrintableString;break;case 20:c=M.TeletexString;break;case 21:c=M.VideotexString;break;case 22:c=M.IA5String;break;case 23:c=M.UTCTime;break;case 24:c=M.GeneralizedTime;break;case 25:c=M.GraphicString;break;case 26:c=M.VisibleString;break;case 27:c=M.GeneralString;break;case 28:c=M.UniversalString;break;case 29:c=M.CharacterString;break;case 30:c=M.BmpString;break;case 31:c=M.DATE;break;case 32:c=M.TimeOfDay;break;case 33:c=M.DateTime;break;case 34:c=M.Duration;break;default:{let l=o.idBlock.isConstructed?new M.Constructed:new M.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?M.Constructed:M.Primitive}return o=UE(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function lf(r){if(!r.byteLength){let t=new Ut({},Gt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return ba(tt.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function FE(r,t){return r?1:t}var Qe=class extends Gt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let i=e;for(;FE(this.isIndefiniteForm,n)>0;){let s=ba(o,i,n);if(s.offset===-1)return this.error=s.result.error,this.warnings.concat(s.result.warnings),-1;if(i=s.offset,this.blockLength+=s.result.blockLength,n-=s.result.blockLength,this.value.push(s.result),this.isIndefiniteForm&&s.result.constructor.NAME===ci)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ci?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(t,e){let n=e||new ai;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?Fe:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};Qe.NAME="ConstructedValueBlock";var Hp,tn=class extends Ut{constructor(t={}){super(t,Qe),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
|
|
2
|
+
"use strict";var HeliaVerifiedFetch=(()=>{var Xb=Object.create;var ms=Object.defineProperty;var Zb=Object.getOwnPropertyDescriptor;var Jb=Object.getOwnPropertyNames;var Qb=Object.getPrototypeOf,tx=Object.prototype.hasOwnProperty;var ge=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Et=(r,t)=>{for(var e in t)ms(r,e,{get:t[e],enumerable:!0})},Ud=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Jb(t))!tx.call(r,o)&&o!==e&&ms(r,o,{get:()=>t[o],enumerable:!(n=Zb(t,o))||n.enumerable});return r};var Ut=(r,t,e)=>(e=r!=null?Xb(Qb(r)):{},Ud(t||!r||!r.__esModule?ms(e,"default",{value:r,enumerable:!0}):e,r)),ex=r=>Ud(ms({},"__esModule",{value:!0}),r);var Vp=ge(fo=>{"use strict";var $E="[object ArrayBuffer]",wr=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===$E}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);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(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let s of e)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of e){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},lf="string",zE=/^[0-9a-f]+$/i,qE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,KE=/^[a-zA-Z0-9-_]+$/,Fs=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=wr.toUint8Array(t),n="";for(let i=0;i<e.length;i++)n+=String.fromCharCode(e[i]);return decodeURIComponent(escape(n))}},Ie=class{static toString(t,e=!1){let n=wr.toArrayBuffer(t),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,e);i+=String.fromCharCode(a)}return i}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let i=0;i<t.length;i++)o.setUint16(i*2,t.charCodeAt(i),e);return n}},Ms=class r{static isHex(t){return typeof t===lf&&zE.test(t)}static isBase64(t){return typeof t===lf&&qE.test(t)}static isBase64Url(t){return typeof t===lf&&KE.test(t)}static ToString(t,e="utf8"){let n=wr.toUint8Array(t);switch(e.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 Ie.toString(n,!0);case"utf16":case"utf16be":return Ie.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return Ie.fromString(t,!0);case"utf16":case"utf16be":return Ie.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=wr.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return Fs.fromString(t);case"utf16":case"utf16be":return Ie.fromString(t);case"utf16le":case"usc2":return Ie.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return Fs.toString(t);case"utf16":case"utf16be":return Ie.toString(t);case"utf16le":case"usc2":return Ie.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=wr.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=wr.toUint8Array(t),n="",o=e.length;for(let i=0;i<o;i++){let s=e[i];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let i=e.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(t,e=!1){return Ie.toString(t,e)}static FromUtf16String(t,e=!1){return Ie.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};Ms.DEFAULT_UTF8_ENCODING="utf8";function GE(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)e[i]=o[i]}return e}function WE(...r){let t=r.map(o=>o.byteLength).reduce((o,i)=>o+i),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)e[n++]=i}),e.buffer}function jE(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}fo.BufferSourceConverter=wr;fo.Convert=Ms;fo.assign=GE;fo.combine=WE;fo.isEqual=jE});var Zm=ge((Si,Da)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function o(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function i(h,m){return h<<m|h>>>32-m}function s(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var p=[0,0,0,0];return p[3]+=h[3]+m[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=h[2]+m[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=h[1]+m[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=h[0]+m[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var p=[0,0,0,0];return p[3]+=h[3]*m[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=h[2]*m[3],p[1]+=p[2]>>>16,p[2]&=65535,p[2]+=h[3]*m[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=h[1]*m[3],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=h[2]*m[2],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=h[3]*m[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function u(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function f(h,m){return[h[0]^m[0],h[1]^m[1]]}function d(h){return h=f(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=f(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=f(h,[0,h[0]>>>1]),h}e.x86.hash32=function(h,m){if(e.inputValidation&&!n(h))return t;m=m||0;for(var p=h.length%4,y=h.length-p,g=m,x=0,b=3432918353,E=461845907,I=0;I<y;I=I+4)x=h[I]|h[I+1]<<8|h[I+2]<<16|h[I+3]<<24,x=o(x,b),x=i(x,15),x=o(x,E),g^=x,g=i(g,13),g=o(g,5)+3864292196;switch(x=0,p){case 3:x^=h[I+2]<<16;case 2:x^=h[I+1]<<8;case 1:x^=h[I],x=o(x,b),x=i(x,15),x=o(x,E),g^=x}return g^=h.length,g=s(g),g>>>0},e.x86.hash128=function(h,m){if(e.inputValidation&&!n(h))return t;m=m||0;for(var p=h.length%16,y=h.length-p,g=m,x=m,b=m,E=m,I=0,B=0,S=0,v=0,k=597399067,z=2869860233,F=951274213,U=2716044179,D=0;D<y;D=D+16)I=h[D]|h[D+1]<<8|h[D+2]<<16|h[D+3]<<24,B=h[D+4]|h[D+5]<<8|h[D+6]<<16|h[D+7]<<24,S=h[D+8]|h[D+9]<<8|h[D+10]<<16|h[D+11]<<24,v=h[D+12]|h[D+13]<<8|h[D+14]<<16|h[D+15]<<24,I=o(I,k),I=i(I,15),I=o(I,z),g^=I,g=i(g,19),g+=x,g=o(g,5)+1444728091,B=o(B,z),B=i(B,16),B=o(B,F),x^=B,x=i(x,17),x+=b,x=o(x,5)+197830471,S=o(S,F),S=i(S,17),S=o(S,U),b^=S,b=i(b,15),b+=E,b=o(b,5)+2530024501,v=o(v,U),v=i(v,18),v=o(v,k),E^=v,E=i(E,13),E+=g,E=o(E,5)+850148119;switch(I=0,B=0,S=0,v=0,p){case 15:v^=h[D+14]<<16;case 14:v^=h[D+13]<<8;case 13:v^=h[D+12],v=o(v,U),v=i(v,18),v=o(v,k),E^=v;case 12:S^=h[D+11]<<24;case 11:S^=h[D+10]<<16;case 10:S^=h[D+9]<<8;case 9:S^=h[D+8],S=o(S,F),S=i(S,17),S=o(S,U),b^=S;case 8:B^=h[D+7]<<24;case 7:B^=h[D+6]<<16;case 6:B^=h[D+5]<<8;case 5:B^=h[D+4],B=o(B,z),B=i(B,16),B=o(B,F),x^=B;case 4:I^=h[D+3]<<24;case 3:I^=h[D+2]<<16;case 2:I^=h[D+1]<<8;case 1:I^=h[D],I=o(I,k),I=i(I,15),I=o(I,z),g^=I}return g^=h.length,x^=h.length,b^=h.length,E^=h.length,g+=x,g+=b,g+=E,x+=g,b+=g,E+=g,g=s(g),x=s(x),b=s(b),E=s(E),g+=x,g+=b,g+=E,x+=g,b+=g,E+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)},e.x64.hash128=function(h,m){if(e.inputValidation&&!n(h))return t;m=m||0;for(var p=h.length%16,y=h.length-p,g=[0,m],x=[0,m],b=[0,0],E=[0,0],I=[2277735313,289559509],B=[1291169091,658871167],S=0;S<y;S=S+16)b=[h[S+4]|h[S+5]<<8|h[S+6]<<16|h[S+7]<<24,h[S]|h[S+1]<<8|h[S+2]<<16|h[S+3]<<24],E=[h[S+12]|h[S+13]<<8|h[S+14]<<16|h[S+15]<<24,h[S+8]|h[S+9]<<8|h[S+10]<<16|h[S+11]<<24],b=c(b,I),b=l(b,31),b=c(b,B),g=f(g,b),g=l(g,27),g=a(g,x),g=a(c(g,[0,5]),[0,1390208809]),E=c(E,B),E=l(E,33),E=c(E,I),x=f(x,E),x=l(x,31),x=a(x,g),x=a(c(x,[0,5]),[0,944331445]);switch(b=[0,0],E=[0,0],p){case 15:E=f(E,u([0,h[S+14]],48));case 14:E=f(E,u([0,h[S+13]],40));case 13:E=f(E,u([0,h[S+12]],32));case 12:E=f(E,u([0,h[S+11]],24));case 11:E=f(E,u([0,h[S+10]],16));case 10:E=f(E,u([0,h[S+9]],8));case 9:E=f(E,[0,h[S+8]]),E=c(E,B),E=l(E,33),E=c(E,I),x=f(x,E);case 8:b=f(b,u([0,h[S+7]],56));case 7:b=f(b,u([0,h[S+6]],48));case 6:b=f(b,u([0,h[S+5]],40));case 5:b=f(b,u([0,h[S+4]],32));case 4:b=f(b,u([0,h[S+3]],24));case 3:b=f(b,u([0,h[S+2]],16));case 2:b=f(b,u([0,h[S+1]],8));case 1:b=f(b,[0,h[S]]),b=c(b,I),b=l(b,31),b=c(b,B),g=f(g,b)}return g=f(g,[0,h.length]),x=f(x,[0,h.length]),g=a(g,x),x=a(x,g),g=d(g),x=d(x),g=a(g,x),x=a(x,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(x[0]>>>0).toString(16)).slice(-8)+("00000000"+(x[1]>>>0).toString(16)).slice(-8)},typeof Si<"u"?(typeof Da<"u"&&Da.exports&&(Si=Da.exports=e),Si.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(Si)});var vf=ge((Z6,Jm)=>{Jm.exports=Zm()});var ig=ge((h3,If)=>{"use strict";var Pv=Object.prototype.hasOwnProperty,te="~";function _i(){}Object.create&&(_i.prototype=Object.create(null),new _i().__proto__||(te=!1));function Lv(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function og(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var i=new Lv(e,n||r,o),s=te?te+t:t;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 Ma(r,t){--r._eventsCount===0?r._events=new _i:delete r._events[t]}function jt(){this._events=new _i,this._eventsCount=0}jt.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)Pv.call(e,n)&&t.push(te?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};jt.prototype.listeners=function(t){var e=te?te+t:t,n=this._events[e];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};jt.prototype.listenerCount=function(t){var e=te?te+t:t,n=this._events[e];return n?n.fn?1:n.length:0};jt.prototype.emit=function(t,e,n,o,i,s){var a=te?te+t:t;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,i),!0;case 6:return c.fn.call(c.context,e,n,o,i,s),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(t,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};jt.prototype.on=function(t,e,n){return og(this,t,e,n,!1)};jt.prototype.once=function(t,e,n){return og(this,t,e,n,!0)};jt.prototype.removeListener=function(t,e,n,o){var i=te?te+t:t;if(!this._events[i])return this;if(!e)return Ma(this,i),this;var s=this._events[i];if(s.fn)s.fn===e&&(!o||s.once)&&(!n||s.context===n)&&Ma(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==e||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:Ma(this,i)}return this};jt.prototype.removeAllListeners=function(t){var e;return t?(e=te?te+t:t,this._events[e]&&Ma(this,e)):(this._events=new _i,this._eventsCount=0),this};jt.prototype.off=jt.prototype.removeListener;jt.prototype.addListener=jt.prototype.on;jt.prefixed=te;jt.EventEmitter=jt;typeof If<"u"&&(If.exports=jt)});var Nf=ge((D3,lg)=>{lg.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(i,s){e[i]=s,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(i){return e[i]!==void 0||n[i]!==void 0},remove:function(i){e[i]!==void 0&&(e[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=e[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){e[i]!==void 0?e[i]=s:o(i,s)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var z0=ge($i=>{(function(){var r,t,e,n,o,i,s,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},s=function(c){var l,u,f,d,h,m;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=t(c),h=m[0],u=m[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),i=e("a"),o=e("A"),t=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(e(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+e(c[f])-i)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,h,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(m=l.split("/",2),l=m[0],u=m[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=s(u)}catch(p){throw f=p,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(l)&this.maskLong)>>>0}catch(p){throw f=p,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(s(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=s(this.first),f=s(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),$i.ip2long=s,$i.long2ip=a,$i.Netmask=r}).call($i)});var Mo=ge((o5,Mh)=>{var n5=function(){typeof Mh<"u"&&(Mh.exports=p);var r=86400,t=3200,e=146097*t/400,n=r*e,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(v){var k=v-v%1;return k==0&&(v<0||v===0&&1/v!=1/0)?-0:k},u=p.prototype,f=(p.fromDate=function(v){return new p(+v)},p.fromInt64BE=E(0,1,2,3,0,4),p.fromInt64LE=E(3,2,1,0,4,0),p.fromString=function(F){var k,z=new p,F=(F+="").replace(/^\s*[+\-]?\d+/,function(D){var D=+D,R=1970+(D-1970)%400;return z.year=D-R,R}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(U,D,R){return D<0&&(R*=-1),k=6e4*(60*+D+ +R),""}).replace(/\.\d+$/,function(U){return z.nano=+(U+c).substr(1,9),""}).split(/\D+/);if(1<F.length?F[1]--:F[1]=0,z.time=k=Date.UTC.apply(Date,F)-(k||0),isNaN(k))throw new TypeError("Invalid Date");return y(z)},p.fromTimeT=function(v){return x(v,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(v){return this.nano+=+v||0,this},u.getNano=function(){var v=y(this);return(v.time%1e3*a+ +v.nano+1e9)%1e9},u.getTimeT=function(){var k=y(this),v=Math.floor(k.time/1e3),k=k.year;return k&&(v+=k*e*r/t),v},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return g(y(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(v){var k=this,z=k.toDate(),F={H:function(){return B(z.getUTCHours())},L:function(){return S(z.getUTCMilliseconds(),3)},M:function(){return B(z.getUTCMinutes())},N:function(){return S(k.getNano(),9)},S:function(){return B(z.getUTCSeconds())},Y:function(){var U=k.getYear();return 999999<U?"+"+U:9999<U?"+"+S(U,6):0<=U?S(U,4):-999999<=U?"-"+S(-U,6):U},a:function(){return h[z.getUTCDay()]},b:function(){return d[z.getUTCMonth()]},d:function(){return B(z.getUTCDate())},e:function(){return function(U){return(9<U?"":" ")+(0|U)}(z.getUTCDate())},m:function(){return B(z.getUTCMonth()+1)}};return function U(D){return D.replace(/%./g,function(R){var A=R[1],N=m[A],A=F[A];return N?U(N):A?A():R})}(v||f)},u.writeInt64BE=b(0,1,2,3,0,4),u.writeInt64LE=b(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m={"%":"%",F:"%Y-%m-%d",n:`
|
|
3
|
+
`,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return p;function p(v,k,z){var F=this;if(!(F instanceof p))return new p(v,k,z);F.time=+v||0,F.nano=+k||0,F.year=+z||0,y(F)}function y(v){var k,z,F,U=v.year,D=v.time,R=v.nano,N=((R<0||a<=R)&&(R-=(z=Math.floor(R/a))*a,D+=z,z=1),U%t);return(D<-i||i<D||N)&&((k=l(D/o))&&(U+=k*t,D-=k*o),(F=g(D)).setUTCFullYear(N+F.getUTCFullYear()),F=(D=+F)+(k=l((U-=N)/t))*o,k&&-i<=F&&F<=i&&(U-=k*t,D=F),z=1),z&&(v.year=U,v.time=D,v.nano=R),v}function g(v){var k=new Date(0);return k.setTime(v),k}function x(U,F){U=+U||0;var z=l((F=(F|0)*s)/n)+l(U/n),F=F%n+U%n,U=l(F/n);return U&&(z+=U,F-=U*n),new p(1e3*F,0,z*t)}function b(v,k,z,F,U,D){return function(N,A){var C=y(this);N=N||new Array(8),I(N,A|=0);var V=Math.floor(C.time/1e3),C=C.year*(e*r/t),_=l(C/s)+l(V/s),C=C%s+V%s,V=Math.floor(C/s);return V&&(_+=V,C-=V*s),R(N,A+U,_),R(N,A+D,C),N};function R(N,A,_){N[A+v]=_>>24&255,N[A+k]=_>>16&255,N[A+z]=_>>8&255,N[A+F]=255&_}}function E(v,k,z,F,U,D){return function(N,A){I(N,A|=0);var _=R(N,A+U);return x(R(N,A+D),_)};function R(N,A){return 16777216*N[A+v]+(N[A+k]<<16|N[A+z]<<8|N[A+F])}}function I(v,k){if(v=v&&v.length,v==null)throw new TypeError("Invalid Buffer");if(v<k+8)throw new RangeError("Out of range")}function B(v){return(9<v?"":"0")+(0|v)}function S(v,k){return(c+(0|v)).substr(-k)}}()});var Wy=ge((OU,Gy)=>{Gy.exports=Zh;var Ky=128,I_=127,k_=~I_,T_=Math.pow(2,31);function Zh(r,t,e){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Zh.bytes=0,new RangeError("Could not encode varint");t=t||[],e=e||0;for(var n=e;r>=T_;)t[e++]=r&255|Ky,r/=128;for(;r&k_;)t[e++]=r&255|Ky,r>>>=7;return t[e]=r|0,Zh.bytes=e-n+1,t}});var Xy=ge((UU,Yy)=>{Yy.exports=Jh;var B_=128,jy=127;function Jh(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw Jh.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&jy)<<o:(s&jy)*Math.pow(2,o),o+=7}while(s>=B_);return Jh.bytes=i-n,e}});var Jy=ge((FU,Zy)=>{var C_=Math.pow(2,7),R_=Math.pow(2,14),N_=Math.pow(2,21),P_=Math.pow(2,28),L_=Math.pow(2,35),D_=Math.pow(2,42),O_=Math.pow(2,49),U_=Math.pow(2,56),F_=Math.pow(2,63);Zy.exports=function(r){return r<C_?1:r<R_?2:r<N_?3:r<P_?4:r<L_?5:r<D_?6:r<O_?7:r<U_?8:r<F_?9:10}});var el=ge((MU,Qy)=>{Qy.exports={encode:Wy(),decode:Xy(),encodingLength:Jy()}});var Gw=ge((xM,Kw)=>{"use strict";Kw.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(t,e){let n=this._internalPositionFor(t,!1);if(e===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(t),this._changedLength=!0,this._changedData=!0);else{let o=!1;n===-1?(n=this._data.length,this._setBit(t),this._changedData=!0):o=!0,this._setInternalPos(n,t,e,o),this._changedLength=!0}}unset(t){this.set(t,void 0)}get(t){this._sortData();let e=this._internalPositionFor(t,!0);if(e!==-1)return this._data[e][1]}push(t){return this.set(this.length,t),this.length}get length(){if(this._sortData(),this._changedLength){let t=this._data[this._data.length-1];this._length=t?t[0]+1:0,this._changedLength=!1}return this._length}forEach(t){let e=0;for(;e<this.length;)t(this.get(e),e,this),e++}map(t){let e=0,n=new Array(this.length);for(;e<this.length;)n[e]=t(this.get(e),e,this),e++;return n}reduce(t,e){let n=0,o=e;for(;n<this.length;){let i=this.get(n);o=t(o,i,n),n++}return o}find(t){let e=0,n,o;for(;e<this.length&&!n;)o=this.get(e),n=t(o),e++;return n?o:void 0}_internalPositionFor(t,e){let n=this._bytePosFor(t,e);if(n>=this._bitArrays.length)return-1;let o=this._bitArrays[n],i=t-n*7;if(!((o&1<<i)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(DA,0),c=~(4294967295<<i+1),l=qw(o&c);return a+l-1}_bytePosFor(t,e){let n=Math.floor(t/7),o=n+1;for(;!e&&this._bitArrays.length<o;)this._bitArrays.push(0);return n}_setBit(t){let e=this._bytePosFor(t,!1);this._bitArrays[e]|=1<<t-e*7}_unsetBit(t){let e=this._bytePosFor(t,!1);this._bitArrays[e]&=~(1<<t-e*7)}_setInternalPos(t,e,n,o){let i=this._data,s=[e,n];if(o)this._sortData(),i[t]=s;else{if(i.length)if(i[i.length-1][0]>=e)i.push(s);else if(i[0][0]<=e)i.unshift(s);else{let a=Math.round(i.length/2);this._data=i.slice(0,a).concat(s).concat(i.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(t){this._data.splice(t,1)}_sortData(){this._changedData&&this._data.sort(OA),this._changedData=!1}bitField(){let t=[],e=8,n=0,o=0,i,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(i=s.shift(),n=7);let c=Math.min(n,e),l=~(255<<c),u=i&l;o|=u<<8-e,i=i>>>c,n-=c,e-=c,(!e||!n&&!s.length)&&(t.push(o),o=0,e=8)}for(var a=t.length-1;a>0&&t[a]===0;a--)t.pop();return t}compactArray(){return this._sortData(),this._data.map(UA)}};function DA(r,t){return r+qw(t)}function qw(r){let t=r;return t=t-(t>>1&1431655765),t=(t&858993459)+(t>>2&858993459),(t+(t>>4)&252645135)*16843009>>24}function OA(r,t){return r[0]-t[0]}function UA(r){return r[1]}});var Ib=ge((PH,Ab)=>{"use strict";Ab.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:256,RTLD_LOCAL:0,RTLD_DEEPBIND:8,E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOPNOTSUPP:95,EOVERFLOW:75,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:17,SIGSTKFLT:16,SIGCONT:18,SIGSTOP:19,SIGTSTP:20,SIGTTIN:21,SIGTTOU:22,SIGURG:23,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:29,SIGPOLL:29,SIGPWR:30,SIGSYS:31,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,EXTENSIONLESS_FORMAT_JAVASCRIPT:0,EXTENSIONLESS_FORMAT_WASM:1,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:64,O_EXCL:128,UV_FS_O_FILEMAP:0,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_DIRECTORY:65536,O_NOATIME:262144,O_NOFOLLOW:131072,O_SYNC:1052672,O_DSYNC:4096,O_DIRECT:16384,O_NONBLOCK:2048,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:805306608,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var e8={};Et(e8,{createVerifiedFetch:()=>Bd,verifiedFetch:()=>jl});var Zo=Symbol.for("@libp2p/content-routing");function Fd(r){return r==null?!1:(r.type==="RSA"||r.type==="Ed25519"||r.type==="secp256k1")&&r.raw instanceof Uint8Array&&typeof r.equals=="function"&&typeof r.toMultihash=="function"&&typeof r.toCID=="function"&&typeof r.verify=="function"}var Gn=Symbol.for("@libp2p/peer-id");var Jo=Symbol.for("@libp2p/peer-routing");var Ne=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var St=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Wn=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var kt=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}};var Qo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},_e=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var pn=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var mt=(r,...t)=>{try{[...t]}catch{}};var jn=class extends EventTarget{#t=new Map;constructor(){super(),mt(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:i})=>i!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Md(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Vr(...r){let t=[];for(let e of r)Md(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Hr(...r){let t=[];for(let e of r)Md(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}function Zt(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function ht(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var gs=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Yn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new gs(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new gs(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Xl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function je(r={}){return rx(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function rx(r,t){t=t??{};let e=t.onEnd,n=new Yn,o,i,s,a=ht(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{i=x=>{i=null,n.push(x);try{y(r(n))}catch(b){g(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ht()})}},l=y=>i!=null?i(y):(n.push(y),o),u=y=>(n=new Yn,i!=null?i({error:y}):(n.push({error:y}),o)),f=y=>{if(s)return o;if(t?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},d=y=>s?o:(s=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new Yn,d(),{done:!0}),m=y=>(d(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:d,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,b;g!=null&&(x=new Promise((E,I)=>{b=()=>{I(new Xl)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},e==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(y){return p.throw(y),e!=null&&(e(y),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(y){return p.end(y),e!=null&&(e(y),e=void 0),o},get readableLength(){return p.readableLength},onEmpty:y=>p.onEmpty(y)},o}var Zl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function ys(r,t,e,n){let o=new Zl(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),s(d);return}a(),i(f)},l=f=>{a(),s(f.detail)},u=()=>{a(),s(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var ws=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Vd(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new ws(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new ws(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}function nx(r){return r[Symbol.asyncIterator]!=null}function ox(r){if(nx(r))return(async()=>{for await(let t of r);})();for(let t of r);}var fr=ox;function re(r=0){return new Uint8Array(r)}function ne(r=0){return new Uint8Array(r)}var ix=Math.pow(2,7),sx=Math.pow(2,14),ax=Math.pow(2,21),Jl=Math.pow(2,28),Ql=Math.pow(2,35),tu=Math.pow(2,42),eu=Math.pow(2,49),st=128,zt=127;function oe(r){if(r<ix)return 1;if(r<sx)return 2;if(r<ax)return 3;if(r<Jl)return 4;if(r<Ql)return 5;if(r<tu)return 6;if(r<eu)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ru(r,t,e=0){switch(oe(r)){case 8:t[e++]=r&255|st,r/=128;case 7:t[e++]=r&255|st,r/=128;case 6:t[e++]=r&255|st,r/=128;case 5:t[e++]=r&255|st,r/=128;case 4:t[e++]=r&255|st,r>>>=7;case 3:t[e++]=r&255|st,r>>>=7;case 2:t[e++]=r&255|st,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function cx(r,t,e=0){switch(oe(r)){case 8:t.set(e++,r&255|st),r/=128;case 7:t.set(e++,r&255|st),r/=128;case 6:t.set(e++,r&255|st),r/=128;case 5:t.set(e++,r&255|st),r/=128;case 4:t.set(e++,r&255|st),r>>>=7;case 3:t.set(e++,r&255|st),r>>>=7;case 2:t.set(e++,r&255|st),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function nu(r,t){let e=r[t],n=0;if(n+=e&zt,e<st||(e=r[t+1],n+=(e&zt)<<7,e<st)||(e=r[t+2],n+=(e&zt)<<14,e<st)||(e=r[t+3],n+=(e&zt)<<21,e<st)||(e=r[t+4],n+=(e&zt)*Jl,e<st)||(e=r[t+5],n+=(e&zt)*Ql,e<st)||(e=r[t+6],n+=(e&zt)*tu,e<st)||(e=r[t+7],n+=(e&zt)*eu,e<st))return n;throw new RangeError("Could not decode varint")}function lx(r,t){let e=r.get(t),n=0;if(n+=e&zt,e<st||(e=r.get(t+1),n+=(e&zt)<<7,e<st)||(e=r.get(t+2),n+=(e&zt)<<14,e<st)||(e=r.get(t+3),n+=(e&zt)<<21,e<st)||(e=r.get(t+4),n+=(e&zt)*Jl,e<st)||(e=r.get(t+5),n+=(e&zt)*Ql,e<st)||(e=r.get(t+6),n+=(e&zt)*tu,e<st)||(e=r.get(t+7),n+=(e&zt)*eu,e<st))return n;throw new RangeError("Could not decode varint")}function Xn(r,t,e=0){return t==null&&(t=ne(oe(r))),t instanceof Uint8Array?ru(r,t,e):cx(r,t,e)}function mn(r,t=0){return r instanceof Uint8Array?nu(r,t):lx(r,t)}function ut(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=ne(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function Y(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var zd=Symbol.for("@achingbrain/uint8arraylist");function $d(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Ye(r){return!!r?.[zd]}var gn=class r{bufs;length;[zd]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Ye(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Ye(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=$d(this.bufs,t);return e.buf[e.index]}set(t,e){let n=$d(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Ye(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return ut(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:ut(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),i=new r;return i.length=o,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(u){if(e===c){n.push(s);break}n.push(s.subarray(0,e-a));break}n.push(s)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Ye(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let f=0;f<i;f++)s[f]=-1;for(let f=0;f<o;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Y(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,i)=>o+i.byteLength,0)),n.length=e,n}};function ux(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Zn=ux;function fx(r){return r[Symbol.asyncIterator]!=null}function hx(r,t){let e=0;if(fx(r))return async function*(){for await(let c of r)yield t(c,e++)}();let n=Zn(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=t(o,e++);if(typeof s.then=="function")return async function*(){yield await s;for await(let c of n)yield t(c,e++)}();let a=t;return function*(){yield s;for(let c of n)yield a(c,e++)}()}var qt=hx;function dx(r){return r[Symbol.asyncIterator]!=null}function px(...r){let t=[];for(let e of r)dx(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=je({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var $r=px;function Xe(r,...t){if(r==null)throw new Error("Empty pipeline");if(ou(r)){let n=r;r=()=>n.source}else if(Kd(r)||qd(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&ou(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)ou(e[n])&&(e[n]=gx(e[n]));return mx(...e)}var mx=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},qd=r=>r?.[Symbol.asyncIterator]!=null,Kd=r=>r?.[Symbol.iterator]!=null,ou=r=>r==null?!1:r.sink!=null&&r.source!=null,gx=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=je({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(qd(i))o=async function*(){yield*i,n.end()};else if(Kd(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return $r(n,o())}return r.source};function yx(r){return r[Symbol.asyncIterator]!=null}function wx(r,t){return yx(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var bs=wx;var H=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var iu=new Float32Array([-0]),zr=new Uint8Array(iu.buffer);function Gd(r,t,e){iu[0]=r,t[e]=zr[0],t[e+1]=zr[1],t[e+2]=zr[2],t[e+3]=zr[3]}function Wd(r,t){return zr[0]=r[t],zr[1]=r[t+1],zr[2]=r[t+2],zr[3]=r[t+3],iu[0]}var su=new Float64Array([-0]),Kt=new Uint8Array(su.buffer);function jd(r,t,e){su[0]=r,t[e]=Kt[0],t[e+1]=Kt[1],t[e+2]=Kt[2],t[e+3]=Kt[3],t[e+4]=Kt[4],t[e+5]=Kt[5],t[e+6]=Kt[6],t[e+7]=Kt[7]}function Yd(r,t){return Kt[0]=r[t],Kt[1]=r[t+1],Kt[2]=r[t+2],Kt[3]=r[t+3],Kt[4]=r[t+4],Kt[5]=r[t+5],Kt[6]=r[t+6],Kt[7]=r[t+7],su[0]}var bx=BigInt(Number.MAX_SAFE_INTEGER),xx=BigInt(Number.MIN_SAFE_INTEGER),ye=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return yn;if(t<bx&&t>xx)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Xd&&(o=0n,++n>Xd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return yn;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):yn}},yn=new ye(0,0);yn.toBigInt=function(){return 0n};yn.zzEncode=yn.zzDecode=function(){return this};yn.length=function(){return 1};var Xd=4294967296n;function Zd(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Jd(r,t,e){if(e-t<1)return"";let o,i=[],s=0,a;for(;t<e;)a=r[t++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&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 au(r,t,e){let n=e,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Pe(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function xs(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var cu=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Pe(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Pe(this,4);return xs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Pe(this,4);return xs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Pe(this,4);let t=Wd(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Pe(this,4);let t=Yd(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Pe(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Jd(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Pe(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Pe(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new ye(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Pe(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Pe(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Pe(this,8);let t=xs(this.buf,this.pos+=4),e=xs(this.buf,this.pos+=4);return new ye(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=nu(this.buf,this.pos);return this.pos+=oe(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function lu(r){return new cu(r instanceof Uint8Array?r:r.subarray())}function ie(r,t,e){let n=lu(r);return t.decode(n,void 0,e)}var yu={};Et(yu,{base10:()=>Bx});var wn={};Et(wn,{coerce:()=>Ae,empty:()=>tp,equals:()=>uu,fromHex:()=>vx,fromString:()=>fu,isBinary:()=>Sx,toHex:()=>Ex,toString:()=>hu});var tp=new Uint8Array(0);function Ex(r){return r.reduce((t,e)=>t+e.toString(16).padStart(2,"0"),"")}function vx(r){let t=r.match(/../g);return t!=null?new Uint8Array(t.map(e=>parseInt(e,16))):tp}function uu(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ae(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 Sx(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function fu(r){return new TextEncoder().encode(r)}function hu(r){return new TextDecoder().decode(r)}function _x(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(e[s]!==255)throw new TypeError(i+" is ambiguous");e[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 f(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var p=0,y=0,g=0,x=m.length;g!==x&&m[g]===0;)g++,p++;for(var b=(x-g)*u+1>>>0,E=new Uint8Array(b);g!==x;){for(var I=m[g],B=0,S=b-1;(I!==0||B<y)&&S!==-1;S--,B++)I+=256*E[S]>>>0,E[S]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");y=B,g++}for(var v=b-y;v!==b&&E[v]===0;)v++;for(var k=c.repeat(p);v<b;++v)k+=r.charAt(E[v]);return k}function d(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var p=0;if(m[p]!==" "){for(var y=0,g=0;m[p]===c;)y++,p++;for(var x=(m.length-p)*l+1>>>0,b=new Uint8Array(x);m[p];){var E=e[m.charCodeAt(p)];if(E===255)return;for(var I=0,B=x-1;(E!==0||I<g)&&B!==-1;B--,I++)E+=a*b[B]>>>0,b[B]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");g=I,p++}if(m[p]!==" "){for(var S=x-g;S!==x&&b[S]===0;)S++;for(var v=new Uint8Array(y+(x-S)),k=y;S!==x;)v[k++]=b[S++];return v}}}function h(m){var p=d(m);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Ax=_x,Ix=Ax,ep=Ix;var du=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},pu=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return rp(this,t)}},mu=class{decoders;constructor(t){this.decoders=t}or(t){return rp(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function rp(r,t){return new mu({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var gu=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new du(t,e,n),this.decoder=new pu(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Jn({name:r,prefix:t,encode:e,decode:n}){return new gu(r,t,e,n)}function qr({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ep(e,r);return Jn({prefix:t,name:r,encode:n,decode:i=>Ae(o(i))})}function kx(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function Tx(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>e;)s-=e,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<e-s]),n)for(;i.length*e&7;)i+="=";return i}function yt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Jn({prefix:t,name:r,encode(o){return Tx(o,n,e)},decode(o){return kx(o,n,e,r)}})}var Bx=qr({prefix:"9",name:"base10",alphabet:"0123456789"});var wu={};Et(wu,{base16:()=>Cx,base16upper:()=>Rx});var Cx=yt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Rx=yt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var bu={};Et(bu,{base2:()=>Nx});var Nx=yt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var xu={};Et(xu,{base256emoji:()=>Ux});var np=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}"),Px=np.reduce((r,t,e)=>(r[e]=t,r),[]),Lx=np.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Dx(r){return r.reduce((t,e)=>(t+=Px[e],t),"")}function Ox(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Lx[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Ux=Jn({prefix:"\u{1F680}",name:"base256emoji",encode:Dx,decode:Ox});var Eu={};Et(Eu,{base32:()=>vt,base32hex:()=>Hx,base32hexpad:()=>zx,base32hexpadupper:()=>qx,base32hexupper:()=>$x,base32pad:()=>Mx,base32padupper:()=>Vx,base32upper:()=>Fx,base32z:()=>Kx});var vt=yt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Fx=yt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Mx=yt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Vx=yt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Hx=yt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),$x=yt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zx=yt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),qx=yt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Kx=yt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vu={};Et(vu,{base36:()=>Gt,base36upper:()=>Gx});var Gt=qr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Gx=qr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Su={};Et(Su,{base58btc:()=>X,base58flickr:()=>Wx});var X=qr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Wx=qr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Au={};Et(Au,{base64:()=>se,base64pad:()=>jx,base64url:()=>_u,base64urlpad:()=>Yx});var se=yt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jx=yt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_u=yt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yx=yt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Iu={};Et(Iu,{base8:()=>Xx});var Xx=yt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ku={};Et(ku,{identity:()=>Zx});var Zx=Jn({prefix:"\0",name:"identity",encode:r=>hu(r),decode:r=>fu(r)});var Qn={};Et(Qn,{code:()=>hr,decode:()=>Tu,encode:()=>e1,name:()=>t1});var Jx=new TextEncoder,Qx=new TextDecoder,t1="json",hr=512;function e1(r){return Jx.encode(JSON.stringify(r))}function Tu(r){return JSON.parse(Qx.decode(r))}var bn={};Et(bn,{code:()=>ae,decode:()=>o1,encode:()=>n1,name:()=>r1});var r1="raw",ae=85;function n1(r){return Ae(r)}function o1(r){return Ae(r)}var Cu={};Et(Cu,{identity:()=>bt});var i1=sp,op=128,s1=127,a1=~s1,c1=Math.pow(2,31);function sp(r,t,e){t=t||[],e=e||0;for(var n=e;r>=c1;)t[e++]=r&255|op,r/=128;for(;r&a1;)t[e++]=r&255|op,r>>>=7;return t[e]=r|0,sp.bytes=e-n+1,t}var l1=Bu,u1=128,ip=127;function Bu(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Bu.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&ip)<<o:(s&ip)*Math.pow(2,o),o+=7}while(s>=u1);return Bu.bytes=i-n,e}var f1=Math.pow(2,7),h1=Math.pow(2,14),d1=Math.pow(2,21),p1=Math.pow(2,28),m1=Math.pow(2,35),g1=Math.pow(2,42),y1=Math.pow(2,49),w1=Math.pow(2,56),b1=Math.pow(2,63),x1=function(r){return r<f1?1:r<h1?2:r<d1?3:r<p1?4:r<m1?5:r<g1?6:r<y1?7:r<w1?8:r<b1?9:10},E1={encode:i1,decode:l1,encodingLength:x1},v1=E1,ti=v1;function ei(r,t=0){return[ti.decode(r,t),ti.decode.bytes]}function to(r,t,e=0){return ti.encode(r,t,e),t}function eo(r){return ti.encodingLength(r)}function Le(r,t){let e=t.byteLength,n=eo(r),o=n+eo(e),i=new Uint8Array(o+e);return to(r,i,0),to(e,i,n),i.set(t,o),new ro(r,e,t,i)}function wt(r){let t=Ae(r),[e,n]=ei(t),[o,i]=ei(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new ro(e,o,s,t)}function ap(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&uu(r.bytes,e.bytes)}}var ro=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var cp=0,S1="identity",lp=Ae;function _1(r){return Le(cp,lp(r))}var bt={code:cp,name:S1,encode:lp,digest:_1};var Nu={};Et(Nu,{sha256:()=>Ze,sha512:()=>vs});function xn({name:r,code:t,encode:e}){return new Ru(r,t,e)}var Ru=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Le(this.code,e):e.then(n=>Le(this.code,n))}else throw Error("Unknown type, must be binary type")}};function fp(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ze=xn({name:"sha2-256",code:18,encode:fp("SHA-256")}),vs=xn({name:"sha2-512",code:19,encode:fp("SHA-512")});function hp(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return I1(e,Pu(r),t??X.encoder);default:return k1(e,Pu(r),t??vt.encoder)}}var dp=new WeakMap;function Pu(r){let t=dp.get(r);if(t==null){let e=new Map;return dp.set(r,e),e}return t}var P=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==ri)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==T1)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Le(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&ap(t.multihash,n.multihash)}toString(t){return hp(this,t)}toJSON(){return{"/":hp(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:i,bytes:s}=e;return new r(n,o,i,s??pp(n,o,i.bytes))}else if(e[B1]===!0){let{version:n,multihash:o,code:i}=e,s=wt(o);return r.create(n,i,s)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==ri)throw new Error(`Version 0 CID must use dag-pb (code: ${ri}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=pp(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,ri,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ae(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new ro(e.multihashCode,e.digestSize,i,o);return[e.version===0?r.createV0(s):r.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=ei(t.subarray(e));return e+=d,f},o=n(),i=ri;if(o===18?(o=0,e=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=e,a=n(),c=n(),l=e+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=A1(t,e),i=r.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Pu(i).set(n,t),i}};function A1(r,t){switch(r[0]){case"Q":{let e=t??X;return[X.prefix,e.decode(`${X.prefix}${r}`)]}case X.prefix:{let e=t??X;return[X.prefix,e.decode(r)]}case vt.prefix:{let e=t??vt;return[vt.prefix,e.decode(r)]}case Gt.prefix:{let e=t??Gt;return[Gt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function I1(r,t,e){let{prefix:n}=e;if(n!==X.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return o}function k1(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let i=e.encode(r);return t.set(n,i),i}else return o}var ri=112,T1=18;function pp(r,t,e){let n=eo(r),o=n+eo(t),i=new Uint8Array(o+e.byteLength);return to(r,i,0),to(t,i,n),i.set(e,o),i}var B1=Symbol.for("@ipld/js-cid/CID");var ni={...ku,...bu,...Iu,...yu,...wu,...Eu,...vu,...Su,...Au,...xu},Pk={...Nu,...Cu};function gp(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var mp=gp("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Lu=gp("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=ne(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),C1={utf8:mp,"utf-8":mp,hex:ni.base16,latin1:Lu,ascii:Lu,binary:Lu,...ni},Ss=C1;function L(r,t="utf8"){let e=Ss[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Du(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return ne(s);o+s>t&&(n=ne(t),o=0);let a=n.subarray(o,o+=s);return o&7&&(o=(o|7)+1),a}}var En=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ou(){}var Fu=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},R1=Du();function N1(r){return globalThis.Buffer!=null?ne(r):R1(r)}var ii=class{len;head;tail;states;constructor(){this.len=0,this.head=new En(Ou,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new En(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Mu((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(_s,10,ye.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=ye.fromBigInt(t);return this._push(_s,e.length(),e)}uint64Number(t){return this._push(ru,oe(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=ye.fromBigInt(t).zzEncode();return this._push(_s,e.length(),e)}sint64Number(t){let e=ye.fromNumber(t).zzEncode();return this._push(_s,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Uu,1,t?1:0)}fixed32(t){return this._push(oi,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=ye.fromBigInt(t);return this._push(oi,4,e.lo)._push(oi,4,e.hi)}fixed64Number(t){let e=ye.fromNumber(t);return this._push(oi,4,e.lo)._push(oi,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Gd,4,t)}double(t){return this._push(jd,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Uu,1,0):this.uint32(e)._push(L1,e,t)}string(t){let e=Zd(t);return e!==0?this.uint32(e)._push(au,e,t):this._push(Uu,1,0)}fork(){return this.states=new Fu(this),this.head=this.tail=new En(Ou,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 En(Ou,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=N1(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Uu(r,t,e){t[e]=r&255}function P1(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Mu=class extends En{next;constructor(t,e){super(P1,t,e),this.next=void 0}};function _s(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function oi(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function L1(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(ii.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(D1,t,r),this},ii.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(O1,t,r),this});function D1(r,t,e){t.set(r,e)}function O1(r,t,e){r.length<40?au(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(L(r),e)}function Vu(){return new ii}function ce(r,t){let e=Vu();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var no;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(no||(no={}));function As(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function dr(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,s){let a=t(i);s.int32(a)},n=function(i){let s=i.int32();return t(s)};return As("enum",no.VARINT,e,n)}function le(r,t){return As("message",no.LENGTH_DELIMITED,r,t)}function yp(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function U1(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function oo(r,...t){if(!U1(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function wp(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");yp(r.outputLen),yp(r.blockLen)}function io(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function bp(r,t){oo(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var vn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Is=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),De=(r,t)=>r<<32-t|r>>>t;var dT=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xp(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function si(r){return typeof r=="string"&&(r=xp(r)),oo(r),r}function Hu(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];oo(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}var so=class{clone(){return this._cloneInto()}},pT={}.toString;function ks(r){let t=n=>r().update(si(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Ts(r=32){if(vn&&typeof vn.getRandomValues=="function")return vn.getRandomValues(new Uint8Array(r));if(vn&&typeof vn.randomBytes=="function")return vn.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function F1(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(e>>o&i),a=Number(e&i),c=n?4:0,l=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+l,a,n)}var Ep=(r,t,e)=>r&t^~r&e,vp=(r,t,e)=>r&t^r&e^t&e,ao=class extends so{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Is(this.buffer)}update(t){io(this);let{view:e,buffer:n,blockLen:o}=this;t=si(t);let i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Is(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){io(this),bp(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;F1(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=Is(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.length=o,t.pos=a,t.finished=i,t.destroyed=s,o%e&&t.buffer.set(n),t}};var Bs=BigInt(4294967295),$u=BigInt(32);function Sp(r,t=!1){return t?{h:Number(r&Bs),l:Number(r>>$u&Bs)}:{h:Number(r>>$u&Bs)|0,l:Number(r&Bs)|0}}function M1(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=Sp(r[o],t);[e[o],n[o]]=[i,s]}return[e,n]}var V1=(r,t)=>BigInt(r>>>0)<<$u|BigInt(t>>>0),H1=(r,t,e)=>r>>>e,$1=(r,t,e)=>r<<32-e|t>>>e,z1=(r,t,e)=>r>>>e|t<<32-e,q1=(r,t,e)=>r<<32-e|t>>>e,K1=(r,t,e)=>r<<64-e|t>>>e-32,G1=(r,t,e)=>r>>>e-32|t<<64-e,W1=(r,t)=>t,j1=(r,t)=>r,Y1=(r,t,e)=>r<<e|t>>>32-e,X1=(r,t,e)=>t<<e|r>>>32-e,Z1=(r,t,e)=>t<<e-32|r>>>64-e,J1=(r,t,e)=>r<<e-32|t>>>64-e;function Q1(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var tE=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),eE=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,rE=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),nE=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,oE=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),iE=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var sE={fromBig:Sp,split:M1,toBig:V1,shrSH:H1,shrSL:$1,rotrSH:z1,rotrSL:q1,rotrBH:K1,rotrBL:G1,rotr32H:W1,rotr32L:j1,rotlSH:Y1,rotlSL:X1,rotlBH:Z1,rotlBL:J1,add:Q1,add3L:tE,add3H:eE,add4L:rE,add4H:nE,add5H:iE,add5L:oE},j=sE;var[aE,cE]=j.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Kr=new Uint32Array(80),Gr=new Uint32Array(80),zu=class extends ao{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:m,Hh:p,Hl:y}=this;return[t,e,n,o,i,s,a,c,l,u,f,d,h,m,p,y]}set(t,e,n,o,i,s,a,c,l,u,f,d,h,m,p,y){this.Ah=t|0,this.Al=e|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=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=p|0,this.Hl=y|0}process(t,e){for(let b=0;b<16;b++,e+=4)Kr[b]=t.getUint32(e),Gr[b]=t.getUint32(e+=4);for(let b=16;b<80;b++){let E=Kr[b-15]|0,I=Gr[b-15]|0,B=j.rotrSH(E,I,1)^j.rotrSH(E,I,8)^j.shrSH(E,I,7),S=j.rotrSL(E,I,1)^j.rotrSL(E,I,8)^j.shrSL(E,I,7),v=Kr[b-2]|0,k=Gr[b-2]|0,z=j.rotrSH(v,k,19)^j.rotrBH(v,k,61)^j.shrSH(v,k,6),F=j.rotrSL(v,k,19)^j.rotrBL(v,k,61)^j.shrSL(v,k,6),U=j.add4L(S,F,Gr[b-7],Gr[b-16]),D=j.add4H(U,B,z,Kr[b-7],Kr[b-16]);Kr[b]=D|0,Gr[b]=U|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:m,Gh:p,Gl:y,Hh:g,Hl:x}=this;for(let b=0;b<80;b++){let E=j.rotrSH(f,d,14)^j.rotrSH(f,d,18)^j.rotrBH(f,d,41),I=j.rotrSL(f,d,14)^j.rotrSL(f,d,18)^j.rotrBL(f,d,41),B=f&h^~f&p,S=d&m^~d&y,v=j.add5L(x,I,S,cE[b],Gr[b]),k=j.add5H(v,g,E,B,aE[b],Kr[b]),z=v|0,F=j.rotrSH(n,o,28)^j.rotrBH(n,o,34)^j.rotrBH(n,o,39),U=j.rotrSL(n,o,28)^j.rotrBL(n,o,34)^j.rotrBL(n,o,39),D=n&i^n&a^i&a,R=o&s^o&c^s&c;g=p|0,x=y|0,p=h|0,y=m|0,h=f|0,m=d|0,{h:f,l:d}=j.add(l|0,u|0,k|0,z|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let N=j.add3L(z,U,R);n=j.add3H(N,k,F,D),o=N|0}({h:n,l:o}=j.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=j.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=j.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=j.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=j.add(this.Eh|0,this.El|0,f|0,d|0),{h,l:m}=j.add(this.Fh|0,this.Fl|0,h|0,m|0),{h:p,l:y}=j.add(this.Gh|0,this.Gl|0,p|0,y|0),{h:g,l:x}=j.add(this.Hh|0,this.Hl|0,g|0,x|0),this.set(n,o,i,s,a,c,l,u,f,d,h,m,p,y,g,x)}roundClean(){Kr.fill(0),Gr.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var _p=ks(()=>new zu);var Rs={};Et(Rs,{aInRange:()=>ue,abool:()=>Oe,abytes:()=>co,bitGet:()=>pE,bitLen:()=>ju,bitMask:()=>ci,bitSet:()=>mE,bytesToHex:()=>mr,bytesToNumberBE:()=>gr,bytesToNumberLE:()=>jr,concatBytes:()=>yr,createHmacDrbg:()=>Yu,ensureBytes:()=>xt,equalBytes:()=>hE,hexToBytes:()=>_n,hexToNumber:()=>Wu,inRange:()=>ai,isBytes:()=>Wr,memoized:()=>In,notImplemented:()=>yE,numberToBytesBE:()=>Yr,numberToBytesLE:()=>An,numberToHexUnpadded:()=>Sn,numberToVarBytesBE:()=>fE,utf8ToBytes:()=>dE,validateObject:()=>Je});var Gu=BigInt(0),Cs=BigInt(1),lE=BigInt(2);function Wr(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function co(r){if(!Wr(r))throw new Error("Uint8Array expected")}function Oe(r,t){if(typeof t!="boolean")throw new Error(`${r} must be valid boolean, got "${t}".`)}var uE=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function mr(r){co(r);let t="";for(let e=0;e<r.length;e++)t+=uE[r[e]];return t}function Sn(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function Wu(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var pr={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Ap(r){if(r>=pr._0&&r<=pr._9)return r-pr._0;if(r>=pr._A&&r<=pr._F)return r-(pr._A-10);if(r>=pr._a&&r<=pr._f)return r-(pr._a-10)}function _n(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,i=0;o<e;o++,i+=2){let s=Ap(r.charCodeAt(i)),a=Ap(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function gr(r){return Wu(mr(r))}function jr(r){return co(r),Wu(mr(Uint8Array.from(r).reverse()))}function Yr(r,t){return _n(r.toString(16).padStart(t*2,"0"))}function An(r,t){return Yr(r,t).reverse()}function fE(r){return _n(Sn(r))}function xt(r,t,e){let n;if(typeof t=="string")try{n=_n(t)}catch(i){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${i}`)}else if(Wr(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function yr(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];co(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}function hE(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function dE(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var qu=r=>typeof r=="bigint"&&Gu<=r;function ai(r,t,e){return qu(r)&&qu(t)&&qu(e)&&t<=r&&r<e}function ue(r,t,e,n){if(!ai(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function ju(r){let t;for(t=0;r>Gu;r>>=Cs,t+=1);return t}function pE(r,t){return r>>BigInt(t)&Cs}function mE(r,t,e){return r|(e?Cs:Gu)<<BigInt(t)}var ci=r=>(lE<<BigInt(r-1))-Cs,Ku=r=>new Uint8Array(r),Ip=r=>Uint8Array.from(r);function Yu(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Ku(r),o=Ku(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>e(o,n,...f),c=(f=Ku())=>{o=a(Ip([0]),f),n=a(),f.length!==0&&(o=a(Ip([1]),f),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let h=n.slice();d.push(h),f+=n.length}return yr(...d)};return(f,d)=>{s(),c(f);let h;for(;!(h=d(l()));)c();return s(),h}}var gE={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Wr(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Je(r,t,e={}){let n=(o,i,s)=>{let a=gE[i];if(typeof a!="function")throw new Error(`Invalid validator "${i}", expected function`);let c=r[o];if(!(s&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${i}`)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(e))n(o,i,!0);return r}var yE=()=>{throw new Error("not implemented")};function In(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let i=r(e,...n);return t.set(e,i),i}}var Tt=BigInt(0),dt=BigInt(1),kn=BigInt(2),wE=BigInt(3),Xu=BigInt(4),kp=BigInt(5),Tp=BigInt(8),bE=BigInt(9),xE=BigInt(16);function ct(r,t){let e=r%t;return e>=Tt?e:t+e}function EE(r,t,e){if(e<=Tt||t<Tt)throw new Error("Expected power/modulo > 0");if(e===dt)return Tt;let n=dt;for(;t>Tt;)t&dt&&(n=n*r%e),r=r*r%e,t>>=dt;return n}function pt(r,t,e){let n=r;for(;t-- >Tt;)n*=n,n%=e;return n}function Ns(r,t){if(r===Tt||t<=Tt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=ct(r,t),n=t,o=Tt,i=dt,s=dt,a=Tt;for(;e!==Tt;){let l=n/e,u=n%e,f=o-s*l,d=i-a*l;n=e,e=u,o=s,i=a,s=f,a=d}if(n!==dt)throw new Error("invert: does not exist");return ct(o,t)}function vE(r){let t=(r-dt)/kn,e,n,o;for(e=r-dt,n=0;e%kn===Tt;e/=kn,n++);for(o=kn;o<r&&EE(o,t,r)!==r-dt;o++);if(n===1){let s=(r+dt)/Xu;return function(c,l){let u=c.pow(l,s);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let i=(e+dt)/kn;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,i),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let p=a.sqr(d);h<l&&!a.eql(p,a.ONE);h++)p=a.sqr(p);let m=a.pow(u,dt<<BigInt(l-h-1));u=a.sqr(m),f=a.mul(f,m),d=a.mul(d,u),l=h}return f}}function SE(r){if(r%Xu===wE){let t=(r+dt)/Xu;return function(n,o){let i=n.pow(o,t);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%Tp===kp){let t=(r-kp)/Tp;return function(n,o){let i=n.mul(o,kn),s=n.pow(i,t),a=n.mul(o,s),c=n.mul(n.mul(a,kn),s),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%xE,vE(r)}var Bp=(r,t)=>(ct(r,t)&dt)===dt,_E=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Zu(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=_E.reduce((n,o)=>(n[o]="function",n),t);return Je(r,e)}function AE(r,t,e){if(e<Tt)throw new Error("Expected power > 0");if(e===Tt)return r.ONE;if(e===dt)return t;let n=r.ONE,o=t;for(;e>Tt;)e&dt&&(n=r.mul(n,o)),o=r.sqr(o),e>>=dt;return n}function IE(r,t){let e=new Array(t.length),n=t.reduce((i,s,a)=>r.is0(s)?i:(e[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return t.reduceRight((i,s,a)=>r.is0(s)?i:(e[a]=r.mul(i,e[a]),r.mul(i,s)),o),e}function Ju(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Xr(r,t,e=!1,n={}){if(r<=Tt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:i}=Ju(r,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=SE(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:i,MASK:ci(o),ZERO:Tt,ONE:dt,create:c=>ct(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Tt<=c&&c<r},is0:c=>c===Tt,isOdd:c=>(c&dt)===dt,neg:c=>ct(-c,r),eql:(c,l)=>c===l,sqr:c=>ct(c*c,r),add:(c,l)=>ct(c+l,r),sub:(c,l)=>ct(c-l,r),mul:(c,l)=>ct(c*l,r),pow:(c,l)=>AE(a,c,l),div:(c,l)=>ct(c*Ns(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Ns(c,r),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>IE(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?An(c,i):Yr(c,i),fromBytes:c=>{if(c.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);return e?jr(c):gr(c)}});return Object.freeze(a)}function Cp(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Qu(r){let t=Cp(r);return t+Math.ceil(t/2)}function Rp(r,t,e=!1){let n=r.length,o=Cp(t),i=Qu(t);if(n<16||n<i||n>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);let s=e?gr(r):jr(r),a=ct(s,t-dt)+dt;return e?An(a,o):Yr(a,o)}var TE=BigInt(0),tf=BigInt(1),ef=new WeakMap,Np=new WeakMap;function Ps(r,t){let e=(i,s)=>{let a=s.negate();return i?a:s},n=i=>{if(!Number.isSafeInteger(i)||i<=0||i>t)throw new Error(`Wrong window size=${i}, should be [1..${t}]`)},o=i=>{n(i);let s=Math.ceil(t/i)+1,a=2**(i-1);return{windows:s,windowSize:a}};return{constTimeNegate:e,unsafeLadder(i,s){let a=r.ZERO,c=i;for(;s>TE;)s&tf&&(a=a.add(c)),c=c.double(),s>>=tf;return a},precomputeWindow(i,s){let{windows:a,windowSize:c}=o(s),l=[],u=i,f=u;for(let d=0;d<a;d++){f=u,l.push(f);for(let h=1;h<c;h++)f=f.add(u),l.push(f);u=f.double()}return l},wNAF(i,s,a){let{windows:c,windowSize:l}=o(i),u=r.ZERO,f=r.BASE,d=BigInt(2**i-1),h=2**i,m=BigInt(i);for(let p=0;p<c;p++){let y=p*l,g=Number(a&d);a>>=m,g>l&&(g-=h,a+=tf);let x=y,b=y+Math.abs(g)-1,E=p%2!==0,I=g<0;g===0?f=f.add(e(E,s[x])):u=u.add(e(I,s[b]))}return{p:u,f}},wNAFCached(i,s,a){let c=Np.get(i)||1,l=ef.get(i);return l||(l=this.precomputeWindow(i,c),c!==1&&ef.set(i,a(l))),this.wNAF(c,l,s)},setWindowSize(i,s){n(s),Np.set(i,s),ef.delete(i)}}}function Ls(r,t,e,n){if(!Array.isArray(e)||!Array.isArray(n)||n.length!==e.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((u,f)=>{if(!t.isValid(u))throw new Error(`wrong scalar at index ${f}`)}),e.forEach((u,f)=>{if(!(u instanceof r))throw new Error(`wrong point at index ${f}`)});let o=ju(BigInt(e.length)),i=o>12?o-3:o>4?o-2:o?2:1,s=(1<<i)-1,a=new Array(s+1).fill(r.ZERO),c=Math.floor((t.BITS-1)/i)*i,l=r.ZERO;for(let u=c;u>=0;u-=i){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],m=Number(h>>BigInt(u)&BigInt(s));a[m]=a[m].add(e[d])}let f=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),f=f.add(h);if(l=l.add(f),u!==0)for(let d=0;d<i;d++)l=l.double()}return l}function li(r){return Zu(r.Fp),Je(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ju(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Ue=BigInt(0),fe=BigInt(1),Ds=BigInt(2),BE=BigInt(8),CE={zip215:!0};function RE(r){let t=li(r);return Je(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Pp(r){let t=RE(r),{Fp:e,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=Ds<<BigInt(a*8)-fe,u=e.create,f=Xr(t.n,t.nBitLength),d=t.uvRatio||((A,_)=>{try{return{isValid:!0,value:e.sqrt(A*e.inv(_))}}catch{return{isValid:!1,value:Ue}}}),h=t.adjustScalarBytes||(A=>A),m=t.domain||((A,_,C)=>{if(Oe("phflag",C),_.length||C)throw new Error("Contexts/pre-hash are not supported");return A});function p(A,_){ue("coordinate "+A,_,Ue,l)}function y(A){if(!(A instanceof b))throw new Error("ExtendedPoint expected")}let g=In((A,_)=>{let{ex:C,ey:V,ez:q}=A,K=A.is0();_==null&&(_=K?BE:e.inv(q));let J=u(C*_),et=u(V*_),Q=u(q*_);if(K)return{x:Ue,y:fe};if(Q!==fe)throw new Error("invZ was invalid");return{x:J,y:et}}),x=In(A=>{let{a:_,d:C}=t;if(A.is0())throw new Error("bad point: ZERO");let{ex:V,ey:q,ez:K,et:J}=A,et=u(V*V),Q=u(q*q),at=u(K*K),ft=u(at*at),Rt=u(et*_),Nt=u(at*u(Rt+Q)),Ot=u(ft+u(C*u(et*Q)));if(Nt!==Ot)throw new Error("bad point: equation left != right (1)");let Xt=u(V*q),It=u(K*J);if(Xt!==It)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(_,C,V,q){this.ex=_,this.ey=C,this.ez=V,this.et=q,p("x",_),p("y",C),p("z",V),p("t",q),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof b)throw new Error("extended point not allowed");let{x:C,y:V}=_||{};return p("x",C),p("y",V),new b(C,V,fe,u(C*V))}static normalizeZ(_){let C=e.invertBatch(_.map(V=>V.ez));return _.map((V,q)=>V.toAffine(C[q])).map(b.fromAffine)}static msm(_,C){return Ls(b,f,_,C)}_setWindowSize(_){B.setWindowSize(this,_)}assertValidity(){x(this)}equals(_){y(_);let{ex:C,ey:V,ez:q}=this,{ex:K,ey:J,ez:et}=_,Q=u(C*et),at=u(K*q),ft=u(V*et),Rt=u(J*q);return Q===at&&ft===Rt}is0(){return this.equals(b.ZERO)}negate(){return new b(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:_}=t,{ex:C,ey:V,ez:q}=this,K=u(C*C),J=u(V*V),et=u(Ds*u(q*q)),Q=u(_*K),at=C+V,ft=u(u(at*at)-K-J),Rt=Q+J,Nt=Rt-et,Ot=Q-J,Xt=u(ft*Nt),It=u(Rt*Ot),ee=u(ft*Ot),ur=u(Nt*Rt);return new b(Xt,It,ur,ee)}add(_){y(_);let{a:C,d:V}=t,{ex:q,ey:K,ez:J,et}=this,{ex:Q,ey:at,ez:ft,et:Rt}=_;if(C===BigInt(-1)){let Cd=u((K-q)*(at+Q)),Rd=u((K+q)*(at-Q)),Yl=u(Rd-Cd);if(Yl===Ue)return this.double();let Nd=u(J*Ds*Rt),Pd=u(et*Ds*ft),Ld=Pd+Nd,Dd=Rd+Cd,Od=Pd-Nd,Gb=u(Ld*Yl),Wb=u(Dd*Od),jb=u(Ld*Od),Yb=u(Yl*Dd);return new b(Gb,Wb,Yb,jb)}let Nt=u(q*Q),Ot=u(K*at),Xt=u(et*V*Rt),It=u(J*ft),ee=u((q+K)*(Q+at)-Nt-Ot),ur=It-Xt,Yo=It+Xt,Xo=u(Ot-C*Nt),$b=u(ee*ur),zb=u(Yo*Xo),qb=u(ee*Xo),Kb=u(ur*Yo);return new b($b,zb,Kb,qb)}subtract(_){return this.add(_.negate())}wNAF(_){return B.wNAFCached(this,_,b.normalizeZ)}multiply(_){let C=_;ue("scalar",C,fe,n);let{p:V,f:q}=this.wNAF(C);return b.normalizeZ([V,q])[0]}multiplyUnsafe(_){let C=_;return ue("scalar",C,Ue,n),C===Ue?I:this.equals(I)||C===fe?this:this.equals(E)?this.wNAF(C).p:B.unsafeLadder(this,C)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return B.unsafeLadder(this,n).is0()}toAffine(_){return g(this,_)}clearCofactor(){let{h:_}=t;return _===fe?this:this.multiplyUnsafe(_)}static fromHex(_,C=!1){let{d:V,a:q}=t,K=e.BYTES;_=xt("pointHex",_,K),Oe("zip215",C);let J=_.slice(),et=_[K-1];J[K-1]=et&-129;let Q=jr(J),at=C?l:e.ORDER;ue("pointHex.y",Q,Ue,at);let ft=u(Q*Q),Rt=u(ft-fe),Nt=u(V*ft-q),{isValid:Ot,value:Xt}=d(Rt,Nt);if(!Ot)throw new Error("Point.fromHex: invalid y coordinate");let It=(Xt&fe)===fe,ee=(et&128)!==0;if(!C&&Xt===Ue&&ee)throw new Error("Point.fromHex: x=0 and x_0=1");return ee!==It&&(Xt=u(-Xt)),b.fromAffine({x:Xt,y:Q})}static fromPrivateKey(_){return k(_).point}toRawBytes(){let{x:_,y:C}=this.toAffine(),V=An(C,e.BYTES);return V[V.length-1]|=_&fe?128:0,V}toHex(){return mr(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,fe,u(t.Gx*t.Gy)),b.ZERO=new b(Ue,fe,fe,Ue);let{BASE:E,ZERO:I}=b,B=Ps(b,a*8);function S(A){return ct(A,n)}function v(A){return S(jr(A))}function k(A){let _=a;A=xt("private key",A,_);let C=xt("hashed private key",i(A),2*_),V=h(C.slice(0,_)),q=C.slice(_,2*_),K=v(V),J=E.multiply(K),et=J.toRawBytes();return{head:V,prefix:q,scalar:K,point:J,pointBytes:et}}function z(A){return k(A).pointBytes}function F(A=new Uint8Array,..._){let C=yr(..._);return v(i(m(C,xt("context",A),!!o)))}function U(A,_,C={}){A=xt("message",A),o&&(A=o(A));let{prefix:V,scalar:q,pointBytes:K}=k(_),J=F(C.context,V,A),et=E.multiply(J).toRawBytes(),Q=F(C.context,et,K,A),at=S(J+Q*q);ue("signature.s",at,Ue,n);let ft=yr(et,An(at,e.BYTES));return xt("result",ft,a*2)}let D=CE;function R(A,_,C,V=D){let{context:q,zip215:K}=V,J=e.BYTES;A=xt("signature",A,2*J),_=xt("message",_),K!==void 0&&Oe("zip215",K),o&&(_=o(_));let et=jr(A.slice(J,2*J)),Q,at,ft;try{Q=b.fromHex(C,K),at=b.fromHex(A.slice(0,J),K),ft=E.multiplyUnsafe(et)}catch{return!1}if(!K&&Q.isSmallOrder())return!1;let Rt=F(q,at.toRawBytes(),Q.toRawBytes(),_);return at.add(Q.multiplyUnsafe(Rt)).subtract(ft).clearCofactor().equals(b.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:z,sign:U,verify:R,ExtendedPoint:b,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>s(e.BYTES),precompute(A=8,_=b.BASE){return _._setWindowSize(A),_.multiply(BigInt(3)),_}}}}var rf=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Lp=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),UT=BigInt(0),NE=BigInt(1),Dp=BigInt(2),FT=BigInt(3),PE=BigInt(5),LE=BigInt(8);function DE(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=rf,a=r*r%i*r%i,c=pt(a,Dp,i)*a%i,l=pt(c,NE,i)*r%i,u=pt(l,PE,i)*l%i,f=pt(u,t,i)*u%i,d=pt(f,e,i)*f%i,h=pt(d,n,i)*d%i,m=pt(h,o,i)*h%i,p=pt(m,o,i)*h%i,y=pt(p,t,i)*u%i;return{pow_p_5_8:pt(y,Dp,i)*r%i,b2:a}}function OE(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function UE(r,t){let e=rf,n=ct(t*t*t,e),o=ct(n*n*t,e),i=DE(r*o).pow_p_5_8,s=ct(r*n*i,e),a=ct(t*s*s,e),c=s,l=ct(s*Lp,e),u=a===r,f=a===ct(-r,e),d=a===ct(-r*Lp,e);return u&&(s=c),(f||d)&&(s=l),Bp(s,e)&&(s=ct(-s,e)),{isValid:u||f,value:s}}var FE=Xr(rf,void 0,!0),ME={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:FE,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:LE,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:_p,randomBytes:Ts,adjustScalarBytes:OE,uvRatio:UE},Op=Pp(ME);var Os=32;function Up(r,t,e){return Op.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var Us=class{type="Ed25519";raw;constructor(t){this.raw=nf(t,Os)}toMultihash(){return bt.digest(lo(this))}toCID(){return P.createV1(114,this.toMultihash())}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Y(this.raw,t.raw)}verify(t,e){return Up(this.raw,e,t)}};function of(r){return r=nf(r,Os),new Us(r)}function nf(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new St(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Bt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(Bt||(Bt={}));var sf;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(sf||(sf={}));(function(r){r.codec=()=>dr(sf)})(Bt||(Bt={}));var Qe;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),Bt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=Bt.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>ce(e,r.codec()),r.decode=(e,n)=>ie(e,r.codec(),n)})(Qe||(Qe={}));var af;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),Bt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=Bt.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>ce(e,r.codec()),r.decode=(e,n)=>ie(e,r.codec(),n)})(af||(af={}));var bi={};Et(bi,{MAX_RSA_KEY_SIZE:()=>Ta,generateRSAKeyPair:()=>Dm,jwkToJWKKeyPair:()=>Om,jwkToPkcs1:()=>rv,jwkToPkix:()=>gf,jwkToRSAPrivateKey:()=>Lm,pkcs1ToJwk:()=>Rm,pkcs1ToRSAPrivateKey:()=>Pm,pkixToJwk:()=>Nm,pkixToRSAPublicKey:()=>yf});var HE=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Zr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jr=new Uint32Array(64),cf=class extends ao{constructor(){super(64,32,8,!1),this.A=Zr[0]|0,this.B=Zr[1]|0,this.C=Zr[2]|0,this.D=Zr[3]|0,this.E=Zr[4]|0,this.F=Zr[5]|0,this.G=Zr[6]|0,this.H=Zr[7]|0}get(){let{A:t,B:e,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,e,n,o,i,s,a,c]}set(t,e,n,o,i,s,a,c){this.A=t|0,this.B=e|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(t,e){for(let f=0;f<16;f++,e+=4)Jr[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Jr[f-15],h=Jr[f-2],m=De(d,7)^De(d,18)^d>>>3,p=De(h,17)^De(h,19)^h>>>10;Jr[f]=p+Jr[f-7]+m+Jr[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=De(a,6)^De(a,11)^De(a,25),h=u+d+Ep(a,c,l)+HE[f]+Jr[f]|0,p=(De(n,2)^De(n,13)^De(n,22))+vp(n,o,i)|0;u=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+p|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(){Jr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var uo=ks(()=>new cf);var tt=Ut(Vp());function Tn(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function Qr(r,t,e=-1){let n=e,o=r,i=0,s=Math.pow(2,t);for(let a=1;a<8;a++){if(r<s){let c;if(n<0)c=new ArrayBuffer(a),i=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*t);l[i-u-1]=Math.floor(o/f),o-=l[i-u-1]*f}return c}s*=Math.pow(2,t)}return new ArrayBuffer(0)}function Vs(...r){let t=0,e=0;for(let i of r)t+=i.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let i of r)o.set(i,e),e+=i.length;return o}function uf(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=Tn(e,8),o=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=r[a];return i[0]&=127,Tn(i,8)-n}function Hp(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let s=e-t,a=Qr(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Qr(t,8,n),i=new Uint8Array(o);if(i[0]&128){let s=o.slice(0),a=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),i=new Uint8Array(o);for(let c=0;c<s.byteLength;c++)i[c+1]=a[c];i[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function $p(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function he(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(e)}var aB=Math.log(2);function Hs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function ff(r){let t=0,e=0;for(let o=0;o<r.length;o++){let i=r[o];t+=i.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let i=r[o];n.set(new Uint8Array(i),e),e+=i.byteLength}return n.buffer}function vr(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var fi=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return ff(this.items)}},ui=[new Uint8Array([1])],zp="0123456789";var go="",Fe=new ArrayBuffer(0),hf=new Uint8Array(0),hi="EndOfContent",Kp="OCTET STRING",Gp="BIT STRING";function Sr(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let i=n[0]||{};this.isHexOnly=(o=i.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=i.valueHex?tt.BufferSourceConverter.toUint8Array(i.valueHex):hf}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,i){let s=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!vr(this,s,o,i))return-1;let a=o+i;return this.valueHexView=s.subarray(o,a),this.valueHexView.length?(this.blockLength=i,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Fe)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:tt.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var br=class{constructor({blockLength:t=0,error:e=go,warnings:n=[],valueBeforeDecode:o=hf}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=tt.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:tt.Convert.ToHex(this.valueBeforeDecodeView)}}};br.NAME="baseBlock";var Wt=class extends br{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Wt.NAME="valueBlock";var $s=class extends Sr(br){constructor({idBlock:t={}}={}){var e,n,o,i;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?tt.BufferSourceConverter.toUint8Array(t.valueHex):hf,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(i=t.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",Fe}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let i=this.tagNumber;i&=31,e|=i,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=Qr(this.tagNumber,7),i=new Uint8Array(o),s=o.byteLength,a=new Uint8Array(s+1);if(a[0]=e|31,!t){for(let c=0;c<s-1;c++)a[c+1]=i[c]|128;a[s]=i[s-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let i=0;i<o.length-1;i++)n[i+1]=o[i]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;i[c]&128;){if(l[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let h=0;h<l.length;h++)d[h]=l[h];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=i[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=Tn(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};$s.NAME="identificationBlock";var zs=class extends br{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,e+this.blockLength;let s=i[0]&127;if(s>8)return this.error="Too big integer",-1;if(s+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Tn(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=Qr(this.length,8);if(o.byteLength>127)return this.error="Too big length",Fe;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let i=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let s=0;s<o.byteLength;s++)n[s+1]=i[s];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};zs.NAME="lengthBlock";var M={},Ft=class extends br{constructor({name:t=go,optional:e=!1,primitiveSchema:n,...o}={},i){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new $s(o),this.lenBlock=new zs(o),this.valueBlock=i?new i(o):new Wt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(t,e){let n=e||new fi;e||Wp(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(t);this.lenBlock.length=i.byteLength;let s=this.lenBlock.toBER(t);n.write(s),n.write(i)}return e?Fe:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():tt.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${tt.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return $p(e,n)}};Ft.NAME="BaseBlock";function Wp(r){if(r instanceof M.Constructed)for(let t of r.valueBlock.value)Wp(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var qs=class extends Ft{constructor({value:t=go,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};qs.NAME="BaseStringBlock";var Ks=class extends Sr(Wt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};Ks.NAME="PrimitiveValueBlock";var jp,Gs=class extends Ft{constructor(t={}){super(t,Ks),this.idBlock.isConstructed=!1}};jp=Gs;M.Primitive=jp;Gs.NAME="PRIMITIVE";function XE(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function Ia(r,t=0,e=r.length){let n=t,o=new Ft({},Wt),i=new br;if(!vr(i,r,t,e))return o.error=i.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ft;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=M.EndOfContent;break;case 1:c=M.Boolean;break;case 2:c=M.Integer;break;case 3:c=M.BitString;break;case 4:c=M.OctetString;break;case 5:c=M.Null;break;case 6:c=M.ObjectIdentifier;break;case 10:c=M.Enumerated;break;case 12:c=M.Utf8String;break;case 13:c=M.RelativeObjectIdentifier;break;case 14:c=M.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=M.Sequence;break;case 17:c=M.Set;break;case 18:c=M.NumericString;break;case 19:c=M.PrintableString;break;case 20:c=M.TeletexString;break;case 21:c=M.VideotexString;break;case 22:c=M.IA5String;break;case 23:c=M.UTCTime;break;case 24:c=M.GeneralizedTime;break;case 25:c=M.GraphicString;break;case 26:c=M.VisibleString;break;case 27:c=M.GeneralString;break;case 28:c=M.UniversalString;break;case 29:c=M.CharacterString;break;case 30:c=M.BmpString;break;case 31:c=M.DATE;break;case 32:c=M.TimeOfDay;break;case 33:c=M.DateTime;break;case 34:c=M.Duration;break;default:{let l=o.idBlock.isConstructed?new M.Constructed:new M.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?M.Constructed:M.Primitive}return o=XE(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function df(r){if(!r.byteLength){let t=new Ft({},Wt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Ia(tt.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function ZE(r,t){return r?1:t}var tr=class extends Wt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let i=e;for(;ZE(this.isIndefiniteForm,n)>0;){let s=Ia(o,i,n);if(s.offset===-1)return this.error=s.result.error,this.warnings.concat(s.result.warnings),-1;if(i=s.offset,this.blockLength+=s.result.blockLength,n-=s.result.blockLength,this.value.push(s.result),this.isIndefiniteForm&&s.result.constructor.NAME===hi)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===hi?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(t,e){let n=e||new fi;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?Fe:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};tr.NAME="ConstructedValueBlock";var Yp,tn=class extends Ft{constructor(t={}){super(t,tr),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
|
|
4
4
|
`).map(o=>` ${o}`).join(`
|
|
5
5
|
`));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
|
|
6
6
|
${t.join(`
|
|
7
|
-
`)}`:`${e} :`}};Hp=tn;M.Constructed=Hp;tn.NAME="CONSTRUCTED";var Vs=class extends Gt{fromBER(t,e,n){return e}toBER(t){return Fe}};Vs.override="EndOfContentValueBlock";var $p,Hs=class extends Ut{constructor(t={}){super(t,Vs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};$p=Hs;M.EndOfContent=$p;Hs.NAME=ci;var zp,lo=class extends Ut{constructor(t={}){super(t,Gt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};zp=lo;M.Null=zp;lo.NAME="NULL";var $s=class extends Sr(Gt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=tt.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);return vr(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,sf.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};$s.NAME="BooleanValueBlock";var qp,zs=class extends Ut{constructor(t={}){super(t,$s),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};qp=zs;M.Boolean=qp;zs.NAME="BOOLEAN";var qs=class extends Sr(Qe){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=Qe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===ci){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==Up)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?Qe.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};qs.NAME="OctetStringValueBlock";var Kp,Ks=class r extends Ut{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},qs),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let i=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(i.byteLength){let s=ba(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?tn.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${tt.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return tt.BufferSourceConverter.concat(t)}};Kp=Ks;M.OctetString=Kp;Ks.NAME=Up;var Gs=class extends Sr(Qe){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=Qe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===ci){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Fp)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,i,e,n))return-1;let s=i.subarray(e,e+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=ba(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,e+n}toBER(t,e){if(this.isConstructed)return Qe.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Fe;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Gs.NAME="BitStringValueBlock";var Gp,uo=class extends Ut{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Gs),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return tn.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Gp=uo;M.BitString=Gp;uo.NAME=Fp;var Wp;function ME(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<s?s:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=i[s-f]+a[c-f]+e[0];break;default:l=i[s-f]+e[0]}switch(e[0]=l/10,!0){case f>=i.length:i=Ls(new Uint8Array([l%10]),i);break;default:i[s-f]=l%10}}return e[0]>0&&(i=Ls(e,i)),i}function Op(r){if(r>=si.length)for(let t=si.length;t<=r;t++){let e=new Uint8Array([0]),n=si[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=i[0]/10,n[o]=i[0]%10}e[0]>0&&(n=Ls(e,n)),si.push(n)}return si[r]}function VE(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=i[s-u]-a[c-u]-e,!0){case l<0:e=1,i[s-u]=l+10;break;default:e=0,i[s-u]=l}if(e>0)for(let f=s-c+1;f>=0;f--,u++)if(l=i[s-u]-e,l<0)e=1,i[s-u]=l+10;else{e=0,i[s-u]=l;break}return i.slice()}var li=class extends Sr(Gt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=sf.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Lp(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let i=this.fromBER(t,e,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&s[1]&128?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case t:e=VE(Op(n),e),s="-";break;default:e=ME(e,Op(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(s+=Dp.charAt(e[c]));return a===!1&&(s+=Dp.charAt(0)),s}};Wp=li;li.NAME="IntegerValueBlock";Object.defineProperty(Wp.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var jp,Ft=class r extends Ut{constructor(t={}){super(t,li),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Ps(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Ps();let e=BigInt(t),n=new ai,o=e.toString(16).replace(/^-/,""),i=new Uint8Array(tt.Convert.FromHex(o));if(e<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${tt.Convert.ToHex(a)}`)+e,u=tt.BufferSourceConverter.toUint8Array(tt.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};jp=Ft;M.Integer=jp;Ft.NAME="INTEGER";var Yp,Ws=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Yp=Ws;M.Enumerated=Yp;Ws.NAME="ENUMERATED";var ui=class extends Sr(Gt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=_n(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Ps();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let e=Qr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",Fe;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),i=e.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let t="";if(this.isHexOnly)t=tt.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};ui.NAME="sidBlock";var js=class extends Gt{constructor({value:t=ho,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let i=new ui;if(o=i.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,Fe;e.push(o)}return af(e)}fromString(t){this.value=[];let e=0,n=0,o="",i=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,i){let s=this.value[0],a=0;switch(s.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;s.valueDec=c+a,i=!1}else{let s=new ui;if(o>Number.MAX_SAFE_INTEGER){Ps();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};js.NAME="ObjectIdentifierValueBlock";var Xp,fo=class extends Ut{constructor(t={}){super(t,js),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Xp=fo;M.ObjectIdentifier=Xp;fo.NAME="OBJECT IDENTIFIER";var fi=class extends Sr(br){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=_n(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let e=Qr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",Fe;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),i=e.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let t="";return this.isHexOnly?t=tt.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};fi.NAME="relativeSidBlock";var Ys=class extends Gt{constructor({value:t=ho,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let i=new fi;if(o=i.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(t);if(i.byteLength===0)return this.error=this.value[o].error,Fe;n.push(i)}return af(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let i=new fi;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Ys.NAME="RelativeObjectIdentifierValueBlock";var Zp,Xs=class extends Ut{constructor(t={}){super(t,Ys),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Zp=Xs;M.RelativeObjectIdentifier=Zp;Xs.NAME="RelativeObjectIdentifier";var Jp,xr=class extends tn{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Jp=xr;M.Sequence=Jp;xr.NAME="SEQUENCE";var Qp,Zs=class extends tn{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Qp=Zs;M.Set=Qp;Zs.NAME="SET";var Js=class extends Sr(Gt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=ho}toJSON(){return{...super.toJSON(),value:this.value}}};Js.NAME="StringValueBlock";var Qs=class extends Js{};Qs.NAME="SimpleStringValueBlock";var Zt=class extends Us{constructor({...t}={}){super(t,Qs)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,tt.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Zt.NAME="SIMPLE STRING";var ta=class extends Zt{fromBuffer(t){this.valueBlock.valueHexView=tt.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=tt.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=tt.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(tt.Convert.FromUtf8String(t)),this.valueBlock.value=t}};ta.NAME="Utf8StringValueBlock";var tm,Er=class extends ta{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};tm=Er;M.Utf8String=tm;Er.NAME="UTF8String";var ea=class extends Zt{fromBuffer(t){this.valueBlock.value=tt.Convert.ToUtf16String(t),this.valueBlock.valueHexView=tt.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(tt.Convert.FromUtf16String(t))}};ea.NAME="BmpStringValueBlock";var em,ra=class extends ea{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};em=ra;M.BmpString=em;ra.NAME="BMPString";var na=class extends Zt{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let i=Qr(t.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=t}};na.NAME="UniversalStringValueBlock";var rm,oa=class extends na{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};rm=oa;M.UniversalString=rm;oa.NAME="UniversalString";var nm,ia=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};nm=ia;M.NumericString=nm;ia.NAME="NumericString";var om,sa=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};om=sa;M.PrintableString=om;sa.NAME="PrintableString";var im,aa=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};im=aa;M.TeletexString=im;aa.NAME="TeletexString";var sm,ca=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};sm=ca;M.VideotexString=sm;ca.NAME="VideotexString";var am,la=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};am=la;M.IA5String=am;la.NAME="IA5String";var cm,ua=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};cm=ua;M.GraphicString=cm;ua.NAME="GraphicString";var lm,hi=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};lm=hi;M.VisibleString=lm;hi.NAME="VisibleString";var um,fa=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};um=fa;M.GeneralString=um;fa.NAME="GeneralString";var fm,ha=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};fm=ha;M.CharacterString=fm;ha.NAME="CharacterString";var hm,di=class extends hi{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,tt.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=he(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=he(this.month,2),e[2]=he(this.day,2),e[3]=he(this.hour,2),e[4]=he(this.minute,2),e[5]=he(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};hm=di;M.UTCTime=hm;di.NAME="UTCTime";var dm,da=class extends di{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",i=0,s,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(h.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*m,h.length===4){if(m=parseInt(h.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=f*m}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");i=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*i;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*i;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*i;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=s.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(he(this.year,4)),e.push(he(this.month,2)),e.push(he(this.day,2)),e.push(he(this.hour,2)),e.push(he(this.minute,2)),e.push(he(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(he(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};dm=da;M.GeneralizedTime=dm;da.NAME="GeneralizedTime";var pm,pa=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};pm=pa;M.DATE=pm;pa.NAME="DATE";var mm,ma=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};mm=ma;M.TimeOfDay=mm;ma.NAME="TimeOfDay";var gm,ga=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};gm=ga;M.DateTime=gm;ga.NAME="DateTime";var ym,ya=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};ym=ya;M.Duration=ym;ya.NAME="Duration";var wm,wa=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};wm=wa;M.TIME=wm;wa.NAME="TIME";function q(r,t="utf8"){let e=ys[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function xa(r){if(isNaN(r)||r<=0)throw new gt("random bytes length must be a Number bigger than 0");return no(r)}var pi=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Ea=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var bm={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Ea("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var en=bm;async function xm(r){let t=await en.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await $E(t);return{privateKey:e[0],publicKey:e[1]}}async function Em(r,t){let e=await en.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await en.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function vm(r,t,e){let n=await en.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return en.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function $E(r){if(r.privateKey==null||r.publicKey==null)throw new gt("Private and public key are required");return Promise.all([en.get().subtle.exportKey("jwk",r.privateKey),en.get().subtle.exportKey("jwk",r.publicKey)])}function uf(r){if(r.kty!=="RSA")throw new gt("invalid key type");if(r.n==null)throw new gt("invalid key modulus");return D(r.n,"base64url").length*8}var po=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=mi.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return L.createV1(114,this._multihash)}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}verify(t,e){return vm(this._key,e,t)}},gi=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=mi.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}sign(t){return Em(this._key,t)}};var va=8192,ff=18;function Sm(r){let{result:t}=lf(r),e=t.valueBlock.value;return{n:q(tr(e[1].toBigInt()),"base64url"),e:q(tr(e[2].toBigInt()),"base64url"),d:q(tr(e[3].toBigInt()),"base64url"),p:q(tr(e[4].toBigInt()),"base64url"),q:q(tr(e[5].toBigInt()),"base64url"),dp:q(tr(e[6].toBigInt()),"base64url"),dq:q(tr(e[7].toBigInt()),"base64url"),qi:q(tr(e[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function zE(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 gt("JWK was missing components");let e=new xr({value:[new Ft({value:0}),Ft.fromBigInt(er(D(r.n,"base64url"))),Ft.fromBigInt(er(D(r.e,"base64url"))),Ft.fromBigInt(er(D(r.d,"base64url"))),Ft.fromBigInt(er(D(r.p,"base64url"))),Ft.fromBigInt(er(D(r.q,"base64url"))),Ft.fromBigInt(er(D(r.dp,"base64url"))),Ft.fromBigInt(er(D(r.dq,"base64url"))),Ft.fromBigInt(er(D(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Am(r){let{result:t}=lf(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:q(tr(e[0].toBigInt()),"base64url"),e:q(tr(e[1].toBigInt()),"base64url")}}function hf(r){if(r.n==null||r.e==null)throw new gt("JWK was missing components");let e=new xr({value:[new xr({value:[new fo({value:"1.2.840.113549.1.1.1"}),new lo]}),new uo({valueHex:new xr({value:[Ft.fromBigInt(er(D(r.n,"base64url"))),Ft.fromBigInt(er(D(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function tr(r){let t=r.toString(16);t.length%2>0&&(t=`0${t}`);let e=t.length/2,n=new Uint8Array(e),o=0,i=0;for(;o<e;)n[o]=parseInt(t.slice(i,i+2),16),o+=1,i+=2;return n}function er(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Im(r){let t=Sm(r);return km(t)}function df(r){let t=Am(r);if(uf(t)>va)throw new zn("Key size is too large");let e=ao(Je.encode({Type:Tt.RSA,Data:r})),n=Pe(ff,e);return new po(t,n)}function km(r){if(uf(r)>va)throw new gt("Key size is too large");let t=Bm(r),e=ao(Je.encode({Type:Tt.RSA,Data:hf(t.publicKey)})),n=Pe(ff,e);return new gi(t.privateKey,new po(t.publicKey,n))}async function _m(r){if(r>va)throw new gt("Key size is too large");let t=await xm(r),e=ao(Je.encode({Type:Tt.RSA,Data:hf(t.publicKey)})),n=Pe(ff,e);return new gi(t.privateKey,new po(t.publicKey,n))}function Bm(r){if(r==null)throw new gt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Sa=class extends ro{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,up(t);let n=ri(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(t){return eo(this),this.iHash.update(t),this}digestInto(t){eo(this),to(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},pf=(r,t,e)=>new Sa(r,t).update(e).digest();pf.create=(r,t)=>new Sa(r,t);function Tm(r){r.lowS!==void 0&&Oe("lowS",r.lowS),r.prehash!==void 0&&Oe("prehash",r.prehash)}function qE(r){let t=ii(r);Ze(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:KE,hexToBytes:GE}=As,Ar={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Ar;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=vn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?vn(o.length/2|128):"";return`${vn(r)}${i}${o}${t}`},decode(r,t){let{Err:e}=Ar,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(r){let{Err:t}=Ar;if(r<Ir)throw new t("integer: negative integers are not allowed");let e=vn(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=Ar;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return KE(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ar,o=typeof r=="string"?GE(r):r;io(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("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 t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Ar,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Ir=BigInt(0),Lt=BigInt(1),AT=BigInt(2),Cm=BigInt(3),IT=BigInt(4);function WE(r){let t=qE(r),{Fp:e}=t,n=Xr(t.n,t.nBitLength),o=t.toBytes||((p,y,g)=>{let x=y.toAffine();return yr(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),i=t.fromBytes||(p=>{let y=p.subarray(1),g=e.fromBytes(y.subarray(0,e.BYTES)),x=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:g,y:x}});function s(p){let{a:y,b:g}=t,x=e.sqr(p),b=e.mul(x,p);return e.add(e.add(b,e.mul(p,y)),g)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function a(p){return ni(p,Lt,t.n)}function c(p){let{allowedPrivateKeyLengths:y,nByteLength:g,wrapPrivateKey:x,n:b}=t;if(y&&typeof p!="bigint"){if(Wr(p)&&(p=mr(p)),typeof p!="string"||!y.includes(p.length))throw new Error("Invalid key");p=p.padStart(g*2,"0")}let E;try{E=typeof p=="bigint"?p:gr(xt("private key",p,g))}catch{throw new Error(`private key must be ${g} bytes, hex or bigint, not ${typeof p}`)}return x&&(E=at(E,b)),ue("private key",E,Lt,b),E}function l(p){if(!(p instanceof d))throw new Error("ProjectivePoint expected")}let u=In((p,y)=>{let{px:g,py:x,pz:b}=p;if(e.eql(b,e.ONE))return{x:g,y:x};let E=p.is0();y==null&&(y=E?e.ONE:e.inv(b));let k=e.mul(g,y),T=e.mul(x,y),S=e.mul(b,y);if(E)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:k,y:T}}),f=In(p=>{if(p.is0()){if(t.allowInfinityPoint&&!e.is0(p.py))return;throw new Error("bad point: ZERO")}let{x:y,y:g}=p.toAffine();if(!e.isValid(y)||!e.isValid(g))throw new Error("bad point: x or y not FE");let x=e.sqr(g),b=s(y);if(!e.eql(x,b))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(y,g,x){if(this.px=y,this.py=g,this.pz=x,y==null||!e.isValid(y))throw new Error("x required");if(g==null||!e.isValid(g))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(y){let{x:g,y:x}=y||{};if(!y||!e.isValid(g)||!e.isValid(x))throw new Error("invalid affine point");if(y instanceof d)throw new Error("projective point not allowed");let b=E=>e.eql(E,e.ZERO);return b(g)&&b(x)?d.ZERO:new d(g,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let g=e.invertBatch(y.map(x=>x.pz));return y.map((x,b)=>x.toAffine(g[b])).map(d.fromAffine)}static fromHex(y){let g=d.fromAffine(i(xt("pointHex",y)));return g.assertValidity(),g}static fromPrivateKey(y){return d.BASE.multiply(c(y))}static msm(y,g){return _s(d,n,y,g)}_setWindowSize(y){m.setWindowSize(this,y)}assertValidity(){f(this)}hasEvenY(){let{y}=this.toAffine();if(e.isOdd)return!e.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){l(y);let{px:g,py:x,pz:b}=this,{px:E,py:k,pz:T}=y,S=e.eql(e.mul(g,T),e.mul(E,b)),v=e.eql(e.mul(x,T),e.mul(k,b));return S&&v}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:y,b:g}=t,x=e.mul(g,Cm),{px:b,py:E,pz:k}=this,T=e.ZERO,S=e.ZERO,v=e.ZERO,_=e.mul(b,b),z=e.mul(E,E),F=e.mul(k,k),U=e.mul(b,E);return U=e.add(U,U),v=e.mul(b,k),v=e.add(v,v),T=e.mul(y,v),S=e.mul(x,F),S=e.add(T,S),T=e.sub(z,S),S=e.add(z,S),S=e.mul(T,S),T=e.mul(U,T),v=e.mul(x,v),F=e.mul(y,F),U=e.sub(_,F),U=e.mul(y,U),U=e.add(U,v),v=e.add(_,_),_=e.add(v,_),_=e.add(_,F),_=e.mul(_,U),S=e.add(S,_),F=e.mul(E,k),F=e.add(F,F),_=e.mul(F,U),T=e.sub(T,_),v=e.mul(F,z),v=e.add(v,v),v=e.add(v,v),new d(T,S,v)}add(y){l(y);let{px:g,py:x,pz:b}=this,{px:E,py:k,pz:T}=y,S=e.ZERO,v=e.ZERO,_=e.ZERO,z=t.a,F=e.mul(t.b,Cm),U=e.mul(g,E),P=e.mul(x,k),R=e.mul(b,T),N=e.add(g,x),I=e.add(E,k);N=e.mul(N,I),I=e.add(U,P),N=e.sub(N,I),I=e.add(g,b);let A=e.add(E,T);return I=e.mul(I,A),A=e.add(U,R),I=e.sub(I,A),A=e.add(x,b),S=e.add(k,T),A=e.mul(A,S),S=e.add(P,R),A=e.sub(A,S),_=e.mul(z,I),S=e.mul(F,R),_=e.add(S,_),S=e.sub(P,_),_=e.add(P,_),v=e.mul(S,_),P=e.add(U,U),P=e.add(P,U),R=e.mul(z,R),I=e.mul(F,I),P=e.add(P,R),R=e.sub(U,R),R=e.mul(z,R),I=e.add(I,R),U=e.mul(P,I),v=e.add(v,U),U=e.mul(A,I),S=e.mul(N,S),S=e.sub(S,U),U=e.mul(N,P),_=e.mul(A,_),_=e.add(_,U),new d(S,v,_)}subtract(y){return this.add(y.negate())}is0(){return this.equals(d.ZERO)}wNAF(y){return m.wNAFCached(this,y,d.normalizeZ)}multiplyUnsafe(y){ue("scalar",y,Ir,t.n);let g=d.ZERO;if(y===Ir)return g;if(y===Lt)return this;let{endo:x}=t;if(!x)return m.unsafeLadder(this,y);let{k1neg:b,k1:E,k2neg:k,k2:T}=x.splitScalar(y),S=g,v=g,_=this;for(;E>Ir||T>Ir;)E&Lt&&(S=S.add(_)),T&Lt&&(v=v.add(_)),_=_.double(),E>>=Lt,T>>=Lt;return b&&(S=S.negate()),k&&(v=v.negate()),v=new d(e.mul(v.px,x.beta),v.py,v.pz),S.add(v)}multiply(y){let{endo:g,n:x}=t;ue("scalar",y,Lt,x);let b,E;if(g){let{k1neg:k,k1:T,k2neg:S,k2:v}=g.splitScalar(y),{p:_,f:z}=this.wNAF(T),{p:F,f:U}=this.wNAF(v);_=m.constTimeNegate(k,_),F=m.constTimeNegate(S,F),F=new d(e.mul(F.px,g.beta),F.py,F.pz),b=_.add(F),E=z.add(U)}else{let{p:k,f:T}=this.wNAF(y);b=k,E=T}return d.normalizeZ([b,E])[0]}multiplyAndAddUnsafe(y,g,x){let b=d.BASE,E=(T,S)=>S===Ir||S===Lt||!T.equals(b)?T.multiplyUnsafe(S):T.multiply(S),k=E(this,g).add(E(y,x));return k.is0()?void 0:k}toAffine(y){return u(this,y)}isTorsionFree(){let{h:y,isTorsionFree:g}=t;if(y===Lt)return!0;if(g)return g(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:g}=t;return y===Lt?this:g?g(d,this):this.multiplyUnsafe(t.h)}toRawBytes(y=!0){return Oe("isCompressed",y),this.assertValidity(),o(d,this,y)}toHex(y=!0){return Oe("isCompressed",y),mr(this.toRawBytes(y))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let h=t.nBitLength,m=ks(d,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function jE(r){let t=ii(r);return Ze(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Rm(r){let t=jE(r),{Fp:e,n}=t,o=e.BYTES+1,i=2*e.BYTES+1;function s(R){return at(R,n)}function a(R){return Is(R,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=WE({...t,toBytes(R,N,I){let A=N.toAffine(),C=e.toBytes(A.x),V=yr;return Oe("isCompressed",I),I?V(Uint8Array.from([N.hasEvenY()?2:3]),C):V(Uint8Array.from([4]),C,e.toBytes(A.y))},fromBytes(R){let N=R.length,I=R[0],A=R.subarray(1);if(N===o&&(I===2||I===3)){let C=gr(A);if(!ni(C,Lt,e.ORDER))throw new Error("Point is not on curve");let V=u(C),K;try{K=e.sqrt(V)}catch(et){let Q=et instanceof Error?": "+et.message:"";throw new Error("Point is not on curve"+Q)}let G=(K&Lt)===Lt;return(I&1)===1!==G&&(K=e.neg(K)),{x:C,y:K}}else if(N===i&&I===4){let C=e.fromBytes(A.subarray(0,e.BYTES)),V=e.fromBytes(A.subarray(e.BYTES,2*e.BYTES));return{x:C,y:V}}else throw new Error(`Point of length ${N} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),d=R=>mr(Yr(R,t.nByteLength));function h(R){let N=n>>Lt;return R>N}function m(R){return h(R)?s(-R):R}let p=(R,N,I)=>gr(R.slice(N,I));class y{constructor(N,I,A){this.r=N,this.s=I,this.recovery=A,this.assertValidity()}static fromCompact(N){let I=t.nByteLength;return N=xt("compactSignature",N,I*2),new y(p(N,0,I),p(N,I,2*I))}static fromDER(N){let{r:I,s:A}=Ar.toSig(xt("DER",N));return new y(I,A)}assertValidity(){ue("r",this.r,Lt,n),ue("s",this.s,Lt,n)}addRecoveryBit(N){return new y(this.r,this.s,N)}recoverPublicKey(N){let{r:I,s:A,recovery:C}=this,V=T(xt("msgHash",N));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");let K=C===2||C===3?I+t.n:I;if(K>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let G=C&1?"03":"02",J=c.fromHex(G+d(K)),et=a(K),Q=s(-V*et),st=s(A*et),lt=c.BASE.multiplyAndAddUnsafe(J,Q,st);if(!lt)throw new Error("point at infinify");return lt.assertValidity(),lt}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return Sn(this.toDERHex())}toDERHex(){return Ar.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Sn(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let g={isValidPrivateKey(R){try{return l(R),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let R=Yu(t.n);return Sp(t.randomBytes(R),t.n)},precompute(R=8,N=c.BASE){return N._setWindowSize(R),N.multiply(BigInt(3)),N}};function x(R,N=!0){return c.fromPrivateKey(R).toRawBytes(N)}function b(R){let N=Wr(R),I=typeof R=="string",A=(N||I)&&R.length;return N?A===o||A===i:I?A===2*o||A===2*i:R instanceof c}function E(R,N,I=!0){if(b(R))throw new Error("first arg must be private key");if(!b(N))throw new Error("second arg must be public key");return c.fromHex(N).multiply(l(R)).toRawBytes(I)}let k=t.bits2int||function(R){let N=gr(R),I=R.length*8-t.nBitLength;return I>0?N>>BigInt(I):N},T=t.bits2int_modN||function(R){return s(k(R))},S=oi(t.nBitLength);function v(R){return ue(`num < 2^${t.nBitLength}`,R,Ir,S),Yr(R,t.nByteLength)}function _(R,N,I=z){if(["recovered","canonical"].some(Nt=>Nt in I))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:C}=t,{lowS:V,prehash:K,extraEntropy:G}=I;V==null&&(V=!0),R=xt("msgHash",R),Tm(I),K&&(R=xt("prehashed msgHash",A(R)));let J=T(R),et=l(N),Q=[v(et),v(J)];if(G!=null&&G!==!1){let Nt=G===!0?C(e.BYTES):G;Q.push(xt("extraEntropy",Nt))}let st=yr(...Q),lt=J;function Rt(Nt){let Dt=k(Nt);if(!f(Dt))return;let jt=a(Dt),kt=c.BASE.multiply(Dt).toAffine(),ee=s(kt.x);if(ee===Ir)return;let lr=s(jt*s(lt+ee*et));if(lr===Ir)return;let Ko=(kt.x===ee?0:2)|Number(kt.y&Lt),Go=lr;return V&&h(lr)&&(Go=m(lr),Ko^=1),new y(ee,Go,Ko)}return{seed:st,k2sig:Rt}}let z={lowS:t.lowS,prehash:!1},F={lowS:t.lowS,prehash:!1};function U(R,N,I=z){let{seed:A,k2sig:C}=_(R,N,I),V=t;return Ku(V.hash.outputLen,V.nByteLength,V.hmac)(A,C)}c.BASE._setWindowSize(8);function P(R,N,I,A=F){let C=R;if(N=xt("msgHash",N),I=xt("publicKey",I),"strict"in A)throw new Error("options.strict was renamed to lowS");Tm(A);let{lowS:V,prehash:K}=A,G,J;try{if(typeof C=="string"||Wr(C))try{G=y.fromDER(C)}catch(kt){if(!(kt instanceof Ar.Err))throw kt;G=y.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){let{r:kt,s:ee}=C;G=new y(kt,ee)}else throw new Error("PARSE");J=c.fromHex(I)}catch(kt){if(kt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(V&&G.hasHighS())return!1;K&&(N=t.hash(N));let{r:et,s:Q}=G,st=T(N),lt=a(Q),Rt=s(st*lt),Nt=s(et*lt),Dt=c.BASE.multiplyAndAddUnsafe(J,Rt,Nt)?.toAffine();return Dt?s(Dt.x)===et:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:E,sign:U,verify:P,ProjectivePoint:c,Signature:y,utils:g}}function YE(r){return{hash:r,hmac:(t,...e)=>pf(r,t,Uu(...e)),randomBytes:no}}function Nm(r,t){let e=n=>Rm({...r,...YE(n)});return Object.freeze({...e(t),create:e})}var Dm=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Lm=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),XE=BigInt(1),mf=BigInt(2),Pm=(r,t)=>(r+t/mf)/t;function ZE(r){let t=Dm,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=dt(u,e,t)*u%t,d=dt(f,e,t)*u%t,h=dt(d,mf,t)*l%t,m=dt(h,o,t)*h%t,p=dt(m,i,t)*m%t,y=dt(p,a,t)*p%t,g=dt(y,c,t)*y%t,x=dt(g,a,t)*p%t,b=dt(x,e,t)*u%t,E=dt(b,s,t)*m%t,k=dt(E,n,t)*l%t,T=dt(k,mf,t);if(!gf.eql(gf.sqr(T),r))throw new Error("Cannot find square root");return T}var gf=Xr(Dm,void 0,void 0,{sqrt:ZE}),Bn=Nm({a:BigInt(0),b:BigInt(7),Fp:gf,n:Lm,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Lm,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-XE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=Pm(i*r,t),c=Pm(-n*r,t),l=at(r-a*e-c*o,t),u=at(-a*n-c*i,t),f=l>s,d=u>s;if(f&&(l=t-l),d&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ao),PT=BigInt(0);var DT=Bn.ProjectivePoint;function Om(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Um(r,t,e){let n=Xe.digest(e instanceof Uint8Array?e:e.subarray());if(Om(n))return n.then(({digest:o})=>Bn.verify(t,o,r)).catch(o=>{throw new pi(String(o))});try{return Bn.verify(t,n.digest,r)}catch(o){throw new pi(String(o))}}var Aa=class{type="secp256k1";raw;_key;constructor(t){this._key=Mm(t),this.raw=Fm(this._key)}toMultihash(){return bt.digest(so(this))}toCID(){return L.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}verify(t,e){return Um(this._key,e,t)}};function yf(r){return new Aa(r)}function Fm(r){return Bn.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Mm(r){try{return Bn.ProjectivePoint.fromHex(r),r}catch(t){throw new zn(String(t))}}function Ia(r){let{Type:t,Data:e}=Je.decode(r),n=e??new Uint8Array;switch(t){case Tt.RSA:return df(n);case Tt.Ed25519:return tf(n);case Tt.secp256k1:return yf(n);default:throw new pn}}function rn(r){let{Type:t,Data:e}=Je.decode(r.digest),n=e??new Uint8Array;switch(t){case Tt.Ed25519:return tf(n);case Tt.secp256k1:return yf(n);default:throw new pn}}function so(r){return Je.encode({Type:Tt[r.type],Data:r.raw})}var Vm=Symbol.for("nodejs.util.inspect.custom"),JE=114,yi=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[$n]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return L.createV1(JE,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Z(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Z(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Vm](){return`PeerId(${this.toString()})`}},ka=class extends yi{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},_a=class extends yi{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Ba=class extends yi{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},QE=2336,wi=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=bt.digest(D(this.url))}[Vm](){return`PeerId(${this.url})`}[$n]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return L.createV1(QE,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=q(t)),t.toString()===this.toString())}};var tv=114,Hm=2336;function mo(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=wt(Y.decode(`z${r}`));else{if(t==null)throw new gt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=wt(t.decode(r))}return $m(e)}function $m(r){if(rv(r))return new ka({multihash:r});if(ev(r))try{let t=rn(r);if(t.type==="Ed25519")return new _a({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Ba({multihash:r,publicKey:t})}catch{let e=q(r.digest);return new wi(new URL(e))}throw new Ae("Supplied PeerID Multihash is invalid")}function Ta(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==tv&&r.code!==Hm)throw new Yo("Supplied PeerID CID is invalid");if(r.code===Hm){let t=q(r.multihash.digest);return new wi(new URL(t))}return $m(r.multihash)}function ev(r){return r.code===bt.code}function rv(r){return r.code===Xe.code}function nv(r,t){try{if(typeof r=="string"&&r.length>0)return ov(r);if(typeof r=="number"&&isFinite(r))return t?.long?sv(r):iv(r);throw new Error("Value is not a string or number.")}catch(e){let n=av(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function ov(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Na=nv;function iv(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function sv(r){let t=Math.abs(r);return t>=864e5?Ra(r,t,864e5,"day"):t>=36e5?Ra(r,t,36e5,"hour"):t>=6e4?Ra(r,t,6e4,"minute"):t>=1e3?Ra(r,t,1e3,"second"):`${r} ms`}function Ra(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function av(r){return typeof r=="object"&&r!==null&&"message"in r}function bf(r){e.debug=e,e.default=e,e.coerce=c,e.disable=i,e.enable=o,e.enabled=s,e.humanize=Na,e.destroy=l,Object.keys(r).forEach(u=>{e[u]=r[u]}),e.names=[],e.skips=[],e.formatters={};function t(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(u){let f,d=null,h,m;function p(...y){if(!p.enabled)return;let g=p,x=Number(new Date),b=x-(f||x);g.diff=b,g.prev=f,g.curr=x,f=x,y[0]=e.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let E=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(T,S)=>{if(T==="%%")return"%";E++;let v=e.formatters[S];if(typeof v=="function"){let _=y[E];T=v.call(g,_),y.splice(E,1),E--}return T}),e.formatArgs.call(g,y),(g.log||e.log).apply(g,y)}return p.namespace=u,p.useColors=e.useColors(),p.color=e.selectColor(u),p.extend=n,p.destroy=e.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,m=e.enabled(u)),m),set:y=>{d=y}}),typeof e.init=="function"&&e.init(p),p}function n(u,f){let d=e(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){e.save(u),e.namespaces=u,e.names=[],e.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?e.skips.push(new RegExp("^"+u.substr(1)+"$")):e.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(u))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.setupFormatters(e.formatters),e.enable(e.load()),e}var La=pv(),cv=["#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 lv(){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 uv(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Na(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var fv=console.debug??console.log??(()=>{});function hv(r){try{r?La?.setItem("debug",r):La?.removeItem("debug")}catch{}}function dv(){let r;try{r=La?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function pv(){try{return localStorage}catch{}}function mv(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Km=bf({formatArgs:uv,save:hv,load:dv,useColors:lv,setupFormatters:mv,colors:cv,storage:La,log:fv});var W=Km;W.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);W.formatters.t=r=>r==null?"undefined":St.baseEncode(r);W.formatters.m=r=>r==null?"undefined":se.baseEncode(r);W.formatters.p=r=>r==null?"undefined":r.toString();W.formatters.c=r=>r==null?"undefined":r.toString();W.formatters.k=r=>r==null?"undefined":r.toString();W.formatters.a=r=>r==null?"undefined":r.toString();W.formatters.e=r=>r==null?"undefined":Gm(r.stack)??Gm(r.message)??r.toString();function gv(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function Wm(){return{forComponent(r){return yv(r)}}}function yv(r){let t=gv(`${r}:trace`);return W.enabled(`${r}:trace`)&&W.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=W(`${r}:trace`)),Object.assign(W(r),{error:W(`${r}:error`),trace:t})}function Gm(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Ef=Ot(Ym(),1);var Ei=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},vf=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Xm=r=>globalThis.DOMException===void 0?new vf(r):new DOMException(r),Zm=r=>{let t=r.reason===void 0?Xm("This operation was aborted."):r.reason;return t instanceof Error?t:Xm(t)};function vi(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=t,s,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&u(Zm(d));let h=()=>{u(Zm(d))};d.addEventListener("abort",h,{once:!0}),r.finally(()=>{d.removeEventListener("abort",h)})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Ei;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){u(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(d){u(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function Sf(r,t,e){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;e(r[s],t)<=0?(n=++s,o-=i+1):o=i}return n}var Si=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,run:t};if(this.size&&this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=Sf(this.#t,n,(i,s)=>s.priority-i.priority);this.#t.splice(o,0,n)}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var de=class extends Ef.default{#t;#r;#a=0;#c;#g;#S=0;#o;#y;#n;#i;#e=0;#h;#l;#d;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Si,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#r=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#c=t.intervalCap,this.#g=t.interval,this.#n=new t.queueClass,this.#i=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#d=t.throwOnTimeout===!0,this.#l=t.autoStart===!1}get#u(){return this.#r||this.#a<this.#c}get#b(){return this.#e<this.#h}#f(){this.#e--,this.#m(),this.emit("next")}#x(){this.#A(),this.#w(),this.#y=void 0}get#E(){let t=Date.now();if(this.#o===void 0){let e=this.#S-t;if(e<0)this.#a=this.#t?this.#e:0;else return this.#y===void 0&&(this.#y=setTimeout(()=>{this.#x()},e)),!0}return!1}#m(){if(this.#n.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#e===0&&this.emit("idle"),!1;if(!this.#l){let t=!this.#E;if(this.#u&&this.#b){let e=this.#n.dequeue();return e?(this.emit("active"),e(),t&&this.#w(),!0):!1}}return!1}#w(){this.#r||this.#o!==void 0||(this.#o=setInterval(()=>{this.#A()},this.#g),this.#S=Date.now()+this.#g)}#A(){this.#a===0&&this.#e===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#a=this.#t?this.#e:0,this.#p()}#p(){for(;this.#m(););}get concurrency(){return this.#h}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#h=t,this.#p()}async#C(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}async add(t,e={}){return e={timeout:this.timeout,throwOnTimeout:this.#d,...e},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#e++,this.#a++;try{e.signal?.throwIfAborted();let i=t({signal:e.signal});e.timeout&&(i=vi(Promise.resolve(i),{milliseconds:e.timeout})),e.signal&&(i=Promise.race([i,this.#C(e.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof Ei&&!e.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#f()}},e),this.emit("add"),this.#m()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#l?(this.#l=!1,this.#p(),this):this}pause(){this.#l=!0}clear(){this.#n=new this.#i}async onEmpty(){this.#n.size!==0&&await this.#I("empty")}async onSizeLessThan(t){this.#n.size<t||await this.#I("next",()=>this.#n.size<t)}async onIdle(){this.#e===0&&this.#n.size===0||await this.#I("idle")}async#I(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#n.size}sizeBy(t){return this.#n.filter(t).length}get pending(){return this.#e}get isPaused(){return this.#l}};function Da(r){let t=[pe.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Af=60;function Oa(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(t=>({name:t.name,type:pe[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:pe[t.type],TTL:t.TTL??t.ttl??Af,data:t.data instanceof Uint8Array?q(t.data):t.data}))}}var xv=4;function If(r,t={}){let e=new de({concurrency:t.queryConcurrency??xv});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),Da(o.types).forEach(a=>{i.append("type",pe[a])}),o.onProgress?.(new H("dns:query",{detail:n}));let s=await e.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Oa(await a.json());return o.onProgress?.(new H("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Jm(){return[If("https://cloudflare-dns.com/dns-query"),If("https://dns.google/resolve")]}var tg=Ot(kf(),1);var _f=class{lru;constructor(t){this.lru=(0,tg.default)(t)}get(t,e){let n=!0,o=[];for(let i of e){let s=this.getAnswers(t,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return Oa({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,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:pe[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Af)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function eg(r){return new _f(r)}var Ev=1e3,Ua=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=eg(t.cacheSize??Ev),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Jm())}async query(t,e={}){let n=Da(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new H("dns:cache",{detail:o})),o;let i=`${t.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(e.signal?.aborted===!0)break;try{let l=await c(t,{...e,types:n});for(let u of l.Answer)this.cache.add(t,u);return l}catch(l){a.push(l),e.onProgress?.(new H("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var pe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(pe||(pe={}));function Ai(r={}){return new Ua(r)}var Fa=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Ma=class{deferred;signal;constructor(t){this.signal=t,this.deferred=ft(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ne)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function vv(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Va=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=vv(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,mt(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ne),this.cleanup())}async join(t={}){let e=new Ma(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Nd(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var kr=class extends qn{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Fa;let n=new Va(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Ne)}),this.clear()}async onEmpty(t){this.size!==0&&await fs(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await fs(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await fs(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=We({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new Ne("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var Sv=["string","number","bigint","symbol"],Av=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function rg(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let t=typeof r;if(Sv.includes(t))return t;if(t==="function")return"Function";if(Array.isArray(r))return"Array";if(Iv(r))return"Buffer";let e=kv(r);return e||"Object"}function Iv(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function kv(r){let t=Object.prototype.toString.call(r).slice(8,-1);if(Av.includes(t))return t}var w=class{constructor(t,e,n){this.major=t,this.majorEncoded=t<<5,this.name=e,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(7,"break",!0);var B=class{constructor(t,e,n){this.type=t,this.value=e,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var go=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",_v=new TextDecoder,Bv=new TextEncoder;function Ha(r){return go&&globalThis.Buffer.isBuffer(r)}function Ii(r){return r instanceof Uint8Array?Ha(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var sg=go?(r,t,e)=>e-t>64?globalThis.Buffer.from(r.subarray(t,e)).toString("utf8"):og(r,t,e):(r,t,e)=>e-t>64?_v.decode(r.subarray(t,e)):og(r,t,e),$a=go?r=>r.length>64?globalThis.Buffer.from(r):ng(r):r=>r.length>64?Bv.encode(r):ng(r),rr=r=>Uint8Array.from(r),yo=go?(r,t,e)=>Ha(r)?new Uint8Array(r.subarray(t,e)):r.slice(t,e):(r,t,e)=>r.slice(t,e),ag=go?(r,t)=>(r=r.map(e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e)),Ii(globalThis.Buffer.concat(r,t))):(r,t)=>{let e=new Uint8Array(t),n=0;for(let o of r)n+o.length>e.length&&(o=o.subarray(0,e.length-n)),e.set(o,n),n+=o.length;return e},cg=go?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function lg(r,t){if(Ha(r)&&Ha(t))return r.compare(t);for(let e=0;e<r.length;e++)if(r[e]!==t[e])return r[e]<t[e]?-1:1;return 0}function ng(r){let t=[],e=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=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),t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128)}return t}function og(r,t,e){let n=[];for(;t<e;){let o=r[t],i=null,s=o>239?4:o>223?3:o>191?2:1;if(t+s<=e){let a,c,l,u;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[t+1],(a&192)===128&&(u=(o&31)<<6|a&63,u>127&&(i=u));break;case 3:a=r[t+1],c=r[t+2],(a&192)===128&&(c&192)===128&&(u=(o&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:a=r[t+1],c=r[t+2],l=r[t+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(i=u))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),t+=s}return Bf(n)}var ig=4096;function Bf(r){let t=r.length;if(t<=ig)return String.fromCharCode.apply(String,r);let e="",n=0;for(;n<t;)e+=String.fromCharCode.apply(String,r.slice(n,n+=ig));return e}var Tv=256,ki=class{constructor(t=Tv){this.chunkSize=t,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(t){let e=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let o=e.length-(this.maxCursor-this.cursor)-1;e.set(t,o)}else{if(e){let o=e.length-(this.maxCursor-this.cursor)-1;o<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,o),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(e=cg(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let e;if(this.chunks.length===1){let n=this.chunks[0];t&&this.cursor>n.length/2?(e=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=yo(n,0,this.cursor)}else e=ag(this.chunks,this.cursor);return t&&this.reset(),e}};var $="CBOR decode error:",_r="CBOR encode error:",_i=[];_i[23]=1;_i[24]=2;_i[25]=3;_i[26]=5;_i[27]=9;function Br(r,t,e){if(r.length-t<e)throw new Error(`${$} not enough data for type`)}var Pt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function we(r,t,e){Br(r,t,1);let n=r[t];if(e.strict===!0&&n<Pt[0])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);return n}function be(r,t,e){Br(r,t,2);let n=r[t]<<8|r[t+1];if(e.strict===!0&&n<Pt[1])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);return n}function xe(r,t,e){Br(r,t,4);let n=r[t]*16777216+(r[t+1]<<16)+(r[t+2]<<8)+r[t+3];if(e.strict===!0&&n<Pt[2])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);return n}function Ee(r,t,e){Br(r,t,8);let n=r[t]*16777216+(r[t+1]<<16)+(r[t+2]<<8)+r[t+3],o=r[t+4]*16777216+(r[t+5]<<16)+(r[t+6]<<8)+r[t+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(e.strict===!0&&i<Pt[3])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(e.allowBigInt===!0)return i;throw new Error(`${$} integers outside of the safe integer range are not supported`)}function ug(r,t,e,n){return new B(w.uint,we(r,t+1,n),2)}function fg(r,t,e,n){return new B(w.uint,be(r,t+1,n),3)}function hg(r,t,e,n){return new B(w.uint,xe(r,t+1,n),5)}function dg(r,t,e,n){return new B(w.uint,Ee(r,t+1,n),9)}function _e(r,t){return Mt(r,0,t.value)}function Mt(r,t,e){if(e<Pt[0]){let n=Number(e);r.push([t|n])}else if(e<Pt[1]){let n=Number(e);r.push([t|24,n])}else if(e<Pt[2]){let n=Number(e);r.push([t|25,n>>>8,n&255])}else if(e<Pt[3]){let n=Number(e);r.push([t|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(e);if(n<Pt[4]){let o=[t|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(`${$} encountered BigInt larger than allowable range`)}}_e.encodedSize=function(t){return Mt.encodedSize(t.value)};Mt.encodedSize=function(t){return t<Pt[0]?1:t<Pt[1]?2:t<Pt[2]?3:t<Pt[3]?5:9};_e.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};function pg(r,t,e,n){return new B(w.negint,-1-we(r,t+1,n),2)}function mg(r,t,e,n){return new B(w.negint,-1-be(r,t+1,n),3)}function gg(r,t,e,n){return new B(w.negint,-1-xe(r,t+1,n),5)}var Tf=BigInt(-1),yg=BigInt(1);function wg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new B(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${$} integers outside of the safe integer range are not supported`);return new B(w.negint,Tf-BigInt(o),9)}function za(r,t){let e=t.value,n=typeof e=="bigint"?e*Tf-yg:e*-1-1;Mt(r,t.type.majorEncoded,n)}za.encodedSize=function(t){let e=t.value,n=typeof e=="bigint"?e*Tf-yg:e*-1-1;return n<Pt[0]?1:n<Pt[1]?2:n<Pt[2]?3:n<Pt[3]?5:9};za.compareTokens=function(t,e){return t.value<e.value?1:t.value>e.value?-1:0};function Bi(r,t,e,n){Br(r,t,e+n);let o=yo(r,t+e,t+e+n);return new B(w.bytes,o,e+n)}function bg(r,t,e,n){return Bi(r,t,1,e)}function xg(r,t,e,n){return Bi(r,t,2,we(r,t+1,n))}function Eg(r,t,e,n){return Bi(r,t,3,be(r,t+1,n))}function vg(r,t,e,n){return Bi(r,t,5,xe(r,t+1,n))}function Sg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer bytes lengths not supported`);return Bi(r,t,9,o)}function qa(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===w.string?$a(r.value):r.value),r.encodedBytes}function wo(r,t){let e=qa(t);Mt(r,t.type.majorEncoded,e.length),r.push(e)}wo.encodedSize=function(t){let e=qa(t);return Mt.encodedSize(e.length)+e.length};wo.compareTokens=function(t,e){return Rv(qa(t),qa(e))};function Rv(r,t){return r.length<t.length?-1:r.length>t.length?1:lg(r,t)}function Ti(r,t,e,n,o){let i=e+n;Br(r,t,i);let s=new B(w.string,sg(r,t+e,t+i),i);return o.retainStringBytes===!0&&(s.byteValue=yo(r,t+e,t+i)),s}function Ag(r,t,e,n){return Ti(r,t,1,e,n)}function Ig(r,t,e,n){return Ti(r,t,2,we(r,t+1,n),n)}function kg(r,t,e,n){return Ti(r,t,3,be(r,t+1,n),n)}function _g(r,t,e,n){return Ti(r,t,5,xe(r,t+1,n),n)}function Bg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer string lengths not supported`);return Ti(r,t,9,o,n)}var Tg=wo;function bo(r,t,e,n){return new B(w.array,n,e)}function Cg(r,t,e,n){return bo(r,t,1,e)}function Rg(r,t,e,n){return bo(r,t,2,we(r,t+1,n))}function Ng(r,t,e,n){return bo(r,t,3,be(r,t+1,n))}function Lg(r,t,e,n){return bo(r,t,5,xe(r,t+1,n))}function Pg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer array lengths not supported`);return bo(r,t,9,o)}function Dg(r,t,e,n){if(n.allowIndefinite===!1)throw new Error(`${$} indefinite length items not allowed`);return bo(r,t,1,1/0)}function Ka(r,t){Mt(r,w.array.majorEncoded,t.value)}Ka.compareTokens=_e.compareTokens;Ka.encodedSize=function(t){return Mt.encodedSize(t.value)};function xo(r,t,e,n){return new B(w.map,n,e)}function Og(r,t,e,n){return xo(r,t,1,e)}function Ug(r,t,e,n){return xo(r,t,2,we(r,t+1,n))}function Fg(r,t,e,n){return xo(r,t,3,be(r,t+1,n))}function Mg(r,t,e,n){return xo(r,t,5,xe(r,t+1,n))}function Vg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer map lengths not supported`);return xo(r,t,9,o)}function Hg(r,t,e,n){if(n.allowIndefinite===!1)throw new Error(`${$} indefinite length items not allowed`);return xo(r,t,1,1/0)}function Ga(r,t){Mt(r,w.map.majorEncoded,t.value)}Ga.compareTokens=_e.compareTokens;Ga.encodedSize=function(t){return Mt.encodedSize(t.value)};function $g(r,t,e,n){return new B(w.tag,e,1)}function zg(r,t,e,n){return new B(w.tag,we(r,t+1,n),2)}function qg(r,t,e,n){return new B(w.tag,be(r,t+1,n),3)}function Kg(r,t,e,n){return new B(w.tag,xe(r,t+1,n),5)}function Gg(r,t,e,n){return new B(w.tag,Ee(r,t+1,n),9)}function Wa(r,t){Mt(r,w.tag.majorEncoded,t.value)}Wa.compareTokens=_e.compareTokens;Wa.encodedSize=function(t){return Mt.encodedSize(t.value)};var Uv=20,Fv=21,Mv=22,Vv=23;function Wg(r,t,e,n){if(n.allowUndefined===!1)throw new Error(`${$} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new B(w.null,null,1):new B(w.undefined,void 0,1)}function jg(r,t,e,n){if(n.allowIndefinite===!1)throw new Error(`${$} indefinite length items not allowed`);return new B(w.break,void 0,1)}function Cf(r,t,e){if(e){if(e.allowNaN===!1&&Number.isNaN(r))throw new Error(`${$} NaN values are not supported`);if(e.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${$} Infinity values are not supported`)}return new B(w.float,r,t)}function Yg(r,t,e,n){return Cf(Rf(r,t+1),3,n)}function Xg(r,t,e,n){return Cf(Nf(r,t+1),5,n)}function Zg(r,t,e,n){return Cf(e0(r,t+1),9,n)}function ja(r,t,e){let n=t.value;if(n===!1)r.push([w.float.majorEncoded|Uv]);else if(n===!0)r.push([w.float.majorEncoded|Fv]);else if(n===null)r.push([w.float.majorEncoded|Mv]);else if(n===void 0)r.push([w.float.majorEncoded|Vv]);else{let o,i=!1;(!e||e.float64!==!0)&&(Qg(n),o=Rf(Me,1),n===o||Number.isNaN(n)?(Me[0]=249,r.push(Me.slice(0,3)),i=!0):(t0(n),o=Nf(Me,1),n===o&&(Me[0]=250,r.push(Me.slice(0,5)),i=!0))),i||(Hv(n),o=e0(Me,1),Me[0]=251,r.push(Me.slice(0,9)))}}ja.encodedSize=function(t,e){let n=t.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!e||e.float64!==!0){Qg(n);let o=Rf(Me,1);if(n===o||Number.isNaN(n))return 3;if(t0(n),o=Nf(Me,1),n===o)return 5}return 9};var Jg=new ArrayBuffer(9),Be=new DataView(Jg,1),Me=new Uint8Array(Jg,0);function Qg(r){if(r===1/0)Be.setUint16(0,31744,!1);else if(r===-1/0)Be.setUint16(0,64512,!1);else if(Number.isNaN(r))Be.setUint16(0,32256,!1);else{Be.setFloat32(0,r);let t=Be.getUint32(0),e=(t&2139095040)>>23,n=t&8388607;if(e===255)Be.setUint16(0,31744,!1);else if(e===0)Be.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=e-127;o<-24?Be.setUint16(0,0):o<-14?Be.setUint16(0,(t&2147483648)>>16|1<<24+o,!1):Be.setUint16(0,(t&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Rf(r,t){if(r.length-t<2)throw new Error(`${$} not enough data for float16`);let e=(r[t]<<8)+r[t+1];if(e===31744)return 1/0;if(e===64512)return-1/0;if(e===32256)return NaN;let n=e>>10&31,o=e&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,e&32768?-i:i}function t0(r){Be.setFloat32(0,r,!1)}function Nf(r,t){if(r.length-t<4)throw new Error(`${$} not enough data for float32`);let e=(r.byteOffset||0)+t;return new DataView(r.buffer,e,4).getFloat32(0,!1)}function Hv(r){Be.setFloat64(0,r,!1)}function e0(r,t){if(r.length-t<8)throw new Error(`${$} not enough data for float64`);let e=(r.byteOffset||0)+t;return new DataView(r.buffer,e,8).getFloat64(0,!1)}ja.compareTokens=_e.compareTokens;function rt(r,t,e){throw new Error(`${$} encountered invalid minor (${e}) for major ${r[t]>>>5}`)}function Ya(r){return()=>{throw new Error(`${$} ${r}`)}}var O=[];for(let r=0;r<=23;r++)O[r]=rt;O[24]=ug;O[25]=fg;O[26]=hg;O[27]=dg;O[28]=rt;O[29]=rt;O[30]=rt;O[31]=rt;for(let r=32;r<=55;r++)O[r]=rt;O[56]=pg;O[57]=mg;O[58]=gg;O[59]=wg;O[60]=rt;O[61]=rt;O[62]=rt;O[63]=rt;for(let r=64;r<=87;r++)O[r]=bg;O[88]=xg;O[89]=Eg;O[90]=vg;O[91]=Sg;O[92]=rt;O[93]=rt;O[94]=rt;O[95]=Ya("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)O[r]=Ag;O[120]=Ig;O[121]=kg;O[122]=_g;O[123]=Bg;O[124]=rt;O[125]=rt;O[126]=rt;O[127]=Ya("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)O[r]=Cg;O[152]=Rg;O[153]=Ng;O[154]=Lg;O[155]=Pg;O[156]=rt;O[157]=rt;O[158]=rt;O[159]=Dg;for(let r=160;r<=183;r++)O[r]=Og;O[184]=Ug;O[185]=Fg;O[186]=Mg;O[187]=Vg;O[188]=rt;O[189]=rt;O[190]=rt;O[191]=Hg;for(let r=192;r<=215;r++)O[r]=$g;O[216]=zg;O[217]=qg;O[218]=Kg;O[219]=Gg;O[220]=rt;O[221]=rt;O[222]=rt;O[223]=rt;for(let r=224;r<=243;r++)O[r]=Ya("simple values are not supported");O[244]=rt;O[245]=rt;O[246]=rt;O[247]=Wg;O[248]=Ya("simple values are not supported");O[249]=Yg;O[250]=Xg;O[251]=Zg;O[252]=rt;O[253]=rt;O[254]=rt;O[255]=jg;var Ve=[];for(let r=0;r<24;r++)Ve[r]=new B(w.uint,r,1);for(let r=-1;r>=-24;r--)Ve[31-r]=new B(w.negint,r,1);Ve[64]=new B(w.bytes,new Uint8Array(0),1);Ve[96]=new B(w.string,"",1);Ve[128]=new B(w.array,0,1);Ve[160]=new B(w.map,0,1);Ve[244]=new B(w.false,!1,1);Ve[245]=new B(w.true,!0,1);Ve[246]=new B(w.null,null,1);function Lf(r){switch(r.type){case w.false:return rr([244]);case w.true:return rr([245]);case w.null:return rr([246]);case w.bytes:return r.value.length?void 0:rr([64]);case w.string:return r.value===""?rr([96]):void 0;case w.array:return r.value===0?rr([128]):void 0;case w.map:return r.value===0?rr([160]):void 0;case w.uint:return r.value<24?rr([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return rr([31-Number(r.value)])}}var zv={float64:!1,mapSorter:Kv,quickEncodeToken:Lf};function Df(){let r=[];return r[w.uint.major]=_e,r[w.negint.major]=za,r[w.bytes.major]=wo,r[w.string.major]=Tg,r[w.array.major]=Ka,r[w.map.major]=Ga,r[w.tag.major]=Wa,r[w.float.major]=ja,r}var r0=Df(),Pf=new ki,Xa=class r{constructor(t,e){this.obj=t,this.parent=e}includes(t){let e=this;do if(e.obj===t)return!0;while(e=e.parent);return!1}static createCheck(t,e){if(t&&t.includes(e))throw new Error(`${_r} object contains circular references`);return new r(e,t)}},nn={null:new B(w.null,null),undefined:new B(w.undefined,void 0),true:new B(w.true,!0),false:new B(w.false,!1),emptyArray:new B(w.array,0),emptyMap:new B(w.map,0)},on={number(r,t,e,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new B(w.float,r):r>=0?new B(w.uint,r):new B(w.negint,r)},bigint(r,t,e,n){return r>=BigInt(0)?new B(w.uint,r):new B(w.negint,r)},Uint8Array(r,t,e,n){return new B(w.bytes,r)},string(r,t,e,n){return new B(w.string,r)},boolean(r,t,e,n){return r?nn.true:nn.false},null(r,t,e,n){return nn.null},undefined(r,t,e,n){return nn.undefined},ArrayBuffer(r,t,e,n){return new B(w.bytes,new Uint8Array(r))},DataView(r,t,e,n){return new B(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,t,e,n){if(!r.length)return e.addBreakTokens===!0?[nn.emptyArray,new B(w.break)]:nn.emptyArray;n=Xa.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Ci(s,e,n);return e.addBreakTokens?[new B(w.array,r.length),o,new B(w.break)]:[new B(w.array,r.length),o]},Object(r,t,e,n){let o=t!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return e.addBreakTokens===!0?[nn.emptyMap,new B(w.break)]:nn.emptyMap;n=Xa.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[Ci(l,e,n),Ci(o?r.get(l):r[l],e,n)];return qv(a,e),e.addBreakTokens?[new B(w.map,s),a,new B(w.break)]:[new B(w.map,s),a]}};on.Map=on.Object;on.Buffer=on.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))on[`${r}Array`]=on.DataView;function Ci(r,t={},e){let n=rg(r),o=t&&t.typeEncoders&&t.typeEncoders[n]||on[n];if(typeof o=="function"){let s=o(r,n,t,e);if(s!=null)return s}let i=on[n];if(!i)throw new Error(`${_r} unsupported type: ${n}`);return i(r,n,t,e)}function qv(r,t){t.mapSorter&&r.sort(t.mapSorter)}function Kv(r,t){let e=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(t[0])?t[0][0]:t[0];if(e.type!==n.type)return e.type.compare(n.type);let o=e.type.major,i=r0[o].compareTokens(e,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function n0(r,t,e,n){if(Array.isArray(t))for(let o of t)n0(r,o,e,n);else e[t.type.major](r,t,n)}function Of(r,t,e){let n=Ci(r,e);if(!Array.isArray(n)&&e.quickEncodeToken){let o=e.quickEncodeToken(n);if(o)return o;let i=t[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,e),a=new ki(s);if(i(a,n,e),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Ii(a.chunks[0])}}return Pf.reset(),n0(Pf,n,t,e),Pf.toBytes(!0)}function nr(r,t){return t=Object.assign({},zv,t),Of(r,r0,t)}var Gv={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Za=class{constructor(t,e={}){this._pos=0,this.data=t,this.options=e}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let t=this.data[this._pos],e=Ve[t];if(e===void 0){let n=O[t];if(!n)throw new Error(`${$} no decoder for major type ${t>>>5} (byte 0x${t.toString(16).padStart(2,"0")})`);let o=t&31;e=n(this.data,this._pos,o,this.options)}return this._pos+=e.encodedLength,e}},Ri=Symbol.for("DONE"),Ja=Symbol.for("BREAK");function Wv(r,t,e){let n=[];for(let o=0;o<r.value;o++){let i=Eo(t,e);if(i===Ja){if(r.value===1/0)break;throw new Error(`${$} got unexpected break to lengthed array`)}if(i===Ri)throw new Error(`${$} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function jv(r,t,e){let n=e.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=Eo(t,e);if(a===Ja){if(r.value===1/0)break;throw new Error(`${$} got unexpected break to lengthed map`)}if(a===Ri)throw new Error(`${$} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${$} non-string keys not supported (got ${typeof a})`);if(e.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${$} found repeat map key "${a}"`);let c=Eo(t,e);if(c===Ri)throw new Error(`${$} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function Eo(r,t){if(r.done())return Ri;let e=r.next();if(e.type===w.break)return Ja;if(e.type.terminal)return e.value;if(e.type===w.array)return Wv(e,r,t);if(e.type===w.map)return jv(e,r,t);if(e.type===w.tag){if(t.tags&&typeof t.tags[e.value]=="function"){let n=Eo(r,t);return t.tags[e.value](n)}throw new Error(`${$} tag not supported (${e.value})`)}throw new Error("unsupported")}function Uf(r,t){if(!(r instanceof Uint8Array))throw new Error(`${$} data to decode must be a Uint8Array`);t=Object.assign({},Gv,t);let e=t.tokenizer||new Za(r,t),n=Eo(e,t);if(n===Ri)throw new Error(`${$} did not find any content to decode`);if(n===Ja)throw new Error(`${$} got unexpected break`);return[n,r.subarray(e.pos())]}function Vt(r,t){let[e,n]=Uf(r,t);if(n.length>0)throw new Error(`${$} too many terminals, data makes no sense`);return e}var Tr="/",o0=new TextEncoder().encode(Tr),tc=o0[0],At=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=D(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==tc)throw new Error("Invalid key")}toString(t="utf8"){return q(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Tr))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=o0),this._buf[0]!==tc){let t=new Uint8Array(this._buf.byteLength+1);t.fill(tc,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===tc;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let i=e[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Tr).slice(1)}type(){return Yv(this.baseNamespace())}name(){return Xv(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Tr)||(t+=Tr),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Tr):new r(t.slice(0,-1).join(Tr))}child(t){return this.toString()===Tr?t:t.toString()===Tr?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...Zv(t.map(e=>e.namespaces()))])}};function Yv(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function Xv(r){let t=r.split(":");return t[t.length-1]}function Zv(r){return[].concat(...r)}function ec({enumerable:r=!0,configurable:t=!1}={}){return{enumerable:r,configurable:t,writable:!1}}function*Jv(r,t){if(t!=null&&typeof t=="object")if(Array.isArray(t))for(let[e,n]of t.entries()){let o=[...r,e],i=L.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*Ff(n,o))}else{let e=L.asCID(t);e!=null?yield[r.join("/"),e]:yield*Ff(t,r)}}function*Ff(r,t){if(r==null||r instanceof Uint8Array)return;let e=L.asCID(r);e!=null&&(yield[t.join("/"),e]);for(let[n,o]of Object.entries(r)){let i=[...t,n];yield*Jv(i,o)}}function*Qv(r,t){if(Array.isArray(t))for(let[e,n]of t.entries()){let o=[...r,e];yield o.join("/"),typeof n=="object"&&L.asCID(n)==null&&(yield*Mf(n,o))}else yield*Mf(t,r)}function*Mf(r,t){if(!(r==null||typeof r!="object"))for(let[e,n]of Object.entries(r)){let o=[...t,e];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&L.asCID(n)==null&&(yield*Qv(o,n))}}function t2(r,t){let e=r;for(let[n,o]of t.entries()){if(e=e[o],e==null)throw new Error(`Object has no property at ${t.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=L.asCID(e);if(i!=null)return{value:i,remaining:t.slice(n+1).join("/")}}return{value:e}}var Vf=class{cid;bytes;value;asBlock;constructor({cid:t,bytes:e,value:n}){if(t==null||e==null||typeof n>"u")throw new Error("Missing required argument");this.cid=t,this.bytes=e,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:ec(),bytes:ec(),value:ec(),asBlock:ec()})}links(){return Ff(this.value,[])}tree(){return Mf(this.value,[])}get(t="/"){return t2(this.value,t.split("/").filter(Boolean))}};function rc({bytes:r,cid:t,value:e,codec:n}){let o=e!==void 0?e:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Vf({cid:t,bytes:r,value:o})}var a0="/pin/",i0="/pinned-block/",Hf=Kt,s0=1;function nc(r){return r.version===0&&(r=r.toV1()),new At(`${a0}${r.toString(Hf)}`)}var oc=class{datastore;blockstore;getCodec;constructor(t,e,n){this.datastore=t,this.blockstore=e,this.getCodec=n}async*add(t,e={}){let n=nc(t);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(e.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new kr({concurrency:s0});for await(let a of this.#t(t,i,{...e,depth:o}))await this.#r(a,c=>c.pinnedBy.find(l=>Z(l,t.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(t.bytes),!0),e),yield a;let s={depth:o,metadata:e.metadata??{}};await this.datastore.put(n,nr(s),e)}async*#t(t,e,n){if(n.depth===-1)return;let o=await this.getCodec(t.code),i=await this.blockstore.get(t,n),s=rc({bytes:i,cid:t,codec:o});yield t;for await(let[,a]of s.links())yield*await e.add(async()=>this.#t(a,e,{...n,depth:n.depth-1}))}async#r(t,e,n){let o=new At(`${i0}${Hf.encode(t.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=Vt(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(e(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,nr(i),n),n.onProgress?.(new H("helia:pin:add",t))}}async*rm(t,e={}){let n=nc(t),o=await this.datastore.get(n,e),i=Vt(o);await this.datastore.delete(n,e);let s=new kr({concurrency:s0});for await(let a of this.#t(t,s,{...e,depth:i.depth}))await this.#r(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Z(l,t.bytes)),!0),{...e,depth:i.depth}),yield a}async*ls(t={}){for await(let{key:e,value:n}of this.datastore.query({prefix:a0+(t.cid!=null?`${t.cid.toString(Kt)}`:"")},t)){let o=L.parse(e.toString().substring(5),Kt),i=Vt(n);yield{cid:o,...i}}}async isPinned(t,e={}){let n=new At(`${i0}${Hf.encode(t.multihash.bytes)}`);return this.datastore.has(n,e)}async get(t,e){let n=nc(t),o=await this.datastore.get(n,e);return Vt(o)}async setMetadata(t,e,n){let o=nc(t),i=await this.datastore.get(o,n),s=Vt(i);s.metadata=e??{},await this.datastore.put(o,nr(s),n)}};var ic=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}},Cn=class extends Error{static name="NoRoutersAvailableError";constructor(t="No routers available"){super(t),this.name="NoRoutersAvailableError"}},sc=class extends Error{static name="UnknownHashAlgorithmError";constructor(t="Unknown hash algorithm"){super(t),this.name="UnknownHashAlgorithmError"}},ac=class extends Error{static name="UnknownCodecError";constructor(t="Unknown codec"){super(t),this.name="UnknownCodecError"}};var cc=class extends kr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var e2=5,lc=class{log;routers;providerLookupConcurrency;constructor(t,e){this.log=t.logger.forComponent("helia:routing"),this.routers=e.routers??[],this.providerLookupConcurrency=e.providerLookupConcurrency??e2}async start(){await Vr(...this.routers)}async stop(){await Hr(...this.routers)}async*findProviders(t,e={}){if(this.routers.length===0)throw new Cn("No content routers available");let n=new cc({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of $r(n.toGenerator(),...vo(this.routers,"findProviders").map(i=>i.findProviders(t,e))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,e);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:e.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(t,e={}){if(this.routers.length===0)throw new Cn("No content routers available");await Promise.all(vo(this.routers,"provide").map(async n=>{await n.provide(t,e)}))}async put(t,e,n){await Promise.all(vo(this.routers,"put").map(async o=>{await o.put(t,e,n)}))}async get(t,e){return Promise.any(vo(this.routers,"get").map(async n=>n.get(t,e)))}async findPeer(t,e){if(this.routers.length===0)throw new Cn("No peer routers available");let n=this,o=$r(...vo(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(t,e)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new _t("Could not find peer in routing")}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new Cn("No peer routers available");for await(let n of $r(...vo(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(t,e))))n!=null&&(yield n)}};function vo(r,t){return r.filter(e=>e[t]!=null)}var sn={},So=r=>{r.addEventListener("message",t=>{So.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{So.dispatchEvent("message",r,t)})};So.addEventListener=(r,t)=>{sn[r]==null&&(sn[r]=[]),sn[r].push(t)};So.removeEventListener=(r,t)=>{sn[r]!=null&&(sn[r]=sn[r].filter(e=>e===t))};So.dispatchEvent=function(r,t,e){sn[r]!=null&&sn[r].forEach(n=>n(t,e))};var $f=So;var zf="lock:worker:request-read",qf="lock:worker:release-read",Kf="lock:master:grant-read",Gf="lock:worker:request-write",Wf="lock:worker:release-write",jf="lock:master:grant-write";var c0=(r=21)=>Math.random().toString().substring(2);var l0=(r,t,e,n,o)=>(i,s)=>{if(s.data.type!==e)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u==null||u.data==null)return;let f={type:u.data.type,name:u.data.name,identifier:u.data.identifier};f.type===n&&f.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},u0=(r,t,e,n)=>async()=>{let o=c0();return globalThis.postMessage({type:t,identifier:o,name:r}),new Promise(i=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===e&&c.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},r2={singleProcess:!1},f0=r=>{if(r=Object.assign({},r2,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return $f.addEventListener("message",l0(e,"requestReadLock",zf,qf,Kf)),$f.addEventListener("message",l0(e,"requestWriteLock",Gf,Wf,jf)),e}return{isWorker:!0,readLock:e=>u0(e,zf,Kf,qf),writeLock:e=>u0(e,Gf,jf,Wf)}};var Rn={},an;async function Yf(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>vi((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var n2=(r,t)=>{if(an.isWorker===!0)return{readLock:an.readLock(r,t),writeLock:an.writeLock(r,t)};let e=new de({concurrency:1}),n;return{async readLock(){if(n!=null)return Yf(n,t);n=new de({concurrency:t.concurrency,autoStart:!1});let o=n,i=Yf(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,Yf(e,t)}}},o2={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Xf(r){let t=Object.assign({},o2,r);return an==null&&(an=f0(t),an.isWorker!==!0&&(an.addEventListener("requestReadLock",e=>{Rn[e.data.name]!=null&&Rn[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),an.addEventListener("requestWriteLock",async e=>{Rn[e.data.name]!=null&&Rn[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),Rn[t.name]==null&&(Rn[t.name]=n2(t.name,t)),Rn[t.name]}var uc=class{lock;child;pins;started;constructor(t,e,n={}){this.child=t,this.pins=e,this.lock=Xf({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Vr(this.child),this.started=!0}async stop(){await Hr(this.child),this.started=!1}unwrap(){return this.child}async put(t,e,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(t,e,n)}finally{o()}}async*putMany(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(t,e)}finally{n()}}async get(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(t,e)}finally{n()}}async*getMany(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(t,e)}finally{n()}}async delete(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(t))throw new Error("CID was pinned");await this.child.delete(t,e)}finally{n()}}async*deleteMany(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of t){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),e)}finally{n()}}async has(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(t,e)}finally{n()}}async*getAll(t={}){t?.signal?.throwIfAborted();let e=await this.lock.readLock();try{yield*this.child.getAll(t)}finally{e()}}createSession(t,e){return e?.signal?.throwIfAborted(),this.child.createSession(t,e)}};var Zf=new At("/version"),h0=1;async function d0(r){if(!await r.has(Zf)){await r.put(Zf,D(`${h0}`));return}let t=await r.get(Zf),e=q(t);if(parseInt(e,10)!==h0)throw new Error("Unknown datastore version, a datastore migration may be required")}var Nn={};vt(Nn,{code:()=>Cr,decode:()=>cn,decodeOptions:()=>u2,encode:()=>Ao,encodeOptions:()=>c2,name:()=>f2,toByteView:()=>m0});var p0=42;function m0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function i2(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let t=L.asCID(r);if(!t)return null;let e=new Uint8Array(t.bytes.byteLength+1);return e.set(t.bytes,1),[new B(w.tag,p0),new B(w.bytes,e)]}function s2(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function a2(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var Jf={float64:!0,typeEncoders:{Object:i2,undefined:s2,number:a2}},c2={...Jf,typeEncoders:{...Jf.typeEncoders}};function l2(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return L.decode(r.subarray(1))}var fc={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};fc.tags[p0]=l2;var u2={...fc,tags:fc.tags.slice()},f2="dag-cbor",Cr=113,Ao=r=>nr(r,Jf),cn=r=>Vt(m0(r),fc);var _o={};vt(_o,{code:()=>Rr,decode:()=>ko,encode:()=>dc,format:()=>v2,name:()=>E2,parse:()=>A2,stringify:()=>v2});var Qf=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(t){let e=this.inRecursive[this.inRecursive.length-1];e&&(e.type===w.array&&(e.elements++,e.elements!==1&&t.push([44])),e.type===w.map&&(e.elements++,e.elements!==1&&(e.elements%2===1?t.push([44]):t.push([58]))))}[w.uint.major](t,e){this.prefix(t);let n=String(e.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);t.push(o)}[w.negint.major](t,e){this[w.uint.major](t,e)}[w.bytes.major](t,e){throw new Error(`${_r} unsupported type: Uint8Array`)}[w.string.major](t,e){this.prefix(t);let n=$a(JSON.stringify(e.value));t.push(n.length>32?Ii(n):n)}[w.array.major](t,e){this.prefix(t),this.inRecursive.push({type:w.array,elements:0}),t.push([91])}[w.map.major](t,e){this.prefix(t),this.inRecursive.push({type:w.map,elements:0}),t.push([123])}[w.tag.major](t,e){}[w.float.major](t,e){if(e.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===w.array)t.push([93]);else if(s.type===w.map)t.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(e.value===void 0)throw new Error(`${_r} unsupported type: undefined`);if(this.prefix(t),e.type.name==="true"){t.push([116,114,117,101]);return}else if(e.type.name==="false"){t.push([102,97,108,115,101]);return}else if(e.type.name==="null"){t.push([110,117,108,108]);return}let n=String(e.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),t.push(o)}};function h2(r,t){if(Array.isArray(r[0])||Array.isArray(t[0]))throw new Error(`${_r} complex map keys are not supported`);let e=r[0],n=t[0];if(e.type!==w.string||n.type!==w.string)throw new Error(`${_r} non-string map keys are not supported`);if(e<n)return-1;if(e>n)return 1;throw new Error(`${_r} unexpected duplicate map keys, this is not supported`)}var d2={addBreakTokens:!0,mapSorter:h2};function Ni(r,t){return t=Object.assign({},d2,t),Of(r,new Qf,t)}var Io=class{constructor(t,e={}){this._pos=0,this.data=t,this.options=e,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let t=this.ch();for(;t===32||t===9||t===13||t===10;)t=this.data[++this._pos]}expect(t){if(this.data.length-this._pos<t.length)throw new Error(`${$} unexpected end of input at position ${this._pos}`);for(let e=0;e<t.length;e++)if(this.data[this._pos++]!==t[e])throw new Error(`${$} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...t)}'`)}parseNumber(){let t=this._pos,e=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(e=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new B(w.uint,0,this._pos-t);if(o([48,49,50,51,52,53,54,55,56,57]),e&&this._pos===t+1)throw new Error(`${$} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${$} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(t,this._pos)),s=parseFloat(i);return n?new B(w.float,s,this._pos-t):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new B(s>=0?w.uint:w.negint,s,this._pos-t):new B(s>=0?w.uint:w.negint,BigInt(i),this._pos-t)}parseString(){if(this.ch()!==34)throw new Error(`${$} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new B(w.string,c,s)}}let t=this._pos,e=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${$} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${$} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${$} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(i&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(i&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(i&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,e.push(s>>>10&1023|55296),s=56320|s&1023),e.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${$} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:e.push(s);break;case 98:e.push(8);break;case 116:e.push(9);break;case 110:e.push(10);break;case 102:e.push(12);break;case 114:e.push(13);break;case 117:e.push(n());break;default:throw new Error(`${$} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new B(w.string,Bf(e),this._pos-t);default:if(i<32)throw new Error(`${$} invalid control character at position ${this._pos}`);i<128?(e.push(i),this._pos++):o()}}throw new Error(`${$} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new B(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new B(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new B(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new B(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new B(w.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${$} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new B(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${$} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new B(w.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new B(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${$} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new B(w.break,void 0,1);let t=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${$} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),t}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${$} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function th(r,t){return t=Object.assign({tokenizer:new Io(r,t)},t),Vt(r,t)}function m2(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function g2(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let t=L.asCID(r);if(!t)return null;let e=t.toString();return[new B(w.map,1/0,1),new B(w.string,"/",1),new B(w.string,e,e.length),new B(w.break,void 0,1)]}function hc(r){let t=se.encode(r).slice(1);return[new B(w.map,1/0,1),new B(w.string,"/",1),new B(w.map,1/0,1),new B(w.string,"bytes",5),new B(w.string,t,t.length),new B(w.break,void 0,1),new B(w.break,void 0,1)]}function He(r){return hc(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function y2(r){return hc(new Uint8Array(r))}function w2(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function b2(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var x2={typeEncoders:{Object:g2,Buffer:hc,Uint8Array:hc,Int8Array:He,Uint16Array:He,Int16Array:He,Uint32Array:He,Int32Array:He,Float32Array:He,Float64Array:He,Uint8ClampedArray:He,BigInt64Array:He,BigUint64Array:He,DataView:He,ArrayBuffer:y2,undefined:w2,number:b2}},eh=class extends Io{constructor(t,e){super(t,e),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let t=this._next();if(t.type===w.map){let e=this._next();if(e.type===w.string&&e.value==="/"){let n=this._next();if(n.type===w.string){if(this._next().type!==w.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new B(w.tag,42,0)}if(n.type===w.map){let o=this._next();if(o.type===w.string&&o.value==="bytes"){let i=this._next();if(i.type===w.string){for(let a=0;a<2;a++)if(this._next().type!==w.break)throw new Error("Invalid encoded Bytes form");let s=se.decode(`m${i.value}`);return new B(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(e)}return t}},rh={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};rh.tags[42]=L.parse;var E2="dag-json",Rr=297,dc=r=>Ni(r,x2),ko=r=>{let t=m2(r),e=Object.assign(rh,{tokenizer:new eh(t,rh)});return th(t,e)},v2=r=>S2.decode(dc(r));var S2=new TextDecoder,A2=r=>ko(I2.encode(r)),I2=new TextEncoder;var Pi={};vt(Pi,{code:()=>Te,createLink:()=>I0,createNode:()=>A0,decode:()=>Nr,encode:()=>U2,name:()=>O2,prepare:()=>ih,validate:()=>sh});var k2=new TextDecoder;function nh(r,t){let e=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(t>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[t++];if(e+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[e,t]}function pc(r,t){let e;[e,t]=nh(r,t);let n=t+e;if(e<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(t,n),n]}function g0(r,t){let e;return[e,t]=nh(r,t),[e&7,e>>3,t]}function _2(r){let t={},e=r.length,n=0;for(;n<e;){let o,i;if([o,i,n]=g0(r,n),i===1){if(t.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(t.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(t.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[t.Hash,n]=pc(r,n)}else if(i===2){if(t.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(t.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=pc(r,n),t.Name=k2.decode(s)}else if(i===3){if(t.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[t.Tsize,n]=nh(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>e)throw new Error("protobuf: (PBLink) unexpected end of data");return t}function y0(r){let t=r.length,e=0,n,o=!1,i;for(;e<t;){let a,c;if([a,c,e]=g0(r,e),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,e]=pc(r,e),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,e]=pc(r,e),n.push(_2(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(e>t)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var b0=new TextEncoder,w0=2**32,B2=2**31;function T2(r,t){let e=t.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");e=Li(t,e,r.Tsize)-1,t[e]=24}if(typeof r.Name=="string"){let n=b0.encode(r.Name);e-=n.length,t.set(n,e),e=Li(t,e,n.length)-1,t[e]=18}return r.Hash&&(e-=r.Hash.length,t.set(r.Hash,e),e=Li(t,e,r.Hash.length)-1,t[e]=10),t.length-e}function x0(r){let t=R2(r),e=new Uint8Array(t),n=t;if(r.Data&&(n-=r.Data.length,e.set(r.Data,n),n=Li(e,n,r.Data.length)-1,e[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=T2(r.Links[o],e.subarray(0,n));n-=i,n=Li(e,n,i)-1,e[n]=18}return e}function C2(r){let t=0;if(r.Hash){let e=r.Hash.length;t+=1+e+Bo(e)}if(typeof r.Name=="string"){let e=b0.encode(r.Name).length;t+=1+e+Bo(e)}return typeof r.Tsize=="number"&&(t+=1+Bo(r.Tsize)),t}function R2(r){let t=0;if(r.Data){let e=r.Data.length;t+=1+e+Bo(e)}if(r.Links)for(let e of r.Links){let n=C2(e);t+=1+n+Bo(n)}return t}function Li(r,t,e){t-=Bo(e);let n=t;for(;e>=B2;)r[t++]=e&127|128,e/=128;for(;e>=128;)r[t++]=e&127|128,e>>>=7;return r[t]=e,n}function Bo(r){return r%2===0&&r++,Math.floor((N2(r)+6)/7)}function N2(r){let t=0;return r>=w0&&(r=Math.floor(r/w0),t=32),r>=65536&&(r>>>=16,t+=16),r>=256&&(r>>>=8,t+=8),t+L2[r]}var L2=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var P2=["Data","Links"],D2=["Hash","Name","Tsize"],oh=new TextEncoder;function v0(r,t){if(r===t)return 0;let e=r.Name?oh.encode(r.Name):[],n=t.Name?oh.encode(t.Name):[],o=e.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(e[s]!==n[s]){o=e[s],i=n[s];break}return o<i?-1:i<o?1:0}function E0(r,t){return!Object.keys(r).some(e=>!t.includes(e))}function S0(r){if(typeof r.asCID=="object"){let e=L.asCID(r);if(!e)throw new TypeError("Invalid DAG-PB form");return{Hash:e}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let t={};if(r.Hash){let e=L.asCID(r.Hash);try{e||(typeof r.Hash=="string"?e=L.parse(r.Hash):r.Hash instanceof Uint8Array&&(e=L.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}e&&(t.Hash=e)}if(!t.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(t.Name=r.Name),typeof r.Tsize=="number"&&(t.Tsize=r.Tsize),t}function ih(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let t={};if(r.Data!==void 0)if(typeof r.Data=="string")t.Data=oh.encode(r.Data);else if(r.Data instanceof Uint8Array)t.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))t.Links=r.Links.map(S0),t.Links.sort(v0);else throw new TypeError("Invalid DAG-PB form");else t.Links=[];return t}function sh(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!E0(r,P2))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let t=0;t<r.Links.length;t++){let e=r.Links[t];if(!e||typeof e!="object"||Array.isArray(e)||e instanceof Uint8Array||e["/"]&&e["/"]===e.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!E0(e,D2))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(e.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(e.Hash==null||!e.Hash["/"]||e.Hash["/"]!==e.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(e.Name!==void 0&&typeof e.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(e.Tsize!==void 0){if(typeof e.Tsize!="number"||e.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(e.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(t>0&&v0(e,r.Links[t-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function A0(r,t=[]){return ih({Data:r,Links:t})}function I0(r,t,e){return S0({Hash:e,Name:r,Tsize:t})}function k0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var O2="dag-pb",Te=112;function U2(r){sh(r);let t={};return r.Links&&(t.Links=r.Links.map(e=>{let n={};return e.Hash&&(n.Hash=e.Hash.bytes),e.Name!==void 0&&(n.Name=e.Name),e.Tsize!==void 0&&(n.Tsize=e.Tsize),n})),r.Data&&(t.Data=r.Data),x0(t)}function Nr(r){let t=k0(r),e=y0(t),n={};return e.Data&&(n.Data=e.Data),e.Links&&(n.Links=e.Links.map(o=>{let i={};try{i.Hash=L.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function To(r){return r?.then!=null}function _0(r=[],t){let e={[Te]:Pi,[ae]:wn,[Cr]:Nn,[Rr]:_o,[hr]:Yn};return r.forEach(n=>{e[n.code]=n}),async n=>{let o=e[n];if(o==null&&t!=null){let i=t(n);To(i)?o=await i:o=i,e[o.code]=o}if(o!=null)return o;throw new ac(`Could not load codec for ${n}`)}}function B0(r=[],t){let e={[Xe.code]:Xe,[gs.code]:gs,[bt.code]:bt};return r.forEach(n=>{e[n.code]=n}),async n=>{let o=e[n];if(o==null&&t!=null){let i=t(n);To(i)?o=await i:o=i,e[o.code]=o}if(o!=null)return o;throw new sc(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var mc=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};var gc=class{has(t,e){return Promise.reject(new Error(".has is not implemented"))}put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(t,e){for await(let{cid:n,block:o}of t)await this.put(n,o,e),yield n}get(t,e){return Promise.reject(new Error(".get is not implemented"))}async*getMany(t,e){for await(let n of t)yield{cid:n,block:await this.get(n,e)}}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(t,e){for await(let n of t)await this.delete(n,e),yield n}async*getAll(t){throw new Error(".getAll is not implemented")}};var yc=0,wc=class extends gc{child;constructor(t){super(),this.child=t}put(t,e){return t.multihash.code===yc||this.child==null?t:this.child.put(t,e)}get(t){if(t.multihash.code===yc)return t.multihash.digest;if(this.child==null)throw new mc;return this.child.get(t)}has(t){return t.multihash.code===yc?!0:this.child==null?!1:this.child.has(t)}delete(t){if(t.code!==yc&&this.child!=null)return this.child.delete(t)}getAll(t){return this.child!=null?this.child.getAll(t):[]}};function F2(r){return r[Symbol.asyncIterator]!=null}function M2(r,t){let e=0;if(F2(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Wn(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=t(o,e++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){s===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var ve=M2;function V2(r){return r[Symbol.asyncIterator]!=null}function T0(r){return r?.then!=null}function H2(r,t){let e=0;if(V2(r))return async function*(){for await(let c of r){let l=t(c,e++);T0(l)&&await l,yield c}}();let n=Wn(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(o,e++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=t(c,e++);T0(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var ah=H2;var bc=class{child;getHasher;log;logger;components;constructor(t){this.log=t.logger.forComponent("helia:networked-storage"),this.logger=t.logger,this.components=t,this.child=new wc(t.blockstore),this.getHasher=t.getHasher}async put(t,e,n={}){return await this.child.has(t,n)?(n.onProgress?.(new H("blocks:put:duplicate",t)),t):(n.onProgress?.(new H("blocks:put:providers:notify",t)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(t,e,n))),n.onProgress?.(new H("blocks:put:blockstore:put",t)),this.child.put(t,e,n))}async*putMany(t,e={}){let n=ve(t,async({cid:i})=>{let s=await this.child.has(i,e);return s&&e.onProgress?.(new H("blocks:put-many:duplicate",i)),!s}),o=ah(n,async({cid:i,block:s})=>{e.onProgress?.(new H("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,e)))});e.onProgress?.(new H("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,e)}async get(t,e={}){if(e.offline!==!0&&!await this.child.has(t,e)){let n=await this.getHasher(t.multihash.code);e.onProgress?.(new H("blocks:get:providers:get",t));let o=await C0(t,this.components.blockBrokers,n,{...e,log:this.log});return e.onProgress?.(new H("blocks:get:blockstore:put",t)),await this.child.put(t,o,e),e.onProgress?.(new H("blocks:get:providers:notify",t)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(t,o,e))),o}return e.onProgress?.(new H("blocks:get:blockstore:get",t)),this.child.get(t,e)}async*getMany(t,e={}){e.onProgress?.(new H("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ah(t,async n=>{if(e.offline!==!0&&!await this.child.has(n,e)){let o=await this.getHasher(n.multihash.code);e.onProgress?.(new H("blocks:get-many:providers:get",n));let i=await C0(n,this.components.blockBrokers,o,{...e,log:this.log});e.onProgress?.(new H("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,e),e.onProgress?.(new H("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,i,e)))}}))}async delete(t,e={}){e.onProgress?.(new H("blocks:delete:blockstore:delete",t)),await this.child.delete(t,e)}async*deleteMany(t,e={}){e.onProgress?.(new H("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of t)yield n}(),e)}async has(t,e={}){return this.child.has(t,e)}async*getAll(t={}){t.onProgress?.(new H("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(t)}},xc=class extends bc{started;constructor(t){super(t),this.started=!1}isStarted(){return this.started}async start(){await Vr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Hr(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(t,e){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(e));return new ch({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:t})}},ch=class extends bc{closeController;constructor(t,e){super(t),this.closeController=new AbortController,mt(1/0,this.closeController.signal),this.log=t.logger.forComponent(`helia:session-storage:${e.root}`)}close(){this.closeController.abort()}async put(t,e,n={}){let o=Yt([this.closeController.signal,n.signal]);mt(1/0,o);try{return await super.put(t,e,{...n,signal:o})}finally{o.clear()}}async*putMany(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{yield*super.putMany(t,{...e,signal:n})}finally{n.clear()}}async get(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{return await super.get(t,{...e,signal:n})}finally{n.clear()}}async*getMany(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{yield*super.getMany(t,{...e,signal:n})}finally{n.clear()}}async delete(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{await super.delete(t,{...e,signal:n})}finally{n.clear()}}async*deleteMany(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{yield*super.deleteMany(t,{...e,signal:n})}finally{n.clear()}}async has(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{return await super.has(t,{...e,signal:n})}finally{n.clear()}}async*getAll(t={}){let e=Yt([this.closeController.signal,t.signal]);mt(1/0,e);try{yield*super.getAll({...t,signal:e})}finally{e.clear()}}};function $2(r){return typeof r.retrieve=="function"}var z2=(r,t)=>{if(t==null)throw new gt(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async e=>{let n,o=t.digest(e);if(To(o)?n=await o:n=o,!Z(n.digest,r.multihash.digest))throw new Ae("Hash of downloaded block did not match multihash from passed CID")}};async function C0(r,t,e,n){let o=z2(r,e),i=new AbortController,s=Yt([i.signal,n.signal]);mt(1/0,i.signal,s);let a=[];for(let c of t)$2(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async f=>{await o(f),l=!0}});return l||await o(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var lh=Ot(wf(),1);var q2=Math.LN2*Math.LN2,Ec=class r{static create(t,e=.005){let n=K2(t,e);return new r(n)}seeds;bits;buffer;constructor(t={}){t.seeds!=null?this.seeds=t.seeds:this.seeds=G2(t.hashes??8),this.bits=t.bits??1024,this.buffer=re(Math.ceil(this.bits/8))}add(t){typeof t=="string"&&(t=D(t));for(let e=0;e<this.seeds.length;e++){let o=lh.default.x86.hash32(t,this.seeds[e])%this.bits;this.setbit(o)}}has(t){typeof t=="string"&&(t=D(t));for(let e=0;e<this.seeds.length;e++){let o=lh.default.x86.hash32(t,this.seeds[e])%this.bits;if(!this.getbit(o))return!1}return!0}clear(){this.buffer.fill(0)}setbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;let o=this.buffer[e];o|=1<<n,this.buffer[e]=o}getbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;return(this.buffer[e]&1<<n)!==0}};function K2(r,t=.005){let e=Math.round(-1*r*Math.log(t)/q2),n=Math.round(e/r*Math.LN2);return{bits:e,hashes:n}}function G2(r){let t,e,n=[];for(let o=0;o<r;o++)for(t=new fr(xa(4)),n[o]=t.getUint32(0,!0),e=0;e<o;e++)if(n[o]===n[e]){o--;break}return n}var Di=class extends qn{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(t,e){super(),mt(1/0,this),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=Ec.create(this.maxProviders)}async retrieve(t,e={}){let n=se.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o;let i=ft();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.intialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",t)}let s=!1,a=new kr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||e.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let u=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(u)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),i.resolve(await this.retrieve(t,e))}).catch(l=>{this.log.error("could not find new providers for %c",t,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(t,l.detail,e),{provider:l.detail}).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,u)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(t,l,e),{provider:l}))).catch(l=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,l)});try{return await i.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toEvictionKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let o=ft(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t);for await(let s of this.findNewProviders(t,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===e&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<e)throw new ic(`Found ${i} of ${e} ${this.name} providers for ${t}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",t,s.errors??s),o.reject(s)}),o.promise}};var vc=class{blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(t){this.logger=t.logger??Wm(),this.log=this.logger.forComponent("helia"),this.getHasher=B0(t.hashers,t.loadHasher),this.getCodec=_0(t.codecs,t.loadCodec),this.dns=t.dns??Ai(),this.metrics=t.metrics;let e={blockstore:t.blockstore,datastore:t.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...t.components??{}};this.routing=e.routing=new lc(e,{routers:(t.routers??[]).flatMap(o=>{let i=[o];return o[Wo]!=null&&i.push(o[Wo]),o[jo]!=null&&i.push(o[jo]),i}),providerLookupConcurrency:t.providerLookupConcurrency});let n=new xc(e);this.pins=new oc(t.datastore,n,this.getCodec),this.blockstore=new uc(n,this.pins,{holdGcLock:t.holdGcLock??!0}),this.datastore=t.datastore,e.blockBrokers=t.blockBrokers.map(o=>o(e))}async start(){await d0(this.datastore),await Vr(this.blockstore,this.datastore,this.routing)}async stop(){await Hr(this.blockstore,this.datastore,this.routing)}async gc(t={}){let e=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await ur(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,t))continue;yield i,t.onProgress?.(new H("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),t.onProgress?.(new H("helia:gc:error",s))}}()))}finally{e()}this.log("gc finished")}};var Sc=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let 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 f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(i*=t,i+=u,i>l||(s+=1,e!==void 0&&s>e))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return e[o]=s[0],e[o+1]=s[1],e[o+2]=s[2],e[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];e[o]=i>>8,e[o+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=t(i.subarray(0,s));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var R0=45,Y2=15,Co=new Sc;function uh(r){if(!(r.length>Y2))return Co.new(r).parseWith(()=>Co.readIPv4Addr())}function fh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>R0))return Co.new(r).parseWith(()=>Co.readIPv6Addr())}function Ac(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>R0))return Co.new(r).parseWith(()=>Co.readIPAddr())}function Ro(r){return!!uh(r)}function No(r){return!!fh(r)}function Ic(r){return!!Ac(r)}var L0=Ot(N0(),1),X2=["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"],Z2=X2.map(r=>new L0.Netmask(r));function hh(r){for(let t of Z2)if(t.contains(r))return!0;return!1}function J2(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Q2(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return hh(o)}function tS(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function eS(r){let t=r.split(":"),e=t[t.length-1];return hh(e)}function rS(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 P0(r){return Ro(r)?hh(r):J2(r)?Q2(r):tS(r)?eS(r):No(r)?rS(r):void 0}var nS=r=>r.toString().split("/").slice(1),Lo=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),nt=r=>({match:t=>Lo(e=>e===r).match(t),pattern:r}),Ui=()=>({match:r=>Lo(t=>typeof t=="string").match(r),pattern:"{string}"}),Fi=()=>({match:r=>Lo(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),pt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Y.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Mi=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{xu.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),ut=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Qt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),ot=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function Et(...r){function t(o){let i=nS(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function e(o){return t(o)!==!1}function n(o){let i=t(o);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var _c=ot(nt("dns4"),Ui()),Bc=ot(nt("dns6"),Ui()),Tc=ot(nt("dnsaddr"),Ui()),ph=ot(nt("dns"),Ui()),gN=Et(_c,ut(pt())),yN=Et(Bc,ut(pt())),wN=Et(Tc,ut(pt())),D0=Et(Qt(ph,Tc,_c,Bc),ut(pt())),O0=ot(nt("ip4"),Lo(Ro)),U0=ot(nt("ip6"),Lo(No)),mh=Qt(O0,U0),Lr=Qt(mh,ph,_c,Bc,Tc),bN=Et(Qt(mh,ot(Qt(ph,Tc,_c,Bc),ut(pt())))),xN=Et(O0),EN=Et(U0),vN=Et(mh),gh=ot(Lr,nt("tcp"),Fi()),Vi=ot(Lr,nt("udp"),Fi()),SN=Et(ot(gh,ut(pt()))),AN=Et(Vi),yh=ot(Vi,nt("quic")),Cc=ot(Vi,nt("quic-v1")),oS=Qt(yh,Cc),IN=Et(yh),kN=Et(Cc),dh=Qt(Lr,gh,Vi,yh,Cc),F0=Qt(ot(dh,nt("ws"),ut(pt()))),_N=Et(F0),M0=Qt(ot(dh,nt("wss"),ut(pt())),ot(dh,nt("tls"),nt("ws"),ut(pt()))),BN=Et(M0),V0=ot(Vi,nt("webrtc-direct"),ut(Mi()),ut(Mi()),ut(pt())),TN=Et(V0),H0=ot(Cc,nt("webtransport"),ut(Mi()),ut(Mi()),ut(pt())),CN=Et(H0),kc=Qt(F0,M0,ot(gh,ut(pt())),ot(oS,ut(pt())),ot(Lr,ut(pt())),V0,H0,pt()),RN=Et(kc),iS=ot(kc,nt("p2p-circuit"),pt()),NN=Et(iS),sS=Qt(ot(kc,nt("p2p-circuit"),nt("webrtc"),ut(pt())),ot(kc,nt("webrtc"),ut(pt())),nt("webrtc")),LN=Et(sS),aS=Qt(ot(Lr,nt("tcp"),Fi(),nt("http"),ut(pt())),ot(Lr,nt("http"),ut(pt()))),$0=Et(aS),cS=Qt(ot(Lr,nt("tcp"),Qt(ot(nt("443"),nt("http")),ot(Fi(),nt("https"))),ut(pt())),ot(Lr,nt("tls"),nt("http"),ut(pt())),ot(Lr,nt("https"),ut(pt()))),z0=Et(cS);var HN=parseInt("0xFFFF",16),$N=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var G0=Ro,dS=No,wh=function(r){let t=0;if(r=r.toString().trim(),G0(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(dS(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=G0(e[n]),s;i&&(s=wh(e[n]),e[n]=q(s.slice(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,q(s.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);o[t++]=i>>8&255,o[t++]=i&255}return o}throw new Error("invalid ip address")},W0=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let i=0;i<e;i++)o.push(r[t+i]);return o.join(".")}if(e===16){let o=[];for(let i=0;i<e;i+=2)o.push(n.getUint16(t+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Po={},bh={},mS=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];mS.forEach(r=>{let t=gS(...r);bh[t.code]=t,Po[t.name]=t});function gS(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function X(r){if(typeof r=="number"){if(bh[r]!=null)return bh[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Po[r]!=null)return Po[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var SL=X("ip4"),AL=X("ip6"),IL=X("ipcidr");function Sh(r,t){switch(X(r).code){case 4:case 41:return wS(t);case 42:return vh(t);case 6:case 273:case 33:case 132:return X0(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return vh(t);case 421:return vS(t);case 444:return Y0(t);case 445:return Y0(t);case 466:return ES(t);case 481:return globalThis.encodeURIComponent(vh(t));default:return q(t,"base16")}}function Ah(r,t){switch(X(r).code){case 4:return j0(t);case 41:return j0(t);case 42:return Eh(t);case 6:case 273:case 33:case 132:return Ih(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Eh(t);case 421:return bS(t);case 444:return SS(t);case 445:return AS(t);case 466:return xS(t);case 481:return Eh(globalThis.decodeURIComponent(t));default:return D(t,"base16")}}var xh=Object.values(Qo).map(r=>r.decoder),yS=function(){let r=xh[0].or(xh[1]);return xh.slice(2).forEach(t=>r=r.or(t)),r}();function j0(r){if(!Ic(r))throw new Error("invalid ip address");return wh(r)}function wS(r){let t=W0(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Ic(t))throw new Error("invalid ip address");return t}function Ih(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function X0(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Eh(r){let t=D(r),e=Uint8Array.from(Gn(t.length));return ct([e,t],e.length+t.length)}function vh(r){let t=mn(r);if(r=r.slice(oe(t)),r.length!==t)throw new Error("inconsistent lengths");return q(r)}function bS(r){let t;r[0]==="Q"||r[0]==="1"?t=wt(Y.decode(`z${r}`)).bytes:t=L.parse(r).multihash.bytes;let e=Uint8Array.from(Gn(t.length));return ct([e,t],e.length+t.length)}function xS(r){let t=yS.decode(r),e=Uint8Array.from(Gn(t.length));return ct([e,t],e.length+t.length)}function ES(r){let t=mn(r),e=r.slice(oe(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+q(e,"base64url")}function vS(r){let t=mn(r),e=r.slice(oe(t));if(e.length!==t)throw new Error("inconsistent lengths");return q(e,"base58btc")}function SS(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=St.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ih(n);return ct([e,o],e.length+o.length)}function AS(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=St.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ih(n);return ct([e,o],e.length+o.length)}function Y0(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=q(t,"base32"),o=X0(e);return`${n}:${o}`}function Z0(r){r=kh(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<o.length;i++){let s=o[i],a=X(s);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=o.length)throw Q0("invalid address: "+r);if(a.path===!0){n=kh(o.slice(i).join("/")),t.push([a.code,Ah(a.code,n)]),e.push([a.code,n]);break}let c=Ah(a.code,o[i]);t.push([a.code,c]),e.push([a.code,Sh(a.code,c)])}return{string:J0(e),bytes:Bh(t),tuples:t,stringTuples:e,path:n}}function _h(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let i=mn(r,o),s=oe(i),a=X(i),c=IS(a,r.slice(o+s));if(c===0){t.push([i]),e.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw Q0("Invalid address Uint8Array: "+q(r,"base16"));t.push([i,l]);let u=Sh(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:J0(e),tuples:t,stringTuples:e,path:n}}function J0(r){let t=[];return r.map(e=>{let n=X(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),kh(t.join("/"))}function Bh(r){return ct(r.map(t=>{let e=X(t[0]),n=Uint8Array.from(Gn(e.code));return t.length>1&&t[1]!=null&&(n=ct([n,t[1]])),n}))}function IS(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=mn(t instanceof Uint8Array?t:Uint8Array.from(t));return e+oe(e)}}function kh(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Q0(r){return new Error("Error parsing address: "+r)}var kS=Symbol.for("nodejs.util.inspect.custom"),Ch=Symbol.for("@multiformats/js-multiaddr/multiaddr"),_S=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],Th=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Rc=class r{bytes;#t;#r;#a;#c;[Ch]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=_h(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Z0(t)}else if(ey(t))e=_h(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#r=e.tuples,this.#a=e.stringTuples,this.#c=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="",s=X("tcp"),a=X("udp"),c=X("ip4"),l=X("ip6"),u=X("dns6"),f=X("ip6zone");for(let[h,m]of this.stringTuples())h===f.code&&(i=`%${m??""}`),_S.includes(h)&&(e=s.name,o=443,n=`${m??""}${i}`,t=h===u.code?6:4),(h===s.code||h===a.code)&&(e=X(h).name,o=parseInt(m??"")),(h===c.code||h===l.code)&&(e=X(h).name,n=`${m??""}${i}`,t=h===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#r.map(([t])=>Object.assign({},X(t)))}protoCodes(){return this.#r.map(([t])=>t)}protoNames(){return this.#r.map(([t])=>X(t).name)}tuples(){return this.#r}stringTuples(){return this.#a}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Bh(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Po.p2p.code&&t.push([n,o]),n===Po["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?q(Y.decode(`z${n}`),"base58btc"):q(L.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#c}equals(t){return Z(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=ty.get(e.name);if(n==null)throw new Th(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>Pr(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[kS](){return`Multiaddr(${this.#t})`}};var ty=new Map;function ey(r){return!!r?.[Ch]}function Pr(r){return new Rc(r)}var BS=[X("tcp").code,X("dns").code,X("dnsaddr").code,X("dns4").code,X("dns6").code];function ry(r){let t;try{t=X("sni").code}catch{return null}for(let[e,n]of r)if(e===t&&n!==void 0)return n;return null}function ny(r){return r.some(([t,e])=>t===X("tls").code)}function me(r,t,e){let n=oy[X(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${X(r).name}`);let o=n(t,e);return r===X("ip6").code?`[${o}]`:o}var oy={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${me(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${me(e[0],e[1]??"",t)}:${r}`},dnsaddr:(r,t)=>r,dns4:(r,t)=>r,dns6:(r,t)=>r,dns:(r,t)=>r,ipfs:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/ipfs/${r}`},p2p:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p/${r}`},http:(r,t)=>{let e=ny(t),n=ry(t);if(e&&n!==null)return`https://${n}`;let o=e?"https://":"http://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=me(i[0],i[1]??"",t);return s=s.replace("tcp://",""),`${o}${s}`},"http-path":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=me(e[0],e[1]??"",t),o=decodeURIComponent(r);return`${n}/${o}`},tls:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return me(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return me(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=me(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=ny(t),n=ry(t);if(e&&n!==null)return`wss://${n}`;let o=e?"wss://":"ws://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=me(i[0],i[1]??"",t);return s=s.replace("tcp://",""),`${o}${s}`},wss:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=me(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p-webrtc-direct`}};function iy(r,t){let n=Pr(r).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=X(o[0]),s=oy[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return t?.assumeHttp!==!1&&BS.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var Nc=class{url;#t=0;#r=0;#a=0;#c=0;#g=new Map;log;constructor(t,e){this.url=t instanceof URL?t:new URL(t),this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#S(t){let e=t.multihash.bytes;return se.encode(e)}async getRawBlock(t,e){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${t.toString()}`,n.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let o=this.#S(t),i=new AbortController,s=()=>{i.abort()};e?.addEventListener("abort",s);try{let a=this.#g.get(o);return a==null&&(this.#t++,a=fetch(n.toString(),{signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#r++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#c++,new Uint8Array(await c.arrayBuffer())}),this.#g.set(o,a)),await a}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#r++,new Error(`unable to fetch raw block for CID ${t}`))}finally{e?.removeEventListener("abort",s),this.#g.delete(o)}}reliability(){return this.#t===0?1:this.#a>0?-1/0:this.#c/(this.#t+this.#r*3)}incrementInvalidBlocks(){this.#a++}getStats(){return{attempts:this.#t,errors:this.#r,invalidBlocks:this.#a,successes:this.#c,pendingResponses:this.#g.size}}};function TS(r,t,e){return r.filter(n=>{if(z0.matches(n)||t&&$0.matches(n))return e||D0.matches(n)?!0:P0(n.toOptions().host)===!1;if(!t&&e){let{host:o}=n.toOptions();if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*Lc(r,t,e,n,o,i){for await(let s of t.findProviders(r,i)){let a=TS(s.multiaddrs,n,o);if(a.length===0)continue;let c=iy(a[0]);yield new Nc(c,e)}}var Rh=class extends Di{routing;allowInsecure;allowLocal;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Pc,this.allowLocal=e.allowLocal??Dc}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let o=await e.getRawBlock(t,n.signal);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(o),o}async*findNewProviders(t,e={}){yield*Lc(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}};function sy(r,t){return new Rh(r,t)}var Oc=class{allowInsecure;allowLocal;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??Pc,this.allowLocal=e.allowLocal??Dc}async retrieve(t,e={}){let n=[];for await(let o of Lc(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)){this.log("getting block for %c from %s",t,o.url);try{let i=await o.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s",t,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",t,o.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return sy({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure})}};var Pc=!1,Dc=!1;function Hi(r={}){return t=>new Oc(t,r)}W.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);W.formatters.t=r=>r==null?"undefined":St.baseEncode(r);W.formatters.m=r=>r==null?"undefined":se.baseEncode(r);W.formatters.p=r=>r==null?"undefined":r.toString();W.formatters.c=r=>r==null?"undefined":r.toString();W.formatters.k=r=>r==null?"undefined":r.toString();W.formatters.a=r=>r==null?"undefined":r.toString();W.formatters.e=r=>r==null?"undefined":ay(r.stack)??ay(r.message)??r.toString();function CS(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function Ce(r){let t=CS(`${r}:trace`);return W.enabled(`${r}:trace`)&&W.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=W(`${r}:trace`)),Object.assign(W(r),{error:W(`${r}:error`),trace:t})}function ay(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}async function*Uc(r,t={}){let e=r.getReader();try{for(;;){let n=await e.read();if(n.done)return;yield n.value}}finally{t.preventCancel!==!0&&await e.cancel(),e.releaseLock()}}var OS=Ot(Do(),1);var $e=class extends Error{static name="SignatureVerificationError";constructor(t="Record signature verification failed"){super(t),this.name="SignatureVerificationError"}},Fc=class extends Error{static name="RecordExpiredError";constructor(t="Record has expired"){super(t),this.name="RecordExpiredError"}},Oo=class extends Error{static name="UnsupportedValidityError";constructor(t="The validity type is unsupported"){super(t),this.name="UnsupportedValidityError"}},Mc=class extends Error{static name="RecordTooLargeError";constructor(t="The record is too large"){super(t),this.name="RecordTooLargeError"}},Vc=class extends Error{static name="InvalidValueError";constructor(t="Value must be a valid content path starting with /"){super(t),this.name="InvalidValueError"}},Hc=class extends Error{static name="InvalidRecordDataError";constructor(t="Invalid record data"){super(t),this.name="InvalidRecordDataError"}},$i=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(t="Invalid embedded public key"){super(t),this.name="InvalidEmbeddedPublicKeyError"}};var ze;(function(r){let t;(function(o){o.EOL="EOL"})(t=r.ValidityType||(r.ValidityType={}));let e;(function(o){o[o.EOL=0]="EOL"})(e||(e={})),function(o){o.codec=()=>dr(e)}(t=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=le((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ce(o,r.codec()),r.decode=(o,i)=>ie(o,r.codec(),i)})(ze||(ze={}));var RS=Ce("ipns:utils"),cy=D("/ipns/");var NS=0,LS=18;function ly(r){let t;if(r.pubKey!=null)try{t=Ia(r.pubKey)}catch(e){throw RS.error(e),e}if(t!=null)return t}function uy(r){let t=D("ipns-signature:");return ct([t,r])}function Ln(r){return"signatureV1"in r?ze.encode({value:D(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:D(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):ze.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function or(r){let t=ze.decode(r);if(t.sequence!=null&&(t.sequence=BigInt(t.sequence)),t.ttl!=null&&(t.ttl=BigInt(t.ttl)),t.signatureV2==null||t.data==null)throw new $e("Missing data or signatureV2");let e=fy(t.data),n=PS(e.Value),o=q(e.Validity);if(t.value!=null&&t.signatureV1!=null)return DS(t),{value:n,validityType:ze.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV1:t.signatureV1,signatureV2:t.signatureV2,data:t.data};if(t.signatureV2!=null)return{value:n,validityType:ze.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV2:t.signatureV2,data:t.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function zi(r){return ct([cy,r.bytes])}function Dr(r){let t=wt(r.slice(cy.length));if(!$c(t,NS)&&!$c(t,LS))throw new Ae("Multihash in IPNS key was not identity or sha2-256");return t}function fy(r){let t=Vt(r);if(t.ValidityType===0)t.ValidityType=ze.ValidityType.EOL;else throw new Oo("The validity type is unsupported");return Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function PS(r){let t=q(r).trim();if(t.startsWith("/"))return t;try{return`/ipfs/${L.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${L.parse(t).toV1().toString()}`}catch{}throw new Vc("Value must be a valid content path starting with /")}function DS(r){if(r.data==null)throw new Hc("Record data is missing");let t=fy(r.data);if(!Z(t.Value,r.value??new Uint8Array(0)))throw new $e('Field "value" did not match between protobuf and CBOR');if(!Z(t.Validity,r.validity??new Uint8Array(0)))throw new $e('Field "validity" did not match between protobuf and CBOR');if(t.ValidityType!==r.validityType)throw new $e('Field "validityType" did not match between protobuf and CBOR');if(t.Sequence!==r.sequence)throw new $e('Field "sequence" did not match between protobuf and CBOR');if(t.TTL!==r.ttl)throw new $e('Field "ttl" did not match between protobuf and CBOR')}function $c(r,t){return r.code===t}var qP=Ce("ipns"),KP=60*60*1e9,US="/ipns/",GP=US.length;var hy=Ot(Do(),1);var zc=Ce("ipns:validator"),FS=1024*10,MS=async(r,t)=>{let e=or(t),n;try{let o=uy(e.data);n=await r.verify(o,e.signatureV2)}catch{n=!1}if(!n)throw zc.error("record signature verification failed"),new $e("Record signature verification failed");if(e.validityType===ze.ValidityType.EOL){if(hy.default.fromString(e.validity).toDate().getTime()<Date.now())throw zc.error("record has expired"),new Fc("record has expired")}else if(e.validityType!=null)throw zc.error("the validity type is unsupported"),new Oo("The validity type is unsupported");zc("ipns record for %s is valid",e.value)};async function dy(r,t){if(t.byteLength>FS)throw new Mc("The record is too large");let e=Dr(r),n;$c(e,0)&&(n=rn(e));let o=or(t),i=ly(o)??n;if(i==null)throw new $i("Could not extract public key from IPNS record or routing key");let s=zi(i.toMultihash());if(!Z(r,s))throw new $i("Embedded public key did not match routing key");await MS(i,t)}async function*qi(r){let t=/\r?\n/,e=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=e.decode(o,{stream:!0});let i=n.split(t);n=i.pop()??"";for(let s=0;s<i.length;s++)yield JSON.parse(i[s])}n+=e.decode(),n!==""&&(yield JSON.parse(n))}var Uo=class extends Error{static name="InvalidRequestError";constructor(t="Invalid request"){super(t),this.name="InvalidRequestError"}},Pn=class extends Error{static name="BadResponseError";constructor(t="Bad response"){super(t),this.name="BadResponseError"}};function VS(r){return r[Symbol.asyncIterator]!=null}function HS(r){if(VS(r))return(async()=>{for await(let t of r)return t})();for(let t of r)return t}var qc=HS;var py=D("/ipns/");function my(r){return Z(r.subarray(0,py.byteLength),py)}var Kc=class{client;constructor(t){this.client=t}async*findProviders(t,e={}){yield*zt(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(t,e,n){if(!my(t))return;let o=Dr(t),i=L.createV1(114,o),s=or(e);await this.client.putIPNS(i,s,n)}async get(t,e){if(!my(t))throw new _t("Not found");let n=Dr(t),o=L.createV1(114,n);try{let i=await this.client.getIPNS(o,e);return Ln(i)}catch(i){throw i.name==="BadResponseError"?new _t("Not found"):i}}},Gc=class{client;constructor(t){this.client=t}async findPeer(t,e={}){let n=await qc(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new _t("Not found")}async*getClosestPeers(t,e={}){}};var te=Ce("delegated-routing-v1-http-api-client"),gy={concurrentRequests:4,timeout:3e4},Wc=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;constructor(t,e={}){this.started=!1,this.shutDownController=new AbortController,mt(1/0,this.shutDownController.signal),this.httpQueue=new de({concurrency:e.concurrentRequests??gy.concurrentRequests}),this.clientUrl=t instanceof URL?t:new URL(t),this.timeout=e.timeout??gy.timeout,this.filterAddrs=e.filterAddrs,this.filterProtocols=e.filterProtocols,this.contentRouting=new Kc(this),this.peerRouting=new Gc(this)}get[Wo](){return this.contentRouting}get[jo](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(t,e={}){te("getProviders starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Yt([this.shutDownController.signal,n,e.signal]);mt(1/0,n,o);let i=ft(),s=ft();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${t.toString()}`);this.#r(a,e.filterAddrs,e.filterProtocols);let l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new _t("No matching records found");if(l.status===422)throw new Uo("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pn("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Providers){let h=this.#t(d);h!=null&&(yield h)}}else for await(let f of qi(Uc(l.body))){let d=this.#t(f);d!=null&&(yield d)}}catch(a){te.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),te("getProviders finished: %c",t)}}async*getPeers(t,e={}){te("getPeers starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Yt([this.shutDownController.signal,n,e.signal]);mt(1/0,n,o);let i=ft(),s=ft();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${t.toCID().toString()}`);this.#r(a,e.filterAddrs,e.filterProtocols);let l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new _t("No matching records found");if(l.status===422)throw new Uo("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pn("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Peers){let h=this.#t(d);h!=null&&(yield h)}}else for await(let f of qi(Uc(l.body))){let d=this.#t(f);d!=null&&(yield d)}}catch(a){te.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),te("getPeers finished: %c",t)}}async getIPNS(t,e={}){te("getIPNS starts: %s",t);let n=AbortSignal.timeout(this.timeout),o=Yt([this.shutDownController.signal,n,e.signal]);mt(1/0,n,o);let i=ft(),s=ft();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${t}`;try{await i.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(te("getIPNS GET %s %d",a,l.status),l.status===404)throw new _t("No matching records found");if(l.status===422)throw new Uo("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pn("GET ipns response had no body");let u=await l.arrayBuffer(),f=new Uint8Array(u,0,u.byteLength);return e.validate!==!1&&await dy(zi(t.multihash),f),or(f)}catch(c){throw te.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),te("getIPNS finished: %s",t)}}async putIPNS(t,e,n={}){te("putIPNS starts: %c",t);let o=AbortSignal.timeout(this.timeout),i=Yt([this.shutDownController.signal,o,n.signal]);mt(1/0,o,i);let s=ft(),a=ft();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${t}`;try{await s.promise;let l=Ln(e),f=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i});if(te("putIPNS PUT %s %d",c,f.status),f.status!==200)throw new Pn("PUT ipns response had status other than 200")}catch(l){throw te.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),te("putIPNS finished: %c",t)}}#t(t){try{let e=[],n=t.Addrs?.map(Pr)??[];return t.Protocols!=null&&e.push(...t.Protocols),t.Protocol!=null&&(e.push(t.Protocol),delete t.Protocol),{...t,Schema:"peer",ID:mo(t.ID),Addrs:n,Protocols:e}}catch(e){te.error("could not conform record to peer schema",e)}}#r(t,e,n){if(e!=null||this.filterAddrs!=null){let o=e?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&t.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&t.searchParams.set("filter-protocols",o)}}};function yy(r,t={}){return new Wc(new URL(r),t)}var wy=D("/ipns/");function by(r){return Z(r.subarray(0,wy.byteLength),wy)}var Lh=class{client;constructor(t){this.client=yy(t)}async provide(t,e){}async*findProviders(t,e){yield*zt(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols}))}async put(t,e,n){if(!by(t))return;let o=Dr(t),i=L.createV1(114,o),s=or(e);await this.client.putIPNS(i,s,n)}async get(t,e){if(!by(t))throw new _t("Not found");let n=Dr(t),o=L.createV1(114,n);try{let i=await this.client.getIPNS(o,e);return Ln(i)}catch(i){throw i.name==="BadResponseError"?new _t("Not found"):i}}async findPeer(t,e){let n=await qc(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new _t("Not found")}async*getClosestPeers(t,e){}};function Ki(r){return new Lh(new URL(r))}var xy="[a-fA-F\\d:]",ln=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${xy})|(?<=${xy})(?=\\s|$))`:"",qe="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",It="[a-fA-F\\d]{1,4}",jc=`
|
|
7
|
+
`)}`:`${e} :`}};Yp=tn;M.Constructed=Yp;tn.NAME="CONSTRUCTED";var Ws=class extends Wt{fromBER(t,e,n){return e}toBER(t){return Fe}};Ws.override="EndOfContentValueBlock";var Xp,js=class extends Ft{constructor(t={}){super(t,Ws),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Xp=js;M.EndOfContent=Xp;js.NAME=hi;var Zp,ho=class extends Ft{constructor(t={}){super(t,Wt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Zp=ho;M.Null=Zp;ho.NAME="NULL";var Ys=class extends Sr(Wt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=tt.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);return vr(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,uf.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Ys.NAME="BooleanValueBlock";var Jp,Xs=class extends Ft{constructor(t={}){super(t,Ys),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Jp=Xs;M.Boolean=Jp;Xs.NAME="BOOLEAN";var Zs=class extends Sr(tr){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=tr.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===hi){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==Kp)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?tr.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Zs.NAME="OctetStringValueBlock";var Qp,Js=class r extends Ft{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Zs),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let i=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(i.byteLength){let s=Ia(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?tn.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${tt.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return tt.BufferSourceConverter.concat(t)}};Qp=Js;M.OctetString=Qp;Js.NAME=Kp;var Qs=class extends Sr(tr){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=tr.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===hi){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Gp)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,i,e,n))return-1;let s=i.subarray(e,e+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=Ia(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,e+n}toBER(t,e){if(this.isConstructed)return tr.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Fe;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Qs.NAME="BitStringValueBlock";var tm,po=class extends Ft{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Qs),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return tn.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};tm=po;M.BitString=tm;po.NAME=Gp;var em;function JE(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<s?s:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=i[s-f]+a[c-f]+e[0];break;default:l=i[s-f]+e[0]}switch(e[0]=l/10,!0){case f>=i.length:i=Vs(new Uint8Array([l%10]),i);break;default:i[s-f]=l%10}}return e[0]>0&&(i=Vs(e,i)),i}function qp(r){if(r>=ui.length)for(let t=ui.length;t<=r;t++){let e=new Uint8Array([0]),n=ui[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=i[0]/10,n[o]=i[0]%10}e[0]>0&&(n=Vs(e,n)),ui.push(n)}return ui[r]}function QE(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=i[s-u]-a[c-u]-e,!0){case l<0:e=1,i[s-u]=l+10;break;default:e=0,i[s-u]=l}if(e>0)for(let f=s-c+1;f>=0;f--,u++)if(l=i[s-u]-e,l<0)e=1,i[s-u]=l+10;else{e=0,i[s-u]=l;break}return i.slice()}var di=class extends Sr(Wt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=uf.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Hp(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let i=this.fromBER(t,e,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&s[1]&128?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case t:e=QE(qp(n),e),s="-";break;default:e=JE(e,qp(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(s+=zp.charAt(e[c]));return a===!1&&(s+=zp.charAt(0)),s}};em=di;di.NAME="IntegerValueBlock";Object.defineProperty(em.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var rm,Mt=class r extends Ft{constructor(t={}){super(t,di),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Hs(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Hs();let e=BigInt(t),n=new fi,o=e.toString(16).replace(/^-/,""),i=new Uint8Array(tt.Convert.FromHex(o));if(e<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${tt.Convert.ToHex(a)}`)+e,u=tt.BufferSourceConverter.toUint8Array(tt.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};rm=Mt;M.Integer=rm;Mt.NAME="INTEGER";var nm,ta=class extends Mt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};nm=ta;M.Enumerated=nm;ta.NAME="ENUMERATED";var pi=class extends Sr(Wt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Tn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Hs();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let e=Qr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",Fe;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),i=e.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let t="";if(this.isHexOnly)t=tt.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};pi.NAME="sidBlock";var ea=class extends Wt{constructor({value:t=go,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let i=new pi;if(o=i.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,Fe;e.push(o)}return ff(e)}fromString(t){this.value=[];let e=0,n=0,o="",i=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,i){let s=this.value[0],a=0;switch(s.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;s.valueDec=c+a,i=!1}else{let s=new pi;if(o>Number.MAX_SAFE_INTEGER){Hs();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};ea.NAME="ObjectIdentifierValueBlock";var om,mo=class extends Ft{constructor(t={}){super(t,ea),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};om=mo;M.ObjectIdentifier=om;mo.NAME="OBJECT IDENTIFIER";var mi=class extends Sr(br){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Tn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let e=Qr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",Fe;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),i=e.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let t="";return this.isHexOnly?t=tt.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};mi.NAME="relativeSidBlock";var ra=class extends Wt{constructor({value:t=go,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let i=new mi;if(o=i.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(t);if(i.byteLength===0)return this.error=this.value[o].error,Fe;n.push(i)}return ff(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let i=new mi;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};ra.NAME="RelativeObjectIdentifierValueBlock";var im,na=class extends Ft{constructor(t={}){super(t,ra),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};im=na;M.RelativeObjectIdentifier=im;na.NAME="RelativeObjectIdentifier";var sm,xr=class extends tn{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};sm=xr;M.Sequence=sm;xr.NAME="SEQUENCE";var am,oa=class extends tn{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};am=oa;M.Set=am;oa.NAME="SET";var ia=class extends Sr(Wt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=go}toJSON(){return{...super.toJSON(),value:this.value}}};ia.NAME="StringValueBlock";var sa=class extends ia{};sa.NAME="SimpleStringValueBlock";var Qt=class extends qs{constructor({...t}={}){super(t,sa)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,tt.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Qt.NAME="SIMPLE STRING";var aa=class extends Qt{fromBuffer(t){this.valueBlock.valueHexView=tt.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=tt.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=tt.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(tt.Convert.FromUtf8String(t)),this.valueBlock.value=t}};aa.NAME="Utf8StringValueBlock";var cm,Er=class extends aa{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};cm=Er;M.Utf8String=cm;Er.NAME="UTF8String";var ca=class extends Qt{fromBuffer(t){this.valueBlock.value=tt.Convert.ToUtf16String(t),this.valueBlock.valueHexView=tt.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(tt.Convert.FromUtf16String(t))}};ca.NAME="BmpStringValueBlock";var lm,la=class extends ca{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};lm=la;M.BmpString=lm;la.NAME="BMPString";var ua=class extends Qt{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let i=Qr(t.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=t}};ua.NAME="UniversalStringValueBlock";var um,fa=class extends ua{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};um=fa;M.UniversalString=um;fa.NAME="UniversalString";var fm,ha=class extends Qt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};fm=ha;M.NumericString=fm;ha.NAME="NumericString";var hm,da=class extends Qt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};hm=da;M.PrintableString=hm;da.NAME="PrintableString";var dm,pa=class extends Qt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};dm=pa;M.TeletexString=dm;pa.NAME="TeletexString";var pm,ma=class extends Qt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};pm=ma;M.VideotexString=pm;ma.NAME="VideotexString";var mm,ga=class extends Qt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};mm=ga;M.IA5String=mm;ga.NAME="IA5String";var gm,ya=class extends Qt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};gm=ya;M.GraphicString=gm;ya.NAME="GraphicString";var ym,gi=class extends Qt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};ym=gi;M.VisibleString=ym;gi.NAME="VisibleString";var wm,wa=class extends Qt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};wm=wa;M.GeneralString=wm;wa.NAME="GeneralString";var bm,ba=class extends Qt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};bm=ba;M.CharacterString=bm;ba.NAME="CharacterString";var xm,yi=class extends gi{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,tt.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=he(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=he(this.month,2),e[2]=he(this.day,2),e[3]=he(this.hour,2),e[4]=he(this.minute,2),e[5]=he(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};xm=yi;M.UTCTime=xm;yi.NAME="UTCTime";var Em,xa=class extends yi{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",i=0,s,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(h.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*m,h.length===4){if(m=parseInt(h.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=f*m}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");i=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*i;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*i;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*i;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=s.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(he(this.year,4)),e.push(he(this.month,2)),e.push(he(this.day,2)),e.push(he(this.hour,2)),e.push(he(this.minute,2)),e.push(he(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(he(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Em=xa;M.GeneralizedTime=Em;xa.NAME="GeneralizedTime";var vm,Ea=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};vm=Ea;M.DATE=vm;Ea.NAME="DATE";var Sm,va=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Sm=va;M.TimeOfDay=Sm;va.NAME="TimeOfDay";var _m,Sa=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};_m=Sa;M.DateTime=_m;Sa.NAME="DateTime";var Am,_a=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Am=_a;M.Duration=Am;_a.NAME="Duration";var Im,Aa=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Im=Aa;M.TIME=Im;Aa.NAME="TIME";function G(r,t="utf8"){let e=Ss[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var wi=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ka=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var km={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new ka("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var en=km;async function Tm(r){let t=await en.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await ev(t);return{privateKey:e[0],publicKey:e[1]}}async function Bm(r,t){let e=await en.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await en.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Cm(r,t,e){let n=await en.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return en.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function ev(r){if(r.privateKey==null||r.publicKey==null)throw new St("Private and public key are required");return Promise.all([en.get().subtle.exportKey("jwk",r.privateKey),en.get().subtle.exportKey("jwk",r.publicKey)])}function pf(r){if(r.kty!=="RSA")throw new St("invalid key type");if(r.n==null)throw new St("invalid key modulus");return L(r.n,"base64url").length*8}var yo=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=bi.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return P.createV1(114,this._multihash)}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Y(this.raw,t.raw)}verify(t,e){return Cm(this._key,e,t)}},xi=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=bi.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Y(this.raw,t.raw)}sign(t){return Bm(this._key,t)}};var Ta=8192,mf=18;function Rm(r){let{result:t}=df(r),e=t.valueBlock.value;return{n:er(e[1]),e:er(e[2]),d:er(e[3]),p:er(e[4]),q:er(e[5]),dp:er(e[6]),dq:er(e[7]),qi:er(e[8]),kty:"RSA",alg:"RS256"}}function rv(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 St("JWK was missing components");let e=new xr({value:[new Mt({value:0}),Mt.fromBigInt(rr(L(r.n,"base64url"))),Mt.fromBigInt(rr(L(r.e,"base64url"))),Mt.fromBigInt(rr(L(r.d,"base64url"))),Mt.fromBigInt(rr(L(r.p,"base64url"))),Mt.fromBigInt(rr(L(r.q,"base64url"))),Mt.fromBigInt(rr(L(r.dp,"base64url"))),Mt.fromBigInt(rr(L(r.dq,"base64url"))),Mt.fromBigInt(rr(L(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Nm(r){let{result:t}=df(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:er(e[0]),e:er(e[1])}}function gf(r){if(r.n==null||r.e==null)throw new St("JWK was missing components");let e=new xr({value:[new xr({value:[new mo({value:"1.2.840.113549.1.1.1"}),new ho]}),new po({valueHex:new xr({value:[Mt.fromBigInt(rr(L(r.n,"base64url"))),Mt.fromBigInt(rr(L(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function er(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return G(t,"base64url")}function rr(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Pm(r){let t=Rm(r);return Lm(t)}function yf(r){let t=Nm(r);if(pf(t)>Ta)throw new Wn("Key size is too large");let e=uo(Qe.encode({Type:Bt.RSA,Data:r})),n=Le(mf,e);return new yo(t,n)}function Lm(r){if(pf(r)>Ta)throw new St("Key size is too large");let t=Om(r),e=uo(Qe.encode({Type:Bt.RSA,Data:gf(t.publicKey)})),n=Le(mf,e);return new xi(t.privateKey,new yo(t.publicKey,n))}async function Dm(r){if(r>Ta)throw new St("Key size is too large");let t=await Tm(r),e=uo(Qe.encode({Type:Bt.RSA,Data:gf(t.publicKey)})),n=Le(mf,e);return new xi(t.privateKey,new yo(t.publicKey,n))}function Om(r){if(r==null)throw new St("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Ba=class extends so{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,wp(t);let n=si(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(t){return io(this),this.iHash.update(t),this}digestInto(t){io(this),oo(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wf=(r,t,e)=>new Ba(r,t).update(e).digest();wf.create=(r,t)=>new Ba(r,t);function Um(r){r.lowS!==void 0&&Oe("lowS",r.lowS),r.prehash!==void 0&&Oe("prehash",r.prehash)}function nv(r){let t=li(r);Je(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:ov,hexToBytes:iv}=Rs,_r={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=_r;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Sn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?Sn(o.length/2|128):"";return`${Sn(r)}${i}${o}${t}`},decode(r,t){let{Err:e}=_r,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(r){let{Err:t}=_r;if(r<Ar)throw new t("integer: negative integers are not allowed");let e=Sn(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=_r;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return ov(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=_r,o=typeof r=="string"?iv(r):r;co(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("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 t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=_r,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Ar=BigInt(0),Pt=BigInt(1),MB=BigInt(2),Fm=BigInt(3),VB=BigInt(4);function sv(r){let t=nv(r),{Fp:e}=t,n=Xr(t.n,t.nBitLength),o=t.toBytes||((p,y,g)=>{let x=y.toAffine();return yr(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),i=t.fromBytes||(p=>{let y=p.subarray(1),g=e.fromBytes(y.subarray(0,e.BYTES)),x=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:g,y:x}});function s(p){let{a:y,b:g}=t,x=e.sqr(p),b=e.mul(x,p);return e.add(e.add(b,e.mul(p,y)),g)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function a(p){return ai(p,Pt,t.n)}function c(p){let{allowedPrivateKeyLengths:y,nByteLength:g,wrapPrivateKey:x,n:b}=t;if(y&&typeof p!="bigint"){if(Wr(p)&&(p=mr(p)),typeof p!="string"||!y.includes(p.length))throw new Error("Invalid key");p=p.padStart(g*2,"0")}let E;try{E=typeof p=="bigint"?p:gr(xt("private key",p,g))}catch{throw new Error(`private key must be ${g} bytes, hex or bigint, not ${typeof p}`)}return x&&(E=ct(E,b)),ue("private key",E,Pt,b),E}function l(p){if(!(p instanceof d))throw new Error("ProjectivePoint expected")}let u=In((p,y)=>{let{px:g,py:x,pz:b}=p;if(e.eql(b,e.ONE))return{x:g,y:x};let E=p.is0();y==null&&(y=E?e.ONE:e.inv(b));let I=e.mul(g,y),B=e.mul(x,y),S=e.mul(b,y);if(E)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:I,y:B}}),f=In(p=>{if(p.is0()){if(t.allowInfinityPoint&&!e.is0(p.py))return;throw new Error("bad point: ZERO")}let{x:y,y:g}=p.toAffine();if(!e.isValid(y)||!e.isValid(g))throw new Error("bad point: x or y not FE");let x=e.sqr(g),b=s(y);if(!e.eql(x,b))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(y,g,x){if(this.px=y,this.py=g,this.pz=x,y==null||!e.isValid(y))throw new Error("x required");if(g==null||!e.isValid(g))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(y){let{x:g,y:x}=y||{};if(!y||!e.isValid(g)||!e.isValid(x))throw new Error("invalid affine point");if(y instanceof d)throw new Error("projective point not allowed");let b=E=>e.eql(E,e.ZERO);return b(g)&&b(x)?d.ZERO:new d(g,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let g=e.invertBatch(y.map(x=>x.pz));return y.map((x,b)=>x.toAffine(g[b])).map(d.fromAffine)}static fromHex(y){let g=d.fromAffine(i(xt("pointHex",y)));return g.assertValidity(),g}static fromPrivateKey(y){return d.BASE.multiply(c(y))}static msm(y,g){return Ls(d,n,y,g)}_setWindowSize(y){m.setWindowSize(this,y)}assertValidity(){f(this)}hasEvenY(){let{y}=this.toAffine();if(e.isOdd)return!e.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){l(y);let{px:g,py:x,pz:b}=this,{px:E,py:I,pz:B}=y,S=e.eql(e.mul(g,B),e.mul(E,b)),v=e.eql(e.mul(x,B),e.mul(I,b));return S&&v}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:y,b:g}=t,x=e.mul(g,Fm),{px:b,py:E,pz:I}=this,B=e.ZERO,S=e.ZERO,v=e.ZERO,k=e.mul(b,b),z=e.mul(E,E),F=e.mul(I,I),U=e.mul(b,E);return U=e.add(U,U),v=e.mul(b,I),v=e.add(v,v),B=e.mul(y,v),S=e.mul(x,F),S=e.add(B,S),B=e.sub(z,S),S=e.add(z,S),S=e.mul(B,S),B=e.mul(U,B),v=e.mul(x,v),F=e.mul(y,F),U=e.sub(k,F),U=e.mul(y,U),U=e.add(U,v),v=e.add(k,k),k=e.add(v,k),k=e.add(k,F),k=e.mul(k,U),S=e.add(S,k),F=e.mul(E,I),F=e.add(F,F),k=e.mul(F,U),B=e.sub(B,k),v=e.mul(F,z),v=e.add(v,v),v=e.add(v,v),new d(B,S,v)}add(y){l(y);let{px:g,py:x,pz:b}=this,{px:E,py:I,pz:B}=y,S=e.ZERO,v=e.ZERO,k=e.ZERO,z=t.a,F=e.mul(t.b,Fm),U=e.mul(g,E),D=e.mul(x,I),R=e.mul(b,B),N=e.add(g,x),A=e.add(E,I);N=e.mul(N,A),A=e.add(U,D),N=e.sub(N,A),A=e.add(g,b);let _=e.add(E,B);return A=e.mul(A,_),_=e.add(U,R),A=e.sub(A,_),_=e.add(x,b),S=e.add(I,B),_=e.mul(_,S),S=e.add(D,R),_=e.sub(_,S),k=e.mul(z,A),S=e.mul(F,R),k=e.add(S,k),S=e.sub(D,k),k=e.add(D,k),v=e.mul(S,k),D=e.add(U,U),D=e.add(D,U),R=e.mul(z,R),A=e.mul(F,A),D=e.add(D,R),R=e.sub(U,R),R=e.mul(z,R),A=e.add(A,R),U=e.mul(D,A),v=e.add(v,U),U=e.mul(_,A),S=e.mul(N,S),S=e.sub(S,U),U=e.mul(N,D),k=e.mul(_,k),k=e.add(k,U),new d(S,v,k)}subtract(y){return this.add(y.negate())}is0(){return this.equals(d.ZERO)}wNAF(y){return m.wNAFCached(this,y,d.normalizeZ)}multiplyUnsafe(y){ue("scalar",y,Ar,t.n);let g=d.ZERO;if(y===Ar)return g;if(y===Pt)return this;let{endo:x}=t;if(!x)return m.unsafeLadder(this,y);let{k1neg:b,k1:E,k2neg:I,k2:B}=x.splitScalar(y),S=g,v=g,k=this;for(;E>Ar||B>Ar;)E&Pt&&(S=S.add(k)),B&Pt&&(v=v.add(k)),k=k.double(),E>>=Pt,B>>=Pt;return b&&(S=S.negate()),I&&(v=v.negate()),v=new d(e.mul(v.px,x.beta),v.py,v.pz),S.add(v)}multiply(y){let{endo:g,n:x}=t;ue("scalar",y,Pt,x);let b,E;if(g){let{k1neg:I,k1:B,k2neg:S,k2:v}=g.splitScalar(y),{p:k,f:z}=this.wNAF(B),{p:F,f:U}=this.wNAF(v);k=m.constTimeNegate(I,k),F=m.constTimeNegate(S,F),F=new d(e.mul(F.px,g.beta),F.py,F.pz),b=k.add(F),E=z.add(U)}else{let{p:I,f:B}=this.wNAF(y);b=I,E=B}return d.normalizeZ([b,E])[0]}multiplyAndAddUnsafe(y,g,x){let b=d.BASE,E=(B,S)=>S===Ar||S===Pt||!B.equals(b)?B.multiplyUnsafe(S):B.multiply(S),I=E(this,g).add(E(y,x));return I.is0()?void 0:I}toAffine(y){return u(this,y)}isTorsionFree(){let{h:y,isTorsionFree:g}=t;if(y===Pt)return!0;if(g)return g(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:g}=t;return y===Pt?this:g?g(d,this):this.multiplyUnsafe(t.h)}toRawBytes(y=!0){return Oe("isCompressed",y),this.assertValidity(),o(d,this,y)}toHex(y=!0){return Oe("isCompressed",y),mr(this.toRawBytes(y))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let h=t.nBitLength,m=Ps(d,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function av(r){let t=li(r);return Je(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Mm(r){let t=av(r),{Fp:e,n}=t,o=e.BYTES+1,i=2*e.BYTES+1;function s(R){return ct(R,n)}function a(R){return Ns(R,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=sv({...t,toBytes(R,N,A){let _=N.toAffine(),C=e.toBytes(_.x),V=yr;return Oe("isCompressed",A),A?V(Uint8Array.from([N.hasEvenY()?2:3]),C):V(Uint8Array.from([4]),C,e.toBytes(_.y))},fromBytes(R){let N=R.length,A=R[0],_=R.subarray(1);if(N===o&&(A===2||A===3)){let C=gr(_);if(!ai(C,Pt,e.ORDER))throw new Error("Point is not on curve");let V=u(C),q;try{q=e.sqrt(V)}catch(et){let Q=et instanceof Error?": "+et.message:"";throw new Error("Point is not on curve"+Q)}let K=(q&Pt)===Pt;return(A&1)===1!==K&&(q=e.neg(q)),{x:C,y:q}}else if(N===i&&A===4){let C=e.fromBytes(_.subarray(0,e.BYTES)),V=e.fromBytes(_.subarray(e.BYTES,2*e.BYTES));return{x:C,y:V}}else throw new Error(`Point of length ${N} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),d=R=>mr(Yr(R,t.nByteLength));function h(R){let N=n>>Pt;return R>N}function m(R){return h(R)?s(-R):R}let p=(R,N,A)=>gr(R.slice(N,A));class y{constructor(N,A,_){this.r=N,this.s=A,this.recovery=_,this.assertValidity()}static fromCompact(N){let A=t.nByteLength;return N=xt("compactSignature",N,A*2),new y(p(N,0,A),p(N,A,2*A))}static fromDER(N){let{r:A,s:_}=_r.toSig(xt("DER",N));return new y(A,_)}assertValidity(){ue("r",this.r,Pt,n),ue("s",this.s,Pt,n)}addRecoveryBit(N){return new y(this.r,this.s,N)}recoverPublicKey(N){let{r:A,s:_,recovery:C}=this,V=B(xt("msgHash",N));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");let q=C===2||C===3?A+t.n:A;if(q>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let K=C&1?"03":"02",J=c.fromHex(K+d(q)),et=a(q),Q=s(-V*et),at=s(_*et),ft=c.BASE.multiplyAndAddUnsafe(J,Q,at);if(!ft)throw new Error("point at infinify");return ft.assertValidity(),ft}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return _n(this.toDERHex())}toDERHex(){return _r.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return _n(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let g={isValidPrivateKey(R){try{return l(R),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let R=Qu(t.n);return Rp(t.randomBytes(R),t.n)},precompute(R=8,N=c.BASE){return N._setWindowSize(R),N.multiply(BigInt(3)),N}};function x(R,N=!0){return c.fromPrivateKey(R).toRawBytes(N)}function b(R){let N=Wr(R),A=typeof R=="string",_=(N||A)&&R.length;return N?_===o||_===i:A?_===2*o||_===2*i:R instanceof c}function E(R,N,A=!0){if(b(R))throw new Error("first arg must be private key");if(!b(N))throw new Error("second arg must be public key");return c.fromHex(N).multiply(l(R)).toRawBytes(A)}let I=t.bits2int||function(R){let N=gr(R),A=R.length*8-t.nBitLength;return A>0?N>>BigInt(A):N},B=t.bits2int_modN||function(R){return s(I(R))},S=ci(t.nBitLength);function v(R){return ue(`num < 2^${t.nBitLength}`,R,Ar,S),Yr(R,t.nByteLength)}function k(R,N,A=z){if(["recovered","canonical"].some(Nt=>Nt in A))throw new Error("sign() legacy options not supported");let{hash:_,randomBytes:C}=t,{lowS:V,prehash:q,extraEntropy:K}=A;V==null&&(V=!0),R=xt("msgHash",R),Um(A),q&&(R=xt("prehashed msgHash",_(R)));let J=B(R),et=l(N),Q=[v(et),v(J)];if(K!=null&&K!==!1){let Nt=K===!0?C(e.BYTES):K;Q.push(xt("extraEntropy",Nt))}let at=yr(...Q),ft=J;function Rt(Nt){let Ot=I(Nt);if(!f(Ot))return;let Xt=a(Ot),It=c.BASE.multiply(Ot).toAffine(),ee=s(It.x);if(ee===Ar)return;let ur=s(Xt*s(ft+ee*et));if(ur===Ar)return;let Yo=(It.x===ee?0:2)|Number(It.y&Pt),Xo=ur;return V&&h(ur)&&(Xo=m(ur),Yo^=1),new y(ee,Xo,Yo)}return{seed:at,k2sig:Rt}}let z={lowS:t.lowS,prehash:!1},F={lowS:t.lowS,prehash:!1};function U(R,N,A=z){let{seed:_,k2sig:C}=k(R,N,A),V=t;return Yu(V.hash.outputLen,V.nByteLength,V.hmac)(_,C)}c.BASE._setWindowSize(8);function D(R,N,A,_=F){let C=R;if(N=xt("msgHash",N),A=xt("publicKey",A),"strict"in _)throw new Error("options.strict was renamed to lowS");Um(_);let{lowS:V,prehash:q}=_,K,J;try{if(typeof C=="string"||Wr(C))try{K=y.fromDER(C)}catch(It){if(!(It instanceof _r.Err))throw It;K=y.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){let{r:It,s:ee}=C;K=new y(It,ee)}else throw new Error("PARSE");J=c.fromHex(A)}catch(It){if(It.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(V&&K.hasHighS())return!1;q&&(N=t.hash(N));let{r:et,s:Q}=K,at=B(N),ft=a(Q),Rt=s(at*ft),Nt=s(et*ft),Ot=c.BASE.multiplyAndAddUnsafe(J,Rt,Nt)?.toAffine();return Ot?s(Ot.x)===et:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:E,sign:U,verify:D,ProjectivePoint:c,Signature:y,utils:g}}function cv(r){return{hash:r,hmac:(t,...e)=>wf(r,t,Hu(...e)),randomBytes:Ts}}function Vm(r,t){let e=n=>Mm({...r,...cv(n)});return Object.freeze({...e(t),create:e})}var zm=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Hm=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),lv=BigInt(1),bf=BigInt(2),$m=(r,t)=>(r+t/bf)/t;function uv(r){let t=zm,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=pt(u,e,t)*u%t,d=pt(f,e,t)*u%t,h=pt(d,bf,t)*l%t,m=pt(h,o,t)*h%t,p=pt(m,i,t)*m%t,y=pt(p,a,t)*p%t,g=pt(y,c,t)*y%t,x=pt(g,a,t)*p%t,b=pt(x,e,t)*u%t,E=pt(b,s,t)*m%t,I=pt(E,n,t)*l%t,B=pt(I,bf,t);if(!xf.eql(xf.sqr(B),r))throw new Error("Cannot find square root");return B}var xf=Xr(zm,void 0,void 0,{sqrt:uv}),Bn=Vm({a:BigInt(0),b:BigInt(7),Fp:xf,n:Hm,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Hm,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-lv*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=$m(i*r,t),c=$m(-n*r,t),l=ct(r-a*e-c*o,t),u=ct(-a*n-c*i,t),f=l>s,d=u>s;if(f&&(l=t-l),d&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},uo),YB=BigInt(0);var XB=Bn.ProjectivePoint;function qm(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Km(r,t,e){let n=Ze.digest(e instanceof Uint8Array?e:e.subarray());if(qm(n))return n.then(({digest:o})=>Bn.verify(t,o,r)).catch(o=>{throw new wi(String(o))});try{return Bn.verify(t,n.digest,r)}catch(o){throw new wi(String(o))}}var Ca=class{type="secp256k1";raw;_key;constructor(t){this._key=Wm(t),this.raw=Gm(this._key)}toMultihash(){return bt.digest(lo(this))}toCID(){return P.createV1(114,this.toMultihash())}toString(){return X.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Y(this.raw,t.raw)}verify(t,e){return Km(this._key,e,t)}};function Ef(r){return new Ca(r)}function Gm(r){return Bn.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Wm(r){try{return Bn.ProjectivePoint.fromHex(r),r}catch(t){throw new Wn(String(t))}}function Ra(r){let{Type:t,Data:e}=Qe.decode(r),n=e??new Uint8Array;switch(t){case Bt.RSA:return yf(n);case Bt.Ed25519:return of(n);case Bt.secp256k1:return Ef(n);default:throw new pn}}function rn(r){let{Type:t,Data:e}=Qe.decode(r.digest),n=e??new Uint8Array;switch(t){case Bt.Ed25519:return of(n);case Bt.secp256k1:return Ef(n);default:throw new pn}}function lo(r){return Qe.encode({Type:Bt[r.type],Data:r.raw})}var jm=Symbol.for("nodejs.util.inspect.custom"),fv=114,Ei=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Gn]=!0;toString(){return this.string==null&&(this.string=X.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return P.createV1(fv,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Y(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Y(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[jm](){return`PeerId(${this.toString()})`}},Na=class extends Ei{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Pa=class extends Ei{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},La=class extends Ei{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},hv=2336,vi=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=bt.digest(L(this.url))}[jm](){return`PeerId(${this.url})`}[Gn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return P.createV1(hv,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=G(t)),t.toString()===this.toString())}};var dv=114,Ym=2336;function wo(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=wt(X.decode(`z${r}`));else{if(t==null)throw new St('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=wt(t.decode(r))}return Xm(e)}function Xm(r){if(mv(r))return new Na({multihash:r});if(pv(r))try{let t=rn(r);if(t.type==="Ed25519")return new Pa({multihash:r,publicKey:t});if(t.type==="secp256k1")return new La({multihash:r,publicKey:t})}catch{let e=G(r.digest);return new vi(new URL(e))}throw new _e("Supplied PeerID Multihash is invalid")}function bo(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==dv&&r.code!==Ym)throw new Qo("Supplied PeerID CID is invalid");if(r.code===Ym){let t=G(r.multihash.digest);return new vi(new URL(t))}return Xm(r.multihash)}function pv(r){return r.code===bt.code}function mv(r){return r.code===Ze.code}var Sf={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Qm={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},tg=new globalThis.TextEncoder;function gv(r,t){let e=Sf[t],n=Qm[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function yv(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Sf[t],o=Qm[t],i=r;for(;i.length>0;){let s=tg.encodeInto(i,e);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function _f(r,{size:t=32,utf8Buffer:e}={}){if(!Sf[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return yv(r,t,e);r=tg.encode(r)}return gv(r,t)}function wv(r,t){try{if(typeof r=="string"&&r.length>0)return bv(r);if(typeof r=="number"&&isFinite(r))return t?.long?Ev(r):xv(r);throw new Error("Value is not a string or number.")}catch(e){let n=vv(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function bv(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Ua=wv;function xv(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Ev(r){let t=Math.abs(r);return t>=864e5?Oa(r,t,864e5,"day"):t>=36e5?Oa(r,t,36e5,"hour"):t>=6e4?Oa(r,t,6e4,"minute"):t>=1e3?Oa(r,t,1e3,"second"):`${r} ms`}function Oa(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function vv(r){return typeof r=="object"&&r!==null&&"message"in r}function Af(r){e.debug=e,e.default=e,e.coerce=c,e.disable=i,e.enable=o,e.enabled=s,e.humanize=Ua,e.destroy=l,Object.keys(r).forEach(u=>{e[u]=r[u]}),e.names=[],e.skips=[],e.formatters={};function t(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(u){let f,d=null,h,m;function p(...y){if(!p.enabled)return;let g=p,x=Number(new Date),b=x-(f||x);g.diff=b,g.prev=f,g.curr=x,f=x,y[0]=e.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let E=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(B,S)=>{if(B==="%%")return"%";E++;let v=e.formatters[S];if(typeof v=="function"){let k=y[E];B=v.call(g,k),y.splice(E,1),E--}return B}),e.formatArgs.call(g,y),(g.log||e.log).apply(g,y)}return p.namespace=u,p.useColors=e.useColors(),p.color=e.selectColor(u),p.extend=n,p.destroy=e.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,m=e.enabled(u)),m),set:y=>{d=y}}),typeof e.init=="function"&&e.init(p),p}function n(u,f){let d=e(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){e.save(u),e.namespaces=u,e.names=[],e.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?e.skips.push(new RegExp("^"+u.substr(1)+"$")):e.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(u))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.setupFormatters(e.formatters),e.enable(e.load()),e}var Fa=Bv(),Sv=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function _v(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Av(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ua(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var Iv=console.debug??console.log??(()=>{});function kv(r){try{r?Fa?.setItem("debug",r):Fa?.removeItem("debug")}catch{}}function Tv(){let r;try{r=Fa?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Bv(){try{return localStorage}catch{}}function Cv(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var eg=Af({formatArgs:Av,save:kv,load:Tv,useColors:_v,setupFormatters:Cv,colors:Sv,storage:Fa,log:Iv});var W=eg;W.formatters.b=r=>r==null?"undefined":X.baseEncode(r);W.formatters.t=r=>r==null?"undefined":vt.baseEncode(r);W.formatters.m=r=>r==null?"undefined":se.baseEncode(r);W.formatters.p=r=>r==null?"undefined":r.toString();W.formatters.c=r=>r==null?"undefined":r.toString();W.formatters.k=r=>r==null?"undefined":r.toString();W.formatters.a=r=>r==null?"undefined":r.toString();W.formatters.e=r=>r==null?"undefined":rg(r.stack)??rg(r.message)??r.toString();function Rv(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function ng(){return{forComponent(r){return Nv(r)}}}function Nv(r){let t=Rv(`${r}:trace`);return W.enabled(`${r}:trace`)&&W.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=W(`${r}:trace`)),Object.assign(W(r),{error:W(`${r}:error`),trace:t})}function rg(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var kf=Ut(ig(),1);var Ai=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Tf=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},sg=r=>globalThis.DOMException===void 0?new Tf(r):new DOMException(r),ag=r=>{let t=r.reason===void 0?sg("This operation was aborted."):r.reason;return t instanceof Error?t:sg(t)};function Ii(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=t,s,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&u(ag(d));let h=()=>{u(ag(d))};d.addEventListener("abort",h,{once:!0}),r.finally(()=>{d.removeEventListener("abort",h)})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Ai;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){u(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(d){u(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function Bf(r,t,e){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;e(r[s],t)<=0?(n=++s,o-=i+1):o=i}return n}var ki=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,run:t};if(this.size&&this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=Bf(this.#t,n,(i,s)=>s.priority-i.priority);this.#t.splice(o,0,n)}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var de=class extends kf.default{#t;#r;#o=0;#c;#g;#S=0;#i;#y;#n;#s;#e=0;#h;#l;#d;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ki,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#r=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#c=t.intervalCap,this.#g=t.interval,this.#n=new t.queueClass,this.#s=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#d=t.throwOnTimeout===!0,this.#l=t.autoStart===!1}get#u(){return this.#r||this.#o<this.#c}get#b(){return this.#e<this.#h}#f(){this.#e--,this.#m(),this.emit("next")}#x(){this.#_(),this.#w(),this.#y=void 0}get#E(){let t=Date.now();if(this.#i===void 0){let e=this.#S-t;if(e<0)this.#o=this.#t?this.#e:0;else return this.#y===void 0&&(this.#y=setTimeout(()=>{this.#x()},e)),!0}return!1}#m(){if(this.#n.size===0)return this.#i&&clearInterval(this.#i),this.#i=void 0,this.emit("empty"),this.#e===0&&this.emit("idle"),!1;if(!this.#l){let t=!this.#E;if(this.#u&&this.#b){let e=this.#n.dequeue();return e?(this.emit("active"),e(),t&&this.#w(),!0):!1}}return!1}#w(){this.#r||this.#i!==void 0||(this.#i=setInterval(()=>{this.#_()},this.#g),this.#S=Date.now()+this.#g)}#_(){this.#o===0&&this.#e===0&&this.#i&&(clearInterval(this.#i),this.#i=void 0),this.#o=this.#t?this.#e:0,this.#p()}#p(){for(;this.#m(););}get concurrency(){return this.#h}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#h=t,this.#p()}async#C(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}async add(t,e={}){return e={timeout:this.timeout,throwOnTimeout:this.#d,...e},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#e++,this.#o++;try{e.signal?.throwIfAborted();let i=t({signal:e.signal});e.timeout&&(i=Ii(Promise.resolve(i),{milliseconds:e.timeout})),e.signal&&(i=Promise.race([i,this.#C(e.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof Ai&&!e.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#f()}},e),this.emit("add"),this.#m()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#l?(this.#l=!1,this.#p(),this):this}pause(){this.#l=!0}clear(){this.#n=new this.#s}async onEmpty(){this.#n.size!==0&&await this.#A("empty")}async onSizeLessThan(t){this.#n.size<t||await this.#A("next",()=>this.#n.size<t)}async onIdle(){this.#e===0&&this.#n.size===0||await this.#A("idle")}async#A(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#n.size}sizeBy(t){return this.#n.filter(t).length}get pending(){return this.#e}get isPaused(){return this.#l}};function Va(r){let t=[pe.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Cf=60;function Ha(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(t=>({name:t.name,type:pe[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:pe[t.type],TTL:t.TTL??t.ttl??Cf,data:t.data instanceof Uint8Array?G(t.data):t.data}))}}var Dv=4;function Rf(r,t={}){let e=new de({concurrency:t.queryConcurrency??Dv});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),Va(o.types).forEach(a=>{i.append("type",pe[a])}),o.onProgress?.(new H("dns:query",{detail:n}));let s=await e.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Ha(await a.json());return o.onProgress?.(new H("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function cg(){return[Rf("https://cloudflare-dns.com/dns-query"),Rf("https://dns.google/resolve")]}var ug=Ut(Nf(),1);var Pf=class{lru;constructor(t){this.lru=(0,ug.default)(t)}get(t,e){let n=!0,o=[];for(let i of e){let s=this.getAnswers(t,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return Ha({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,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:pe[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Cf)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function fg(r){return new Pf(r)}var Ov=1e3,$a=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=fg(t.cacheSize??Ov),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=cg())}async query(t,e={}){let n=Va(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new H("dns:cache",{detail:o})),o;let i=`${t.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(e.signal?.aborted===!0)break;try{let l=await c(t,{...e,types:n});for(let u of l.Answer)this.cache.add(t,u);return l}catch(l){a.push(l),e.onProgress?.(new H("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var pe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(pe||(pe={}));function Ti(r={}){return new $a(r)}var za=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var qa=class{deferred;signal;constructor(t){this.signal=t,this.deferred=ht(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ne)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Uv(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ka=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=Uv(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,mt(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ne),this.cleanup())}async join(t={}){let e=new qa(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Vd(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Ir=class extends jn{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new za;let n=new Ka(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Ne)}),this.clear()}async onEmpty(t){this.size!==0&&await ys(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await ys(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await ys(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=je({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new Ne("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var Fv=["string","number","bigint","symbol"],Mv=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function hg(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let t=typeof r;if(Fv.includes(t))return t;if(t==="function")return"Function";if(Array.isArray(r))return"Array";if(Vv(r))return"Buffer";let e=Hv(r);return e||"Object"}function Vv(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Hv(r){let t=Object.prototype.toString.call(r).slice(8,-1);if(Mv.includes(t))return t}var w=class{constructor(t,e,n){this.major=t,this.majorEncoded=t<<5,this.name=e,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(7,"break",!0);var T=class{constructor(t,e,n){this.type=t,this.value=e,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var xo=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",$v=new TextDecoder,zv=new TextEncoder;function Ga(r){return xo&&globalThis.Buffer.isBuffer(r)}function Bi(r){return r instanceof Uint8Array?Ga(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var gg=xo?(r,t,e)=>e-t>64?globalThis.Buffer.from(r.subarray(t,e)).toString("utf8"):pg(r,t,e):(r,t,e)=>e-t>64?$v.decode(r.subarray(t,e)):pg(r,t,e),Wa=xo?r=>r.length>64?globalThis.Buffer.from(r):dg(r):r=>r.length>64?zv.encode(r):dg(r),nr=r=>Uint8Array.from(r),Eo=xo?(r,t,e)=>Ga(r)?new Uint8Array(r.subarray(t,e)):r.slice(t,e):(r,t,e)=>r.slice(t,e),yg=xo?(r,t)=>(r=r.map(e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e)),Bi(globalThis.Buffer.concat(r,t))):(r,t)=>{let e=new Uint8Array(t),n=0;for(let o of r)n+o.length>e.length&&(o=o.subarray(0,e.length-n)),e.set(o,n),n+=o.length;return e},wg=xo?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function bg(r,t){if(Ga(r)&&Ga(t))return r.compare(t);for(let e=0;e<r.length;e++)if(r[e]!==t[e])return r[e]<t[e]?-1:1;return 0}function dg(r){let t=[],e=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=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),t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128)}return t}function pg(r,t,e){let n=[];for(;t<e;){let o=r[t],i=null,s=o>239?4:o>223?3:o>191?2:1;if(t+s<=e){let a,c,l,u;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[t+1],(a&192)===128&&(u=(o&31)<<6|a&63,u>127&&(i=u));break;case 3:a=r[t+1],c=r[t+2],(a&192)===128&&(c&192)===128&&(u=(o&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:a=r[t+1],c=r[t+2],l=r[t+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(i=u))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),t+=s}return Lf(n)}var mg=4096;function Lf(r){let t=r.length;if(t<=mg)return String.fromCharCode.apply(String,r);let e="",n=0;for(;n<t;)e+=String.fromCharCode.apply(String,r.slice(n,n+=mg));return e}var qv=256,Ci=class{constructor(t=qv){this.chunkSize=t,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(t){let e=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let o=e.length-(this.maxCursor-this.cursor)-1;e.set(t,o)}else{if(e){let o=e.length-(this.maxCursor-this.cursor)-1;o<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,o),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(e=wg(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let e;if(this.chunks.length===1){let n=this.chunks[0];t&&this.cursor>n.length/2?(e=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=Eo(n,0,this.cursor)}else e=yg(this.chunks,this.cursor);return t&&this.reset(),e}};var $="CBOR decode error:",kr="CBOR encode error:",Ri=[];Ri[23]=1;Ri[24]=2;Ri[25]=3;Ri[26]=5;Ri[27]=9;function Tr(r,t,e){if(r.length-t<e)throw new Error(`${$} not enough data for type`)}var Lt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function we(r,t,e){Tr(r,t,1);let n=r[t];if(e.strict===!0&&n<Lt[0])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);return n}function be(r,t,e){Tr(r,t,2);let n=r[t]<<8|r[t+1];if(e.strict===!0&&n<Lt[1])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);return n}function xe(r,t,e){Tr(r,t,4);let n=r[t]*16777216+(r[t+1]<<16)+(r[t+2]<<8)+r[t+3];if(e.strict===!0&&n<Lt[2])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);return n}function Ee(r,t,e){Tr(r,t,8);let n=r[t]*16777216+(r[t+1]<<16)+(r[t+2]<<8)+r[t+3],o=r[t+4]*16777216+(r[t+5]<<16)+(r[t+6]<<8)+r[t+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(e.strict===!0&&i<Lt[3])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(e.allowBigInt===!0)return i;throw new Error(`${$} integers outside of the safe integer range are not supported`)}function xg(r,t,e,n){return new T(w.uint,we(r,t+1,n),2)}function Eg(r,t,e,n){return new T(w.uint,be(r,t+1,n),3)}function vg(r,t,e,n){return new T(w.uint,xe(r,t+1,n),5)}function Sg(r,t,e,n){return new T(w.uint,Ee(r,t+1,n),9)}function ke(r,t){return Vt(r,0,t.value)}function Vt(r,t,e){if(e<Lt[0]){let n=Number(e);r.push([t|n])}else if(e<Lt[1]){let n=Number(e);r.push([t|24,n])}else if(e<Lt[2]){let n=Number(e);r.push([t|25,n>>>8,n&255])}else if(e<Lt[3]){let n=Number(e);r.push([t|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(e);if(n<Lt[4]){let o=[t|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(`${$} encountered BigInt larger than allowable range`)}}ke.encodedSize=function(t){return Vt.encodedSize(t.value)};Vt.encodedSize=function(t){return t<Lt[0]?1:t<Lt[1]?2:t<Lt[2]?3:t<Lt[3]?5:9};ke.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};function _g(r,t,e,n){return new T(w.negint,-1-we(r,t+1,n),2)}function Ag(r,t,e,n){return new T(w.negint,-1-be(r,t+1,n),3)}function Ig(r,t,e,n){return new T(w.negint,-1-xe(r,t+1,n),5)}var Df=BigInt(-1),kg=BigInt(1);function Tg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new T(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${$} integers outside of the safe integer range are not supported`);return new T(w.negint,Df-BigInt(o),9)}function ja(r,t){let e=t.value,n=typeof e=="bigint"?e*Df-kg:e*-1-1;Vt(r,t.type.majorEncoded,n)}ja.encodedSize=function(t){let e=t.value,n=typeof e=="bigint"?e*Df-kg:e*-1-1;return n<Lt[0]?1:n<Lt[1]?2:n<Lt[2]?3:n<Lt[3]?5:9};ja.compareTokens=function(t,e){return t.value<e.value?1:t.value>e.value?-1:0};function Ni(r,t,e,n){Tr(r,t,e+n);let o=Eo(r,t+e,t+e+n);return new T(w.bytes,o,e+n)}function Bg(r,t,e,n){return Ni(r,t,1,e)}function Cg(r,t,e,n){return Ni(r,t,2,we(r,t+1,n))}function Rg(r,t,e,n){return Ni(r,t,3,be(r,t+1,n))}function Ng(r,t,e,n){return Ni(r,t,5,xe(r,t+1,n))}function Pg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer bytes lengths not supported`);return Ni(r,t,9,o)}function Ya(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===w.string?Wa(r.value):r.value),r.encodedBytes}function vo(r,t){let e=Ya(t);Vt(r,t.type.majorEncoded,e.length),r.push(e)}vo.encodedSize=function(t){let e=Ya(t);return Vt.encodedSize(e.length)+e.length};vo.compareTokens=function(t,e){return Gv(Ya(t),Ya(e))};function Gv(r,t){return r.length<t.length?-1:r.length>t.length?1:bg(r,t)}function Pi(r,t,e,n,o){let i=e+n;Tr(r,t,i);let s=new T(w.string,gg(r,t+e,t+i),i);return o.retainStringBytes===!0&&(s.byteValue=Eo(r,t+e,t+i)),s}function Lg(r,t,e,n){return Pi(r,t,1,e,n)}function Dg(r,t,e,n){return Pi(r,t,2,we(r,t+1,n),n)}function Og(r,t,e,n){return Pi(r,t,3,be(r,t+1,n),n)}function Ug(r,t,e,n){return Pi(r,t,5,xe(r,t+1,n),n)}function Fg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer string lengths not supported`);return Pi(r,t,9,o,n)}var Mg=vo;function So(r,t,e,n){return new T(w.array,n,e)}function Vg(r,t,e,n){return So(r,t,1,e)}function Hg(r,t,e,n){return So(r,t,2,we(r,t+1,n))}function $g(r,t,e,n){return So(r,t,3,be(r,t+1,n))}function zg(r,t,e,n){return So(r,t,5,xe(r,t+1,n))}function qg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer array lengths not supported`);return So(r,t,9,o)}function Kg(r,t,e,n){if(n.allowIndefinite===!1)throw new Error(`${$} indefinite length items not allowed`);return So(r,t,1,1/0)}function Xa(r,t){Vt(r,w.array.majorEncoded,t.value)}Xa.compareTokens=ke.compareTokens;Xa.encodedSize=function(t){return Vt.encodedSize(t.value)};function _o(r,t,e,n){return new T(w.map,n,e)}function Gg(r,t,e,n){return _o(r,t,1,e)}function Wg(r,t,e,n){return _o(r,t,2,we(r,t+1,n))}function jg(r,t,e,n){return _o(r,t,3,be(r,t+1,n))}function Yg(r,t,e,n){return _o(r,t,5,xe(r,t+1,n))}function Xg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer map lengths not supported`);return _o(r,t,9,o)}function Zg(r,t,e,n){if(n.allowIndefinite===!1)throw new Error(`${$} indefinite length items not allowed`);return _o(r,t,1,1/0)}function Za(r,t){Vt(r,w.map.majorEncoded,t.value)}Za.compareTokens=ke.compareTokens;Za.encodedSize=function(t){return Vt.encodedSize(t.value)};function Jg(r,t,e,n){return new T(w.tag,e,1)}function Qg(r,t,e,n){return new T(w.tag,we(r,t+1,n),2)}function t0(r,t,e,n){return new T(w.tag,be(r,t+1,n),3)}function e0(r,t,e,n){return new T(w.tag,xe(r,t+1,n),5)}function r0(r,t,e,n){return new T(w.tag,Ee(r,t+1,n),9)}function Ja(r,t){Vt(r,w.tag.majorEncoded,t.value)}Ja.compareTokens=ke.compareTokens;Ja.encodedSize=function(t){return Vt.encodedSize(t.value)};var Jv=20,Qv=21,t2=22,e2=23;function n0(r,t,e,n){if(n.allowUndefined===!1)throw new Error(`${$} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new T(w.null,null,1):new T(w.undefined,void 0,1)}function o0(r,t,e,n){if(n.allowIndefinite===!1)throw new Error(`${$} indefinite length items not allowed`);return new T(w.break,void 0,1)}function Of(r,t,e){if(e){if(e.allowNaN===!1&&Number.isNaN(r))throw new Error(`${$} NaN values are not supported`);if(e.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${$} Infinity values are not supported`)}return new T(w.float,r,t)}function i0(r,t,e,n){return Of(Uf(r,t+1),3,n)}function s0(r,t,e,n){return Of(Ff(r,t+1),5,n)}function a0(r,t,e,n){return Of(f0(r,t+1),9,n)}function Qa(r,t,e){let n=t.value;if(n===!1)r.push([w.float.majorEncoded|Jv]);else if(n===!0)r.push([w.float.majorEncoded|Qv]);else if(n===null)r.push([w.float.majorEncoded|t2]);else if(n===void 0)r.push([w.float.majorEncoded|e2]);else{let o,i=!1;(!e||e.float64!==!0)&&(l0(n),o=Uf(Me,1),n===o||Number.isNaN(n)?(Me[0]=249,r.push(Me.slice(0,3)),i=!0):(u0(n),o=Ff(Me,1),n===o&&(Me[0]=250,r.push(Me.slice(0,5)),i=!0))),i||(r2(n),o=f0(Me,1),Me[0]=251,r.push(Me.slice(0,9)))}}Qa.encodedSize=function(t,e){let n=t.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!e||e.float64!==!0){l0(n);let o=Uf(Me,1);if(n===o||Number.isNaN(n))return 3;if(u0(n),o=Ff(Me,1),n===o)return 5}return 9};var c0=new ArrayBuffer(9),Te=new DataView(c0,1),Me=new Uint8Array(c0,0);function l0(r){if(r===1/0)Te.setUint16(0,31744,!1);else if(r===-1/0)Te.setUint16(0,64512,!1);else if(Number.isNaN(r))Te.setUint16(0,32256,!1);else{Te.setFloat32(0,r);let t=Te.getUint32(0),e=(t&2139095040)>>23,n=t&8388607;if(e===255)Te.setUint16(0,31744,!1);else if(e===0)Te.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=e-127;o<-24?Te.setUint16(0,0):o<-14?Te.setUint16(0,(t&2147483648)>>16|1<<24+o,!1):Te.setUint16(0,(t&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Uf(r,t){if(r.length-t<2)throw new Error(`${$} not enough data for float16`);let e=(r[t]<<8)+r[t+1];if(e===31744)return 1/0;if(e===64512)return-1/0;if(e===32256)return NaN;let n=e>>10&31,o=e&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,e&32768?-i:i}function u0(r){Te.setFloat32(0,r,!1)}function Ff(r,t){if(r.length-t<4)throw new Error(`${$} not enough data for float32`);let e=(r.byteOffset||0)+t;return new DataView(r.buffer,e,4).getFloat32(0,!1)}function r2(r){Te.setFloat64(0,r,!1)}function f0(r,t){if(r.length-t<8)throw new Error(`${$} not enough data for float64`);let e=(r.byteOffset||0)+t;return new DataView(r.buffer,e,8).getFloat64(0,!1)}Qa.compareTokens=ke.compareTokens;function ot(r,t,e){throw new Error(`${$} encountered invalid minor (${e}) for major ${r[t]>>>5}`)}function tc(r){return()=>{throw new Error(`${$} ${r}`)}}var O=[];for(let r=0;r<=23;r++)O[r]=ot;O[24]=xg;O[25]=Eg;O[26]=vg;O[27]=Sg;O[28]=ot;O[29]=ot;O[30]=ot;O[31]=ot;for(let r=32;r<=55;r++)O[r]=ot;O[56]=_g;O[57]=Ag;O[58]=Ig;O[59]=Tg;O[60]=ot;O[61]=ot;O[62]=ot;O[63]=ot;for(let r=64;r<=87;r++)O[r]=Bg;O[88]=Cg;O[89]=Rg;O[90]=Ng;O[91]=Pg;O[92]=ot;O[93]=ot;O[94]=ot;O[95]=tc("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)O[r]=Lg;O[120]=Dg;O[121]=Og;O[122]=Ug;O[123]=Fg;O[124]=ot;O[125]=ot;O[126]=ot;O[127]=tc("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)O[r]=Vg;O[152]=Hg;O[153]=$g;O[154]=zg;O[155]=qg;O[156]=ot;O[157]=ot;O[158]=ot;O[159]=Kg;for(let r=160;r<=183;r++)O[r]=Gg;O[184]=Wg;O[185]=jg;O[186]=Yg;O[187]=Xg;O[188]=ot;O[189]=ot;O[190]=ot;O[191]=Zg;for(let r=192;r<=215;r++)O[r]=Jg;O[216]=Qg;O[217]=t0;O[218]=e0;O[219]=r0;O[220]=ot;O[221]=ot;O[222]=ot;O[223]=ot;for(let r=224;r<=243;r++)O[r]=tc("simple values are not supported");O[244]=ot;O[245]=ot;O[246]=ot;O[247]=n0;O[248]=tc("simple values are not supported");O[249]=i0;O[250]=s0;O[251]=a0;O[252]=ot;O[253]=ot;O[254]=ot;O[255]=o0;var Ve=[];for(let r=0;r<24;r++)Ve[r]=new T(w.uint,r,1);for(let r=-1;r>=-24;r--)Ve[31-r]=new T(w.negint,r,1);Ve[64]=new T(w.bytes,new Uint8Array(0),1);Ve[96]=new T(w.string,"",1);Ve[128]=new T(w.array,0,1);Ve[160]=new T(w.map,0,1);Ve[244]=new T(w.false,!1,1);Ve[245]=new T(w.true,!0,1);Ve[246]=new T(w.null,null,1);function Mf(r){switch(r.type){case w.false:return nr([244]);case w.true:return nr([245]);case w.null:return nr([246]);case w.bytes:return r.value.length?void 0:nr([64]);case w.string:return r.value===""?nr([96]):void 0;case w.array:return r.value===0?nr([128]):void 0;case w.map:return r.value===0?nr([160]):void 0;case w.uint:return r.value<24?nr([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return nr([31-Number(r.value)])}}var o2={float64:!1,mapSorter:s2,quickEncodeToken:Mf};function Hf(){let r=[];return r[w.uint.major]=ke,r[w.negint.major]=ja,r[w.bytes.major]=vo,r[w.string.major]=Mg,r[w.array.major]=Xa,r[w.map.major]=Za,r[w.tag.major]=Ja,r[w.float.major]=Qa,r}var h0=Hf(),Vf=new Ci,ec=class r{constructor(t,e){this.obj=t,this.parent=e}includes(t){let e=this;do if(e.obj===t)return!0;while(e=e.parent);return!1}static createCheck(t,e){if(t&&t.includes(e))throw new Error(`${kr} object contains circular references`);return new r(e,t)}},nn={null:new T(w.null,null),undefined:new T(w.undefined,void 0),true:new T(w.true,!0),false:new T(w.false,!1),emptyArray:new T(w.array,0),emptyMap:new T(w.map,0)},on={number(r,t,e,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new T(w.float,r):r>=0?new T(w.uint,r):new T(w.negint,r)},bigint(r,t,e,n){return r>=BigInt(0)?new T(w.uint,r):new T(w.negint,r)},Uint8Array(r,t,e,n){return new T(w.bytes,r)},string(r,t,e,n){return new T(w.string,r)},boolean(r,t,e,n){return r?nn.true:nn.false},null(r,t,e,n){return nn.null},undefined(r,t,e,n){return nn.undefined},ArrayBuffer(r,t,e,n){return new T(w.bytes,new Uint8Array(r))},DataView(r,t,e,n){return new T(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,t,e,n){if(!r.length)return e.addBreakTokens===!0?[nn.emptyArray,new T(w.break)]:nn.emptyArray;n=ec.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Li(s,e,n);return e.addBreakTokens?[new T(w.array,r.length),o,new T(w.break)]:[new T(w.array,r.length),o]},Object(r,t,e,n){let o=t!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return e.addBreakTokens===!0?[nn.emptyMap,new T(w.break)]:nn.emptyMap;n=ec.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[Li(l,e,n),Li(o?r.get(l):r[l],e,n)];return i2(a,e),e.addBreakTokens?[new T(w.map,s),a,new T(w.break)]:[new T(w.map,s),a]}};on.Map=on.Object;on.Buffer=on.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))on[`${r}Array`]=on.DataView;function Li(r,t={},e){let n=hg(r),o=t&&t.typeEncoders&&t.typeEncoders[n]||on[n];if(typeof o=="function"){let s=o(r,n,t,e);if(s!=null)return s}let i=on[n];if(!i)throw new Error(`${kr} unsupported type: ${n}`);return i(r,n,t,e)}function i2(r,t){t.mapSorter&&r.sort(t.mapSorter)}function s2(r,t){let e=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(t[0])?t[0][0]:t[0];if(e.type!==n.type)return e.type.compare(n.type);let o=e.type.major,i=h0[o].compareTokens(e,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function d0(r,t,e,n){if(Array.isArray(t))for(let o of t)d0(r,o,e,n);else e[t.type.major](r,t,n)}function $f(r,t,e){let n=Li(r,e);if(!Array.isArray(n)&&e.quickEncodeToken){let o=e.quickEncodeToken(n);if(o)return o;let i=t[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,e),a=new Ci(s);if(i(a,n,e),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Bi(a.chunks[0])}}return Vf.reset(),d0(Vf,n,t,e),Vf.toBytes(!0)}function or(r,t){return t=Object.assign({},o2,t),$f(r,h0,t)}var a2={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},rc=class{constructor(t,e={}){this._pos=0,this.data=t,this.options=e}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let t=this.data[this._pos],e=Ve[t];if(e===void 0){let n=O[t];if(!n)throw new Error(`${$} no decoder for major type ${t>>>5} (byte 0x${t.toString(16).padStart(2,"0")})`);let o=t&31;e=n(this.data,this._pos,o,this.options)}return this._pos+=e.encodedLength,e}},Di=Symbol.for("DONE"),nc=Symbol.for("BREAK");function c2(r,t,e){let n=[];for(let o=0;o<r.value;o++){let i=Ao(t,e);if(i===nc){if(r.value===1/0)break;throw new Error(`${$} got unexpected break to lengthed array`)}if(i===Di)throw new Error(`${$} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function l2(r,t,e){let n=e.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=Ao(t,e);if(a===nc){if(r.value===1/0)break;throw new Error(`${$} got unexpected break to lengthed map`)}if(a===Di)throw new Error(`${$} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${$} non-string keys not supported (got ${typeof a})`);if(e.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${$} found repeat map key "${a}"`);let c=Ao(t,e);if(c===Di)throw new Error(`${$} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function Ao(r,t){if(r.done())return Di;let e=r.next();if(e.type===w.break)return nc;if(e.type.terminal)return e.value;if(e.type===w.array)return c2(e,r,t);if(e.type===w.map)return l2(e,r,t);if(e.type===w.tag){if(t.tags&&typeof t.tags[e.value]=="function"){let n=Ao(r,t);return t.tags[e.value](n)}throw new Error(`${$} tag not supported (${e.value})`)}throw new Error("unsupported")}function zf(r,t){if(!(r instanceof Uint8Array))throw new Error(`${$} data to decode must be a Uint8Array`);t=Object.assign({},a2,t);let e=t.tokenizer||new rc(r,t),n=Ao(e,t);if(n===Di)throw new Error(`${$} did not find any content to decode`);if(n===nc)throw new Error(`${$} got unexpected break`);return[n,r.subarray(e.pos())]}function Ht(r,t){let[e,n]=zf(r,t);if(n.length>0)throw new Error(`${$} too many terminals, data makes no sense`);return e}var Br="/",p0=new TextEncoder().encode(Br),ic=p0[0],_t=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=L(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ic)throw new Error("Invalid key")}toString(t="utf8"){return G(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Br))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=p0),this._buf[0]!==ic){let t=new Uint8Array(this._buf.byteLength+1);t.fill(ic,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ic;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let i=e[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Br).slice(1)}type(){return u2(this.baseNamespace())}name(){return f2(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Br)||(t+=Br),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Br):new r(t.slice(0,-1).join(Br))}child(t){return this.toString()===Br?t:t.toString()===Br?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...h2(t.map(e=>e.namespaces()))])}};function u2(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function f2(r){let t=r.split(":");return t[t.length-1]}function h2(r){return[].concat(...r)}function sc({enumerable:r=!0,configurable:t=!1}={}){return{enumerable:r,configurable:t,writable:!1}}function*d2(r,t){if(t!=null&&typeof t=="object")if(Array.isArray(t))for(let[e,n]of t.entries()){let o=[...r,e],i=P.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*qf(n,o))}else{let e=P.asCID(t);e!=null?yield[r.join("/"),e]:yield*qf(t,r)}}function*qf(r,t){if(r==null||r instanceof Uint8Array)return;let e=P.asCID(r);e!=null&&(yield[t.join("/"),e]);for(let[n,o]of Object.entries(r)){let i=[...t,n];yield*d2(i,o)}}function*p2(r,t){if(Array.isArray(t))for(let[e,n]of t.entries()){let o=[...r,e];yield o.join("/"),typeof n=="object"&&P.asCID(n)==null&&(yield*Kf(n,o))}else yield*Kf(t,r)}function*Kf(r,t){if(!(r==null||typeof r!="object"))for(let[e,n]of Object.entries(r)){let o=[...t,e];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&P.asCID(n)==null&&(yield*p2(o,n))}}function m2(r,t){let e=r;for(let[n,o]of t.entries()){if(e=e[o],e==null)throw new Error(`Object has no property at ${t.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=P.asCID(e);if(i!=null)return{value:i,remaining:t.slice(n+1).join("/")}}return{value:e}}var Gf=class{cid;bytes;value;asBlock;constructor({cid:t,bytes:e,value:n}){if(t==null||e==null||typeof n>"u")throw new Error("Missing required argument");this.cid=t,this.bytes=e,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:sc(),bytes:sc(),value:sc(),asBlock:sc()})}links(){return qf(this.value,[])}tree(){return Kf(this.value,[])}get(t="/"){return m2(this.value,t.split("/").filter(Boolean))}};function ac({bytes:r,cid:t,value:e,codec:n}){let o=e!==void 0?e:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Gf({cid:t,bytes:r,value:o})}var y0="/pin/",m0="/pinned-block/",Wf=Gt,g0=1;function cc(r){return r.version===0&&(r=r.toV1()),new _t(`${y0}${r.toString(Wf)}`)}var lc=class{datastore;blockstore;getCodec;constructor(t,e,n){this.datastore=t,this.blockstore=e,this.getCodec=n}async*add(t,e={}){let n=cc(t);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(e.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new Ir({concurrency:g0});for await(let a of this.#t(t,i,{...e,depth:o}))await this.#r(a,c=>c.pinnedBy.find(l=>Y(l,t.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(t.bytes),!0),e),yield a;let s={depth:o,metadata:e.metadata??{}};await this.datastore.put(n,or(s),e)}async*#t(t,e,n){if(n.depth===-1)return;let o=await this.getCodec(t.code),i=await this.blockstore.get(t,n),s=ac({bytes:i,cid:t,codec:o});yield t;for await(let[,a]of s.links())yield*await e.add(async()=>this.#t(a,e,{...n,depth:n.depth-1}))}async#r(t,e,n){let o=new _t(`${m0}${Wf.encode(t.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=Ht(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(e(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,or(i),n),n.onProgress?.(new H("helia:pin:add",t))}}async*rm(t,e={}){let n=cc(t),o=await this.datastore.get(n,e),i=Ht(o);await this.datastore.delete(n,e);let s=new Ir({concurrency:g0});for await(let a of this.#t(t,s,{...e,depth:i.depth}))await this.#r(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Y(l,t.bytes)),!0),{...e,depth:i.depth}),yield a}async*ls(t={}){for await(let{key:e,value:n}of this.datastore.query({prefix:y0+(t.cid!=null?`${t.cid.toString(Gt)}`:"")},t)){let o=P.parse(e.toString().substring(5),Gt),i=Ht(n);yield{cid:o,...i}}}async isPinned(t,e={}){let n=new _t(`${m0}${Wf.encode(t.multihash.bytes)}`);return this.datastore.has(n,e)}async get(t,e){let n=cc(t),o=await this.datastore.get(n,e);return Ht(o)}async setMetadata(t,e,n){let o=cc(t),i=await this.datastore.get(o,n),s=Ht(i);s.metadata=e??{},await this.datastore.put(o,or(s),n)}};var uc=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}},Rn=class extends Error{static name="NoRoutersAvailableError";constructor(t="No routers available"){super(t),this.name="NoRoutersAvailableError"}},fc=class extends Error{static name="UnknownHashAlgorithmError";constructor(t="Unknown hash algorithm"){super(t),this.name="UnknownHashAlgorithmError"}},hc=class extends Error{static name="UnknownCodecError";constructor(t="Unknown codec"){super(t),this.name="UnknownCodecError"}};var dc=class extends Ir{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var g2=5,pc=class{log;routers;providerLookupConcurrency;constructor(t,e){this.log=t.logger.forComponent("helia:routing"),this.routers=e.routers??[],this.providerLookupConcurrency=e.providerLookupConcurrency??g2}async start(){await Vr(...this.routers)}async stop(){await Hr(...this.routers)}async*findProviders(t,e={}){if(this.routers.length===0)throw new Rn("No content routers available");let n=new dc({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of $r(n.toGenerator(),...Io(this.routers,"findProviders").map(i=>i.findProviders(t,e))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,e);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:e.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(t,e={}){if(this.routers.length===0)throw new Rn("No content routers available");await Promise.all(Io(this.routers,"provide").map(async n=>{await n.provide(t,e)}))}async put(t,e,n){await Promise.all(Io(this.routers,"put").map(async o=>{await o.put(t,e,n)}))}async get(t,e){return Promise.any(Io(this.routers,"get").map(async n=>n.get(t,e)))}async findPeer(t,e){if(this.routers.length===0)throw new Rn("No peer routers available");let n=this,o=$r(...Io(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(t,e)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new kt("Could not find peer in routing")}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new Rn("No peer routers available");for await(let n of $r(...Io(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(t,e))))n!=null&&(yield n)}};function Io(r,t){return r.filter(e=>e[t]!=null)}var sn={},ko=r=>{r.addEventListener("message",t=>{ko.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{ko.dispatchEvent("message",r,t)})};ko.addEventListener=(r,t)=>{sn[r]==null&&(sn[r]=[]),sn[r].push(t)};ko.removeEventListener=(r,t)=>{sn[r]!=null&&(sn[r]=sn[r].filter(e=>e===t))};ko.dispatchEvent=function(r,t,e){sn[r]!=null&&sn[r].forEach(n=>n(t,e))};var jf=ko;var Yf="lock:worker:request-read",Xf="lock:worker:release-read",Zf="lock:master:grant-read",Jf="lock:worker:request-write",Qf="lock:worker:release-write",th="lock:master:grant-write";var w0=(r=21)=>Math.random().toString().substring(2);var b0=(r,t,e,n,o)=>(i,s)=>{if(s.data.type!==e)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u?.data==null)return;let f={type:u.data.type,name:u.data.name,identifier:u.data.identifier};f.type===n&&f.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},x0=(r,t,e,n)=>async()=>{let o=w0();return globalThis.postMessage({type:t,identifier:o,name:r}),new Promise(i=>{let s=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===e&&c.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},y2={singleProcess:!1},E0=r=>{if(r=Object.assign({},y2,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return jf.addEventListener("message",b0(e,"requestReadLock",Yf,Xf,Zf)),jf.addEventListener("message",b0(e,"requestWriteLock",Jf,Qf,th)),e}return{isWorker:!0,readLock:e=>x0(e,Yf,Zf,Xf),writeLock:e=>x0(e,Jf,th,Qf)}};var Nn={},an;async function eh(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>Ii((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var w2=(r,t)=>{if(an.isWorker===!0)return{readLock:an.readLock(r,t),writeLock:an.writeLock(r,t)};let e=new de({concurrency:1}),n;return{async readLock(){if(n!=null)return eh(n,t);n=new de({concurrency:t.concurrency,autoStart:!1});let o=n,i=eh(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,eh(e,t)}}},b2={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function rh(r){let t=Object.assign({},b2,r);return an==null&&(an=E0(t),an.isWorker!==!0&&(an.addEventListener("requestReadLock",e=>{Nn[e.data.name]!=null&&Nn[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),an.addEventListener("requestWriteLock",async e=>{Nn[e.data.name]!=null&&Nn[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),Nn[t.name]==null&&(Nn[t.name]=w2(t.name,t)),Nn[t.name]}var mc=class{lock;child;pins;started;constructor(t,e,n={}){this.child=t,this.pins=e,this.lock=rh({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Vr(this.child),this.started=!0}async stop(){await Hr(this.child),this.started=!1}unwrap(){return this.child}async put(t,e,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(t,e,n)}finally{o()}}async*putMany(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(t,e)}finally{n()}}async get(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(t,e)}finally{n()}}async*getMany(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(t,e)}finally{n()}}async delete(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(t))throw new Error("CID was pinned");await this.child.delete(t,e)}finally{n()}}async*deleteMany(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of t){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),e)}finally{n()}}async has(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(t,e)}finally{n()}}async*getAll(t={}){t?.signal?.throwIfAborted();let e=await this.lock.readLock();try{yield*this.child.getAll(t)}finally{e()}}createSession(t,e){return e?.signal?.throwIfAborted(),this.child.createSession(t,e)}};var nh=new _t("/version"),v0=1;async function S0(r){if(!await r.has(nh)){await r.put(nh,L(`${v0}`));return}let t=await r.get(nh),e=G(t);if(parseInt(e,10)!==v0)throw new Error("Unknown datastore version, a datastore migration may be required")}var Pn={};Et(Pn,{code:()=>Cr,decode:()=>cn,decodeOptions:()=>A2,encode:()=>To,encodeOptions:()=>S2,name:()=>I2,toByteView:()=>A0});var _0=42;function A0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function x2(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let t=P.asCID(r);if(!t)return null;let e=new Uint8Array(t.bytes.byteLength+1);return e.set(t.bytes,1),[new T(w.tag,_0),new T(w.bytes,e)]}function E2(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function v2(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var oh={float64:!0,typeEncoders:{Object:x2,undefined:E2,number:v2}},S2={...oh,typeEncoders:{...oh.typeEncoders}};function _2(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return P.decode(r.subarray(1))}var gc={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};gc.tags[_0]=_2;var A2={...gc,tags:gc.tags.slice()},I2="dag-cbor",Cr=113,To=r=>or(r,oh),cn=r=>Ht(A0(r),gc);var Ro={};Et(Ro,{code:()=>Rr,decode:()=>Co,encode:()=>wc,format:()=>U2,name:()=>O2,parse:()=>M2,stringify:()=>U2});var ih=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(t){let e=this.inRecursive[this.inRecursive.length-1];e&&(e.type===w.array&&(e.elements++,e.elements!==1&&t.push([44])),e.type===w.map&&(e.elements++,e.elements!==1&&(e.elements%2===1?t.push([44]):t.push([58]))))}[w.uint.major](t,e){this.prefix(t);let n=String(e.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);t.push(o)}[w.negint.major](t,e){this[w.uint.major](t,e)}[w.bytes.major](t,e){throw new Error(`${kr} unsupported type: Uint8Array`)}[w.string.major](t,e){this.prefix(t);let n=Wa(JSON.stringify(e.value));t.push(n.length>32?Bi(n):n)}[w.array.major](t,e){this.prefix(t),this.inRecursive.push({type:w.array,elements:0}),t.push([91])}[w.map.major](t,e){this.prefix(t),this.inRecursive.push({type:w.map,elements:0}),t.push([123])}[w.tag.major](t,e){}[w.float.major](t,e){if(e.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===w.array)t.push([93]);else if(s.type===w.map)t.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(e.value===void 0)throw new Error(`${kr} unsupported type: undefined`);if(this.prefix(t),e.type.name==="true"){t.push([116,114,117,101]);return}else if(e.type.name==="false"){t.push([102,97,108,115,101]);return}else if(e.type.name==="null"){t.push([110,117,108,108]);return}let n=String(e.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),t.push(o)}};function k2(r,t){if(Array.isArray(r[0])||Array.isArray(t[0]))throw new Error(`${kr} complex map keys are not supported`);let e=r[0],n=t[0];if(e.type!==w.string||n.type!==w.string)throw new Error(`${kr} non-string map keys are not supported`);if(e<n)return-1;if(e>n)return 1;throw new Error(`${kr} unexpected duplicate map keys, this is not supported`)}var T2={addBreakTokens:!0,mapSorter:k2};function Oi(r,t){return t=Object.assign({},T2,t),$f(r,new ih,t)}var Bo=class{constructor(t,e={}){this._pos=0,this.data=t,this.options=e,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let t=this.ch();for(;t===32||t===9||t===13||t===10;)t=this.data[++this._pos]}expect(t){if(this.data.length-this._pos<t.length)throw new Error(`${$} unexpected end of input at position ${this._pos}`);for(let e=0;e<t.length;e++)if(this.data[this._pos++]!==t[e])throw new Error(`${$} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...t)}'`)}parseNumber(){let t=this._pos,e=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(e=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new T(w.uint,0,this._pos-t);if(o([48,49,50,51,52,53,54,55,56,57]),e&&this._pos===t+1)throw new Error(`${$} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${$} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(t,this._pos)),s=parseFloat(i);return n?new T(w.float,s,this._pos-t):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new T(s>=0?w.uint:w.negint,s,this._pos-t):new T(s>=0?w.uint:w.negint,BigInt(i),this._pos-t)}parseString(){if(this.ch()!==34)throw new Error(`${$} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new T(w.string,c,s)}}let t=this._pos,e=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${$} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${$} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${$} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(i&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(i&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(i&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,e.push(s>>>10&1023|55296),s=56320|s&1023),e.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${$} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:e.push(s);break;case 98:e.push(8);break;case 116:e.push(9);break;case 110:e.push(10);break;case 102:e.push(12);break;case 114:e.push(13);break;case 117:e.push(n());break;default:throw new Error(`${$} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new T(w.string,Lf(e),this._pos-t);default:if(i<32)throw new Error(`${$} invalid control character at position ${this._pos}`);i<128?(e.push(i),this._pos++):o()}}throw new Error(`${$} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new T(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new T(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new T(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new T(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new T(w.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${$} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new T(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${$} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new T(w.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new T(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${$} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new T(w.break,void 0,1);let t=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${$} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),t}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${$} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function sh(r,t){return t=Object.assign({tokenizer:new Bo(r,t)},t),Ht(r,t)}function C2(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function R2(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let t=P.asCID(r);if(!t)return null;let e=t.toString();return[new T(w.map,1/0,1),new T(w.string,"/",1),new T(w.string,e,e.length),new T(w.break,void 0,1)]}function yc(r){let t=se.encode(r).slice(1);return[new T(w.map,1/0,1),new T(w.string,"/",1),new T(w.map,1/0,1),new T(w.string,"bytes",5),new T(w.string,t,t.length),new T(w.break,void 0,1),new T(w.break,void 0,1)]}function He(r){return yc(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function N2(r){return yc(new Uint8Array(r))}function P2(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function L2(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var D2={typeEncoders:{Object:R2,Buffer:yc,Uint8Array:yc,Int8Array:He,Uint16Array:He,Int16Array:He,Uint32Array:He,Int32Array:He,Float32Array:He,Float64Array:He,Uint8ClampedArray:He,BigInt64Array:He,BigUint64Array:He,DataView:He,ArrayBuffer:N2,undefined:P2,number:L2}},ah=class extends Bo{constructor(t,e){super(t,e),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let t=this._next();if(t.type===w.map){let e=this._next();if(e.type===w.string&&e.value==="/"){let n=this._next();if(n.type===w.string){if(this._next().type!==w.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new T(w.tag,42,0)}if(n.type===w.map){let o=this._next();if(o.type===w.string&&o.value==="bytes"){let i=this._next();if(i.type===w.string){for(let a=0;a<2;a++)if(this._next().type!==w.break)throw new Error("Invalid encoded Bytes form");let s=se.decode(`m${i.value}`);return new T(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(e)}return t}},ch={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};ch.tags[42]=P.parse;var O2="dag-json",Rr=297,wc=r=>Oi(r,D2),Co=r=>{let t=C2(r),e=Object.assign(ch,{tokenizer:new ah(t,ch)});return sh(t,e)},U2=r=>F2.decode(wc(r));var F2=new TextDecoder,M2=r=>Co(V2.encode(r)),V2=new TextEncoder;var Fi={};Et(Fi,{code:()=>Be,createLink:()=>D0,createNode:()=>L0,decode:()=>Nr,encode:()=>J2,name:()=>Z2,prepare:()=>fh,validate:()=>hh});var H2=new TextDecoder;function lh(r,t){let e=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(t>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[t++];if(e+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[e,t]}function bc(r,t){let e;[e,t]=lh(r,t);let n=t+e;if(e<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(t,n),n]}function I0(r,t){let e;return[e,t]=lh(r,t),[e&7,e>>3,t]}function $2(r){let t={},e=r.length,n=0;for(;n<e;){let o,i;if([o,i,n]=I0(r,n),i===1){if(t.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(t.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(t.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[t.Hash,n]=bc(r,n)}else if(i===2){if(t.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(t.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=bc(r,n),t.Name=H2.decode(s)}else if(i===3){if(t.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[t.Tsize,n]=lh(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>e)throw new Error("protobuf: (PBLink) unexpected end of data");return t}function k0(r){let t=r.length,e=0,n,o=!1,i;for(;e<t;){let a,c;if([a,c,e]=I0(r,e),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,e]=bc(r,e),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,e]=bc(r,e),n.push($2(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(e>t)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var B0=new TextEncoder,T0=2**32,z2=2**31;function q2(r,t){let e=t.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");e=Ui(t,e,r.Tsize)-1,t[e]=24}if(typeof r.Name=="string"){let n=B0.encode(r.Name);e-=n.length,t.set(n,e),e=Ui(t,e,n.length)-1,t[e]=18}return r.Hash&&(e-=r.Hash.length,t.set(r.Hash,e),e=Ui(t,e,r.Hash.length)-1,t[e]=10),t.length-e}function C0(r){let t=G2(r),e=new Uint8Array(t),n=t;if(r.Data&&(n-=r.Data.length,e.set(r.Data,n),n=Ui(e,n,r.Data.length)-1,e[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=q2(r.Links[o],e.subarray(0,n));n-=i,n=Ui(e,n,i)-1,e[n]=18}return e}function K2(r){let t=0;if(r.Hash){let e=r.Hash.length;t+=1+e+No(e)}if(typeof r.Name=="string"){let e=B0.encode(r.Name).length;t+=1+e+No(e)}return typeof r.Tsize=="number"&&(t+=1+No(r.Tsize)),t}function G2(r){let t=0;if(r.Data){let e=r.Data.length;t+=1+e+No(e)}if(r.Links)for(let e of r.Links){let n=K2(e);t+=1+n+No(n)}return t}function Ui(r,t,e){t-=No(e);let n=t;for(;e>=z2;)r[t++]=e&127|128,e/=128;for(;e>=128;)r[t++]=e&127|128,e>>>=7;return r[t]=e,n}function No(r){return r%2===0&&r++,Math.floor((W2(r)+6)/7)}function W2(r){let t=0;return r>=T0&&(r=Math.floor(r/T0),t=32),r>=65536&&(r>>>=16,t+=16),r>=256&&(r>>>=8,t+=8),t+j2[r]}var j2=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var Y2=["Data","Links"],X2=["Hash","Name","Tsize"],uh=new TextEncoder;function N0(r,t){if(r===t)return 0;let e=r.Name?uh.encode(r.Name):[],n=t.Name?uh.encode(t.Name):[],o=e.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(e[s]!==n[s]){o=e[s],i=n[s];break}return o<i?-1:i<o?1:0}function R0(r,t){return!Object.keys(r).some(e=>!t.includes(e))}function P0(r){if(typeof r.asCID=="object"){let e=P.asCID(r);if(!e)throw new TypeError("Invalid DAG-PB form");return{Hash:e}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let t={};if(r.Hash){let e=P.asCID(r.Hash);try{e||(typeof r.Hash=="string"?e=P.parse(r.Hash):r.Hash instanceof Uint8Array&&(e=P.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}e&&(t.Hash=e)}if(!t.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(t.Name=r.Name),typeof r.Tsize=="number"&&(t.Tsize=r.Tsize),t}function fh(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let t={};if(r.Data!==void 0)if(typeof r.Data=="string")t.Data=uh.encode(r.Data);else if(r.Data instanceof Uint8Array)t.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))t.Links=r.Links.map(P0),t.Links.sort(N0);else throw new TypeError("Invalid DAG-PB form");else t.Links=[];return t}function hh(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!R0(r,Y2))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let t=0;t<r.Links.length;t++){let e=r.Links[t];if(!e||typeof e!="object"||Array.isArray(e)||e instanceof Uint8Array||e["/"]&&e["/"]===e.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!R0(e,X2))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(e.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(e.Hash==null||!e.Hash["/"]||e.Hash["/"]!==e.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(e.Name!==void 0&&typeof e.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(e.Tsize!==void 0){if(typeof e.Tsize!="number"||e.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(e.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(t>0&&N0(e,r.Links[t-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function L0(r,t=[]){return fh({Data:r,Links:t})}function D0(r,t,e){return P0({Hash:e,Name:r,Tsize:t})}function O0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var Z2="dag-pb",Be=112;function J2(r){hh(r);let t={};return r.Links&&(t.Links=r.Links.map(e=>{let n={};return e.Hash&&(n.Hash=e.Hash.bytes),e.Name!==void 0&&(n.Name=e.Name),e.Tsize!==void 0&&(n.Tsize=e.Tsize),n})),r.Data&&(t.Data=r.Data),C0(t)}function Nr(r){let t=O0(r),e=k0(t),n={};return e.Data&&(n.Data=e.Data),e.Links&&(n.Links=e.Links.map(o=>{let i={};try{i.Hash=P.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function Po(r){return r?.then!=null}function U0(r=[],t){let e={[Be]:Fi,[ae]:bn,[Cr]:Pn,[Rr]:Ro,[hr]:Qn};return r.forEach(n=>{e[n.code]=n}),async n=>{let o=e[n];if(o==null&&t!=null){let i=t(n);Po(i)?o=await i:o=i,e[o.code]=o}if(o!=null)return o;throw new hc(`Could not load codec for ${n}`)}}function F0(r=[],t){let e={[Ze.code]:Ze,[vs.code]:vs,[bt.code]:bt};return r.forEach(n=>{e[n.code]=n}),async n=>{let o=e[n];if(o==null&&t!=null){let i=t(n);Po(i)?o=await i:o=i,e[o.code]=o}if(o!=null)return o;throw new fc(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var xc=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};var Ec=class{has(t,e){return Promise.reject(new Error(".has is not implemented"))}put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(t,e){for await(let{cid:n,block:o}of t)await this.put(n,o,e),yield n}get(t,e){return Promise.reject(new Error(".get is not implemented"))}async*getMany(t,e){for await(let n of t)yield{cid:n,block:await this.get(n,e)}}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(t,e){for await(let n of t)await this.delete(n,e),yield n}async*getAll(t){throw new Error(".getAll is not implemented")}};var vc=0,Sc=class extends Ec{child;constructor(t){super(),this.child=t}put(t,e){return t.multihash.code===vc||this.child==null?t:this.child.put(t,e)}get(t){if(t.multihash.code===vc)return t.multihash.digest;if(this.child==null)throw new xc;return this.child.get(t)}has(t){return t.multihash.code===vc?!0:this.child==null?!1:this.child.has(t)}delete(t){if(t.code!==vc&&this.child!=null)return this.child.delete(t)}getAll(t){return this.child!=null?this.child.getAll(t):[]}};function Q2(r){return r[Symbol.asyncIterator]!=null}function tS(r,t){let e=0;if(Q2(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Zn(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=t(o,e++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){s===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var ve=tS;function eS(r){return r[Symbol.asyncIterator]!=null}function M0(r){return r?.then!=null}function rS(r,t){let e=0;if(eS(r))return async function*(){for await(let c of r){let l=t(c,e++);M0(l)&&await l,yield c}}();let n=Zn(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(o,e++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=t(c,e++);M0(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var dh=rS;var _c=class{child;getHasher;log;logger;components;constructor(t){this.log=t.logger.forComponent("helia:networked-storage"),this.logger=t.logger,this.components=t,this.child=new Sc(t.blockstore),this.getHasher=t.getHasher}async put(t,e,n={}){return await this.child.has(t,n)?(n.onProgress?.(new H("blocks:put:duplicate",t)),t):(n.onProgress?.(new H("blocks:put:providers:notify",t)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(t,e,n))),n.onProgress?.(new H("blocks:put:blockstore:put",t)),this.child.put(t,e,n))}async*putMany(t,e={}){let n=ve(t,async({cid:i})=>{let s=await this.child.has(i,e);return s&&e.onProgress?.(new H("blocks:put-many:duplicate",i)),!s}),o=dh(n,async({cid:i,block:s})=>{e.onProgress?.(new H("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,e)))});e.onProgress?.(new H("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,e)}async get(t,e={}){if(e.offline!==!0&&!await this.child.has(t,e)){let n=await this.getHasher(t.multihash.code);e.onProgress?.(new H("blocks:get:providers:get",t));let o=await V0(t,this.components.blockBrokers,n,{...e,log:this.log});return e.onProgress?.(new H("blocks:get:blockstore:put",t)),await this.child.put(t,o,e),e.onProgress?.(new H("blocks:get:providers:notify",t)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(t,o,e))),o}return e.onProgress?.(new H("blocks:get:blockstore:get",t)),this.child.get(t,e)}async*getMany(t,e={}){e.onProgress?.(new H("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(dh(t,async n=>{if(e.offline!==!0&&!await this.child.has(n,e)){let o=await this.getHasher(n.multihash.code);e.onProgress?.(new H("blocks:get-many:providers:get",n));let i=await V0(n,this.components.blockBrokers,o,{...e,log:this.log});e.onProgress?.(new H("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,e),e.onProgress?.(new H("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,i,e)))}}))}async delete(t,e={}){e.onProgress?.(new H("blocks:delete:blockstore:delete",t)),await this.child.delete(t,e)}async*deleteMany(t,e={}){e.onProgress?.(new H("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of t)yield n}(),e)}async has(t,e={}){return this.child.has(t,e)}async*getAll(t={}){t.onProgress?.(new H("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(t)}},Ac=class extends _c{started;constructor(t){super(t),this.started=!1}isStarted(){return this.started}async start(){await Vr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Hr(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(t,e){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(e));return new ph({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:t})}},ph=class extends _c{closeController;constructor(t,e){super(t),this.closeController=new AbortController,mt(1/0,this.closeController.signal),this.log=t.logger.forComponent(`helia:session-storage:${e.root}`)}close(){this.closeController.abort()}async put(t,e,n={}){let o=Zt([this.closeController.signal,n.signal]);mt(1/0,o);try{return await super.put(t,e,{...n,signal:o})}finally{o.clear()}}async*putMany(t,e={}){let n=Zt([this.closeController.signal,e.signal]);mt(1/0,n);try{yield*super.putMany(t,{...e,signal:n})}finally{n.clear()}}async get(t,e={}){let n=Zt([this.closeController.signal,e.signal]);mt(1/0,n);try{return await super.get(t,{...e,signal:n})}finally{n.clear()}}async*getMany(t,e={}){let n=Zt([this.closeController.signal,e.signal]);mt(1/0,n);try{yield*super.getMany(t,{...e,signal:n})}finally{n.clear()}}async delete(t,e={}){let n=Zt([this.closeController.signal,e.signal]);mt(1/0,n);try{await super.delete(t,{...e,signal:n})}finally{n.clear()}}async*deleteMany(t,e={}){let n=Zt([this.closeController.signal,e.signal]);mt(1/0,n);try{yield*super.deleteMany(t,{...e,signal:n})}finally{n.clear()}}async has(t,e={}){let n=Zt([this.closeController.signal,e.signal]);mt(1/0,n);try{return await super.has(t,{...e,signal:n})}finally{n.clear()}}async*getAll(t={}){let e=Zt([this.closeController.signal,t.signal]);mt(1/0,e);try{yield*super.getAll({...t,signal:e})}finally{e.clear()}}};function nS(r){return typeof r.retrieve=="function"}var oS=(r,t)=>{if(t==null)throw new St(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async e=>{let n,o=t.digest(e);if(Po(o)?n=await o:n=o,!Y(n.digest,r.multihash.digest))throw new _e("Hash of downloaded block did not match multihash from passed CID")}};async function V0(r,t,e,n){let o=oS(r,e),i=new AbortController,s=Zt([i.signal,n.signal]);mt(1/0,i.signal,s);let a=[];for(let c of t)nS(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async f=>{await o(f),l=!0}});return l||await o(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var mh=64,$e=class{fp;h;seed;constructor(t,e,n,o=2){if(o>mh)throw new TypeError("Invalid Fingerprint Size");let i=e.hashV(t,n),s=re(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?Y(this.fp,t.fp):!1}};function Ln(r,t){return Math.floor(Math.random()*(t-r))+r}var Dn=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof $e))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof $e))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof $e))throw new TypeError("Invalid Fingerprint");let e=Ln(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof $e))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var iS=Ut(vf(),1);var Mi={hash:r=>Number(_f(r,{size:32})),hashV:(r,t)=>sS(Mi.hash(r,t))};function sS(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),L(t,"base16")}var aS=500,Vi=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Mi,this.seed=t.seed??Ln(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=L(t));let e=new $e(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Dn(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Dn(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let i=[n,o],s=i[Ln(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Dn(this.bucketSize));for(let a=0;a<aS;a++){let c=this.buckets[s].swap(e);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Dn(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=L(t));let e=new $e(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let i=(n^e.hash())%this.filterSize;return this.buckets[i]?.has(e)??!1}remove(t){typeof t=="string"&&(t=L(t));let e=new $e(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let i=(n^e.hash())%this.filterSize,s=this.buckets[i]?.remove(e)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},cS={1:.5,2:.84,4:.95,8:.98};function lS(r=.001){return r>.002?2:r>1e-5?4:8}function H0(r,t=.001){let e=lS(t),n=cS[e],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),mh);return{filterSize:o,bucketSize:e,fingerprintSize:i}}var Ic=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Mi,this.seed=t.seed??Ln(0,Math.pow(2,10)),this.filterSeries=[new Vi({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=L(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new Vi({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=L(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=L(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function gh(r,t=.001,e){return new Ic({...H0(r,t),...e??{}})}var Hi=class extends jn{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(t,e){super(),mt(1/0,this),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=gh(this.maxProviders)}async retrieve(t,e={}){let n=se.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o;let i=ht();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.intialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",t)}let s=!1,a=new Ir({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||e.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let u=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(u)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),i.resolve(await this.retrieve(t,e))}).catch(l=>{this.log.error("could not find new providers for %c",t,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(t,l.detail,e),{provider:l.detail}).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,u)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(t,l,e),{provider:l}))).catch(l=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,l)});try{return await i.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toEvictionKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let o=ht(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t);for await(let s of this.findNewProviders(t,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===e&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<e)throw new uc(`Found ${i} of ${e} ${this.name} providers for ${t}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",t,s.errors??s),o.reject(s)}),o.promise}};var kc=class{blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(t){this.logger=t.logger??ng(),this.log=this.logger.forComponent("helia"),this.getHasher=F0(t.hashers,t.loadHasher),this.getCodec=U0(t.codecs,t.loadCodec),this.dns=t.dns??Ti(),this.metrics=t.metrics;let e={blockstore:t.blockstore,datastore:t.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...t.components??{}};this.routing=e.routing=new pc(e,{routers:(t.routers??[]).flatMap(o=>{let i=[o];return o[Zo]!=null&&i.push(o[Zo]),o[Jo]!=null&&i.push(o[Jo]),i}),providerLookupConcurrency:t.providerLookupConcurrency});let n=new Ac(e);this.pins=new lc(t.datastore,n,this.getCodec),this.blockstore=new mc(n,this.pins,{holdGcLock:t.holdGcLock??!0}),this.datastore=t.datastore,e.blockBrokers=t.blockBrokers.map(o=>o(e))}async start(){await S0(this.datastore),await Vr(this.blockstore,this.datastore,this.routing)}async stop(){await Hr(this.blockstore,this.datastore,this.routing)}async gc(t={}){let e=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await fr(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,t))continue;yield i,t.onProgress?.(new H("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),t.onProgress?.(new H("helia:gc:error",s))}}()))}finally{e()}this.log("gc finished")}};var Tc=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let 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 f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(i*=t,i+=u,i>l||(s+=1,e!==void 0&&s>e))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return e[o]=s[0],e[o+1]=s[1],e[o+2]=s[2],e[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];e[o]=i>>8,e[o+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=t(i.subarray(0,s));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var $0=45,hS=15,Lo=new Tc;function yh(r){if(!(r.length>hS))return Lo.new(r).parseWith(()=>Lo.readIPv4Addr())}function wh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>$0))return Lo.new(r).parseWith(()=>Lo.readIPv6Addr())}function Bc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>$0))return Lo.new(r).parseWith(()=>Lo.readIPAddr())}function Do(r){return!!yh(r)}function Oo(r){return!!wh(r)}function Cc(r){return!!Bc(r)}var q0=Ut(z0(),1),dS=["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"],pS=dS.map(r=>new q0.Netmask(r));function bh(r){for(let t of pS)if(t.contains(r))return!0;return!1}function mS(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function gS(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return bh(o)}function yS(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function wS(r){let t=r.split(":"),e=t[t.length-1];return bh(e)}function bS(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 K0(r){return Do(r)?bh(r):mS(r)?gS(r):yS(r)?wS(r):Oo(r)?bS(r):void 0}var xS=r=>r.toString().split("/").slice(1),Uo=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),rt=r=>({match:t=>Uo(e=>e===r).match(t),pattern:r}),On=()=>({match:r=>Uo(t=>typeof t=="string").match(r),pattern:"{string}"}),zi=()=>({match:r=>Uo(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),lt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{X.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),qi=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{_u.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),it=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Yt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),nt=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function gt(...r){function t(o){let i=xS(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function e(o){return t(o)!==!1}function n(o){let i=t(o);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var Nc=nt(rt("dns4"),On()),Pc=nt(rt("dns6"),On()),Lc=nt(rt("dnsaddr"),On()),Eh=nt(rt("dns"),On()),jN=gt(Nc,it(lt())),YN=gt(Pc,it(lt())),XN=gt(Lc,it(lt())),G0=gt(Yt(Eh,Lc,Nc,Pc),it(lt())),W0=nt(rt("ip4"),Uo(Do)),j0=nt(rt("ip6"),Uo(Oo)),vh=Yt(W0,j0),Pr=Yt(vh,Eh,Nc,Pc,Lc),ZN=gt(Yt(vh,nt(Yt(Eh,Lc,Nc,Pc),it(lt())))),JN=gt(W0),QN=gt(j0),tP=gt(vh),Sh=nt(Pr,rt("tcp"),zi()),Ki=nt(Pr,rt("udp"),zi()),eP=gt(nt(Sh,it(lt()))),rP=gt(Ki),_h=nt(Ki,rt("quic"),it(lt())),Dc=nt(Ki,rt("quic-v1"),it(lt())),ES=Yt(_h,Dc),nP=gt(_h),oP=gt(Dc),xh=Yt(Pr,Sh,Ki,_h,Dc),Y0=Yt(nt(xh,rt("ws"),it(lt()))),iP=gt(Y0),X0=Yt(nt(xh,rt("wss"),it(lt())),nt(xh,rt("tls"),it(nt(rt("sni"),On())),rt("ws"),it(lt()))),sP=gt(X0),Z0=nt(Ki,rt("webrtc-direct"),it(qi()),it(qi()),it(lt())),aP=gt(Z0),J0=nt(Dc,rt("webtransport"),it(qi()),it(qi()),it(lt())),cP=gt(J0),Rc=Yt(Y0,X0,nt(Sh,it(lt())),nt(ES,it(lt())),nt(Pr,it(lt())),Z0,J0,lt()),lP=gt(Rc),vS=nt(Rc,rt("p2p-circuit"),lt()),uP=gt(vS),SS=Yt(nt(Rc,rt("p2p-circuit"),rt("webrtc"),it(lt())),nt(Rc,rt("webrtc"),it(lt())),nt(rt("webrtc"),it(lt()))),fP=gt(SS),_S=Yt(nt(Pr,rt("tcp"),zi(),rt("http"),it(lt())),nt(Pr,rt("http"),it(lt()))),Q0=gt(_S),AS=Yt(nt(Pr,rt("tcp"),Yt(nt(rt("443"),rt("http")),nt(zi(),rt("https"))),it(lt())),nt(Pr,rt("tls"),rt("http"),it(lt())),nt(Pr,rt("https"),it(lt()))),ty=gt(AS),IS=Yt(nt(rt("memory"),On(),it(lt()))),hP=gt(IS);var xP=parseInt("0xFFFF",16),EP=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ny=Do,RS=Oo,Ah=function(r){let t=0;if(r=r.toString().trim(),ny(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(RS(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=ny(e[n]),s;i&&(s=Ah(e[n]),e[n]=G(s.slice(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,G(s.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);o[t++]=i>>8&255,o[t++]=i&255}return o}throw new Error("invalid ip address")},oy=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let i=0;i<e;i++)o.push(r[t+i]);return o.join(".")}if(e===16){let o=[];for(let i=0;i<e;i+=2)o.push(n.getUint16(t+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Fo={},Ih={},PS=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];PS.forEach(r=>{let t=LS(...r);Ih[t.code]=t,Fo[t.name]=t});function LS(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function Z(r){if(typeof r=="number"){if(Ih[r]!=null)return Ih[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Fo[r]!=null)return Fo[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var rL=Z("ip4"),nL=Z("ip6"),oL=Z("ipcidr");function Ch(r,t){switch(Z(r).code){case 4:case 41:return OS(t);case 42:return Bh(t);case 6:case 273:case 33:case 132:return ay(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Bh(t);case 421:return VS(t);case 444:return sy(t);case 445:return sy(t);case 466:return MS(t);case 481:return globalThis.encodeURIComponent(Bh(t));default:return G(t,"base16")}}function Rh(r,t){switch(Z(r).code){case 4:return iy(t);case 41:return iy(t);case 42:return Th(t);case 6:case 273:case 33:case 132:return Nh(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Th(t);case 421:return US(t);case 444:return HS(t);case 445:return $S(t);case 466:return FS(t);case 481:return Th(globalThis.decodeURIComponent(t));default:return L(t,"base16")}}var kh=Object.values(ni).map(r=>r.decoder),DS=function(){let r=kh[0].or(kh[1]);return kh.slice(2).forEach(t=>r=r.or(t)),r}();function iy(r){if(!Cc(r))throw new Error("invalid ip address");return Ah(r)}function OS(r){let t=oy(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Cc(t))throw new Error("invalid ip address");return t}function Nh(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function ay(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Th(r){let t=L(r),e=Uint8Array.from(Xn(t.length));return ut([e,t],e.length+t.length)}function Bh(r){let t=mn(r);if(r=r.slice(oe(t)),r.length!==t)throw new Error("inconsistent lengths");return G(r)}function US(r){let t;r[0]==="Q"||r[0]==="1"?t=wt(X.decode(`z${r}`)).bytes:t=P.parse(r).multihash.bytes;let e=Uint8Array.from(Xn(t.length));return ut([e,t],e.length+t.length)}function FS(r){let t=DS.decode(r),e=Uint8Array.from(Xn(t.length));return ut([e,t],e.length+t.length)}function MS(r){let t=mn(r),e=r.slice(oe(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+G(e,"base64url")}function VS(r){let t=mn(r),e=r.slice(oe(t));if(e.length!==t)throw new Error("inconsistent lengths");return G(e,"base58btc")}function HS(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=vt.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Nh(n);return ut([e,o],e.length+o.length)}function $S(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=vt.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Nh(n);return ut([e,o],e.length+o.length)}function sy(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=G(t,"base32"),o=ay(e);return`${n}:${o}`}function cy(r){r=Ph(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<o.length;i++){let s=o[i],a=Z(s);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=o.length)throw uy("invalid address: "+r);if(a.path===!0){n=Ph(o.slice(i).join("/")),t.push([a.code,Rh(a.code,n)]),e.push([a.code,n]);break}let c=Rh(a.code,o[i]);t.push([a.code,c]),e.push([a.code,Ch(a.code,c)])}return{string:ly(e),bytes:Dh(t),tuples:t,stringTuples:e,path:n}}function Lh(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let i=mn(r,o),s=oe(i),a=Z(i),c=zS(a,r.slice(o+s));if(c===0){t.push([i]),e.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw uy("Invalid address Uint8Array: "+G(r,"base16"));t.push([i,l]);let u=Ch(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:ly(e),tuples:t,stringTuples:e,path:n}}function ly(r){let t=[];return r.map(e=>{let n=Z(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Ph(t.join("/"))}function Dh(r){return ut(r.map(t=>{let e=Z(t[0]),n=Uint8Array.from(Xn(e.code));return t.length>1&&t[1]!=null&&(n=ut([n,t[1]])),n}))}function zS(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=mn(t instanceof Uint8Array?t:Uint8Array.from(t));return e+oe(e)}}function Ph(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function uy(r){return new Error("Error parsing address: "+r)}var qS=Symbol.for("nodejs.util.inspect.custom"),Uh=Symbol.for("@multiformats/js-multiaddr/multiaddr"),KS=[Z("dns").code,Z("dns4").code,Z("dns6").code,Z("dnsaddr").code],Oh=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Oc=class r{bytes;#t;#r;#o;#c;[Uh]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Lh(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=cy(t)}else if(hy(t))e=Lh(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#r=e.tuples,this.#o=e.stringTuples,this.#c=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="",s=Z("tcp"),a=Z("udp"),c=Z("ip4"),l=Z("ip6"),u=Z("dns6"),f=Z("ip6zone");for(let[h,m]of this.stringTuples())h===f.code&&(i=`%${m??""}`),KS.includes(h)&&(e=s.name,o=443,n=`${m??""}${i}`,t=h===u.code?6:4),(h===s.code||h===a.code)&&(e=Z(h).name,o=parseInt(m??"")),(h===c.code||h===l.code)&&(e=Z(h).name,n=`${m??""}${i}`,t=h===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#r.map(([t])=>Object.assign({},Z(t)))}protoCodes(){return this.#r.map(([t])=>t)}protoNames(){return this.#r.map(([t])=>Z(t).name)}tuples(){return this.#r}stringTuples(){return this.#o}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Dh(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Fo.p2p.code&&t.push([n,o]),n===Fo["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?G(X.decode(`z${n}`),"base58btc"):G(P.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#c}equals(t){return Y(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=fy.get(e.name);if(n==null)throw new Oh(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>Lr(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[qS](){return`Multiaddr(${this.#t})`}};var fy=new Map;function hy(r){return!!r?.[Uh]}function Lr(r){return new Oc(r)}var GS=[Z("tcp").code,Z("dns").code,Z("dnsaddr").code,Z("dns4").code,Z("dns6").code];function dy(r){return gy("sni",r)?.[1]}function py(r){let t=gy("tcp",r)?.[1];return t==null?"":`:${t}`}function gy(r,t){let e;try{e=Z(r).code}catch{return}for(let[n,o]of t)if(n===e&&o!=null)return[n,o]}function my(r){return r.some(([t,e])=>t===Z("tls").code)}function me(r,t,e){let n=yy[Z(r).name];if(n==null)throw new Error(`Can't interpret protocol ${Z(r).name}`);let o=n(t,e);return r===Z("ip6").code?`[${o}]`:o}var yy={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${me(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${me(e[0],e[1]??"",t)}:${r}`},dnsaddr:(r,t)=>r,dns4:(r,t)=>r,dns6:(r,t)=>r,dns:(r,t)=>r,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/ipfs/${r}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p/${r}`},http:(r,t)=>{let e=my(t),n=dy(t),o=py(t);if(e&&n!=null)return`https://${n}${o}`;let i=e?"https://":"http://",s=t.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=me(s[0],s[1]??"",t);return a=a.replace("tcp://",""),`${i}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=me(e[0],e[1]??"",t),o=decodeURIComponent(r);return`${n}/${o}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return me(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return me(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=me(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=my(t),n=dy(t),o=py(t);if(e&&n!=null)return`wss://${n}${o}`;let i=e?"wss://":"ws://",s=t.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=me(s[0],s[1]??"",t);return a=a.replace("tcp://",""),`${i}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=me(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p-webrtc-direct`}};function wy(r,t){let n=Lr(r).stringTuples(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=Z(o[0]),s=yy[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return t?.assumeHttp!==!1&&GS.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var Uc=class{url;#t=0;#r=0;#o=0;#c=0;#g=new Map;log;constructor(t,e){this.url=t instanceof URL?t:new URL(t),this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#S(t){let e=t.multihash.bytes;return se.encode(e)}async getRawBlock(t,e){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${t.toString()}`,n.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let o=this.#S(t),i=new AbortController,s=()=>{i.abort()};e?.addEventListener("abort",s);try{let a=this.#g.get(o);return a==null&&(this.#t++,a=fetch(n.toString(),{signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#r++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#c++,new Uint8Array(await c.arrayBuffer())}),this.#g.set(o,a)),await a}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#r++,new Error(`unable to fetch raw block for CID ${t}`))}finally{e?.removeEventListener("abort",s),this.#g.delete(o)}}reliability(){return this.#t===0?1:this.#o>0?-1/0:this.#c/(this.#t+this.#r*3)}incrementInvalidBlocks(){this.#o++}getStats(){return{attempts:this.#t,errors:this.#r,invalidBlocks:this.#o,successes:this.#c,pendingResponses:this.#g.size}}};function WS(r,t,e){return r.filter(n=>{if(ty.matches(n)||t&&Q0.matches(n))return e||G0.matches(n)?!0:K0(n.toOptions().host)===!1;if(!t&&e){let{host:o}=n.toOptions();if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*Fc(r,t,e,n,o,i){for await(let s of t.findProviders(r,i)){let a=WS(s.multiaddrs,n,o);if(a.length===0)continue;let c=wy(a[0]);yield new Uc(c,e)}}var Fh=class extends Hi{routing;allowInsecure;allowLocal;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Mc,this.allowLocal=e.allowLocal??Vc}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let o=await e.getRawBlock(t,n.signal);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(o),o}async*findNewProviders(t,e={}){yield*Fc(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}};function by(r,t){return new Fh(r,t)}var Hc=class{allowInsecure;allowLocal;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??Mc,this.allowLocal=e.allowLocal??Vc}async retrieve(t,e={}){let n=[];for await(let o of Fc(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)){this.log("getting block for %c from %s",t,o.url);try{let i=await o.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s",t,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",t,o.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return by({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure})}};var Mc=!1,Vc=!1;function Gi(r={}){return t=>new Hc(t,r)}W.formatters.b=r=>r==null?"undefined":X.baseEncode(r);W.formatters.t=r=>r==null?"undefined":vt.baseEncode(r);W.formatters.m=r=>r==null?"undefined":se.baseEncode(r);W.formatters.p=r=>r==null?"undefined":r.toString();W.formatters.c=r=>r==null?"undefined":r.toString();W.formatters.k=r=>r==null?"undefined":r.toString();W.formatters.a=r=>r==null?"undefined":r.toString();W.formatters.e=r=>r==null?"undefined":xy(r.stack)??xy(r.message)??r.toString();function jS(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function Ce(r){let t=jS(`${r}:trace`);return W.enabled(`${r}:trace`)&&W.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=W(`${r}:trace`)),Object.assign(W(r),{error:W(`${r}:error`),trace:t})}function xy(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}async function*$c(r,t={}){let e=r.getReader();try{for(;;){let n=await e.read();if(n.done)return;yield n.value}}finally{t.preventCancel!==!0&&await e.cancel(),e.releaseLock()}}var t_=Ut(Mo(),1);var ze=class extends Error{static name="SignatureVerificationError";constructor(t="Record signature verification failed"){super(t),this.name="SignatureVerificationError"}},zc=class extends Error{static name="RecordExpiredError";constructor(t="Record has expired"){super(t),this.name="RecordExpiredError"}},Vo=class extends Error{static name="UnsupportedValidityError";constructor(t="The validity type is unsupported"){super(t),this.name="UnsupportedValidityError"}},qc=class extends Error{static name="RecordTooLargeError";constructor(t="The record is too large"){super(t),this.name="RecordTooLargeError"}},Kc=class extends Error{static name="InvalidValueError";constructor(t="Value must be a valid content path starting with /"){super(t),this.name="InvalidValueError"}},Gc=class extends Error{static name="InvalidRecordDataError";constructor(t="Invalid record data"){super(t),this.name="InvalidRecordDataError"}},Wi=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(t="Invalid embedded public key"){super(t),this.name="InvalidEmbeddedPublicKeyError"}};var qe;(function(r){let t;(function(o){o.EOL="EOL"})(t=r.ValidityType||(r.ValidityType={}));let e;(function(o){o[o.EOL=0]="EOL"})(e||(e={})),function(o){o.codec=()=>dr(e)}(t=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=le((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ce(o,r.codec()),r.decode=(o,i)=>ie(o,r.codec(),i)})(qe||(qe={}));var YS=Ce("ipns:utils"),Ey=L("/ipns/");var XS=0,ZS=18;function vy(r){let t;if(r.pubKey!=null)try{t=Ra(r.pubKey)}catch(e){throw YS.error(e),e}if(t!=null)return t}function Sy(r){let t=L("ipns-signature:");return ut([t,r])}function Un(r){return"signatureV1"in r?qe.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}):qe.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function ir(r){let t=qe.decode(r);if(t.sequence!=null&&(t.sequence=BigInt(t.sequence)),t.ttl!=null&&(t.ttl=BigInt(t.ttl)),t.signatureV2==null||t.data==null)throw new ze("Missing data or signatureV2");let e=_y(t.data),n=JS(e.Value),o=G(e.Validity);if(t.value!=null&&t.signatureV1!=null)return QS(t),{value:n,validityType:qe.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV1:t.signatureV1,signatureV2:t.signatureV2,data:t.data};if(t.signatureV2!=null)return{value:n,validityType:qe.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV2:t.signatureV2,data:t.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function ji(r){return ut([Ey,r.bytes])}function Dr(r){let t=wt(r.slice(Ey.length));if(!Wc(t,XS)&&!Wc(t,ZS))throw new _e("Multihash in IPNS key was not identity or sha2-256");return t}function _y(r){let t=Ht(r);if(t.ValidityType===0)t.ValidityType=qe.ValidityType.EOL;else throw new Vo("The validity type is unsupported");return Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function JS(r){let t=G(r).trim();if(t.startsWith("/"))return t;try{return`/ipfs/${P.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${P.parse(t).toV1().toString()}`}catch{}throw new Kc("Value must be a valid content path starting with /")}function QS(r){if(r.data==null)throw new Gc("Record data is missing");let t=_y(r.data);if(!Y(t.Value,r.value??new Uint8Array(0)))throw new ze('Field "value" did not match between protobuf and CBOR');if(!Y(t.Validity,r.validity??new Uint8Array(0)))throw new ze('Field "validity" did not match between protobuf and CBOR');if(t.ValidityType!==r.validityType)throw new ze('Field "validityType" did not match between protobuf and CBOR');if(t.Sequence!==r.sequence)throw new ze('Field "sequence" did not match between protobuf and CBOR');if(t.TTL!==r.ttl)throw new ze('Field "ttl" did not match between protobuf and CBOR')}function Wc(r,t){return r.code===t}var S5=Ce("ipns"),_5=60*60*1e9,e_="/ipns/",A5=e_.length;var Ay=Ut(Mo(),1);var jc=Ce("ipns:validator"),r_=1024*10,n_=async(r,t)=>{let e=ir(t),n;try{let o=Sy(e.data);n=await r.verify(o,e.signatureV2)}catch{n=!1}if(!n)throw jc.error("record signature verification failed"),new ze("Record signature verification failed");if(e.validityType===qe.ValidityType.EOL){if(Ay.default.fromString(e.validity).toDate().getTime()<Date.now())throw jc.error("record has expired"),new zc("record has expired")}else if(e.validityType!=null)throw jc.error("the validity type is unsupported"),new Vo("The validity type is unsupported");jc("ipns record for %s is valid",e.value)};async function Iy(r,t){if(t.byteLength>r_)throw new qc("The record is too large");let e=Dr(r),n;Wc(e,0)&&(n=rn(e));let o=ir(t),i=vy(o)??n;if(i==null)throw new Wi("Could not extract public key from IPNS record or routing key");let s=ji(i.toMultihash());if(!Y(r,s))throw new Wi("Embedded public key did not match routing key");await n_(i,t)}async function*Yi(r){let t=/\r?\n/,e=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=e.decode(o,{stream:!0});let i=n.split(t);n=i.pop()??"";for(let s=0;s<i.length;s++)yield JSON.parse(i[s])}n+=e.decode(),n!==""&&(yield JSON.parse(n))}var Ho=class extends Error{static name="InvalidRequestError";constructor(t="Invalid request"){super(t),this.name="InvalidRequestError"}},Fn=class extends Error{static name="BadResponseError";constructor(t="Bad response"){super(t),this.name="BadResponseError"}};function o_(r){return r[Symbol.asyncIterator]!=null}function i_(r){if(o_(r))return(async()=>{for await(let t of r)return t})();for(let t of r)return t}var Yc=i_;var ky=L("/ipns/");function Ty(r){return Y(r.subarray(0,ky.byteLength),ky)}var Xc=class{client;constructor(t){this.client=t}async*findProviders(t,e={}){yield*qt(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async cancelReprovide(){}async put(t,e,n){if(!Ty(t))return;let o=Dr(t),i=P.createV1(114,o),s=ir(e);await this.client.putIPNS(i,s,n)}async get(t,e){if(!Ty(t))throw new kt("Not found");let n=Dr(t),o=P.createV1(114,n);try{let i=await this.client.getIPNS(o,e);return Un(i)}catch(i){throw i.name==="BadResponseError"?new kt("Not found"):i}}},Zc=class{client;constructor(t){this.client=t}async findPeer(t,e={}){let n=await Yc(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new kt("Not found")}async*getClosestPeers(t,e={}){}};var Dt=Ce("delegated-routing-v1-http-api-client"),Vh={concurrentRequests:4,timeout:3e4,cacheTTL:5*60*1e3},Jc=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cache;cacheTTL;constructor(t,e={}){this.started=!1,this.shutDownController=new AbortController,mt(1/0,this.shutDownController.signal),this.httpQueue=new de({concurrency:e.concurrentRequests??Vh.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=t instanceof URL?t:new URL(t),this.timeout=e.timeout??Vh.timeout,this.filterAddrs=e.filterAddrs,this.filterProtocols=e.filterProtocols,this.contentRouting=new Xc(this),this.peerRouting=new Zc(this),this.cacheTTL=e.cacheTTL??Vh.cacheTTL,typeof globalThis.caches<"u"&&this.cacheTTL>0&&(Dt("cache enabled with ttl %d",this.cacheTTL),globalThis.caches.open("delegated-routing-v1-cache").then(o=>{this.cache=o}).catch(()=>{this.cache=void 0}))}get[Zo](){return this.contentRouting}get[Jo](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1,this.cache!=null&&this.cache.delete("delegated-routing-v1-cache")}async*getProviders(t,e={}){Dt("getProviders starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Zt([this.shutDownController.signal,n,e.signal]);mt(1/0,n,o);let i=ht(),s=ht();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${t.toString()}`);this.#r(a,e.filterAddrs,e.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#o(a.toString(),c);if(l.status===404)throw new kt("No matching records found");if(l.status===422)throw new Ho("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Fn("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Providers){let h=this.#t(d);h!=null&&(yield h)}}else for await(let f of Yi($c(l.body))){let d=this.#t(f);d!=null&&(yield d)}}catch(a){Dt.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),Dt("getProviders finished: %c",t)}}async*getPeers(t,e={}){Dt("getPeers starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Zt([this.shutDownController.signal,n,e.signal]);mt(1/0,n,o);let i=ht(),s=ht();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${t.toCID().toString()}`);this.#r(a,e.filterAddrs,e.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#o(a.toString(),c);if(l.status===404)throw new kt("No matching records found");if(l.status===422)throw new Ho("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Fn("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Peers){let h=this.#t(d);h!=null&&(yield h)}}else for await(let f of Yi($c(l.body))){let d=this.#t(f);d!=null&&(yield d)}}catch(a){Dt.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),Dt("getPeers finished: %c",t)}}async getIPNS(t,e={}){Dt("getIPNS starts: %s",t);let n=AbortSignal.timeout(this.timeout),o=Zt([this.shutDownController.signal,n,e.signal]);mt(1/0,n,o);let i=ht(),s=ht();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${t}`;try{await i.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o},l=await this.#o(a,c);if(Dt("getIPNS GET %s %d",a,l.status),l.status===404)throw new kt("No matching records found");if(l.status===422)throw new Ho("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Fn("GET ipns response had no body");let u=await l.arrayBuffer(),f=new Uint8Array(u,0,u.byteLength);return e.validate!==!1&&await Iy(ji(t.multihash),f),ir(f)}catch(c){throw Dt.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),Dt("getIPNS finished: %s",t)}}async putIPNS(t,e,n={}){Dt("putIPNS starts: %c",t);let o=AbortSignal.timeout(this.timeout),i=Zt([this.shutDownController.signal,o,n.signal]);mt(1/0,o,i);let s=ht(),a=ht();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${t}`;try{await s.promise;let l=Un(e),u={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i},f=await this.#o(c,u);if(Dt("putIPNS PUT %s %d",c,f.status),f.status!==200)throw new Fn("PUT ipns response had status other than 200")}catch(l){throw Dt.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),Dt("putIPNS finished: %c",t)}}#t(t){try{let e=[],n=t.Addrs?.map(Lr)??[];return t.Protocols!=null&&e.push(...t.Protocols),t.Protocol!=null&&(e.push(t.Protocol),delete t.Protocol),{...t,Schema:"peer",ID:wo(t.ID),Addrs:n,Protocols:e}}catch(e){Dt.error("could not conform record to peer schema",e)}}#r(t,e,n){if(e!=null||this.filterAddrs!=null){let o=e?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&t.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&t.searchParams.set("filter-protocols",o)}}async#o(t,e){let n=e.method??"GET",o=`${n}-${t}`;if(n==="GET"){let c=await this.cache?.match(t);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return Dt("returning cached response for %s",o),c;await this.cache?.delete(t)}}let i=this.inFlightRequests.get(o);if(i!=null){let c=await i;return Dt("deduplicating outgoing request for %s",o),c.clone()}let s=fetch(t,e).then(async c=>{if(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 f=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(t,f)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,s),await s}};function By(r,t={}){return new Jc(new URL(r),t)}function Cy(){return{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss"]}}var Ry=L("/ipns/");function Ny(r){return Y(r.subarray(0,Ry.byteLength),Ry)}var Hh=class{client;constructor(t,e={}){this.client=By(t,e)}async provide(t,e){}async*findProviders(t,e){yield*qt(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols}))}async put(t,e,n){if(!Ny(t))return;let o=Dr(t),i=P.createV1(114,o),s=ir(e);await this.client.putIPNS(i,s,n)}async get(t,e){if(!Ny(t))throw new kt("Not found");let n=Dr(t),o=P.createV1(114,n);try{let i=await this.client.getIPNS(o,e);return Un(i)}catch(i){throw i.name==="BadResponseError"?new kt("Not found"):i}}async findPeer(t,e){let n=await Yc(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new kt("Not found")}async*getClosestPeers(t,e){}};function Xi(r,t){let e=t??Cy();return new Hh(new URL(r),e)}var Py="[a-fA-F\\d:]",ln=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Py})|(?<=${Py})(?=\\s|$))`:"",Ke="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",At="[a-fA-F\\d]{1,4}",Qc=`
|
|
8
8
|
(?:
|
|
9
|
-
(?:${
|
|
10
|
-
(?:${
|
|
11
|
-
(?:${
|
|
12
|
-
(?:${
|
|
13
|
-
(?:${
|
|
14
|
-
(?:${
|
|
15
|
-
(?:${
|
|
16
|
-
(?::(?:(?::${
|
|
9
|
+
(?:${At}:){7}(?:${At}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
10
|
+
(?:${At}:){6}(?:${Ke}|:${At}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
|
|
11
|
+
(?:${At}:){5}(?::${Ke}|(?::${At}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
|
|
12
|
+
(?:${At}:){4}(?:(?::${At}){0,1}:${Ke}|(?::${At}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
|
|
13
|
+
(?:${At}:){3}(?:(?::${At}){0,2}:${Ke}|(?::${At}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
|
|
14
|
+
(?:${At}:){2}(?:(?::${At}){0,3}:${Ke}|(?::${At}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
|
|
15
|
+
(?:${At}:){1}(?:(?::${At}){0,4}:${Ke}|(?::${At}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
16
|
+
(?::(?:(?::${At}){0,5}:${Ke}|(?::${At}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
17
17
|
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
18
|
-
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),$S=new RegExp(`(?:^${qe}$)|(?:^${jc}$)`),zS=new RegExp(`^${qe}$`),qS=new RegExp(`^${jc}$`),Ph=r=>r&&r.exact?$S:new RegExp(`(?:${ln(r)}${qe}${ln(r)})|(?:${ln(r)}${jc}${ln(r)})`,"g");Ph.v4=r=>r&&r.exact?zS:new RegExp(`${ln(r)}${qe}${ln(r)}`,"g");Ph.v6=r=>r&&r.exact?qS:new RegExp(`${ln(r)}${jc}${ln(r)}`,"g");var Dh=Ph;function Oh(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function Ey(){return!1}var{toString:KS}=Object.prototype;function Uh(r){return KS.call(r)==="[object RegExp]"}var vy={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Fh(r,t={}){if(!Uh(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(vy).map(o=>(typeof t[o]=="boolean"?t[o]:r[o])?vy[o]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function Mh(r,t,{timeout:e}={}){try{return Oh(()=>Fh(r).test(t),{timeout:e})()}catch(n){if(Ey(n))return!1;throw n}}var GS=15,WS=45,Sy={timeout:400};function Vh(r){return r.length>WS?!1:Mh(Dh.v6({exact:!0}),r,Sy)}function Ay(r){return r.length>GS?!1:Mh(Dh.v4({exact:!0}),r,Sy)}var Iy={http:"80",https:"443",ws:"80",wss:"443"},jS=["http","https","ws","wss"];function ky(r,t){t=t??{};let e=t.defaultDnsType??"dns4",{scheme:n,hostname:o,port:i}=YS(r),a="/"+[XS(o,e),ZS(i,n),JS(n)].filter(c=>!!c).reduce((c,l)=>c.concat(l),[]).join("/");return Pr(a)}function YS(r){let[t]=r.split(":");jS.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:o}=new URL(r);if(o==null||o===""){let i=QS(t);i!=null&&(o=i),i==null&&e==="http:"&&(o="80")}return{scheme:t,hostname:n,port:o}}function XS(r,t){if(!(r==null||r==="")){if(Ay(r))return["ip4",r];if(Vh(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(Vh(e))return["ip6",e]}return[t,r]}}function ZS(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function JS(r){if(r.match(/^tcp$|^udp$/)==null)return[r]}function QS(r){if(!(r==null||r===""||Iy[r]==null))return Iy[r]}var tA=["https://trustless-gateway.link","https://4everland.io"],eA=2336;function rA(r){return r=r.toString(),{id:Ta(L.createV1(eA,bt.digest(D(r)))),multiaddrs:[ky(r)]}}var Hh=class{gateways;constructor(t={}){this.gateways=(t.gateways??tA).map(e=>rA(e))}async*findProviders(t,e){yield*this.gateways.toSorted(()=>Math.random()>.5?1:-1).map(n=>({...n,protocols:["transport-ipfs-gateway-http"]}))}};function Gi(r={}){return new Hh(r)}var Dn=class{has(t,e){return Promise.reject(new Error(".has is not implemented"))}put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(t,e){for await(let{cid:n,block:o}of t)await this.put(n,o,e),yield n}get(t,e){return Promise.reject(new Error(".get is not implemented"))}async*getMany(t,e){for await(let n of t)yield{cid:n,block:await this.get(n,e)}}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(t,e){for await(let n of t)await this.delete(n,e),yield n}async*getAll(t){throw new Error(".getAll is not implemented")}};var ir=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};var Wi=class extends Dn{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(St.encode(t.multihash.bytes),e),t}get(t){let e=this.data.get(St.encode(t.multihash.bytes));if(e==null)throw new ir;return e}has(t){return this.data.has(St.encode(t.multihash.bytes))}async delete(t){this.data.delete(St.encode(t.multihash.bytes))}async*getAll(){for(let[t,e]of this.data.entries())yield{cid:L.createV1(ae,wt(St.decode(t))),block:e}}};var U5=Ce("blockstore:core:tiered");var Ty="SHARDING";function oA(r){return r[Symbol.asyncIterator]!=null}function iA(r){if(oA(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var $h=iA;function sA(r){return r[Symbol.asyncIterator]!=null}function aA(r,t){return sA(r)?async function*(){yield*(await $h(r)).sort(t)}():function*(){yield*$h(r).sort(t)}()}var Yc=aA;var Or=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await ur(this.putMany(t,n)),t=[],await ur(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=ve(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,i)=>ve(o,i),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,i)=>Yc(o,i),n)),t.offset!=null){let o=0,i=t.offset;n=ve(n,()=>o++>=i)}return t.limit!=null&&(n=ds(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=ve(n,i=>i.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,i)=>ve(o,i),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,i)=>Yc(o,i),n)),t.offset!=null){let o=t.offset,i=0;n=ve(n,()=>i++>=o)}return t.limit!=null&&(n=ds(n,t.limit)),n}};var ji=class extends Or{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new ir;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new At(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new At(t)}};var gO=new At(Ty);var CO=Ce("datastore:core:tiered");async function Ry(r={}){let t=r.datastore??new ji,e=r.blockstore??new Wi,n=new vc({...r,datastore:t,blockstore:e,blockBrokers:r.blockBrokers??[Hi()],routers:r.routers??[Ki("https://delegated-ipfs.dev"),Gi()]});return r.start!==!1&&await n.start(),n}var Kh=Ot(Xc(),1);var Gh=40;function Wh(r,t){if(!r.length)throw new Error("Unexpected end of data");let e=Kh.default.decode(r);return t.seek(Kh.default.decode.bytes),e}function jh(r){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),e=0;return{version:2,characteristics:[t.getBigUint64(e,!0),t.getBigUint64(e+=8,!0)],dataOffset:Number(t.getBigUint64(e+=8,!0)),dataSize:Number(t.getBigUint64(e+=8,!0)),indexOffset:Number(t.getBigUint64(e+=8,!0))}}var un={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},Yi={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":un.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(un.List(r)!==void 0){for(let t=0;t<r.length;t++){let e=r[t];if(e=Yi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](e),e===void 0)return;if(e!==r[t]){let n=r.slice(0,t);for(let o=t;o<r.length;o++){let i=r[o];if(i=Yi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:un.Int,CarV1HeaderOrV2Pragma:r=>{if(un.Map(r)===void 0)return;let t=Object.entries(r),e=r,n=1;for(let o=0;o<t.length;o++){let[i,s]=t[o];switch(i){case"roots":{let a=Yi["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.roots=a}}break;case"version":{n--;let a=Yi.Int(r[i]);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.version=a}}break;default:return}}if(!(n>0))return e}},Xi={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":un.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(un.List(r)!==void 0){for(let t=0;t<r.length;t++){let e=r[t];if(e=Xi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](e),e===void 0)return;if(e!==r[t]){let n=r.slice(0,t);for(let o=t;o<r.length;o++){let i=r[o];if(i=Xi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:un.Int,CarV1HeaderOrV2Pragma:r=>{if(un.Map(r)===void 0)return;let t=Object.entries(r),e=r,n=1;for(let o=0;o<t.length;o++){let[i,s]=t[o];switch(i){case"roots":{let a=Xi["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.roots=a}}break;case"version":{n--;let a=Xi.Int(s);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.version=a}}break;default:return}}if(!(n>0))return e}},Yh={toTyped:Yi.CarV1HeaderOrV2Pragma,toRepresentation:Xi.CarV1HeaderOrV2Pragma};var mU=Df();var AA=Ot(Xc(),1);var xU=[new B(w.map,2),new B(w.string,"version"),new B(w.uint,1),new B(w.string,"roots")],EU=new B(w.tag,42);async function Xh(r,t){let e=Wh(await r.upTo(8),r);if(e===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(e,!0),o=cn(n);if(Yh.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||t!==void 0&&o.version!==t)throw new Error(`Invalid CAR version: ${o.version}${t!==void 0?` (expected ${t})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=jh(await r.exactly(Gh,!0));r.seek(i.dataOffset-r.pos);let s=await Xh(r,1);return Object.assign(s,i)}function Zi(r){let t=0;return{async upTo(e){return r.subarray(t,t+Math.min(e,r.length-t))},async exactly(e,n=!1){if(e>r.length-t)throw new Error("Unexpected end of data");let o=r.subarray(t,t+e);return n&&(t+=e),o},seek(e){t+=e},get pos(){return t}}}var Zh=Ot(Xc(),1),zy=1;function Jh(r){let t=Ao({version:zy,roots:r}),e=Zh.default.encode(t.length),n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function qy(r){return{async setRoots(t){let e=Jh(t);await r.write(e)},async writeBlock(t){let{cid:e,bytes:n}=t;await r.write(new Uint8Array(Zh.default.encode(e.bytes.length+n.length))),await r.write(e.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return zy}}}function Zc(){}function Ky(){let r=[],t=null,e=Zc,n=!1,o=null,i=Zc,s=()=>(t||(t=new Promise(l=>{e=()=>{t=null,e=Zc,l()}})),t),a={write(l){r.push(l);let u=s();return i(),u},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&e(),{done:!1,value:l}):n?(e(),{done:!0,value:void 0}):(o||(o=new Promise(u=>{i=()=>(o=null,i=Zc,u(c.next()))})),o)}};return{writer:a,iterator:c}}var Ji=class r{constructor(t,e){this._encoder=e,this._mutex=e.setRoots(t),this._ended=!1}async put(t){if(!(t.bytes instanceof Uint8Array)||!t.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let e=L.asCID(t.cid);if(!e)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:e,bytes:t.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(t){t=BA(t);let{encoder:e,iterator:n}=Gy(),o=new r(t,e),i=new Jc(n);return{writer:o,out:i}}static createAppender(){let{encoder:t,iterator:e}=Gy();t.setRoots=()=>Promise.resolve();let n=new r([],t),o=new Jc(e);return{writer:n,out:o}}static async updateRootsInBytes(t,e){let n=Zi(t);await Xh(n);let o=Jh(e);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return t.set(o,0),t}},Jc=class{constructor(t){this._iterator=t}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function Gy(){let r=Ky(),{writer:t,iterator:e}=r;return{encoder:qy(t),iterator:e}}function BA(r){if(r===void 0)return[];if(!Array.isArray(r)){let e=L.asCID(r);if(!e)throw new TypeError("roots must be a single CID or an array of CIDs");return[e]}let t=[];for(let e of r){let n=L.asCID(e);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");t.push(n)}return t}var TA=1,Qh=class{components;constructor(t,e){this.components=t}async import(t,e){await ur(this.components.blockstore.putMany(zt(t.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),e))}async export(t,e,n){let o=ft(),i=Array.isArray(t)?t:[t],s=new de({concurrency:TA});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#t(a,s,async(c,l)=>{n?.blockFilter?.has(c.multihash.bytes)!==!0&&(n?.blockFilter?.add(c.multihash.bytes),await e.put({cid:c,bytes:l}))},n)}).catch(()=>{});try{await o.promise}finally{await e.close()}}async*stream(t,e){let{writer:n,out:o}=Ji.create(t);this.export(t,n,e).catch(()=>{});for await(let i of o)yield i}async#t(t,e,n,o){let i=await this.components.getCodec(t.code),s=await this.components.blockstore.get(t,o);await n(t,s);let a=rc({bytes:s,cid:t,codec:i});for await(let[,c]of a.links())e.add(async()=>{await this.#t(c,e,n,o)})}};function Wy(r,t={}){return new Qh(r,t)}W.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);W.formatters.t=r=>r==null?"undefined":St.baseEncode(r);W.formatters.m=r=>r==null?"undefined":se.baseEncode(r);W.formatters.p=r=>r==null?"undefined":r.toString();W.formatters.c=r=>r==null?"undefined":r.toString();W.formatters.k=r=>r==null?"undefined":r.toString();W.formatters.a=r=>r==null?"undefined":r.toString();W.formatters.e=r=>r==null?"undefined":jy(r.stack)??jy(r.message)??r.toString();function CA(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function fn(r){let t=CA(`${r}:trace`);return W.enabled(`${r}:trace`)&&W.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=W(`${r}:trace`)),Object.assign(W(r),{error:W(`${r}:error`),trace:t})}function jy(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var rw=Ot(Do(),1);var Qc=class extends Error{static name="SignatureCreationError";constructor(t="Record signature creation failed"){super(t),this.name="SignatureCreationError"}},Ke=class extends Error{static name="SignatureVerificationError";constructor(t="Record signature verification failed"){super(t),this.name="SignatureVerificationError"}},tl=class extends Error{static name="RecordExpiredError";constructor(t="Record has expired"){super(t),this.name="RecordExpiredError"}},On=class extends Error{static name="UnsupportedValidityError";constructor(t="The validity type is unsupported"){super(t),this.name="UnsupportedValidityError"}},el=class extends Error{static name="RecordTooLargeError";constructor(t="The record is too large"){super(t),this.name="RecordTooLargeError"}},Qi=class extends Error{static name="InvalidValueError";constructor(t="Value must be a valid content path starting with /"){super(t),this.name="InvalidValueError"}},rl=class extends Error{static name="InvalidRecordDataError";constructor(t="Invalid record data"){super(t),this.name="InvalidRecordDataError"}},ts=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(t="Invalid embedded public key"){super(t),this.name="InvalidEmbeddedPublicKeyError"}};var Ht;(function(r){let t;(function(o){o.EOL="EOL"})(t=r.ValidityType||(r.ValidityType={}));let e;(function(o){o[o.EOL=0]="EOL"})(e||(e={})),function(o){o.codec=()=>dr(e)}(t=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=le((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ce(o,r.codec()),r.decode=(o,i)=>ie(o,r.codec(),i)})(Ht||(Ht={}));var RA=fn("ipns:utils"),Yy=D("/ipns/"),NA=114,LA=0,PA=18;function Xy(r){let t;if(r.pubKey!=null)try{t=Ia(r.pubKey)}catch(e){throw RA.error(e),e}if(t!=null)return t}function Zy(r,t,e){let n=D(t);return ct([r,e,n])}function ol(r){let t=D("ipns-signature:");return ct([t,r])}function td(r){return"signatureV1"in r?Ht.encode({value:D(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:D(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Ht.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function sr(r){let t=Ht.decode(r);if(t.sequence!=null&&(t.sequence=BigInt(t.sequence)),t.ttl!=null&&(t.ttl=BigInt(t.ttl)),t.signatureV2==null||t.data==null)throw new Ke("Missing data or signatureV2");let e=tw(t.data),n=DA(e.Value),o=q(e.Validity);if(t.value!=null&&t.signatureV1!=null)return OA(t),{value:n,validityType:Ht.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV1:t.signatureV1,signatureV2:t.signatureV2,data:t.data};if(t.signatureV2!=null)return{value:n,validityType:Ht.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV2:t.signatureV2,data:t.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function Fo(r){return ct([Yy,r.bytes])}function Jy(r){let t=wt(r.slice(Yy.length));if(!nl(t,LA)&&!nl(t,PA))throw new Ae("Multihash in IPNS key was not identity or sha2-256");return t}function Qy(r,t,e,n,o){let i;if(t===Ht.ValidityType.EOL)i=0;else throw new On("The validity type is unsupported");return nr({Value:r,Validity:e,ValidityType:i,Sequence:n,TTL:o})}function tw(r){let t=Vt(r);if(t.ValidityType===0)t.ValidityType=Ht.ValidityType.EOL;else throw new On("The validity type is unsupported");return Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function DA(r){let t=q(r).trim();if(t.startsWith("/"))return t;try{return`/ipfs/${L.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${L.parse(t).toV1().toString()}`}catch{}throw new Qi("Value must be a valid content path starting with /")}function ew(r){if(r!=null){let t=MA(r);if(t!=null)return t.code===NA?`/ipns/${t.toString(Kt)}`:`/ipfs/${t.toV1().toString()}`;if(UA(r))return`/ipns/${Kt.encode(r.bytes)}`;let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e}throw new Qi("Value must be a valid content path starting with /")}function OA(r){if(r.data==null)throw new rl("Record data is missing");let t=tw(r.data);if(!Z(t.Value,r.value??new Uint8Array(0)))throw new Ke('Field "value" did not match between protobuf and CBOR');if(!Z(t.Validity,r.validity??new Uint8Array(0)))throw new Ke('Field "validity" did not match between protobuf and CBOR');if(t.ValidityType!==r.validityType)throw new Ke('Field "validityType" did not match between protobuf and CBOR');if(t.Sequence!==r.sequence)throw new Ke('Field "sequence" did not match between protobuf and CBOR');if(t.TTL!==r.ttl)throw new Ke('Field "ttl" did not match between protobuf and CBOR')}function UA(r){return r.bytes instanceof Uint8Array}function FA(r){return typeof r?.toCID=="function"}function MA(r){if(FA(r))return r.toCID();try{return L.parse(r)}catch{}return L.asCID(r)}function nl(r,t){return r.code===t}var VA=fn("ipns"),nw=60*60*1e9,HA="/ipns/",OF=HA.length,ow={v1Compatible:!0,ttlNs:nw};async function iw(r,t,e,n,o=ow){let i=new rw.default(Date.now()+Number(n)),s=Ht.ValidityType.EOL,a=BigInt(o.ttlNs??nw);return $A(r,t,e,s,i.toString(),a,o)}var $A=async(r,t,e,n,o,i,s=ow)=>{e=BigInt(e);let a=D(o),c=ew(t),l=D(c),u=Qy(l,n,a,e,i),f=ol(u),d=await r.sign(f),h;if(r.type==="RSA"&&(h=so(r.publicKey)),s.v1Compatible===!0){let m=await zA(r,l,n,a),p={value:c,signatureV1:m,validity:o,validityType:n,sequence:e,ttl:i,signatureV2:d,data:u};return h!=null&&(p.pubKey=h),p}else{let m={value:c,validity:o,validityType:n,sequence:e,ttl:i,signatureV2:d,data:u};return h!=null&&(m.pubKey=h),m}},zA=async(r,t,e,n)=>{try{let o=Zy(t,e,n);return await r.sign(o)}catch(o){throw VA.error("record signature creation failed",o),new Qc("Record signature creation failed")}};var ed=Ot(Do(),1);function sw(r,t){let e=t.map((n,o)=>({record:sr(n),index:o}));return e.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===Ht.ValidityType.EOL&&o.record.validityType===Ht.ValidityType.EOL){let a=ed.default.fromString(n.record.validity).toDate(),c=ed.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),e[0].index}var aw=Ot(Do(),1);var il=fn("ipns:validator"),qA=1024*10,KA=async(r,t)=>{let e=sr(t),n;try{let o=ol(e.data);n=await r.verify(o,e.signatureV2)}catch{n=!1}if(!n)throw il.error("record signature verification failed"),new Ke("Record signature verification failed");if(e.validityType===Ht.ValidityType.EOL){if(aw.default.fromString(e.validity).toDate().getTime()<Date.now())throw il.error("record has expired"),new tl("record has expired")}else if(e.validityType!=null)throw il.error("the validity type is unsupported"),new On("The validity type is unsupported");il("ipns record for %s is valid",e.value)};async function rd(r,t){if(t.byteLength>qA)throw new el("The record is too large");let e=Jy(r),n;nl(e,0)&&(n=rn(e));let o=sr(t),i=Xy(o)??n;if(i==null)throw new ts("Could not extract public key from IPNS record or routing key");let s=Fo(i.toMultihash());if(!Z(r,s))throw new ts("Embedded public key did not match routing key");await KA(i,t)}var cw=Symbol.for("nodejs.util.inspect.custom"),GA=114,es=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[$n]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return L.createV1(GA,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Z(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Z(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[cw](){return`PeerId(${this.toString()})`}},sl=class extends es{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},al=class extends es{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},cl=class extends es{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},WA=2336,ll=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=bt.digest(D(this.url))}[cw](){return`PeerId(${this.url})`}[$n]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return L.createV1(WA,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=q(t)),t.toString()===this.toString())}};function lw(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=wt(Y.decode(`z${r}`));else{if(t==null)throw new gt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=wt(t.decode(r))}return jA(e)}function jA(r){if(XA(r))return new sl({multihash:r});if(YA(r))try{let t=rn(r);if(t.type==="Ed25519")return new al({multihash:r,publicKey:t});if(t.type==="secp256k1")return new cl({multihash:r,publicKey:t})}catch{let e=q(r.digest);return new ll(new URL(e))}throw new Ae("Supplied PeerID Multihash is invalid")}function YA(r){return r.code===bt.code}function XA(r){return r.code===Xe.code}var ul=class extends Error{static name="DNSLinkNotFoundError";constructor(t="DNSLink not found"){super(t),this.name="DNSLinkNotFoundError"}},fl=class extends Error{static name="RecordsFailedValidationError";constructor(t="Records failed validation"){super(t),this.name="RecordsFailedValidationError"}},hl=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(t="Unsupported multibase prefix"){super(t),this.name="UnsupportedMultibasePrefixError"}},dl=class extends Error{static name="UnsupportedMultihashCodecError";constructor(t="Unsupported multihash codec"){super(t),this.name="UnsupportedMultihashCodecError"}},pl=class extends Error{static name="InvalidValueError";constructor(t="Invalid value"){super(t),this.name="InvalidValueError"}};var ZA=32;async function uw(r,t,e,n,o={}){if(t===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=((await e.query(r,{...o,types:[pe.TXT]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;n("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,f,d,...h]=u.split("/");if(f==="ipfs")try{return{value:`/ipfs/${L.parse(d)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}else if(f==="ipns"){try{return{value:`/ipns/${lw(d)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}return await ml(d,t-1,e,n,o)}else{if(f==="dnslink")return await ml(d,t-1,e,n,o);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(u){n.error("could not parse DNS link record for domain %s, %s",r,l.data,u)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=((await e.query(r,{...o,types:[pe.CNAME]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await ml(l.data,t-1,e,n,o)}catch(u){n.error("domain %s cname %s had no DNSLink records",r,l.data,u)}throw new ul(`No DNSLink records found for domain: ${r}`)}async function ml(r,t,e,n,o={}){if(t===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await uw(r,t,e,n,o)}catch(i){if(i.code!=="ENOTFOUND"&&i.code!=="ENODATA"&&i.name!=="DNSLinkNotFoundError"&&i.name!=="NotFoundError")throw i;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,uw(r,t,e,n,o)}}async function fw(r,t,e,n={}){return ml(r,n.maxRecursiveDepth??ZA,t,e,n)}var nd=class{routing;constructor(t){this.routing=t}async put(t,e,n={}){try{await this.routing.put(t,e,n)}catch(o){n.onProgress?.(new H("ipns:routing:helia:error",o))}}async get(t,e={}){try{return await this.routing.get(t,e)}catch(n){e.onProgress?.(new H("ipns:routing:helia:error",n))}throw new Error("Not found")}};function hw(r){return new nd(r)}var rs;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.key!=null&&e.key.byteLength>0&&(n.uint32(10),n.bytes(e.key)),e.value!=null&&e.value.byteLength>0&&(n.uint32(18),n.bytes(e.value)),e.timeReceived!=null&&e.timeReceived!==""&&(n.uint32(42),n.string(e.timeReceived)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={key:re(0),value:re(0),timeReceived:""},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.key=e.bytes();break}case 2:{i.value=e.bytes();break}case 5:{i.timeReceived=e.string();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>ce(e,r.codec()),r.decode=(e,n)=>ie(e,r.codec(),n)})(rs||(rs={}));function dw(r){let t=r.getUTCFullYear(),e=String(r.getUTCMonth()+1).padStart(2,"0"),n=String(r.getUTCDate()).padStart(2,"0"),o=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${t}-${e}-${n}T${o}:${i}:${s}.${c}Z`}function pw(r){let t=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),e=String(r).trim().match(t);if(e==null)throw new Error("Invalid format");let n=parseInt(e[1],10),o=parseInt(e[2],10)-1,i=parseInt(e[3],10),s=parseInt(e[4],10),a=parseInt(e[5],10),c=parseInt(e[6],10),l=parseInt(e[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,l))}var ar=class r{key;value;timeReceived;constructor(t,e,n){if(!(t instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(e instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=t,this.value=e,this.timeReceived=n}serialize(){return rs.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:dw(this.timeReceived)}}static deserialize(t){let e=rs.decode(t);return new r(e.key,e.value,new Date(e.timeReceived))}static fromDeserialized(t){let e=pw(t.timeReceived);if(t.key==null)throw new Error("key missing from deserialized object");if(t.value==null)throw new Error("value missing from deserialized object");return new r(t.key,t.value,e)}};var gl=globalThis.CustomEvent??Event;async function*Un(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered==null?!1:t.ordered,o=new EventTarget,i=[],s=ft(),a=ft(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(i.length===e&&(s=ft(),await s.promise),u)break;let p={done:!1};i.push(p),m().then(y=>{p.done=!0,p.ok=!0,p.value=y,o.dispatchEvent(new gl("task-complete"))},y=>{p.done=!0,p.err=y,o.dispatchEvent(new gl("task-complete"))})}c=!0,o.dispatchEvent(new gl("task-complete"))}catch(m){l=m,o.dispatchEvent(new gl("task-complete"))}});function f(){return n?i[0]?.done:!!i.find(m=>m.done)}function*d(){for(;i.length>0&&i[0].done;){let m=i[0];if(i.shift(),m.ok)yield m.value;else throw u=!0,s.resolve(),m.err;s.resolve()}}function*h(){for(;f();)for(let m=0;m<i.length;m++)if(i[m].done){let p=i[m];if(i.splice(m,1),m--,p.ok)yield p.value;else throw u=!0,s.resolve(),p.err;s.resolve()}}for(;;){if(f()||(a=ft(),await a.promise),l!=null)throw l;if(n?yield*d():yield*h(),c&&i.length===0)break}}var mw;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER"})(mw||(mw={}));function yl(r){return new At("/dht/record/"+q(r,"base32"),!1)}function gw(r){return{async put(t,e,n={}){try{let o=yl(t);try{let s=await r.get(o),a=ar.deserialize(s);if(Z(a.value,e))return}catch(s){if(s.name!=="NotFoundError")throw s}let i=new ar(t,e,new Date);n.onProgress?.(new H("ipns:routing:datastore:put")),await r.put(o,i.serialize(),n)}catch(o){throw n.onProgress?.(new H("ipns:routing:datastore:error",o)),o}},async get(t,e={}){try{let n=yl(t);e.onProgress?.(new H("ipns:routing:datastore:get"));let o=await r.get(n,e),i=ar.deserialize(o);return{record:i.value,created:i.timeReceived}}catch(n){throw e.onProgress?.(new H("ipns:routing:datastore:error",n)),n}},async has(t,e={}){let n=yl(t);return r.has(n,e)},async delete(t,e){let n=yl(t);return r.delete(n,e)}}}function od(r,t){return r.code===t}var Ur=fn("helia:ipns"),eI=60*1e3,ad=60*eI,rI=24*ad,id=23*ad,nI=BigInt(ad)*1000000n,yw={[Kt.prefix]:Kt,[Y.prefix]:Y},sd=class{routers;localStore;timeout;dns;log;constructor(t,e=[]){this.routers=[hw(t.routing),...e],this.localStore=gw(t.datastore),this.dns=t.dns,this.log=t.logger.forComponent("helia:ipns")}async publish(t,e,n={}){try{let o=1n,i=Fo(t.publicKey.toMultihash());if(await this.localStore.has(i,n)){let{record:c}=await this.localStore.get(i,n);o=sr(c).sequence+1n}let s=await iw(t,e,o,n.lifetime??rI,n),a=td(s);return await this.localStore.put(i,a,n),n.offline!==!0&&await Promise.all(this.routers.map(async c=>{await c.put(i,a,n)})),s}catch(o){throw n.onProgress?.(new H("ipns:publish:error",o)),o}}async resolve(t,e={}){let n=Cd(t)?t.toMultihash():t,o=Fo(n),i=await this.#r(o,e);return{...await this.#t(i.value,e),record:i}}async resolveDNSLink(t,e={}){let n=await fw(t,this.dns,this.log,e);return{...await this.#t(n.value,e),answer:n.answer}}republish(t={}){if(this.timeout!=null)throw new Error("Republish is already running");t.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function e(){let n=Date.now();t.onProgress?.(new H("ipns:republish:start"));let i=Date.now()-n,s=id-i;s<0&&(s=t.interval??id),setTimeout(()=>{e().catch(a=>{Ur.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{e().catch(n=>{Ur.error("error republishing",n)})},t.interval??id)}async#t(t,e={}){let n=t.split("/");try{let o=n[1];if(o==="ipns"){let i=n[2],s=i.substring(0,1),a;if(s==="1"||s==="Q")a=Y.decode(`z${i}`);else if(yw[s]!=null)a=yw[s].decode(i);else throw new hl(`Unsupported multibase prefix "${s}"`);let c;try{c=wt(a)}catch{c=L.decode(a).multihash}if(!od(c,0)&&!od(c,18))throw new dl(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,e),u=n.slice(3).join("/");return{cid:l,path:u}}else if(o==="ipfs"){let i=L.parse(n[2]),s=n.slice(3).join("/");return{cid:i,path:s}}}catch(o){Ur.error("error parsing ipfs path",o)}throw Ur.error("invalid ipfs path %s",t),new pl("Invalid value")}async#r(t,e={}){let n=[];if(await this.localStore.has(t,e))if(Ur("record is present in the cache"),e.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(t,e);this.log("record retrieved from cache"),await rd(t,a),this.log("record was valid");let l=sr(a),u=Number((l.ttl??nI)/1000000n);if(c.getTime()+u>Date.now())return this.log("record TTL was valid"),l;if(e.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(t,e)}else Ur("ignoring local cache due to nocache=true option");if(e.offline===!0)throw new _t("Record was not present in the cache or has expired");Ur("did not have record locally");let i=0;if(await Promise.all(this.routers.map(async a=>{let c;try{c=await a.get(t,{...e,validate:!1})}catch(l){Ur.error("error finding IPNS record",l);return}try{await rd(t,c),n.push(c)}catch(l){i++,Ur.error("error finding IPNS record",l)}})),n.length===0)throw i>0?new fl(`${i>1?`${i} records`:"Record"} found for routing key ${i>1?"were":"was"} invalid`):new _t("Could not find record for routing key");let s=n[sw(t,n)];return await this.localStore.put(t,s,e),sr(s)}};function ww(r,{routers:t=[]}={}){return new sd(r,t)}var bw;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER"})(bw||(bw={}));function oI(r){return r[Symbol.asyncIterator]!=null}function iI(r){if(oI(r))return(async()=>{let e;for await(let n of r)e=n;return e})();let t;for(let e of r)t=e;return t}var xw=iI;var wl=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(t="Bad path"){super(t)}},Re=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not found"){super(t)}},bl=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(t="No resolver"){super(t)}},Ct=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(t="Not UnixFS"){super(t)}},xl=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(t="Over read"){super(t)}},El=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(t="Under read"){super(t)}},vl=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(t="No Property found"){super(t)}},Fn=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(t="Invalid parameters"){super(t)}};function Mo(r,t,e,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let u=L.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:o,cid:e,node:t,depth:s,size:BigInt(t.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:i}};a=a[l]}else throw new vl(`No property named ${l} found in node ${e}`)}return{entry:{type:"object",name:n,path:o,cid:e,node:t,depth:s,size:BigInt(t.length),content:async function*(){yield r}}}}var sI=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=cn(c);return Mo(l,c,r,t,e,n,i)},Ew=sI;var aI=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=ko(c);return Mo(l,c,r,t,e,n,i)},vw=aI;function cI(r,t,e,n){let o=BigInt(r.length),i=BigInt(t+o);return e>=i||n<t?new Uint8Array(0):(n>=t&&n<i&&(r=r.subarray(0,Number(n-t))),e>=t&&e<i&&(r=r.subarray(Number(e-t))),r)}var Mn=cI;var lI=(r,t=0,e=r)=>{let n=BigInt(r),o=BigInt(t??0),i=BigInt(e);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw new Fn("Offset must be greater than or equal to 0");if(o>n)throw new Fn("Offset must be less than the file size");if(i<0n)throw new Fn("Length must be greater than or equal to 0");if(i>n)throw new Fn("Length must be less than the file size");return{start:o,end:i}},Vo=lI;var uI=r=>{async function*t(e={}){let{start:n,end:o}=Vo(r.length,e.offset,e.length),i=Mn(r,0n,n,o);e.onProgress?.(new H("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return t},fI=async(r,t,e,n,o,i,s,a)=>{if(n.length>0)throw new Re(`No link named ${e} found in raw node ${r}`);let c=wt(r.multihash.bytes);return{entry:{type:"identity",name:t,path:e,cid:r,content:uI(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},Sw=fI;var hI=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=Au(c);return Mo(l,c,r,t,e,n,i)},Aw=hI;var dI=r=>{async function*t(e={}){let{start:n,end:o}=Vo(r.length,e.offset,e.length),i=Mn(r,0n,n,o);e.onProgress?.(new H("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return t},pI=async(r,t,e,n,o,i,s,a)=>{if(n.length>0)throw new Re(`No link named ${e} found in raw node ${r}`);let c=await s.get(r,a);return{entry:{type:"raw",name:t,path:e,cid:r,content:dI(c),depth:i,size:BigInt(c.length),node:c}}},Iw=pI;var ns=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(t="Invalid type"){super(t)}};var Ge;(function(r){let t;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(t=r.DataType||(r.DataType={}));let e;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(e||(e={})),function(o){o.codec=()=>dr(e)}(t=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=le((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),r.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let a of o.blocksizes)i.uint32(32),i.uint64(a);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),Sl.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=Sl.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>ce(o,r.codec()),r.decode=o=>ie(o,r.codec())})(Ge||(Ge={}));var Sl;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Seconds!=null&&(n.uint32(8),n.int64(e.Seconds)),e.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(e.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let s=e.uint32();switch(s>>>3){case 1:o.Seconds=e.int64();break;case 2:o.FractionalNanoseconds=e.fixed32();break;default:e.skipType(s&7);break}}return o})),t),r.encode=e=>ce(e,r.codec()),r.decode=e=>ie(e,r.codec())})(Sl||(Sl={}));var kw;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.MimeType!=null&&(n.uint32(10),n.string(e.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let s=e.uint32();switch(s>>>3){case 1:o.MimeType=e.string();break;default:e.skipType(s&7);break}}return o})),t),r.encode=e=>ce(e,r.codec()),r.decode=e=>ie(e,r.codec())})(kw||(kw={}));var _w={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},mI=["directory","hamt-sharded-directory"],Bw=parseInt("0644",8),Tw=parseInt("0755",8),cr=class r{static unmarshal(t){let e=Ge.decode(t),n=new r({type:_w[e.Type!=null?e.Type.toString():"File"],data:e.Data,blockSizes:e.blocksizes,mode:e.mode,mtime:e.mtime!=null?{secs:e.mtime.Seconds??0n,nsecs:e.mtime.FractionalNanoseconds}:void 0,fanout:e.fanout});return n._originalMode=e.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(t={type:"file"}){let{type:e,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=t;if(e!=null&&!Object.values(_w).includes(e))throw new ns("Type: "+e+" is not valid");this.type=e??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(t){t==null?this._mode=this.isDirectory()?Tw:Bw:this._mode=t&4095}get mode(){return this._mode}isDirectory(){return mI.includes(this.type)}addBlockSize(t){this.blockSizes.push(t)}removeBlockSize(t){this.blockSizes.splice(t,1)}fileSize(){if(this.isDirectory())return 0n;let t=0n;return this.blockSizes.forEach(e=>{t+=e}),this.data!=null&&(t+=BigInt(this.data.length)),t}marshal(){let t;switch(this.type){case"raw":t=Ge.DataType.Raw;break;case"directory":t=Ge.DataType.Directory;break;case"file":t=Ge.DataType.File;break;case"metadata":t=Ge.DataType.Metadata;break;case"symlink":t=Ge.DataType.Symlink;break;case"hamt-sharded-directory":t=Ge.DataType.HAMTShard;break;default:throw new ns(`Type: ${t} is not valid`)}let e=this.data;(this.data==null||this.data.length===0)&&(e=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===Bw&&!this.isDirectory()&&(n=void 0),n===Tw&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Ge.encode({Type:t,Data:e,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var Al=Ot(wf(),1);function gI(r){let t=new Array(4);for(let e=0;e<4;e++)t[e]=r&255,r=r>>8;return new Uint8Array(t)}var DM=bn({name:"murmur3-32",code:35,encode:r=>gI(Al.default.x86.hash32(r))}),Cw=bn({name:"murmur3-128",code:34,encode:r=>yn.fromHex(Al.default.x64.hash128(r))}),OM=bn({name:"murmur3-x64-64",code:34,encode:r=>yn.fromHex(Al.default.x64.hash128(r)).subarray(0,8)});var Pw=Ot(Lw(),1);var Vn=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(t,e,n=0){this._options=t,this._popCount=0,this._parent=e,this._posAtParent=n,this._children=new Pw.default,this.key=null}async put(t,e){let n=await this._findNewBucketAndPos(t);n.bucket._putAt(n,t,e)}async get(t){let e=await this._findChild(t);if(e!=null)return e.value}async del(t){let e=await this._findPlace(t),n=e.bucket._at(e.pos);n!=null&&n.key===t&&e.bucket._delAt(e.pos)}leafCount(){return this._children.compactArray().reduce((e,n)=>n instanceof r?e+n.leafCount():e+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let t=this._children.compactArray();for(let e of t)e instanceof r?yield*e.eachLeafSeries():yield e}serialize(t,e){let n=[];return e(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(t,e)):o.push(t(i,s))),o),n))}async asyncTransform(t,e){return Dw(this,t,e)}toJSON(){return this.serialize(EI,vI)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(t){let e=await this._findPlace(t),n=e.bucket._at(e.pos);if(!(n instanceof r)&&n!=null&&n.key===t)return n}async _findPlace(t){let e=this._options.hash(typeof t=="string"?D(t):t),n=await e.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(e):{bucket:this,pos:n,hash:e,existingChild:o}}async _findNewBucketAndPos(t){let e=await this._findPlace(t);if(e.existingChild!=null&&e.existingChild.key!==t){let n=new r(this._options,e.bucket,e.pos);e.bucket._putObjectAt(e.pos,n);let o=await n._findPlace(e.existingChild.hash);return o.bucket._putAt(o,e.existingChild.key,e.existingChild.value),n._findNewBucketAndPos(e.hash)}return e}_putAt(t,e,n){this._putObjectAt(t.pos,{key:e,value:n,hash:t.hash})}_putObjectAt(t,e){this._children.get(t)==null&&this._popCount++,this._children.set(t,e)}_delAt(t){if(t===-1)throw new Error("Invalid position");this._children.get(t)!=null&&this._popCount--,this._children.unset(t),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let t=this._children.find(xI);if(t!=null&&!(t instanceof r)){let e=t.hash;e.untake(this._options.bits);let n={pos:this._posAtParent,hash:e,bucket:this._parent};this._parent._putAt(n,t.key,t.value)}}else this._parent._delAt(this._posAtParent)}_at(t){return this._children.get(t)}};function xI(r){return!!r}function EI(r,t){return r.key}function vI(r){return r}async function Dw(r,t,e){let n=[];for(let o of r._children.compactArray())if(o instanceof Vn)await Dw(o,t,e);else{let i=await t(o);n.push({bitField:r._children.bitField(),children:i})}return e(n)}var SI=[255,254,252,248,240,224,192,128],AI=[1,3,7,15,31,63,127,255],Il=class{_value;_currentBytePos;_currentBitPos;constructor(t){this._value=t,this._currentBytePos=t.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(t){let e=t,n=0;for(;e>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,e),a=II(o,i-s,s);n=(n<<s)+a,e-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(t){for(this._currentBitPos+=t;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function II(r,t,e){let n=kI(t,e);return(r&n)>>>t}function kI(r,t){return SI[r]&AI[Math.min(t+r-1,7)]}function Ow(r){function t(e){return e instanceof kl?e:new kl(e,r)}return t}var kl=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(t,e){if(!(t instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=t,this._hashFn=e,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(t){let e=t;for(;this._availableBits<e;)await this._produceMoreBits();let n=0;for(;e>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),e),s=o.take(i);n=(n<<i)+s,e-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(t){let e=t;for(;e>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),e);n.untake(o),e-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let t=this._depth>0?ct([this._value,Uint8Array.from([this._depth])]):this._value,e=await this._hashFn(t),n=new Il(e);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Uw(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let t={bits:r.bits??8,hash:Ow(r.hashFn)};return new Vn(t)}var _I=async function(r){return(await Cw.encode(r)).slice(0,8).reverse()},BI=async(r,t,e)=>{let n=(t.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);t._putObjectAt(i,new Vn({hash:e._options.hash,bits:e._options.bits},t,i));return}await e.put(o.Name.substring(2),!0)}))},Fw=(r,t)=>r.toString(16).toUpperCase().padStart(t,"0").substring(0,t),TI=r=>{let t=r.bucket,e=[];for(;t._parent!=null;)e.push(t),t=t._parent;return e.push(t),e.reverse()},Mw=async(r,t,e,n,o)=>{if(n==null){if(r.Data==null)throw new Ct("no data in PBNode");let f;try{f=cr.unmarshal(r.Data)}catch(h){throw new Ct(h.message)}if(f.type!=="hamt-sharded-directory")throw new Ct("not a HAMT");if(f.fanout==null)throw new Ct("missing fanout");let d=Uw({hashFn:_I,bits:Math.log2(Number(f.fanout))});n={rootBucket:d,hamtDepth:1,lastBucket:d}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await BI(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(t),a=Fw(s.pos,i),c=TI(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=Fw(n.lastBucket._posAtParent,i));let l=r.Links.find(f=>{if(f.Name==null)return!1;let d=f.Name.substring(0,i),h=f.Name.substring(i);return!(d!==a||h!==""&&h!==t)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===t)return l.Hash;n.hamtDepth++;let u=await e.get(l.Hash,o);return r=Nr(u),Mw(r,t,e,n,o)},Vw=Mw;var CI=(r,t,e,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??t.Links.length,f=t.Links.slice(l,u);c.onProgress?.(new H("unixfs:exporter:walk:directory",{cid:r})),yield*Ye(f,d=>zt(d,h=>async()=>{let m=h.Name??"",p=`${n}/${m}`;return(await o(h.Hash,m,p,[],i+1,s,c)).entry}),d=>Un(d,{ordered:!0,concurrency:c.blockReadConcurrency}),d=>ve(d,h=>h!=null))}return a},Hw=CI;async function $w(r,t,e,n,o,i,s){if(t instanceof Uint8Array){let l=Mn(t,n,o,i);e.push(l);return}if(t.Data==null)throw new Ct("no data in PBNode");let a;try{a=cr.unmarshal(t.Data)}catch(l){throw new Ct(l.message)}if(a.data!=null){let l=a.data,u=Mn(l,n,o,i);e.push(u),n+=BigInt(u.byteLength)}let c=[];if(t.Links.length!==a.blockSizes.length)throw new Ct("Inconsistent block sizes and dag links");for(let l=0;l<t.Links.length;l++){let u=t.Links[l],f=n,d=f+a.blockSizes[l];if((o>=f&&o<d||i>=f&&i<=d||o<f&&i>d)&&c.push({link:u,blockStart:n}),n=d,n>i)break}await Ye(c,l=>zt(l,u=>async()=>{let f=await r.get(u.link.Hash,s);return{...u,block:f}}),l=>Un(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:d}of l){let h;switch(u.Hash.code){case Te:h=Nr(f);break;case ae:h=f;break;default:e.end(new Ct(`Unsupported codec: ${u.Hash.code}`));return}let m=new de({concurrency:1});m.on("error",p=>{e.end(p)}),m.add(async()=>{s.onProgress?.(new H("unixfs:exporter:walk:file",{cid:u.Hash})),await $w(r,h,e,d,o,i,s)}),await m.onIdle()}}),n>=i&&e.end()}var RI=(r,t,e,n,o,i,s)=>{async function*a(c={}){let l=e.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=Vo(l,c.offset,c.length);if(f===0n)return;let d=0n,h=f-u,m=We();c.onProgress?.(new H("unixfs:exporter:walk:file",{cid:r})),$w(s,t,m,0n,u,f,c).catch(p=>{m.end(p)});for await(let p of m)if(p!=null){if(d+=BigInt(p.byteLength),d>h)throw m.end(),new xl("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");d===h&&m.end(),c.onProgress?.(new H("unixfs:exporter:progress:unixfs:file",{bytesRead:d,totalBytes:h,fileSize:l})),yield p}if(d<h)throw new El("Traversed entire DAG but did not read enough bytes")}return a},cd=RI;var NI=(r,t,e,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new H("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),zw(t,n,o,i,s,c)}return a};async function*zw(r,t,e,n,o,i){let s=r.Links;if(r.Data==null)throw new Ct("no data in PBNode");let a;try{a=cr.unmarshal(r.Data)}catch(u){throw new Ct(u.message)}if(a.fanout==null)throw new Ct("missing fanout");let c=(a.fanout-1n).toString(16).length,l=Ye(s,u=>zt(u,f=>async()=>{let d=f.Name!=null?f.Name.substring(c):null;if(d!=null&&d!==""){let h=await e(f.Hash,d,`${t}/${d}`,[],n+1,o,i);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await o.get(f.Hash,i);return r=Nr(h),i.onProgress?.(new H("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:zw(r,t,e,n,o,i)}}}),u=>Un(u,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var qw=NI;var LI=(r,t)=>r.Links.find(n=>n.Name===t)?.Hash,PI={raw:cd,file:cd,directory:Hw,"hamt-sharded-directory":qw,metadata:(r,t,e,n,o,i,s)=>()=>[],symlink:(r,t,e,n,o,i,s)=>()=>[]},DI=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=Nr(c),u,f;if(t==null&&(t=r.toString()),l.Data==null)throw new Ct("no data in PBNode");try{u=cr.unmarshal(l.Data)}catch(h){throw new Ct(h.message)}if(e==null&&(e=t),n.length>0){let h;if(u?.type==="hamt-sharded-directory"?h=await Vw(l,n[0],s):h=LI(l,n[0]),h==null)throw new Re("file does not exist");let m=n.shift(),p=`${e}/${m}`;f={cid:h,toResolve:n,name:m??"",path:p}}let d=PI[u.type](r,l,u,e,o,i,s);if(d==null)throw new Re("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:t,path:e,cid:r,content:d,unixfs:u,depth:i,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:t,path:e,cid:r,content:d,unixfs:u,depth:i,node:l,size:u.fileSize()},next:f}},Kw=DI;var OI={[Te]:Kw,[ae]:Iw,[Cr]:Ew,[Rr]:vw,[bt.code]:Sw,[hr]:Aw},Gw=async(r,t,e,n,o,i,s)=>{let a=OI[r.code];if(a==null)throw new bl(`No resolver for code ${r.code}`);return a(r,t,e,n,Gw,o,i,s)},Ww=Gw;var UI=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),FI=r=>{if(r instanceof Uint8Array)return{cid:L.decode(r),toResolve:[]};let t=L.asCID(r);if(t!=null)return{cid:t,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let e=UI(r);return{cid:L.parse(e[0]),toResolve:e.slice(1)}}throw new wl(`Unknown path type ${r}`)};async function*ld(r,t,e={}){let{cid:n,toResolve:o}=FI(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await Ww(n,i,s,o,a,t,e);if(c.entry==null&&c.next==null)throw new Re(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;o=c.next.toResolve,n=c.next.cid,i=c.next.name,s=c.next.path}}async function Ho(r,t,e={}){let n=await xw(ld(r,t,e));if(n==null)throw new Re(`Could not resolve ${r}`);return n}async function*jw(r,t,e={}){let n=await Ho(r,t,e);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,e))yield i;async function*o(i,s){for await(let a of i.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*o(a,s))}}function Yw(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function _l(r,t={}){let e=Yw(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await e.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,t)}var $o=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Zw=new Set,ud=typeof process=="object"&&process?process:{},Jw=(r,t,e,n)=>{typeof ud.emitWarning=="function"?ud.emitWarning(r,t,e,n):console.error(`[${e}] ${t}: ${r}`)},Bl=globalThis.AbortController,Xw=globalThis.AbortSignal;if(typeof Bl>"u"){Xw=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},Bl=class{constructor(){t()}signal=new Xw;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=ud.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{r&&(r=!1,Jw("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var MI=r=>!Zw.has(r),t9=Symbol("type"),hn=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Qw=r=>hn(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?zo:null:null,zo=class extends Array{constructor(t){super(t),this.fill(0)}},fd=class r{heap;length;static#t=!1;static create(t){let e=Qw(t);if(!e)return[];r.#t=!0;let n=new r(t,e);return r.#t=!1,n}constructor(t,e){if(!r.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Tl=class r{#t;#r;#a;#c;#g;#S;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#y;#n;#i;#e;#h;#l;#d;#u;#b;#f;#x;#E;#m;#w;#A;#p;static unsafeExposeInternals(t){return{starts:t.#E,ttls:t.#m,sizes:t.#x,keyMap:t.#n,keyList:t.#i,valList:t.#e,next:t.#h,prev:t.#l,get head(){return t.#d},get tail(){return t.#u},free:t.#b,isBackgroundFetch:e=>t.#s(e),backgroundFetch:(e,n,o,i)=>t.#D(e,n,o,i),moveToTail:e=>t.#N(e),indexes:e=>t.#k(e),rindexes:e=>t.#_(e),isStale:e=>t.#v(e)}}get max(){return this.#t}get maxSize(){return this.#r}get calculatedSize(){return this.#y}get size(){return this.#o}get fetchMethod(){return this.#g}get memoMethod(){return this.#S}get dispose(){return this.#a}get disposeAfter(){return this.#c}constructor(t){let{max:e=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:f,noUpdateTTL:d,maxSize:h=0,maxEntrySize:m=0,sizeCalculation:p,fetchMethod:y,memoMethod:g,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:k,ignoreFetchAbort:T}=t;if(e!==0&&!hn(e))throw new TypeError("max option must be a nonnegative integer");let S=e?Qw(e):Array;if(!S)throw new Error("invalid max value: "+e);if(this.#t=e,this.#r=h,this.maxEntrySize=m||this.#r,this.sizeCalculation=p,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(g!==void 0&&typeof g!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=g,y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#g=y,this.#A=!!y,this.#n=new Map,this.#i=new Array(e).fill(void 0),this.#e=new Array(e).fill(void 0),this.#h=new S(e),this.#l=new S(e),this.#d=0,this.#u=0,this.#b=fd.create(e),this.#o=0,this.#y=0,typeof l=="function"&&(this.#a=l),typeof u=="function"?(this.#c=u,this.#f=[]):(this.#c=void 0,this.#f=void 0),this.#w=!!this.#a,this.#p=!!this.#c,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!T,this.maxEntrySize!==0){if(this.#r!==0&&!hn(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!hn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#H()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=hn(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!hn(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#C()}if(this.#t===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#r){let v="LRU_CACHE_UNBOUNDED";MI(v)&&(Zw.add(v),Jw("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",v,r))}}getRemainingTTL(t){return this.#n.has(t)?1/0:0}#C(){let t=new zo(this.#t),e=new zo(this.#t);this.#m=t,this.#E=e,this.#O=(i,s,a=$o.now())=>{if(e[i]=s!==0?a:0,t[i]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#v(i)&&this.#B(this.#i[i],"expire")},s+1);c.unref&&c.unref()}},this.#I=i=>{e[i]=t[i]!==0?$o.now():0},this.#T=(i,s)=>{if(t[s]){let a=t[s],c=e[s];if(!a||!c)return;i.ttl=a,i.start=c,i.now=n||o();let l=i.now-c;i.remainingTTL=a-l}};let n=0,o=()=>{let i=$o.now();if(this.ttlResolution>0){n=i;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#n.get(i);if(s===void 0)return 0;let a=t[s],c=e[s];if(!a||!c)return 1/0;let l=(n||o())-c;return a-l},this.#v=i=>{let s=e[i],a=t[i];return!!a&&!!s&&(n||o())-s>a}}#I=()=>{};#T=()=>{};#O=()=>{};#v=()=>!1;#H(){let t=new zo(this.#t);this.#y=0,this.#x=t,this.#R=e=>{this.#y-=t[e],t[e]=0},this.#U=(e,n,o,i)=>{if(this.#s(n))return 0;if(!hn(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,e),!hn(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#L=(e,n,o)=>{if(t[e]=n,this.#r){let i=this.#r-t[e];for(;this.#y>i;)this.#P(!0)}this.#y+=t[e],o&&(o.entrySize=n,o.totalCalculatedSize=this.#y)}}#R=t=>{};#L=(t,e,n)=>{};#U=(t,e,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#u;!(!this.#F(e)||((t||!this.#v(e))&&(yield e),e===this.#d));)e=this.#l[e]}*#_({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#d;!(!this.#F(e)||((t||!this.#v(e))&&(yield e),e===this.#u));)e=this.#h[e]}#F(t){return t!==void 0&&this.#n.get(this.#i[t])===t}*entries(){for(let t of this.#k())this.#e[t]!==void 0&&this.#i[t]!==void 0&&!this.#s(this.#e[t])&&(yield[this.#i[t],this.#e[t]])}*rentries(){for(let t of this.#_())this.#e[t]!==void 0&&this.#i[t]!==void 0&&!this.#s(this.#e[t])&&(yield[this.#i[t],this.#e[t]])}*keys(){for(let t of this.#k()){let e=this.#i[t];e!==void 0&&!this.#s(this.#e[t])&&(yield e)}}*rkeys(){for(let t of this.#_()){let e=this.#i[t];e!==void 0&&!this.#s(this.#e[t])&&(yield e)}}*values(){for(let t of this.#k())this.#e[t]!==void 0&&!this.#s(this.#e[t])&&(yield this.#e[t])}*rvalues(){for(let t of this.#_())this.#e[t]!==void 0&&!this.#s(this.#e[t])&&(yield this.#e[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let n of this.#k()){let o=this.#e[n],i=this.#s(o)?o.__staleWhileFetching:o;if(i!==void 0&&t(i,this.#i[n],this))return this.get(this.#i[n],e)}}forEach(t,e=this){for(let n of this.#k()){let o=this.#e[n],i=this.#s(o)?o.__staleWhileFetching:o;i!==void 0&&t.call(e,i,this.#i[n],this)}}rforEach(t,e=this){for(let n of this.#_()){let o=this.#e[n],i=this.#s(o)?o.__staleWhileFetching:o;i!==void 0&&t.call(e,i,this.#i[n],this)}}purgeStale(){let t=!1;for(let e of this.#_({allowStale:!0}))this.#v(e)&&(this.#B(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#n.get(t);if(e===void 0)return;let n=this.#e[e],o=this.#s(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#m&&this.#E){let s=this.#m[e],a=this.#E[e];if(s&&a){let c=s-($o.now()-a);i.ttl=c,i.start=Date.now()}}return this.#x&&(i.size=this.#x[e]),i}dump(){let t=[];for(let e of this.#k({allowStale:!0})){let n=this.#i[e],o=this.#e[e],i=this.#s(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let s={value:i};if(this.#m&&this.#E){s.ttl=this.#m[e];let a=$o.now()-this.#E[e];s.start=Math.floor(Date.now()-a)}this.#x&&(s.size=this.#x[e]),t.unshift([n,s])}return t}load(t){this.clear();for(let[e,n]of t){if(n.start){let o=Date.now()-n.start;n.start=$o.now()-o}this.set(e,n.value,n)}}set(t,e,n={}){if(e===void 0)return this.delete(t),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,u=this.#U(t,e,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#B(t,"set"),this;let f=this.#o===0?void 0:this.#n.get(t);if(f===void 0)f=this.#o===0?this.#u:this.#b.length!==0?this.#b.pop():this.#o===this.#t?this.#P(!1):this.#o,this.#i[f]=t,this.#e[f]=e,this.#n.set(t,f),this.#h[this.#u]=f,this.#l[f]=this.#u,this.#u=f,this.#o++,this.#L(f,u,c),c&&(c.set="add"),l=!1;else{this.#N(f);let d=this.#e[f];if(e!==d){if(this.#A&&this.#s(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:h}=d;h!==void 0&&!s&&(this.#w&&this.#a?.(h,t,"set"),this.#p&&this.#f?.push([h,t,"set"]))}else s||(this.#w&&this.#a?.(d,t,"set"),this.#p&&this.#f?.push([d,t,"set"]));if(this.#R(f),this.#L(f,u,c),this.#e[f]=e,c){c.set="replace";let h=d&&this.#s(d)?d.__staleWhileFetching:d;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(o!==0&&!this.#m&&this.#C(),this.#m&&(l||this.#O(f,o,i),c&&this.#T(c,f)),!s&&this.#p&&this.#f){let d=this.#f,h;for(;h=d?.shift();)this.#c?.(...h)}return this}pop(){try{for(;this.#o;){let t=this.#e[this.#d];if(this.#P(!0),this.#s(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#p&&this.#f){let t=this.#f,e;for(;e=t?.shift();)this.#c?.(...e)}}}#P(t){let e=this.#d,n=this.#i[e],o=this.#e[e];return this.#A&&this.#s(o)?o.__abortController.abort(new Error("evicted")):(this.#w||this.#p)&&(this.#w&&this.#a?.(o,n,"evict"),this.#p&&this.#f?.push([o,n,"evict"])),this.#R(e),t&&(this.#i[e]=void 0,this.#e[e]=void 0,this.#b.push(e)),this.#o===1?(this.#d=this.#u=0,this.#b.length=0):this.#d=this.#h[e],this.#n.delete(n),this.#o--,e}has(t,e={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=e,i=this.#n.get(t);if(i!==void 0){let s=this.#e[i];if(this.#s(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#v(i))o&&(o.has="stale",this.#T(o,i));else return n&&this.#I(i),o&&(o.has="hit",this.#T(o,i)),!0}else o&&(o.has="miss");return!1}peek(t,e={}){let{allowStale:n=this.allowStale}=e,o=this.#n.get(t);if(o===void 0||!n&&this.#v(o))return;let i=this.#e[o];return this.#s(i)?i.__staleWhileFetching:i}#D(t,e,n,o){let i=e===void 0?void 0:this.#e[e];if(this.#s(i))return i;let s=new Bl,{signal:a}=n;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:n,context:o},l=(p,y=!1)=>{let{aborted:g}=s.signal,x=n.ignoreFetchAbort&&p!==void 0;if(n.status&&(g&&!y?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,x&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),g&&!x&&!y)return f(s.signal.reason);let b=h;return this.#e[e]===h&&(p===void 0?b.__staleWhileFetching?this.#e[e]=b.__staleWhileFetching:this.#B(t,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(t,p,c.options))),p},u=p=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=p),f(p)),f=p=>{let{aborted:y}=s.signal,g=y&&n.allowStaleOnFetchAbort,x=g||n.allowStaleOnFetchRejection,b=x||n.noDeleteOnFetchRejection,E=h;if(this.#e[e]===h&&(!b||E.__staleWhileFetching===void 0?this.#B(t,"fetch"):g||(this.#e[e]=E.__staleWhileFetching)),x)return n.status&&E.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw p},d=(p,y)=>{let g=this.#g?.(t,i,c);g&&g instanceof Promise&&g.then(x=>p(x===void 0?void 0:x),y),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(p(void 0),n.allowStaleOnFetchAbort&&(p=x=>l(x,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(d).then(l,u),m=Object.assign(h,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return e===void 0?(this.set(t,m,{...c.options,status:void 0}),e=this.#n.get(t)):this.#e[e]=m,m}#s(t){if(!this.#A)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof Bl}async fetch(t,e={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:p,forceRefresh:y=!1,status:g,signal:x}=e;if(!this.#A)return g&&(g.fetch="get"),this.get(t,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:g});let b={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:h,status:g,signal:x},E=this.#n.get(t);if(E===void 0){g&&(g.fetch="miss");let k=this.#D(t,E,b,p);return k.__returned=k}else{let k=this.#e[E];if(this.#s(k)){let z=n&&k.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",z&&(g.returnedStale=!0)),z?k.__staleWhileFetching:k.__returned=k}let T=this.#v(E);if(!y&&!T)return g&&(g.fetch="hit"),this.#N(E),o&&this.#I(E),g&&this.#T(g,E),k;let S=this.#D(t,E,b,p),_=S.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=T?"stale":"refresh",_&&T&&(g.returnedStale=!0)),_?S.__staleWhileFetching:S.__returned=S}}async forceFetch(t,e={}){let n=await this.fetch(t,e);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(t,e={}){let n=this.#S;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=e,a=this.get(t,s);if(!i&&a!==void 0)return a;let c=n(t,a,{options:s,context:o});return this.set(t,c,s),c}get(t,e={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=e,a=this.#n.get(t);if(a!==void 0){let c=this.#e[a],l=this.#s(c);return s&&this.#T(s,a),this.#v(a)?(s&&(s.get="stale"),l?(s&&n&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.#B(t,"expire"),s&&n&&(s.returnedStale=!0),n?c:void 0)):(s&&(s.get="hit"),l?c.__staleWhileFetching:(this.#N(a),o&&this.#I(a),c))}else s&&(s.get="miss")}#M(t,e){this.#l[e]=t,this.#h[t]=e}#N(t){t!==this.#u&&(t===this.#d?this.#d=this.#h[t]:this.#M(this.#l[t],this.#h[t]),this.#M(this.#u,t),this.#u=t)}delete(t){return this.#B(t,"delete")}#B(t,e){let n=!1;if(this.#o!==0){let o=this.#n.get(t);if(o!==void 0)if(n=!0,this.#o===1)this.#V(e);else{this.#R(o);let i=this.#e[o];if(this.#s(i)?i.__abortController.abort(new Error("deleted")):(this.#w||this.#p)&&(this.#w&&this.#a?.(i,t,e),this.#p&&this.#f?.push([i,t,e])),this.#n.delete(t),this.#i[o]=void 0,this.#e[o]=void 0,o===this.#u)this.#u=this.#l[o];else if(o===this.#d)this.#d=this.#h[o];else{let s=this.#l[o];this.#h[s]=this.#h[o];let a=this.#h[o];this.#l[a]=this.#l[o]}this.#o--,this.#b.push(o)}}if(this.#p&&this.#f?.length){let o=this.#f,i;for(;i=o?.shift();)this.#c?.(...i)}return n}clear(){return this.#V("delete")}#V(t){for(let e of this.#_({allowStale:!0})){let n=this.#e[e];if(this.#s(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#i[e];this.#w&&this.#a?.(n,o,t),this.#p&&this.#f?.push([n,o,t])}}if(this.#n.clear(),this.#e.fill(void 0),this.#i.fill(void 0),this.#m&&this.#E&&(this.#m.fill(0),this.#E.fill(0)),this.#x&&this.#x.fill(0),this.#d=0,this.#u=0,this.#b.length=0,this.#y=0,this.#o=0,this.#p&&this.#f){let e=this.#f,n;for(;n=e?.shift();)this.#c?.(...n)}}};var Se=class extends Error{static name="InvalidRangeError";constructor(t="Invalid range request"){super(t),this.name="InvalidRangeError"}},Cl=class extends Error{static name="NoContentError";constructor(t="No content found"){super(t),this.name="NoContentError"}},Rl=class extends Error{static name="SubdomainNotSupportedError";constructor(t="Subdomain not supported"){super(t),this.name="SubdomainNotSupportedError"}};function tb(r,t){if(r==null)return;if(r instanceof Headers)return r.get(t)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===t.toLowerCase())?.[1];let e=Object.keys(r).find(n=>n.toLowerCase()===t.toLowerCase());if(e!=null)return r[e]}function eb(r,t,e){if((r??0)>(t??1/0))throw new Se("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(t??0)>=(e??1/0))throw new Se("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(t??0)>(e??1/0))throw new Se("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Se("Invalid range: Range-start index cannot be negative.");if(r!=null&&t!=null)return{byteSize:t-r+1,start:r,end:t};if(r==null&&t!=null)return e==null?{end:t}:t===e?{byteSize:e,start:0,end:e-1}:{byteSize:t,start:e-t,end:e-1};if(r!=null&&t==null){if(e==null)return{start:r};let n=e-1;return{byteSize:e-r,start:r,end:n}}return{byteSize:e,start:0,end:e!=null?e-1:0}}function rb({ttl:r,protocol:t,response:e}){let n;t==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,e.headers.set("cache-control",n)}function nb({byteStart:r,byteEnd:t,byteSize:e}){let n=e??"*";if((t??0)>=(e??1/0))throw new Se("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(e??1/0))throw new Se("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&t==null)return e==null?`bytes */${n}`:`bytes ${r}-${e-1}/${e}`;if(r==null&&t!=null){if(e==null)return`bytes */${n}`;let o=e-1;return`bytes ${o-t+1}-${o}/${e}`}return r==null&&t==null?`bytes */${n}`:`bytes ${r}-${t}/${n}`}function hd(r,t){t!=null&&r.headers.set("X-Ipfs-Roots",t.map(e=>e.toV1().toString()).join(","))}function VI(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function HI(r){let t=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(t?.groups==null)throw new Se("Invalid range request");let{start:e,end:n}=t.groups;return{start:e,end:n}}var os=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(t,e){if(this.headers=e,this.log=t.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=tb(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=HI(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=o!=null?parseInt(o):null}catch(n){this.log.error("error parsing range request header: %o",n),this.requestRangeStart=null,this.requestRangeEnd=null}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1,this.requestRangeStart=null,this.requestRangeEnd=null}setBody(t){this._body=t,this.setFileSize(this._fileSize??VI(t)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let t=this._body;if(t==null)return this.log.trace("body is null"),t;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),t;let e=this.byteStart,n=this.byteEnd,o=this.byteSize;return e!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",e,n,o),t instanceof ReadableStream?t:this.getSlicedBody(t)):(this.log.error("returning unmodified body for valid range request"),t)}getSlicedBody(t){let e=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",e,n),t.slice(e,n)}setFileSize(t){this._fileSize=t!=null?Number(t):null,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(){return!(this.byteStart!=null&&(this.byteStart<0||this._fileSize!=null&&this.byteStart>=this._fileSize||this.byteEnd!=null&&this.byteStart>this.byteEnd))}isValidByteEnd(){return!(this.byteEnd!=null&&(this.byteEnd<0||this._fileSize!=null&&this.byteEnd>=this._fileSize||this.byteStart!=null&&this.byteEnd<this.byteStart))}get isValidRangeRequest(){if(!this.isRangeRequest)return!1;if(this.requestRangeStart==null&&this.requestRangeEnd==null)return this.log.trace("invalid range request, range request values not provided"),!1;if(!this.isValidByteStart())return this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1;if(!this.isValidByteEnd())return this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1;if(this.requestRangeEnd!=null&&this.requestRangeStart!=null){if(this.requestRangeStart>this.requestRangeEnd)return this.log.trace("invalid range request, start is greater than end"),!1;if(this.requestRangeStart<0)return this.log.trace("invalid range request, start is less than 0"),!1;if(this.requestRangeEnd<0)return this.log.trace("invalid range request, end is less than 0"),!1}return this.byteEnd==null&&this.byteStart==null&&this.byteSize==null?(this.log.trace("invalid range request, could not calculate byteStart, byteEnd, or byteSize"),!1):!0}get offset(){return this.byteStart??0}get length(){return this.byteEnd!=null&&this.byteStart!=null&&this.byteStart===this.byteEnd?1:this.byteEnd!=null?this.byteEnd+1:this.byteSize!=null?this.byteSize-1:void 0}setOffsetDetails(){if(this.requestRangeStart==null&&this.requestRangeEnd==null){this.log.trace("requestRangeStart and requestRangeEnd are null");return}try{let{start:t,end:e,byteSize:n}=eb(this.requestRangeStart??void 0,this.requestRangeEnd??void 0,this._fileSize??void 0);this.log.trace("set byteStart to %o, byteEnd to %o, byteSize to %o",t,e,n),this.byteStart=t,this.byteEnd=e,this.byteSize=n}catch(t){this.log.error("error setting offset details: %o",t),this.byteStart=void 0,this.byteEnd=void 0,this.byteSize=void 0}}get contentRangeHeaderValue(){if(!this.isValidRangeRequest)throw this.log.error("cannot get contentRangeHeaderValue for invalid range request"),new Se("Invalid range request");return nb({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function ob(r){let t=Vt(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(Ni(t))}function ib(r){let t=$I(r);return t===r?`filename="${r}"`:`filename="${t}"; filename*=UTF-8''${encodeURIComponent(r)}`}function $I(r){return r.replace(/[^\x00-\x7F]/g,"_")}function sb({cid:r,reqFormat:t,weak:e,rangeStart:n,rangeEnd:o}){let i=e===!0?"W/":"",s=t==null?"":`.${t}`;return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}var zI={[Cr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Rr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[hr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Te]:["application/octet-stream","application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","application/x-tar"],[ae]:["application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.dag-json","application/vnd.ipld.car","application/x-tar"]};function ab(r,t){let e=zI[r.code];if(t!=null)return qI(t,e)}function qI(r,t){let e=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:KI(o[1])}}).sort((n,o)=>n.weight===o.weight?0:n.weight>o.weight?-1:1).map(n=>n.mimeType);for(let n of e)for(let o of t)if(n.includes(o)||n==="*/*"||n.startsWith("*/")&&o.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&o.split("/")[0]===n.split("/")[0])return o}function KI(r){if(r!=null&&(r=r.trim()),r?.startsWith("q=")!==!0)return 1;let t=parseFloat(r.replace("q=",""));return isNaN(t)?0:t}var Nl={raw:"application/vnd.ipld.raw",car:"application/vnd.ipld.car","dag-json":"application/vnd.ipld.dag-json","dag-cbor":"application/vnd.ipld.dag-cbor",json:"application/json",cbor:"application/cbor","ipns-record":"application/vnd.ipfs.ipns-record",tar:"application/x-tar"};function cb(r){if(r!=null)return Nl[r]}function dd(r){let t=r.get("accept");return!!(t!=null&&Object.values(Nl).includes(t))}function pd(r){let t=r?.format;return!!(t!=null&&Object.keys(Nl).includes(t))}function lb({query:r,headers:t}){return dd(t)||pd(r)}function ub({query:r,headers:t,logger:e}){let n=e.forComponent("helia:verified-fetch:get-resolved-accept-header"),o=new Headers(t),i=o.get("accept")??void 0;if(i!=null&&n('incoming accept header "%s"',i),!lb({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=cb(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=i;return!dd(o)&&pd(r)&&(n("accept header not recognized, but query format provided, setting accept header to %s",s),a=s),n('resolved accept header to "%s"',a),a}async function fb(r,t,e,n){let o=e.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),i=r[Symbol.asyncIterator](),{value:s,done:a}=await i.next();if(a===!0)throw o.error("no content found for path",t),new Cl;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new H("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await i.next();if(n?.signal?.aborted===!0){l.error(new Ne(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new H("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new H("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var Ll=class extends Error{name;code;constructor(t,e,n){super(t),this.name=e,this.code=n}},is=class extends Ll{constructor(t="not a Unixfs node"){super(t,"NotUnixFSError","ERR_NOT_UNIXFS")}};var Pl=class extends Ll{constructor(t="path does not exist"){super(t,"DoesNotExistError","ERR_DOES_NOT_EXIST")}};var U9=D("ustar\0","binary"),F9=D("ustar ","binary"),M9=D(" \0","binary");var gb=Ot(db(),1);function WI(r){return r[Symbol.asyncIterator]!=null}function jI(r){if(WI(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=ct([n,o],n.length+o.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return ct(t,e)}var pb=jI;var YI="0000000000000000000",XI="7777777777777777777",ZI=48,JI=D("ustar\0","binary"),QI=D("00","binary"),tk=parseInt("7777",8),ek=257,rk=263,nk=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},ok=function(r){let t=256;for(let e=0;e<148;e++)t+=r[e];for(let e=156;e<512;e++)t+=r[e];return t},dn=function(r,t){let e=r.toString(8);return e.length>t?D(XI.slice(0,t)+" "):D(YI.slice(0,t-e.length)+e+" ")},md=function(r){let t=D(r).byteLength,e=Math.floor(Math.log(t)/Math.log(10))+1;return t+e>=Math.pow(10,e)&&e++,`${t+e}${r}`};function mb(r){let t="";r.name!=null&&(t+=md(" path="+r.name+`
|
|
19
|
-
`)),r.linkname!=null&&(t+=
|
|
20
|
-
`));let e=r.pax;if(e!=null)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t+=
|
|
21
|
-
`));return D(t)}function Dl(r){let t=new Uint8Array(512),e=r.name,n="";if(r.typeflag===5&&e[e.length-1]!=="/"&&(e+="/"),D(e).byteLength!==e.length)return null;for(;D(e).byteLength>100;){let o=e.indexOf("/");if(o===-1)return null;n+=n!==""?"/"+e.slice(0,o):e.slice(0,o),e=e.slice(o+1)}return D(e).byteLength>100||D(n).byteLength>155||r.linkname!=null&&D(r.linkname).byteLength>100?null:(t.set(D(e),0),t.set(dn(r.mode&tk,6),100),t.set(dn(r.uid,6),108),t.set(dn(r.gid,6),116),t.set(dn(r.size,11),124),t.set(dn(r.mtime.getTime()/1e3|0,11),136),t[156]=ZI+nk(r.type),r.linkname!=null&&t.set(D(r.linkname),157),t.set(JI,ek),t.set(QI,rk),r.uname!=null&&t.set(D(r.uname),265),r.gname!=null&&t.set(D(r.gname),297),t.set(dn(r.devmajor??0,6),329),t.set(dn(r.devminor??0,6),337),n!=null&&t.set(D(n),345),t.set(dn(ok(t),6),148),t)}var{S_IFMT:sk,S_IFBLK:ak,S_IFCHR:ck,S_IFDIR:lk,S_IFIFO:uk,S_IFLNK:fk}=gb.default,hk=parseInt("755",8),dk=parseInt("644",8),yb=new Uint8Array(1024);function pk(r=0){switch(r&sk){case ak:return"block-device";case ck:return"character-device";case lk:return"directory";case uk:return"fifo";case fk:return"symlink";default:return"file"}}function yd(r){return r&=511,r!==0?yb.subarray(0,512-r):new Uint8Array(0)}function gd(r){if(r.pax==null){let t=Dl(r);if(t!=null)return t}return mk(r)}function mk(r){let t=mb(r),e={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:t.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new fr(Dl(e)??new Uint8Array(0),t,yd(t.length),Dl({...e,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function Ol(){return async function*(r){for await(let{header:t,body:e}of r){let n={...t,size:t.type==="symlink"?0:t.size??0,type:t.type??pk(t.mode),mode:t.mode??(t.type==="directory"?hk:dk),uid:t.uid??0,gid:t.gid??0,mtime:t.mtime??new Date};if(typeof e=="string"&&(e=D(e)),e instanceof Uint8Array||je(e)){n.size=e.length,yield gd(n),yield je(e)?e.subarray():e,yield yd(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(e==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=q(await pb(e)),yield gd(n);continue}if(yield gd(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of e??[])o+=i.length,yield je(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield yd(n.size)}yield yb}}var gk=["file","raw","directory"];function yk(r){let t,e;return(r.type==="file"||r.type==="directory")&&(t=r.unixfs.mode,e=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:t,mtime:e,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function wb(r){if(!gk.includes(r.type))throw new is(`${r.type} is not a UnixFS node`);let t={header:yk(r)};return(r.type==="file"||r.type==="raw")&&(t.body=r.content()),t}async function*bb(r,t,e){let n=await Ho(r,t,e);if(n.type==="file"||n.type==="raw"){yield*Ye([wb(n)],Ol());return}if(n.type==="directory"){yield*Ye(jw(r,t,e),o=>zt(o,i=>wb(i)),Ol());return}throw new is("Not a UnixFS node")}var xb=Ot(kf(),1),Ul=class{lru;constructor(t){this.lru=(0,xb.default)(t)}get(t){let e=this.lru.get(t);if(e!=null){if(e.expire!=null&&e.expire<Date.now()){this.lru.remove(t);return}return e.value}}set(t,e,n){this.lru.set(t,{value:e,expire:Date.now()+n})}has(t){return this.get(t)!=null}remove(t){this.lru.remove(t)}clear(){this.lru.clear()}};var Eb=new Ul(1e3),wk=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,bk=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,xk=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Ek=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function vk(r){let t=r?.protocol;if(t==null)return!1;let e=r?.cidOrPeerIdOrDnsLink;if(e==null)return!1;let n=r?.path,o=r?.queryString;return["ipns","ipfs"].includes(t)&&typeof e=="string"&&(n==null||typeof n=="string")&&(o==null||typeof o=="string")}function ss(r){for(let t of[Ek,wk,xk,bk]){let e=r.match(t);if(vk(e?.groups))return e.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function Sk(r){if(r==null)return;let t=r.answer?.TTL,e=r.record?.ttl,n=e!=null?Number(e/BigInt(1e9)):void 0;return t??n}var Ak=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function Ik(r){return Ak.test(r)&&r.includes("-")&&!r.includes(".")}function kk(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function vb({urlString:r,ipns:t,logger:e},n){let o=e.forComponent("helia:verified-fetch:parse-url-string"),{protocol:i,cidOrPeerIdOrDnsLink:s,path:a,queryString:c}=ss(r),l,u,f=[],d;if(i==="ipfs")try{l=L.parse(s)}catch(p){o.error(p),f.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(d=Eb.get(s),d!=null)l=d.cid,u=d.path,o.trace("resolved %s to %c from cache",s,l);else{o.trace("Attempting to resolve PeerId for %s",s);let p;try{if(s.charAt(0)==="1"||s.charAt(0)==="Q"?p=mo(s):p=Ta(L.parse(s)),p.publicKey==null)throw new TypeError("cidOrPeerIdOrDnsLink contains no public key");d=await t.resolve(p.publicKey,n),l=d?.cid,u=d?.path,o.trace("resolved %s to %c",s,l)}catch(y){n?.signal?.throwIfAborted(),p==null?(o.error('could not parse PeerId string "%s"',s,y),f.push(new TypeError(`Could not parse PeerId in ipns url "${s}", ${y.message}`))):(o.error("could not resolve PeerId %c",p,y),f.push(new TypeError(`Could not resolve PeerId "${s}", ${y.message}`)))}if(l==null){let y=s;Ik(s)&&(y=kk(s),o.trace('decoded dnslink from "%s" to "%s"',s,y)),o.trace("Attempting to resolve DNSLink for %s",y);try{d=await t.resolveDNSLink(y,n),l=d?.cid,u=d?.path,o.trace("resolved %s to %c",y,l)}catch(g){n?.signal?.throwIfAborted(),o.error('could not resolve DnsLink for "%s"',s,g),f.push(g)}}}if(l==null)throw f.length===1?f[0]:new AggregateError(f,`Invalid resource. Cannot determine CID from URL "${r}"`);let h=Sk(d);d!=null&&(h=h??60*2,o.trace("caching %s resolved to %s with TTL: %s",s,l,h),Eb.set(s,d,h*1e3));let m={};if(c!=null&&c.length>0){let p=c.split("&");for(let y of p){let[g,x]=y.split("=");m[g]=decodeURIComponent(x)}m.download!=null&&(m.download=m.download==="true"),m.filename!=null&&(m.filename=m.filename.toString())}return{protocol:i,cid:l,path:_k(u,a??""),query:m,ttl:h,ipfsPath:`/${i}/${s}${a!=null&&a!==""?`/${a}`:""}`}}function _k(r,t){let e="";return r!=null&&(e+=r),t.length>0&&(e=`${e.length>0?`${e}/`:e}${t}`),e=e.replace(/\/(\/)+/g,"/"),e.startsWith("/")&&(e=e.substring(1)),e.split("/").map(decodeURIComponent).join("/")}function wd(r,t,e){Object.defineProperty(r,t,{enumerable:!0,configurable:!1,set:()=>{},get:()=>e})}function Fr(r,t){wd(r,"type",t)}function Mr(r,t){wd(r,"url",t)}function Sb(r){wd(r,"redirected",!0)}function Hn(r,t,e){let n=new Response(t,{...e??{},status:200,statusText:"OK"});return e?.redirected===!0&&Sb(n),Fr(n,"basic"),Mr(n,r),n.headers.set("Accept-Ranges","bytes"),n}function Ml(r,t,e){let n=new Response(t,{...e??{},status:502,statusText:"Bad Gateway"});return Fr(n,"basic"),Mr(n,r),n}function Vl(r,t,e){let n=new Response(t,{...e??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Fr(n,"basic"),Mr(n,r),n}function qo(r,t,e){let n=new Response(t,{...e??{},status:406,statusText:"Not Acceptable"});return Fr(n,"basic"),Mr(n,r),n}function Hl(r,t,e){let n=new Response(t,{...e??{},status:404,statusText:"Not Found"});return Fr(n,"basic"),Mr(n,r),n}function $l(r,t,e){t instanceof Error&&(t=t.message);let n=new Response(t,{...e??{},status:400,statusText:"Bad Request"});return Fr(n,"basic"),Mr(n,r),n}function as(r,t,e){let n=new Response(null,{...e??{},status:301,statusText:"Moved Permanently",headers:{...e?.headers??{},location:t}});return Fr(n,"basic"),Mr(n,r),n}function bd(r,t,{byteRangeContext:e,log:n},o){if(!e.isRangeRequest)return Hn(r,t,o);if(!e.isValidRangeRequest)return Fl(r,t,o);let i;try{i=new Response(t,{...o??{},status:206,statusText:"Partial Content",headers:{...o?.headers??{},"content-range":e.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),Fl(r,t,o)}return o?.redirected===!0&&Sb(i),Fr(i,"basic"),Mr(i,r),i.headers.set("Accept-Ranges","bytes"),i}function Fl(r,t,e){let n=new Response(t,{...e??{},status:416,statusText:"Requested Range Not Satisfiable"});return Fr(n,"basic"),Mr(n,r),n}function Ab(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function Ib({resource:r,options:t,logger:e,cid:n,fetch:o=globalThis.fetch}){let i=e.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||t==null||["ipfs://","ipns://"].some(u=>r.startsWith(u)))return null;let s=new Headers(t?.headers),a=s.get("x-forwarded-host"),c=s.get("host");if(s.get("x-forwarded-for")==null&&a==null&&c==null)return i.trace("no redirect info found in headers"),null;i.trace("checking for redirect info");try{let u=ss(r),f=new URL(r),d=a??f.host,h=new URL(f);if(u.protocol==="ipfs"&&n.version===0?h.host=`${n.toV1()}.ipfs.${d}`:h.host=`${u.cidOrPeerIdOrDnsLink}.${u.protocol}.${d}`,c?.includes(u.protocol)===!0&&h.host.includes(c))return i.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!h.host.includes(c))return i.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(f.host===h.host)return i.trace("req url is the same as the subdomain url, not setting location header"),null;h.pathname=Ab(f.pathname.replace(`/${u.cidOrPeerIdOrDnsLink}`,"").replace(`/${u.protocol}`,"")),i.trace("subdomain url %s",h.href);let m=new URL(f,`${f.protocol}//${d}`);m.pathname=Ab(f.pathname),i.trace("path url %s",m.href);try{let p=await o(h,{method:"HEAD"});if(p.ok)return i("subdomain supported, redirecting to subdomain"),as(r.toString(),h.href);throw i("subdomain not supported, subdomain failed with status %s %s",p.status,p.statusText),new Rl("subdomain not supported")}catch(p){return i("subdomain not supported",p),m.href===f.href?(i("path url is the same as the request url, not setting location header"),null):as(r.toString(),m.href)}}catch(u){i.error("error setting location header for x-forwarded-host",u)}return null}async function kb(r,{ipns:t,logger:e},n){if(typeof r=="string")return vb({urlString:r,ipns:t,logger:e},n);let o=L.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function _b(r){let t=L.asCID(r);if(t!=null)return`ipfs://${t}`;try{return`ipfs://${L.parse(r.toString())}`}catch{}let{protocol:e,cidOrPeerIdOrDnsLink:n}=ss(r.toString());return`${e}://${n}`}async function Bk(r,t,e){let n=[],o;for await(let i of ld(t,r,e))n.push(i.cid),o=i;if(o==null)throw new Pl("No terminal element found");return{ipfsRoots:n,terminalElement:o}}function Bb(r){return r.type==="object"}async function xd({cid:r,path:t,resource:e,options:n,blockstore:o,log:i}){try{return await Bk(o,`${r.toString()}/${t}`,n)}catch(s){return n?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?Hl(e):(i.error("error walking path %s",t,s),Ml(e,"Error walking path"))}}var Tk=100,Ck=60*1e3;function Rk(r){if(r==null)return;let t;return r?.signal===null?t=void 0:t=r?.signal,{...r,signal:t}}var Nk=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function Lk({headers:r,accept:t}){let n=(t??new Headers(r).get("accept")??"").split(",").map(o=>o.split(";")[0]).map(o=>o.trim());for(let o of n){if(o==="*/*")return;if(Nk.includes(o??""))return o}}var zl=class{helia;ipns;log;contentTypeParser;blockstoreSessions;constructor({helia:t,ipns:e},n){this.helia=t,this.log=t.logger.forComponent("helia:verified-fetch"),this.ipns=e??ww(t),this.contentTypeParser=n?.contentTypeParser,this.blockstoreSessions=new Tl({max:n?.sessionCacheSize??Tk,ttl:n?.sessionTTLms??Ck,dispose:o=>{o.close()}}),this.log.trace("created VerifiedFetch instance")}getBlockstore(t,e,n,o){let i=_b(e);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(i);return s==null&&(s=this.helia.blockstore.createSession(t,o),this.blockstoreSessions.set(i,s)),s}async handleIPNSRecord({resource:t,cid:e,path:n,options:o}){if(n!==""||!t.startsWith("ipns://"))return $l(t,"Invalid IPNS name");let i;try{i=mo(t.replace("ipns://",""))}catch(f){return this.log.error("could not parse peer id from IPNS url %s",t),$l(t,f)}let s=ct([D("/ipns/"),i.toMultihash().bytes]),a=new At("/dht/record/"+q(s,"base32"),!1),c=await this.helia.datastore.get(a,o),l=ar.deserialize(c),u=Hn(t,l.value);return u.headers.set("content-type","application/vnd.ipfs.ipns-record"),u}async handleCar({resource:t,cid:e,session:n,options:o}){let i=this.getBlockstore(e,t,n,o),s=Wy({blockstore:i,getCodec:this.helia.getCodec}),a=_l(s.stream(e,o)),c=Hn(t,a);return c.headers.set("content-type","application/vnd.ipld.car; version=1"),c}async handleTar({resource:t,cid:e,path:n,session:o,options:i}){if(e.code!==Te&&e.code!==ae)return qo("only UnixFS data can be returned in a TAR file");let s=this.getBlockstore(e,t,o,i),a=_l(bb(`/ipfs/${e}/${n}`,s,i)),c=Hn(t,a);return c.headers.set("content-type","application/x-tar"),c}async handleJson({resource:t,cid:e,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",e,n);let c=await this.getBlockstore(e,t,i,s).get(e,s),l;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let f=ko(c);l=Ao(f)}catch(f){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",f),qo(t)}else l=c;let u=Hn(t,l);return u.headers.set("content-type",o??"application/json"),u}async handleDagCbor({resource:t,cid:e,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",e,n);let a,c=this.getBlockstore(e,t,i,s),l=await xd({cid:e,path:n,resource:t,options:s,blockstore:c,log:this.log});if(l instanceof Response)return l;let u=l.ipfsRoots;if(Bb(l.terminalElement))a=l.terminalElement;else return this.log.error("terminal element is not a dag-cbor node"),Vl(t,"Terminal element is not a dag-cbor node");let f=a.node,d;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")d=f;else if(o==="application/vnd.ipld.dag-json")try{let m=cn(f);d=dc(m)}catch(m){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",m),qo(t)}else try{d=ob(f)}catch(m){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',m),qo(t);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",m),d=f}let h=Hn(t,d);return o==null&&(o=d instanceof Uint8Array?"application/octet-stream":"application/json"),h.headers.set("content-type",o),hd(h,u),h}async handleDagPb({cid:t,path:e,resource:n,session:o,options:i}){let s=!1,a=new os(this.helia.logger,i?.headers),c=this.getBlockstore(t,n,o,i),l=await xd({cid:t,path:e,resource:n,options:i,blockstore:c,log:this.log});if(l instanceof Response)return l;let u=l.ipfsRoots,f=l.terminalElement,d=f.cid;if(f?.type==="directory"){let p=f.cid;if(e===""?!n.toString().endsWith("/"):!e.endsWith("/")){if(i?.redirect==="error")throw this.log('could not redirect to %s/ as redirect option was set to "error"',n),new TypeError("Failed to fetch");if(i?.redirect==="manual")return this.log("returning 301 permanent redirect to %s/",n),as(n,`${n}/`);n=`${n}/`,s=!0}let g="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",t,e);let x=await Ho(`/ipfs/${p}/${g}`,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress});this.log.trace("found root file at %c/%s with cid %c",p,g,x.cid),e=g,d=x.cid}catch(x){return i?.signal?.throwIfAborted(),this.log("error loading path %c/%s",p,g,x),Vl("Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented")}finally{i?.onProgress?.(new H("verified-fetch:request:end",{cid:p,path:g}))}}a.isRangeRequest&&a.isValidRangeRequest&&f.type==="file"&&(a.setFileSize(f.unixfs.fileSize()),this.log.trace("fileSize for rangeRequest %d",a.getFileSize()));let h=a.offset,m=a.length;this.log.trace("calling exporter for %c/%s with offset=%o & length=%o",d,e,h,m);try{let y=(await Ho(d,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress})).content({signal:i?.signal,onProgress:i?.onProgress,offset:h,length:m});this.log("got async iterator for %c/%s",t,e);let{stream:g,firstChunk:x}=await fb(y,e??"",this.helia.logger,{onProgress:i?.onProgress,signal:i?.signal});a.setBody(g);let b=bd(n,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:s});return await this.setContentType(x,e,b),hd(b,u),b}catch(p){return i?.signal?.throwIfAborted(),this.log.error("error streaming %c/%s",t,e,p),a.isRangeRequest&&p.code==="ERR_INVALID_PARAMS"?Fl(n):Ml(n.toString(),"Unable to stream content")}}async handleRaw({resource:t,cid:e,path:n,session:o,options:i,accept:s}){if(n!=="")return this.log.trace("404-ing raw codec request for %c/%s",e,n),Hl(t,"Raw codec does not support paths");let a=new os(this.helia.logger,i?.headers),l=await this.getBlockstore(e,t,o,i).get(e,i);a.setBody(l);let u=bd(t,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:!1});return await this.setContentType(l,n,u,Lk({headers:i?.headers,accept:s})),u}async setContentType(t,e,n,o="application/octet-stream"){let i;if(this.contentTypeParser!=null)try{let s=e.split("/").pop()?.trim();s=s===""?void 0:s;let a=this.contentTypeParser(t,s);if(Pk(a)){let c=await a;c!=null&&(i=c)}else a!=null&&(i=a)}catch(s){this.log.error("error parsing content type",s)}this.log.trace('setting content type to "%s"',i??o),n.headers.set("content-type",i??o)}codecHandlers={[Te]:this.handleDagPb,[Rr]:this.handleJson,[hr]:this.handleJson,[Cr]:this.handleDagCbor,[ae]:this.handleRaw,[bt.code]:this.handleRaw};async fetch(t,e){this.log("fetch %s",t);let n=Rk(e);n?.onProgress?.(new H("verified-fetch:request:start",{resource:t}));let o,i,s,a,c,l;try{let g=await kb(t,{ipns:this.ipns,logger:this.helia.logger},n);o=g.cid,i=g.path,s=g.query,a=g.ttl,c=g.protocol,l=g.ipfsPath}catch(g){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",t,g),$l(t.toString(),g)}n?.onProgress?.(new H("verified-fetch:request:resolve",{cid:o,path:i}));let u=ub({query:s,headers:n?.headers,logger:this.helia.logger}),f=ab(o,u);if(this.log("output type %s",f),u!=null&&f==null)return qo(t.toString());let d,h,m=await Ib({resource:t,options:n,logger:this.helia.logger,cid:o});if(m!=null)return m;let p={resource:t.toString(),cid:o,path:i,accept:f,session:n?.session??!0,options:n};if(f==="application/vnd.ipfs.ipns-record")h="ipns-record",d=await this.handleIPNSRecord(p);else if(f==="application/vnd.ipld.car")h="car",s.download=!0,s.filename=s.filename??`${o.toString()}.car`,d=await this.handleCar(p);else if(f==="application/vnd.ipld.raw")h="raw",s.download=!0,s.filename=s.filename??`${o.toString()}.bin`,d=await this.handleRaw(p);else if(f==="application/x-tar")h="tar",s.download=!0,s.filename=s.filename??`${o.toString()}.tar`,d=await this.handleTar(p);else{this.log.trace('finding handler for cid code "%s" and output type "%s"',o.code,f);let g=this.codecHandlers[o.code];if(g==null)return Vl(`Support for codec with code ${o.code} is not yet implemented. Please open an issue at https://github.com/ipfs/helia-verified-fetch/issues/new`);this.log.trace('calling handler "%s"',g.name),d=await g.call(this,p)}d.headers.set("etag",sb({cid:o,reqFormat:h,weak:!1})),rb({response:d,ttl:a,protocol:c}),d.headers.set("X-Ipfs-Path",l);let y;return s.download===!0&&(y="attachment"),s.filename!=null&&(y==null&&(y="inline"),y=`${y}; ${ib(s.filename)}`),y!=null&&d.headers.set("Content-Disposition",y),n?.onProgress?.(new H("verified-fetch:request:end",{cid:o,path:i})),d}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function Pk(r){return r?.then!=null}var cs,ql=async function(t,e){return cs==null&&(cs=await Ed()),cs(t,e)};ql.start=async function(){await cs?.start()};ql.stop=async function(){await cs?.stop()};async function Ed(r,t){Dk(r)||(r=await Ry({blockBrokers:[Hi({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})],routers:[...(r?.routers??["https://delegated-ipfs.dev"]).map(o=>Ki(o)),Gi({gateways:r?.gateways??["https://trustless-gateway.link"]})],dns:Ok(r?.dnsResolvers)}));let e=new zl({helia:r},t);async function n(o,i){return e.fetch(o,i)}return n.stop=e.stop.bind(e),n.start=e.start.bind(e),n}function Dk(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function Ok(r){if(r!=null)return Array.isArray(r)?Ai({resolvers:{".":r}}):Ai({resolvers:r})}return $b(Uk);})();
|
|
18
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),s_=new RegExp(`(?:^${Ke}$)|(?:^${Qc}$)`),a_=new RegExp(`^${Ke}$`),c_=new RegExp(`^${Qc}$`),$h=r=>r&&r.exact?s_:new RegExp(`(?:${ln(r)}${Ke}${ln(r)})|(?:${ln(r)}${Qc}${ln(r)})`,"g");$h.v4=r=>r&&r.exact?a_:new RegExp(`${ln(r)}${Ke}${ln(r)}`,"g");$h.v6=r=>r&&r.exact?c_:new RegExp(`${ln(r)}${Qc}${ln(r)}`,"g");var zh=$h;function qh(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function Ly(){return!1}var{toString:l_}=Object.prototype;function Kh(r){return l_.call(r)==="[object RegExp]"}var Dy={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Gh(r,t={}){if(!Kh(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(Dy).map(o=>(typeof t[o]=="boolean"?t[o]:r[o])?Dy[o]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function Wh(r,t,{timeout:e}={}){try{return qh(()=>Gh(r).test(t),{timeout:e})()}catch(n){if(Ly(n))return!1;throw n}}var u_=15,f_=45,Oy={timeout:400};function jh(r){return r.length>f_?!1:Wh(zh.v6({exact:!0}),r,Oy)}function Uy(r){return r.length>u_?!1:Wh(zh.v4({exact:!0}),r,Oy)}var Fy={http:"80",https:"443",ws:"80",wss:"443"},h_=["http","https","ws","wss"];function My(r,t){t=t??{};let e=t.defaultDnsType??"dns4",{scheme:n,hostname:o,port:i}=d_(r),a="/"+[p_(o,e),m_(i,n),g_(n)].filter(c=>!!c).reduce((c,l)=>c.concat(l),[]).join("/");return Lr(a)}function d_(r){let[t]=r.split(":");h_.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:o}=new URL(r);if(o==null||o===""){let i=y_(t);i!=null&&(o=i),i==null&&e==="http:"&&(o="80")}return{scheme:t,hostname:n,port:o}}function p_(r,t){if(!(r==null||r==="")){if(Uy(r))return["ip4",r];if(jh(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(jh(e))return["ip6",e]}return[t,r]}}function m_(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function g_(r){if(r.match(/^tcp$|^udp$/)==null)return[r]}function y_(r){if(!(r==null||r===""||Fy[r]==null))return Fy[r]}var w_=["https://trustless-gateway.link","https://4everland.io"],b_=2336;function x_(r){return r=r.toString(),{id:bo(P.createV1(b_,bt.digest(L(r)))),multiaddrs:[My(r)]}}var Yh=class{gateways;constructor(t={}){this.gateways=(t.gateways??w_).map(e=>x_(e))}async*findProviders(t,e){yield*this.gateways.toSorted(()=>Math.random()>.5?1:-1).map(n=>({...n,protocols:["transport-ipfs-gateway-http"]}))}};function Zi(r={}){return new Yh(r)}var Mn=class{has(t,e){return Promise.reject(new Error(".has is not implemented"))}put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(t,e){for await(let{cid:n,block:o}of t)await this.put(n,o,e),yield n}get(t,e){return Promise.reject(new Error(".get is not implemented"))}async*getMany(t,e){for await(let n of t)yield{cid:n,block:await this.get(n,e)}}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(t,e){for await(let n of t)await this.delete(n,e),yield n}async*getAll(t){throw new Error(".getAll is not implemented")}};var sr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};var Ji=class extends Mn{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(vt.encode(t.multihash.bytes),e),t}get(t){let e=this.data.get(vt.encode(t.multihash.bytes));if(e==null)throw new sr;return e}has(t){return this.data.has(vt.encode(t.multihash.bytes))}async delete(t){this.data.delete(vt.encode(t.multihash.bytes))}async*getAll(){for(let[t,e]of this.data.entries())yield{cid:P.createV1(ae,wt(vt.decode(t))),block:e}}};var wO=Ce("blockstore:core:tiered");var $y="SHARDING";function v_(r){return r[Symbol.asyncIterator]!=null}function S_(r){if(v_(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var Xh=S_;function __(r){return r[Symbol.asyncIterator]!=null}function A_(r,t){return __(r)?async function*(){yield*(await Xh(r)).sort(t)}():function*(){yield*Xh(r).sort(t)}()}var tl=A_;var Or=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await fr(this.putMany(t,n)),t=[],await fr(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=ve(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,i)=>ve(o,i),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,i)=>tl(o,i),n)),t.offset!=null){let o=0,i=t.offset;n=ve(n,()=>o++>=i)}return t.limit!=null&&(n=bs(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=ve(n,i=>i.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,i)=>ve(o,i),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,i)=>tl(o,i),n)),t.offset!=null){let o=t.offset,i=0;n=ve(n,()=>i++>=o)}return t.limit!=null&&(n=bs(n,t.limit)),n}};var Qi=class extends Or{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new sr;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new _t(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new _t(t)}};var ZO=new _t($y);var fU=Ce("datastore:core:tiered");async function qy(r={}){let t=r.datastore??new Qi,e=r.blockstore??new Ji,n=new kc({...r,datastore:t,blockstore:e,blockBrokers:r.blockBrokers??[Gi()],routers:r.routers??[Xi("https://delegated-ipfs.dev"),Zi()]});return r.start!==!1&&await n.start(),n}var Qh=Ut(el(),1);var td=40;function ed(r,t){if(!r.length)throw new Error("Unexpected end of data");let e=Qh.default.decode(r);return t.seek(Qh.default.decode.bytes),e}function rd(r){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),e=0;return{version:2,characteristics:[t.getBigUint64(e,!0),t.getBigUint64(e+=8,!0)],dataOffset:Number(t.getBigUint64(e+=8,!0)),dataSize:Number(t.getBigUint64(e+=8,!0)),indexOffset:Number(t.getBigUint64(e+=8,!0))}}var un={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},ts={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":un.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(un.List(r)!==void 0){for(let t=0;t<r.length;t++){let e=r[t];if(e=ts["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](e),e===void 0)return;if(e!==r[t]){let n=r.slice(0,t);for(let o=t;o<r.length;o++){let i=r[o];if(i=ts["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:un.Int,CarV1HeaderOrV2Pragma:r=>{if(un.Map(r)===void 0)return;let t=Object.entries(r),e=r,n=1;for(let o=0;o<t.length;o++){let[i,s]=t[o];switch(i){case"roots":{let a=ts["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.roots=a}}break;case"version":{n--;let a=ts.Int(r[i]);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.version=a}}break;default:return}}if(!(n>0))return e}},es={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":un.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(un.List(r)!==void 0){for(let t=0;t<r.length;t++){let e=r[t];if(e=es["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](e),e===void 0)return;if(e!==r[t]){let n=r.slice(0,t);for(let o=t;o<r.length;o++){let i=r[o];if(i=es["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:un.Int,CarV1HeaderOrV2Pragma:r=>{if(un.Map(r)===void 0)return;let t=Object.entries(r),e=r,n=1;for(let o=0;o<t.length;o++){let[i,s]=t[o];switch(i){case"roots":{let a=es["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.roots=a}}break;case"version":{n--;let a=es.Int(s);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.version=a}}break;default:return}}if(!(n>0))return e}},nd={toTyped:ts.CarV1HeaderOrV2Pragma,toRepresentation:es.CarV1HeaderOrV2Pragma};var XU=Hf();var $_=Ut(el(),1);var eF=[new T(w.map,2),new T(w.string,"version"),new T(w.uint,1),new T(w.string,"roots")],rF=new T(w.tag,42);async function od(r,t){let e=ed(await r.upTo(8),r);if(e===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(e,!0),o=cn(n);if(nd.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||t!==void 0&&o.version!==t)throw new Error(`Invalid CAR version: ${o.version}${t!==void 0?` (expected ${t})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=rd(await r.exactly(td,!0));r.seek(i.dataOffset-r.pos);let s=await od(r,1);return Object.assign(s,i)}function rs(r){let t=0;return{async upTo(e){return r.subarray(t,t+Math.min(e,r.length-t))},async exactly(e,n=!1){if(e>r.length-t)throw new Error("Unexpected end of data");let o=r.subarray(t,t+e);return n&&(t+=e),o},seek(e){t+=e},get pos(){return t}}}var id=Ut(el(),1),rw=1;function sd(r){let t=To({version:rw,roots:r}),e=id.default.encode(t.length),n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function nw(r){return{async setRoots(t){let e=sd(t);await r.write(e)},async writeBlock(t){let{cid:e,bytes:n}=t;await r.write(new Uint8Array(id.default.encode(e.bytes.length+n.length))),await r.write(e.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return rw}}}function rl(){}function ow(){let r=[],t=null,e=rl,n=!1,o=null,i=rl,s=()=>(t||(t=new Promise(l=>{e=()=>{t=null,e=rl,l()}})),t),a={write(l){r.push(l);let u=s();return i(),u},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&e(),{done:!1,value:l}):n?(e(),{done:!0,value:void 0}):(o||(o=new Promise(u=>{i=()=>(o=null,i=rl,u(c.next()))})),o)}};return{writer:a,iterator:c}}var ns=class r{constructor(t,e){this._encoder=e,this._mutex=e.setRoots(t),this._ended=!1}async put(t){if(!(t.bytes instanceof Uint8Array)||!t.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let e=P.asCID(t.cid);if(!e)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:e,bytes:t.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(t){t=G_(t);let{encoder:e,iterator:n}=iw(),o=new r(t,e),i=new nl(n);return{writer:o,out:i}}static createAppender(){let{encoder:t,iterator:e}=iw();t.setRoots=()=>Promise.resolve();let n=new r([],t),o=new nl(e);return{writer:n,out:o}}static async updateRootsInBytes(t,e){let n=rs(t);await od(n);let o=sd(e);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return t.set(o,0),t}},nl=class{constructor(t){this._iterator=t}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function iw(){let r=ow(),{writer:t,iterator:e}=r;return{encoder:nw(t),iterator:e}}function G_(r){if(r===void 0)return[];if(!Array.isArray(r)){let e=P.asCID(r);if(!e)throw new TypeError("roots must be a single CID or an array of CIDs");return[e]}let t=[];for(let e of r){let n=P.asCID(e);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");t.push(n)}return t}var W_=1,ad=class{components;constructor(t,e){this.components=t}async import(t,e){await fr(this.components.blockstore.putMany(qt(t.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),e))}async export(t,e,n){let o=ht(),i=Array.isArray(t)?t:[t],s=new de({concurrency:W_});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#t(a,s,async(c,l)=>{n?.blockFilter?.has(c.multihash.bytes)!==!0&&(n?.blockFilter?.add(c.multihash.bytes),await e.put({cid:c,bytes:l}))},n)}).catch(()=>{});try{await o.promise}finally{await e.close()}}async*stream(t,e){let{writer:n,out:o}=ns.create(t);this.export(t,n,e).catch(()=>{});for await(let i of o)yield i}async#t(t,e,n,o){let i=await this.components.getCodec(t.code),s=await this.components.blockstore.get(t,o);await n(t,s);let a=ac({bytes:s,cid:t,codec:i});for await(let[,c]of a.links())e.add(async()=>{await this.#t(c,e,n,o)})}};function sw(r,t={}){return new ad(r,t)}W.formatters.b=r=>r==null?"undefined":X.baseEncode(r);W.formatters.t=r=>r==null?"undefined":vt.baseEncode(r);W.formatters.m=r=>r==null?"undefined":se.baseEncode(r);W.formatters.p=r=>r==null?"undefined":r.toString();W.formatters.c=r=>r==null?"undefined":r.toString();W.formatters.k=r=>r==null?"undefined":r.toString();W.formatters.a=r=>r==null?"undefined":r.toString();W.formatters.e=r=>r==null?"undefined":aw(r.stack)??aw(r.message)??r.toString();function j_(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function fn(r){let t=j_(`${r}:trace`);return W.enabled(`${r}:trace`)&&W.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=W(`${r}:trace`)),Object.assign(W(r),{error:W(`${r}:error`),trace:t})}function aw(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var mw=Ut(Mo(),1);var ol=class extends Error{static name="SignatureCreationError";constructor(t="Record signature creation failed"){super(t),this.name="SignatureCreationError"}},Ge=class extends Error{static name="SignatureVerificationError";constructor(t="Record signature verification failed"){super(t),this.name="SignatureVerificationError"}},il=class extends Error{static name="RecordExpiredError";constructor(t="Record has expired"){super(t),this.name="RecordExpiredError"}},Vn=class extends Error{static name="UnsupportedValidityError";constructor(t="The validity type is unsupported"){super(t),this.name="UnsupportedValidityError"}},sl=class extends Error{static name="RecordTooLargeError";constructor(t="The record is too large"){super(t),this.name="RecordTooLargeError"}},os=class extends Error{static name="InvalidValueError";constructor(t="Value must be a valid content path starting with /"){super(t),this.name="InvalidValueError"}},al=class extends Error{static name="InvalidRecordDataError";constructor(t="Invalid record data"){super(t),this.name="InvalidRecordDataError"}},is=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(t="Invalid embedded public key"){super(t),this.name="InvalidEmbeddedPublicKeyError"}};var $t;(function(r){let t;(function(o){o.EOL="EOL"})(t=r.ValidityType||(r.ValidityType={}));let e;(function(o){o[o.EOL=0]="EOL"})(e||(e={})),function(o){o.codec=()=>dr(e)}(t=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=le((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ce(o,r.codec()),r.decode=(o,i)=>ie(o,r.codec(),i)})($t||($t={}));var Y_=fn("ipns:utils"),cw=L("/ipns/"),X_=114,Z_=0,J_=18;function lw(r){let t;if(r.pubKey!=null)try{t=Ra(r.pubKey)}catch(e){throw Y_.error(e),e}if(t!=null)return t}function uw(r,t,e){let n=L(t);return ut([r,e,n])}function ll(r){let t=L("ipns-signature:");return ut([t,r])}function cd(r){return"signatureV1"in r?$t.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}):$t.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function ar(r){let t=$t.decode(r);if(t.sequence!=null&&(t.sequence=BigInt(t.sequence)),t.ttl!=null&&(t.ttl=BigInt(t.ttl)),t.signatureV2==null||t.data==null)throw new Ge("Missing data or signatureV2");let e=dw(t.data),n=Q_(e.Value),o=G(e.Validity);if(t.value!=null&&t.signatureV1!=null)return tA(t),{value:n,validityType:$t.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV1:t.signatureV1,signatureV2:t.signatureV2,data:t.data};if(t.signatureV2!=null)return{value:n,validityType:$t.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV2:t.signatureV2,data:t.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function $o(r){return ut([cw,r.bytes])}function fw(r){let t=wt(r.slice(cw.length));if(!cl(t,Z_)&&!cl(t,J_))throw new _e("Multihash in IPNS key was not identity or sha2-256");return t}function hw(r,t,e,n,o){let i;if(t===$t.ValidityType.EOL)i=0;else throw new Vn("The validity type is unsupported");return or({Value:r,Validity:e,ValidityType:i,Sequence:n,TTL:o})}function dw(r){let t=Ht(r);if(t.ValidityType===0)t.ValidityType=$t.ValidityType.EOL;else throw new Vn("The validity type is unsupported");return Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function Q_(r){let t=G(r).trim();if(t.startsWith("/"))return t;try{return`/ipfs/${P.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${P.parse(t).toV1().toString()}`}catch{}throw new os("Value must be a valid content path starting with /")}function pw(r){if(r!=null){let t=nA(r);if(t!=null)return t.code===X_?`/ipns/${t.toString(Gt)}`:`/ipfs/${t.toV1().toString()}`;if(eA(r))return`/ipns/${Gt.encode(r.bytes)}`;let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e}throw new os("Value must be a valid content path starting with /")}function tA(r){if(r.data==null)throw new al("Record data is missing");let t=dw(r.data);if(!Y(t.Value,r.value??new Uint8Array(0)))throw new Ge('Field "value" did not match between protobuf and CBOR');if(!Y(t.Validity,r.validity??new Uint8Array(0)))throw new Ge('Field "validity" did not match between protobuf and CBOR');if(t.ValidityType!==r.validityType)throw new Ge('Field "validityType" did not match between protobuf and CBOR');if(t.Sequence!==r.sequence)throw new Ge('Field "sequence" did not match between protobuf and CBOR');if(t.TTL!==r.ttl)throw new Ge('Field "ttl" did not match between protobuf and CBOR')}function eA(r){return r.bytes instanceof Uint8Array}function rA(r){return typeof r?.toCID=="function"}function nA(r){if(rA(r))return r.toCID();try{return P.parse(r)}catch{}return P.asCID(r)}function cl(r,t){return r.code===t}var oA=fn("ipns"),gw=60*60*1e9,iA="/ipns/",y7=iA.length,yw={v1Compatible:!0,ttlNs:gw};async function ww(r,t,e,n,o=yw){let i=new mw.default(Date.now()+Number(n)),s=$t.ValidityType.EOL,a=BigInt(o.ttlNs??gw);return sA(r,t,e,s,i.toString(),a,o)}var sA=async(r,t,e,n,o,i,s=yw)=>{e=BigInt(e);let a=L(o),c=pw(t),l=L(c),u=hw(l,n,a,e,i),f=ll(u),d=await r.sign(f),h;if(r.type==="RSA"&&(h=lo(r.publicKey)),s.v1Compatible===!0){let m=await aA(r,l,n,a),p={value:c,signatureV1:m,validity:o,validityType:n,sequence:e,ttl:i,signatureV2:d,data:u};return h!=null&&(p.pubKey=h),p}else{let m={value:c,validity:o,validityType:n,sequence:e,ttl:i,signatureV2:d,data:u};return h!=null&&(m.pubKey=h),m}},aA=async(r,t,e,n)=>{try{let o=uw(t,e,n);return await r.sign(o)}catch(o){throw oA.error("record signature creation failed",o),new ol("Record signature creation failed")}};var ld=Ut(Mo(),1);function bw(r,t){let e=t.map((n,o)=>({record:ar(n),index:o}));return e.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===$t.ValidityType.EOL&&o.record.validityType===$t.ValidityType.EOL){let a=ld.default.fromString(n.record.validity).toDate(),c=ld.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),e[0].index}var xw=Ut(Mo(),1);var ul=fn("ipns:validator"),cA=1024*10,lA=async(r,t)=>{let e=ar(t),n;try{let o=ll(e.data);n=await r.verify(o,e.signatureV2)}catch{n=!1}if(!n)throw ul.error("record signature verification failed"),new Ge("Record signature verification failed");if(e.validityType===$t.ValidityType.EOL){if(xw.default.fromString(e.validity).toDate().getTime()<Date.now())throw ul.error("record has expired"),new il("record has expired")}else if(e.validityType!=null)throw ul.error("the validity type is unsupported"),new Vn("The validity type is unsupported");ul("ipns record for %s is valid",e.value)};async function ud(r,t){if(t.byteLength>cA)throw new sl("The record is too large");let e=fw(r),n;cl(e,0)&&(n=rn(e));let o=ar(t),i=lw(o)??n;if(i==null)throw new is("Could not extract public key from IPNS record or routing key");let s=$o(i.toMultihash());if(!Y(r,s))throw new is("Embedded public key did not match routing key");await lA(i,t)}var Ew=Symbol.for("nodejs.util.inspect.custom"),uA=114,ss=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Gn]=!0;toString(){return this.string==null&&(this.string=X.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return P.createV1(uA,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Y(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Y(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Ew](){return`PeerId(${this.toString()})`}},fl=class extends ss{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},hl=class extends ss{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},dl=class extends ss{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},fA=2336,pl=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=bt.digest(L(this.url))}[Ew](){return`PeerId(${this.url})`}[Gn]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return P.createV1(fA,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=G(t)),t.toString()===this.toString())}};function vw(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=wt(X.decode(`z${r}`));else{if(t==null)throw new St('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=wt(t.decode(r))}return hA(e)}function hA(r){if(pA(r))return new fl({multihash:r});if(dA(r))try{let t=rn(r);if(t.type==="Ed25519")return new hl({multihash:r,publicKey:t});if(t.type==="secp256k1")return new dl({multihash:r,publicKey:t})}catch{let e=G(r.digest);return new pl(new URL(e))}throw new _e("Supplied PeerID Multihash is invalid")}function dA(r){return r.code===bt.code}function pA(r){return r.code===Ze.code}var ml=class extends Error{static name="DNSLinkNotFoundError";constructor(t="DNSLink not found"){super(t),this.name="DNSLinkNotFoundError"}},gl=class extends Error{static name="RecordsFailedValidationError";constructor(t="Records failed validation"){super(t),this.name="RecordsFailedValidationError"}},yl=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(t="Unsupported multibase prefix"){super(t),this.name="UnsupportedMultibasePrefixError"}},wl=class extends Error{static name="UnsupportedMultihashCodecError";constructor(t="Unsupported multihash codec"){super(t),this.name="UnsupportedMultihashCodecError"}},bl=class extends Error{static name="InvalidValueError";constructor(t="Invalid value"){super(t),this.name="InvalidValueError"}};var mA=32;async function Sw(r,t,e,n,o={}){if(t===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=((await e.query(r,{...o,types:[pe.TXT]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;n("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,f,d,...h]=u.split("/");if(f==="ipfs")try{return{value:`/ipfs/${P.parse(d)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}else if(f==="ipns"){try{return{value:`/ipns/${vw(d)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}return await xl(d,t-1,e,n,o)}else{if(f==="dnslink")return await xl(d,t-1,e,n,o);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(u){n.error("could not parse DNS link record for domain %s, %s",r,l.data,u)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=((await e.query(r,{...o,types:[pe.CNAME]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await xl(l.data,t-1,e,n,o)}catch(u){n.error("domain %s cname %s had no DNSLink records",r,l.data,u)}throw new ml(`No DNSLink records found for domain: ${r}`)}async function xl(r,t,e,n,o={}){if(t===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await Sw(r,t,e,n,o)}catch(i){if(i.code!=="ENOTFOUND"&&i.code!=="ENODATA"&&i.name!=="DNSLinkNotFoundError"&&i.name!=="NotFoundError")throw i;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,Sw(r,t,e,n,o)}}async function _w(r,t,e,n={}){return xl(r,n.maxRecursiveDepth??mA,t,e,n)}var fd=class{routing;constructor(t){this.routing=t}async put(t,e,n={}){try{await this.routing.put(t,e,n)}catch(o){n.onProgress?.(new H("ipns:routing:helia:error",o))}}async get(t,e={}){try{return await this.routing.get(t,e)}catch(n){e.onProgress?.(new H("ipns:routing:helia:error",n))}throw new Error("Not found")}};function Aw(r){return new fd(r)}var as;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.key!=null&&e.key.byteLength>0&&(n.uint32(10),n.bytes(e.key)),e.value!=null&&e.value.byteLength>0&&(n.uint32(18),n.bytes(e.value)),e.timeReceived!=null&&e.timeReceived!==""&&(n.uint32(42),n.string(e.timeReceived)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={key:re(0),value:re(0),timeReceived:""},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.key=e.bytes();break}case 2:{i.value=e.bytes();break}case 5:{i.timeReceived=e.string();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>ce(e,r.codec()),r.decode=(e,n)=>ie(e,r.codec(),n)})(as||(as={}));function Iw(r){let t=r.getUTCFullYear(),e=String(r.getUTCMonth()+1).padStart(2,"0"),n=String(r.getUTCDate()).padStart(2,"0"),o=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${t}-${e}-${n}T${o}:${i}:${s}.${c}Z`}function kw(r){let t=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),e=String(r).trim().match(t);if(e==null)throw new Error("Invalid format");let n=parseInt(e[1],10),o=parseInt(e[2],10)-1,i=parseInt(e[3],10),s=parseInt(e[4],10),a=parseInt(e[5],10),c=parseInt(e[6],10),l=parseInt(e[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,l))}var cr=class r{key;value;timeReceived;constructor(t,e,n){if(!(t instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(e instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=t,this.value=e,this.timeReceived=n}serialize(){return as.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:Iw(this.timeReceived)}}static deserialize(t){let e=as.decode(t);return new r(e.key,e.value,new Date(e.timeReceived))}static fromDeserialized(t){let e=kw(t.timeReceived);if(t.key==null)throw new Error("key missing from deserialized object");if(t.value==null)throw new Error("value missing from deserialized object");return new r(t.key,t.value,e)}};var El=globalThis.CustomEvent??Event;async function*Hn(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered==null?!1:t.ordered,o=new EventTarget,i=[],s=ht(),a=ht(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(i.length===e&&(s=ht(),await s.promise),u)break;let p={done:!1};i.push(p),m().then(y=>{p.done=!0,p.ok=!0,p.value=y,o.dispatchEvent(new El("task-complete"))},y=>{p.done=!0,p.err=y,o.dispatchEvent(new El("task-complete"))})}c=!0,o.dispatchEvent(new El("task-complete"))}catch(m){l=m,o.dispatchEvent(new El("task-complete"))}});function f(){return n?i[0]?.done:!!i.find(m=>m.done)}function*d(){for(;i.length>0&&i[0].done;){let m=i[0];if(i.shift(),m.ok)yield m.value;else throw u=!0,s.resolve(),m.err;s.resolve()}}function*h(){for(;f();)for(let m=0;m<i.length;m++)if(i[m].done){let p=i[m];if(i.splice(m,1),m--,p.ok)yield p.value;else throw u=!0,s.resolve(),p.err;s.resolve()}}for(;;){if(f()||(a=ht(),await a.promise),l!=null)throw l;if(n?yield*d():yield*h(),c&&i.length===0)break}}var Tw;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER"})(Tw||(Tw={}));function vl(r){return new _t("/dht/record/"+G(r,"base32"),!1)}function Bw(r){return{async put(t,e,n={}){try{let o=vl(t);try{let s=await r.get(o),a=cr.deserialize(s);if(Y(a.value,e))return}catch(s){if(s.name!=="NotFoundError")throw s}let i=new cr(t,e,new Date);n.onProgress?.(new H("ipns:routing:datastore:put")),await r.put(o,i.serialize(),n)}catch(o){throw n.onProgress?.(new H("ipns:routing:datastore:error",o)),o}},async get(t,e={}){try{let n=vl(t);e.onProgress?.(new H("ipns:routing:datastore:get"));let o=await r.get(n,e),i=cr.deserialize(o);return{record:i.value,created:i.timeReceived}}catch(n){throw e.onProgress?.(new H("ipns:routing:datastore:error",n)),n}},async has(t,e={}){let n=vl(t);return r.has(n,e)},async delete(t,e){let n=vl(t);return r.delete(n,e)}}}function hd(r,t){return r.code===t}var Ur=fn("helia:ipns"),bA=60*1e3,md=60*bA,xA=24*md,dd=23*md,EA=BigInt(md)*1000000n,Cw={[Gt.prefix]:Gt,[X.prefix]:X},pd=class{routers;localStore;timeout;dns;log;constructor(t,e=[]){this.routers=[Aw(t.routing),...e],this.localStore=Bw(t.datastore),this.dns=t.dns,this.log=t.logger.forComponent("helia:ipns")}async publish(t,e,n={}){try{let o=1n,i=$o(t.publicKey.toMultihash());if(await this.localStore.has(i,n)){let{record:c}=await this.localStore.get(i,n);o=ar(c).sequence+1n}let s=await ww(t,e,o,n.lifetime??xA,n),a=cd(s);return await this.localStore.put(i,a,n),n.offline!==!0&&await Promise.all(this.routers.map(async c=>{await c.put(i,a,n)})),s}catch(o){throw n.onProgress?.(new H("ipns:publish:error",o)),o}}async resolve(t,e={}){let n=Fd(t)?t.toMultihash():t,o=$o(n),i=await this.#r(o,e);return{...await this.#t(i.value,e),record:i}}async resolveDNSLink(t,e={}){let n=await _w(t,this.dns,this.log,e);return{...await this.#t(n.value,e),answer:n.answer}}republish(t={}){if(this.timeout!=null)throw new Error("Republish is already running");t.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function e(){let n=Date.now();t.onProgress?.(new H("ipns:republish:start"));let i=Date.now()-n,s=dd-i;s<0&&(s=t.interval??dd),setTimeout(()=>{e().catch(a=>{Ur.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{e().catch(n=>{Ur.error("error republishing",n)})},t.interval??dd)}async#t(t,e={}){let n=t.split("/");try{let o=n[1];if(o==="ipns"){let i=n[2],s=i.substring(0,1),a;if(s==="1"||s==="Q")a=X.decode(`z${i}`);else if(Cw[s]!=null)a=Cw[s].decode(i);else throw new yl(`Unsupported multibase prefix "${s}"`);let c;try{c=wt(a)}catch{c=P.decode(a).multihash}if(!hd(c,0)&&!hd(c,18))throw new wl(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,e),u=n.slice(3).join("/");return{cid:l,path:u}}else if(o==="ipfs"){let i=P.parse(n[2]),s=n.slice(3).join("/");return{cid:i,path:s}}}catch(o){Ur.error("error parsing ipfs path",o)}throw Ur.error("invalid ipfs path %s",t),new bl("Invalid value")}async#r(t,e={}){let n=[];if(await this.localStore.has(t,e))if(Ur("record is present in the cache"),e.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(t,e);this.log("record retrieved from cache"),await ud(t,a),this.log("record was valid");let l=ar(a),u=Number((l.ttl??EA)/1000000n);if(c.getTime()+u>Date.now())return this.log("record TTL was valid"),l;if(e.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(t,e)}else Ur("ignoring local cache due to nocache=true option");if(e.offline===!0)throw new kt("Record was not present in the cache or has expired");Ur("did not have record locally");let i=0;if(await Promise.all(this.routers.map(async a=>{let c;try{c=await a.get(t,{...e,validate:!1})}catch(l){Ur.error("error finding IPNS record",l);return}try{await ud(t,c),n.push(c)}catch(l){i++,Ur.error("error finding IPNS record",l)}})),n.length===0)throw i>0?new gl(`${i>1?`${i} records`:"Record"} found for routing key ${i>1?"were":"was"} invalid`):new kt("Could not find record for routing key");let s=n[bw(t,n)];return await this.localStore.put(t,s,e),ar(s)}};function Rw(r,{routers:t=[]}={}){return new pd(r,t)}var Nw;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER"})(Nw||(Nw={}));function vA(r){return r[Symbol.asyncIterator]!=null}function SA(r){if(vA(r))return(async()=>{let e;for await(let n of r)e=n;return e})();let t;for(let e of r)t=e;return t}var Pw=SA;var Sl=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(t="Bad path"){super(t)}},Re=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not found"){super(t)}},_l=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(t="No resolver"){super(t)}},Ct=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(t="Not UnixFS"){super(t)}},Al=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(t="Over read"){super(t)}},Il=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(t="Under read"){super(t)}},kl=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(t="No Property found"){super(t)}},$n=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(t="Invalid parameters"){super(t)}};function zo(r,t,e,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let u=P.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:o,cid:e,node:t,depth:s,size:BigInt(t.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:i}};a=a[l]}else throw new kl(`No property named ${l} found in node ${e}`)}return{entry:{type:"object",name:n,path:o,cid:e,node:t,depth:s,size:BigInt(t.length),content:async function*(){yield r}}}}var _A=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=cn(c);return zo(l,c,r,t,e,n,i)},Lw=_A;var AA=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=Co(c);return zo(l,c,r,t,e,n,i)},Dw=AA;function IA(r,t,e,n){let o=BigInt(r.length),i=BigInt(t+o);return e>=i||n<t?new Uint8Array(0):(n>=t&&n<i&&(r=r.subarray(0,Number(n-t))),e>=t&&e<i&&(r=r.subarray(Number(e-t))),r)}var zn=IA;var kA=(r,t=0,e=r)=>{let n=BigInt(r),o=BigInt(t??0),i=BigInt(e);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw new $n("Offset must be greater than or equal to 0");if(o>n)throw new $n("Offset must be less than the file size");if(i<0n)throw new $n("Length must be greater than or equal to 0");if(i>n)throw new $n("Length must be less than the file size");return{start:o,end:i}},qo=kA;var TA=r=>{async function*t(e={}){let{start:n,end:o}=qo(r.length,e.offset,e.length),i=zn(r,0n,n,o);e.onProgress?.(new H("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return t},BA=async(r,t,e,n,o,i,s,a)=>{if(n.length>0)throw new Re(`No link named ${e} found in raw node ${r}`);let c=wt(r.multihash.bytes);return{entry:{type:"identity",name:t,path:e,cid:r,content:TA(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},Ow=BA;var CA=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=Tu(c);return zo(l,c,r,t,e,n,i)},Uw=CA;var RA=r=>{async function*t(e={}){let{start:n,end:o}=qo(r.length,e.offset,e.length),i=zn(r,0n,n,o);e.onProgress?.(new H("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return t},NA=async(r,t,e,n,o,i,s,a)=>{if(n.length>0)throw new Re(`No link named ${e} found in raw node ${r}`);let c=await s.get(r,a);return{entry:{type:"raw",name:t,path:e,cid:r,content:RA(c),depth:i,size:BigInt(c.length),node:c}}},Fw=NA;var cs=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(t="Invalid type"){super(t)}};var We;(function(r){let t;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(t=r.DataType||(r.DataType={}));let e;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(e||(e={})),function(o){o.codec=()=>dr(e)}(t=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=le((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),r.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let a of o.blocksizes)i.uint32(32),i.uint64(a);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),Tl.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=Tl.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>ce(o,r.codec()),r.decode=o=>ie(o,r.codec())})(We||(We={}));var Tl;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Seconds!=null&&(n.uint32(8),n.int64(e.Seconds)),e.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(e.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let s=e.uint32();switch(s>>>3){case 1:o.Seconds=e.int64();break;case 2:o.FractionalNanoseconds=e.fixed32();break;default:e.skipType(s&7);break}}return o})),t),r.encode=e=>ce(e,r.codec()),r.decode=e=>ie(e,r.codec())})(Tl||(Tl={}));var Mw;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.MimeType!=null&&(n.uint32(10),n.string(e.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let s=e.uint32();switch(s>>>3){case 1:o.MimeType=e.string();break;default:e.skipType(s&7);break}}return o})),t),r.encode=e=>ce(e,r.codec()),r.decode=e=>ie(e,r.codec())})(Mw||(Mw={}));var Vw={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},PA=["directory","hamt-sharded-directory"],Hw=parseInt("0644",8),$w=parseInt("0755",8),lr=class r{static unmarshal(t){let e=We.decode(t),n=new r({type:Vw[e.Type!=null?e.Type.toString():"File"],data:e.Data,blockSizes:e.blocksizes,mode:e.mode,mtime:e.mtime!=null?{secs:e.mtime.Seconds??0n,nsecs:e.mtime.FractionalNanoseconds}:void 0,fanout:e.fanout});return n._originalMode=e.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(t={type:"file"}){let{type:e,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=t;if(e!=null&&!Object.values(Vw).includes(e))throw new cs("Type: "+e+" is not valid");this.type=e??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(t){t==null?this._mode=this.isDirectory()?$w:Hw:this._mode=t&4095}get mode(){return this._mode}isDirectory(){return PA.includes(this.type)}addBlockSize(t){this.blockSizes.push(t)}removeBlockSize(t){this.blockSizes.splice(t,1)}fileSize(){if(this.isDirectory())return 0n;let t=0n;return this.blockSizes.forEach(e=>{t+=e}),this.data!=null&&(t+=BigInt(this.data.length)),t}marshal(){let t;switch(this.type){case"raw":t=We.DataType.Raw;break;case"directory":t=We.DataType.Directory;break;case"file":t=We.DataType.File;break;case"metadata":t=We.DataType.Metadata;break;case"symlink":t=We.DataType.Symlink;break;case"hamt-sharded-directory":t=We.DataType.HAMTShard;break;default:throw new cs(`Type: ${t} is not valid`)}let e=this.data;(this.data==null||this.data.length===0)&&(e=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===Hw&&!this.isDirectory()&&(n=void 0),n===$w&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),We.encode({Type:t,Data:e,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var Bl=Ut(vf(),1);function LA(r){let t=new Array(4);for(let e=0;e<4;e++)t[e]=r&255,r=r>>8;return new Uint8Array(t)}var gM=xn({name:"murmur3-32",code:35,encode:r=>LA(Bl.default.x86.hash32(r))}),zw=xn({name:"murmur3-128",code:34,encode:r=>wn.fromHex(Bl.default.x64.hash128(r))}),yM=xn({name:"murmur3-x64-64",code:34,encode:r=>wn.fromHex(Bl.default.x64.hash128(r)).subarray(0,8)});var Ww=Ut(Gw(),1);var qn=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(t,e,n=0){this._options=t,this._popCount=0,this._parent=e,this._posAtParent=n,this._children=new Ww.default,this.key=null}async put(t,e){let n=await this._findNewBucketAndPos(t);n.bucket._putAt(n,t,e)}async get(t){let e=await this._findChild(t);if(e!=null)return e.value}async del(t){let e=await this._findPlace(t),n=e.bucket._at(e.pos);n!=null&&n.key===t&&e.bucket._delAt(e.pos)}leafCount(){return this._children.compactArray().reduce((e,n)=>n instanceof r?e+n.leafCount():e+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let t=this._children.compactArray();for(let e of t)e instanceof r?yield*e.eachLeafSeries():yield e}serialize(t,e){let n=[];return e(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(t,e)):o.push(t(i,s))),o),n))}async asyncTransform(t,e){return jw(this,t,e)}toJSON(){return this.serialize(MA,VA)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(t){let e=await this._findPlace(t),n=e.bucket._at(e.pos);if(!(n instanceof r)&&n!=null&&n.key===t)return n}async _findPlace(t){let e=this._options.hash(typeof t=="string"?L(t):t),n=await e.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(e):{bucket:this,pos:n,hash:e,existingChild:o}}async _findNewBucketAndPos(t){let e=await this._findPlace(t);if(e.existingChild!=null&&e.existingChild.key!==t){let n=new r(this._options,e.bucket,e.pos);e.bucket._putObjectAt(e.pos,n);let o=await n._findPlace(e.existingChild.hash);return o.bucket._putAt(o,e.existingChild.key,e.existingChild.value),n._findNewBucketAndPos(e.hash)}return e}_putAt(t,e,n){this._putObjectAt(t.pos,{key:e,value:n,hash:t.hash})}_putObjectAt(t,e){this._children.get(t)==null&&this._popCount++,this._children.set(t,e)}_delAt(t){if(t===-1)throw new Error("Invalid position");this._children.get(t)!=null&&this._popCount--,this._children.unset(t),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let t=this._children.find(FA);if(t!=null&&!(t instanceof r)){let e=t.hash;e.untake(this._options.bits);let n={pos:this._posAtParent,hash:e,bucket:this._parent};this._parent._putAt(n,t.key,t.value)}}else this._parent._delAt(this._posAtParent)}_at(t){return this._children.get(t)}};function FA(r){return!!r}function MA(r,t){return r.key}function VA(r){return r}async function jw(r,t,e){let n=[];for(let o of r._children.compactArray())if(o instanceof qn)await jw(o,t,e);else{let i=await t(o);n.push({bitField:r._children.bitField(),children:i})}return e(n)}var HA=[255,254,252,248,240,224,192,128],$A=[1,3,7,15,31,63,127,255],Cl=class{_value;_currentBytePos;_currentBitPos;constructor(t){this._value=t,this._currentBytePos=t.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(t){let e=t,n=0;for(;e>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,e),a=zA(o,i-s,s);n=(n<<s)+a,e-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(t){for(this._currentBitPos+=t;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function zA(r,t,e){let n=qA(t,e);return(r&n)>>>t}function qA(r,t){return HA[r]&$A[Math.min(t+r-1,7)]}function Yw(r){function t(e){return e instanceof Rl?e:new Rl(e,r)}return t}var Rl=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(t,e){if(!(t instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=t,this._hashFn=e,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(t){let e=t;for(;this._availableBits<e;)await this._produceMoreBits();let n=0;for(;e>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),e),s=o.take(i);n=(n<<i)+s,e-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(t){let e=t;for(;e>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),e);n.untake(o),e-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let t=this._depth>0?ut([this._value,Uint8Array.from([this._depth])]):this._value,e=await this._hashFn(t),n=new Cl(e);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Xw(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let t={bits:r.bits??8,hash:Yw(r.hashFn)};return new qn(t)}var KA=async function(r){return(await zw.encode(r)).slice(0,8).reverse()},GA=async(r,t,e)=>{let n=(t.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);t._putObjectAt(i,new qn({hash:e._options.hash,bits:e._options.bits},t,i));return}await e.put(o.Name.substring(2),!0)}))},Zw=(r,t)=>r.toString(16).toUpperCase().padStart(t,"0").substring(0,t),WA=r=>{let t=r.bucket,e=[];for(;t._parent!=null;)e.push(t),t=t._parent;return e.push(t),e.reverse()},Jw=async(r,t,e,n,o)=>{if(n==null){if(r.Data==null)throw new Ct("no data in PBNode");let f;try{f=lr.unmarshal(r.Data)}catch(h){throw new Ct(h.message)}if(f.type!=="hamt-sharded-directory")throw new Ct("not a HAMT");if(f.fanout==null)throw new Ct("missing fanout");let d=Xw({hashFn:KA,bits:Math.log2(Number(f.fanout))});n={rootBucket:d,hamtDepth:1,lastBucket:d}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await GA(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(t),a=Zw(s.pos,i),c=WA(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=Zw(n.lastBucket._posAtParent,i));let l=r.Links.find(f=>{if(f.Name==null)return!1;let d=f.Name.substring(0,i),h=f.Name.substring(i);return!(d!==a||h!==""&&h!==t)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===t)return l.Hash;n.hamtDepth++;let u=await e.get(l.Hash,o);return r=Nr(u),Jw(r,t,e,n,o)},Qw=Jw;var jA=(r,t,e,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??t.Links.length,f=t.Links.slice(l,u);c.onProgress?.(new H("unixfs:exporter:walk:directory",{cid:r})),yield*Xe(f,d=>qt(d,h=>async()=>{let m=h.Name??"",p=`${n}/${m}`;return(await o(h.Hash,m,p,[],i+1,s,c)).entry}),d=>Hn(d,{ordered:!0,concurrency:c.blockReadConcurrency}),d=>ve(d,h=>h!=null))}return a},tb=jA;async function eb(r,t,e,n,o,i,s){if(t instanceof Uint8Array){let l=zn(t,n,o,i);e.push(l);return}if(t.Data==null)throw new Ct("no data in PBNode");let a;try{a=lr.unmarshal(t.Data)}catch(l){throw new Ct(l.message)}if(a.data!=null){let l=a.data,u=zn(l,n,o,i);e.push(u),n+=BigInt(u.byteLength)}let c=[];if(t.Links.length!==a.blockSizes.length)throw new Ct("Inconsistent block sizes and dag links");for(let l=0;l<t.Links.length;l++){let u=t.Links[l],f=n,d=f+a.blockSizes[l];if((o>=f&&o<d||i>=f&&i<=d||o<f&&i>d)&&c.push({link:u,blockStart:n}),n=d,n>i)break}await Xe(c,l=>qt(l,u=>async()=>{let f=await r.get(u.link.Hash,s);return{...u,block:f}}),l=>Hn(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:d}of l){let h;switch(u.Hash.code){case Be:h=Nr(f);break;case ae:h=f;break;default:e.end(new Ct(`Unsupported codec: ${u.Hash.code}`));return}let m=new de({concurrency:1});m.on("error",p=>{e.end(p)}),m.add(async()=>{s.onProgress?.(new H("unixfs:exporter:walk:file",{cid:u.Hash})),await eb(r,h,e,d,o,i,s)}),await m.onIdle()}}),n>=i&&e.end()}var YA=(r,t,e,n,o,i,s)=>{async function*a(c={}){let l=e.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=qo(l,c.offset,c.length);if(f===0n)return;let d=0n,h=f-u,m=je();c.onProgress?.(new H("unixfs:exporter:walk:file",{cid:r})),eb(s,t,m,0n,u,f,c).catch(p=>{m.end(p)});for await(let p of m)if(p!=null){if(d+=BigInt(p.byteLength),d>h)throw m.end(),new Al("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");d===h&&m.end(),c.onProgress?.(new H("unixfs:exporter:progress:unixfs:file",{bytesRead:d,totalBytes:h,fileSize:l})),yield p}if(d<h)throw new Il("Traversed entire DAG but did not read enough bytes")}return a},gd=YA;var XA=(r,t,e,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new H("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),rb(t,n,o,i,s,c)}return a};async function*rb(r,t,e,n,o,i){let s=r.Links;if(r.Data==null)throw new Ct("no data in PBNode");let a;try{a=lr.unmarshal(r.Data)}catch(u){throw new Ct(u.message)}if(a.fanout==null)throw new Ct("missing fanout");let c=(a.fanout-1n).toString(16).length,l=Xe(s,u=>qt(u,f=>async()=>{let d=f.Name!=null?f.Name.substring(c):null;if(d!=null&&d!==""){let h=await e(f.Hash,d,`${t}/${d}`,[],n+1,o,i);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await o.get(f.Hash,i);return r=Nr(h),i.onProgress?.(new H("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:rb(r,t,e,n,o,i)}}}),u=>Hn(u,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var nb=XA;var ZA=(r,t)=>r.Links.find(n=>n.Name===t)?.Hash,JA={raw:gd,file:gd,directory:tb,"hamt-sharded-directory":nb,metadata:(r,t,e,n,o,i,s)=>()=>[],symlink:(r,t,e,n,o,i,s)=>()=>[]},QA=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=Nr(c),u,f;if(t==null&&(t=r.toString()),l.Data==null)throw new Ct("no data in PBNode");try{u=lr.unmarshal(l.Data)}catch(h){throw new Ct(h.message)}if(e==null&&(e=t),n.length>0){let h;if(u?.type==="hamt-sharded-directory"?h=await Qw(l,n[0],s):h=ZA(l,n[0]),h==null)throw new Re("file does not exist");let m=n.shift(),p=`${e}/${m}`;f={cid:h,toResolve:n,name:m??"",path:p}}let d=JA[u.type](r,l,u,e,o,i,s);if(d==null)throw new Re("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:t,path:e,cid:r,content:d,unixfs:u,depth:i,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:t,path:e,cid:r,content:d,unixfs:u,depth:i,node:l,size:u.fileSize()},next:f}},ob=QA;var tI={[Be]:ob,[ae]:Fw,[Cr]:Lw,[Rr]:Dw,[bt.code]:Ow,[hr]:Uw},ib=async(r,t,e,n,o,i,s)=>{let a=tI[r.code];if(a==null)throw new _l(`No resolver for code ${r.code}`);return a(r,t,e,n,ib,o,i,s)},sb=ib;var eI=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),rI=r=>{if(r instanceof Uint8Array)return{cid:P.decode(r),toResolve:[]};let t=P.asCID(r);if(t!=null)return{cid:t,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let e=eI(r);return{cid:P.parse(e[0]),toResolve:e.slice(1)}}throw new Sl(`Unknown path type ${r}`)};async function*yd(r,t,e={}){let{cid:n,toResolve:o}=rI(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await sb(n,i,s,o,a,t,e);if(c.entry==null&&c.next==null)throw new Re(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;o=c.next.toResolve,n=c.next.cid,i=c.next.name,s=c.next.path}}async function Ko(r,t,e={}){let n=await Pw(yd(r,t,e));if(n==null)throw new Re(`Could not resolve ${r}`);return n}async function*ab(r,t,e={}){let n=await Ko(r,t,e);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,e))yield i;async function*o(i,s){for await(let a of i.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*o(a,s))}}function cb(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Nl(r,t={}){let e=cb(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await e.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,t)}var Go=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,ub=new Set,wd=typeof process=="object"&&process?process:{},fb=(r,t,e,n)=>{typeof wd.emitWarning=="function"?wd.emitWarning(r,t,e,n):console.error(`[${e}] ${t}: ${r}`)},Pl=globalThis.AbortController,lb=globalThis.AbortSignal;if(typeof Pl>"u"){lb=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},Pl=class{constructor(){t()}signal=new lb;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=wd.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{r&&(r=!1,fb("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var nI=r=>!ub.has(r),DV=Symbol("type"),hn=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),hb=r=>hn(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Wo:null:null,Wo=class extends Array{constructor(t){super(t),this.fill(0)}},bd=class r{heap;length;static#t=!1;static create(t){let e=hb(t);if(!e)return[];r.#t=!0;let n=new r(t,e);return r.#t=!1,n}constructor(t,e){if(!r.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Ll=class r{#t;#r;#o;#c;#g;#S;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#n;#s;#e;#h;#l;#d;#u;#b;#f;#x;#E;#m;#w;#_;#p;static unsafeExposeInternals(t){return{starts:t.#E,ttls:t.#m,sizes:t.#x,keyMap:t.#n,keyList:t.#s,valList:t.#e,next:t.#h,prev:t.#l,get head(){return t.#d},get tail(){return t.#u},free:t.#b,isBackgroundFetch:e=>t.#a(e),backgroundFetch:(e,n,o,i)=>t.#D(e,n,o,i),moveToTail:e=>t.#N(e),indexes:e=>t.#I(e),rindexes:e=>t.#k(e),isStale:e=>t.#v(e)}}get max(){return this.#t}get maxSize(){return this.#r}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#g}get memoMethod(){return this.#S}get dispose(){return this.#o}get disposeAfter(){return this.#c}constructor(t){let{max:e=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:f,noUpdateTTL:d,maxSize:h=0,maxEntrySize:m=0,sizeCalculation:p,fetchMethod:y,memoMethod:g,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:I,ignoreFetchAbort:B}=t;if(e!==0&&!hn(e))throw new TypeError("max option must be a nonnegative integer");let S=e?hb(e):Array;if(!S)throw new Error("invalid max value: "+e);if(this.#t=e,this.#r=h,this.maxEntrySize=m||this.#r,this.sizeCalculation=p,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(g!==void 0&&typeof g!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=g,y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#g=y,this.#_=!!y,this.#n=new Map,this.#s=new Array(e).fill(void 0),this.#e=new Array(e).fill(void 0),this.#h=new S(e),this.#l=new S(e),this.#d=0,this.#u=0,this.#b=bd.create(e),this.#i=0,this.#y=0,typeof l=="function"&&(this.#o=l),typeof u=="function"?(this.#c=u,this.#f=[]):(this.#c=void 0,this.#f=void 0),this.#w=!!this.#o,this.#p=!!this.#c,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!I,this.ignoreFetchAbort=!!B,this.maxEntrySize!==0){if(this.#r!==0&&!hn(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!hn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#H()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=hn(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!hn(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#C()}if(this.#t===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#r){let v="LRU_CACHE_UNBOUNDED";nI(v)&&(ub.add(v),fb("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",v,r))}}getRemainingTTL(t){return this.#n.has(t)?1/0:0}#C(){let t=new Wo(this.#t),e=new Wo(this.#t);this.#m=t,this.#E=e,this.#O=(i,s,a=Go.now())=>{if(e[i]=s!==0?a:0,t[i]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#v(i)&&this.#T(this.#s[i],"expire")},s+1);c.unref&&c.unref()}},this.#A=i=>{e[i]=t[i]!==0?Go.now():0},this.#B=(i,s)=>{if(t[s]){let a=t[s],c=e[s];if(!a||!c)return;i.ttl=a,i.start=c,i.now=n||o();let l=i.now-c;i.remainingTTL=a-l}};let n=0,o=()=>{let i=Go.now();if(this.ttlResolution>0){n=i;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#n.get(i);if(s===void 0)return 0;let a=t[s],c=e[s];if(!a||!c)return 1/0;let l=(n||o())-c;return a-l},this.#v=i=>{let s=e[i],a=t[i];return!!a&&!!s&&(n||o())-s>a}}#A=()=>{};#B=()=>{};#O=()=>{};#v=()=>!1;#H(){let t=new Wo(this.#t);this.#y=0,this.#x=t,this.#R=e=>{this.#y-=t[e],t[e]=0},this.#U=(e,n,o,i)=>{if(this.#a(n))return 0;if(!hn(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,e),!hn(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#P=(e,n,o)=>{if(t[e]=n,this.#r){let i=this.#r-t[e];for(;this.#y>i;)this.#L(!0)}this.#y+=t[e],o&&(o.entrySize=n,o.totalCalculatedSize=this.#y)}}#R=t=>{};#P=(t,e,n)=>{};#U=(t,e,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#I({allowStale:t=this.allowStale}={}){if(this.#i)for(let e=this.#u;!(!this.#F(e)||((t||!this.#v(e))&&(yield e),e===this.#d));)e=this.#l[e]}*#k({allowStale:t=this.allowStale}={}){if(this.#i)for(let e=this.#d;!(!this.#F(e)||((t||!this.#v(e))&&(yield e),e===this.#u));)e=this.#h[e]}#F(t){return t!==void 0&&this.#n.get(this.#s[t])===t}*entries(){for(let t of this.#I())this.#e[t]!==void 0&&this.#s[t]!==void 0&&!this.#a(this.#e[t])&&(yield[this.#s[t],this.#e[t]])}*rentries(){for(let t of this.#k())this.#e[t]!==void 0&&this.#s[t]!==void 0&&!this.#a(this.#e[t])&&(yield[this.#s[t],this.#e[t]])}*keys(){for(let t of this.#I()){let e=this.#s[t];e!==void 0&&!this.#a(this.#e[t])&&(yield e)}}*rkeys(){for(let t of this.#k()){let e=this.#s[t];e!==void 0&&!this.#a(this.#e[t])&&(yield e)}}*values(){for(let t of this.#I())this.#e[t]!==void 0&&!this.#a(this.#e[t])&&(yield this.#e[t])}*rvalues(){for(let t of this.#k())this.#e[t]!==void 0&&!this.#a(this.#e[t])&&(yield this.#e[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let n of this.#I()){let o=this.#e[n],i=this.#a(o)?o.__staleWhileFetching:o;if(i!==void 0&&t(i,this.#s[n],this))return this.get(this.#s[n],e)}}forEach(t,e=this){for(let n of this.#I()){let o=this.#e[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&t.call(e,i,this.#s[n],this)}}rforEach(t,e=this){for(let n of this.#k()){let o=this.#e[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&t.call(e,i,this.#s[n],this)}}purgeStale(){let t=!1;for(let e of this.#k({allowStale:!0}))this.#v(e)&&(this.#T(this.#s[e],"expire"),t=!0);return t}info(t){let e=this.#n.get(t);if(e===void 0)return;let n=this.#e[e],o=this.#a(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#m&&this.#E){let s=this.#m[e],a=this.#E[e];if(s&&a){let c=s-(Go.now()-a);i.ttl=c,i.start=Date.now()}}return this.#x&&(i.size=this.#x[e]),i}dump(){let t=[];for(let e of this.#I({allowStale:!0})){let n=this.#s[e],o=this.#e[e],i=this.#a(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let s={value:i};if(this.#m&&this.#E){s.ttl=this.#m[e];let a=Go.now()-this.#E[e];s.start=Math.floor(Date.now()-a)}this.#x&&(s.size=this.#x[e]),t.unshift([n,s])}return t}load(t){this.clear();for(let[e,n]of t){if(n.start){let o=Date.now()-n.start;n.start=Go.now()-o}this.set(e,n.value,n)}}set(t,e,n={}){if(e===void 0)return this.delete(t),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,u=this.#U(t,e,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#T(t,"set"),this;let f=this.#i===0?void 0:this.#n.get(t);if(f===void 0)f=this.#i===0?this.#u:this.#b.length!==0?this.#b.pop():this.#i===this.#t?this.#L(!1):this.#i,this.#s[f]=t,this.#e[f]=e,this.#n.set(t,f),this.#h[this.#u]=f,this.#l[f]=this.#u,this.#u=f,this.#i++,this.#P(f,u,c),c&&(c.set="add"),l=!1;else{this.#N(f);let d=this.#e[f];if(e!==d){if(this.#_&&this.#a(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:h}=d;h!==void 0&&!s&&(this.#w&&this.#o?.(h,t,"set"),this.#p&&this.#f?.push([h,t,"set"]))}else s||(this.#w&&this.#o?.(d,t,"set"),this.#p&&this.#f?.push([d,t,"set"]));if(this.#R(f),this.#P(f,u,c),this.#e[f]=e,c){c.set="replace";let h=d&&this.#a(d)?d.__staleWhileFetching:d;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(o!==0&&!this.#m&&this.#C(),this.#m&&(l||this.#O(f,o,i),c&&this.#B(c,f)),!s&&this.#p&&this.#f){let d=this.#f,h;for(;h=d?.shift();)this.#c?.(...h)}return this}pop(){try{for(;this.#i;){let t=this.#e[this.#d];if(this.#L(!0),this.#a(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#p&&this.#f){let t=this.#f,e;for(;e=t?.shift();)this.#c?.(...e)}}}#L(t){let e=this.#d,n=this.#s[e],o=this.#e[e];return this.#_&&this.#a(o)?o.__abortController.abort(new Error("evicted")):(this.#w||this.#p)&&(this.#w&&this.#o?.(o,n,"evict"),this.#p&&this.#f?.push([o,n,"evict"])),this.#R(e),t&&(this.#s[e]=void 0,this.#e[e]=void 0,this.#b.push(e)),this.#i===1?(this.#d=this.#u=0,this.#b.length=0):this.#d=this.#h[e],this.#n.delete(n),this.#i--,e}has(t,e={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=e,i=this.#n.get(t);if(i!==void 0){let s=this.#e[i];if(this.#a(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#v(i))o&&(o.has="stale",this.#B(o,i));else return n&&this.#A(i),o&&(o.has="hit",this.#B(o,i)),!0}else o&&(o.has="miss");return!1}peek(t,e={}){let{allowStale:n=this.allowStale}=e,o=this.#n.get(t);if(o===void 0||!n&&this.#v(o))return;let i=this.#e[o];return this.#a(i)?i.__staleWhileFetching:i}#D(t,e,n,o){let i=e===void 0?void 0:this.#e[e];if(this.#a(i))return i;let s=new Pl,{signal:a}=n;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:n,context:o},l=(p,y=!1)=>{let{aborted:g}=s.signal,x=n.ignoreFetchAbort&&p!==void 0;if(n.status&&(g&&!y?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,x&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),g&&!x&&!y)return f(s.signal.reason);let b=h;return this.#e[e]===h&&(p===void 0?b.__staleWhileFetching?this.#e[e]=b.__staleWhileFetching:this.#T(t,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(t,p,c.options))),p},u=p=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=p),f(p)),f=p=>{let{aborted:y}=s.signal,g=y&&n.allowStaleOnFetchAbort,x=g||n.allowStaleOnFetchRejection,b=x||n.noDeleteOnFetchRejection,E=h;if(this.#e[e]===h&&(!b||E.__staleWhileFetching===void 0?this.#T(t,"fetch"):g||(this.#e[e]=E.__staleWhileFetching)),x)return n.status&&E.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw p},d=(p,y)=>{let g=this.#g?.(t,i,c);g&&g instanceof Promise&&g.then(x=>p(x===void 0?void 0:x),y),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(p(void 0),n.allowStaleOnFetchAbort&&(p=x=>l(x,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(d).then(l,u),m=Object.assign(h,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return e===void 0?(this.set(t,m,{...c.options,status:void 0}),e=this.#n.get(t)):this.#e[e]=m,m}#a(t){if(!this.#_)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof Pl}async fetch(t,e={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:p,forceRefresh:y=!1,status:g,signal:x}=e;if(!this.#_)return g&&(g.fetch="get"),this.get(t,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:g});let b={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:h,status:g,signal:x},E=this.#n.get(t);if(E===void 0){g&&(g.fetch="miss");let I=this.#D(t,E,b,p);return I.__returned=I}else{let I=this.#e[E];if(this.#a(I)){let z=n&&I.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",z&&(g.returnedStale=!0)),z?I.__staleWhileFetching:I.__returned=I}let B=this.#v(E);if(!y&&!B)return g&&(g.fetch="hit"),this.#N(E),o&&this.#A(E),g&&this.#B(g,E),I;let S=this.#D(t,E,b,p),k=S.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=B?"stale":"refresh",k&&B&&(g.returnedStale=!0)),k?S.__staleWhileFetching:S.__returned=S}}async forceFetch(t,e={}){let n=await this.fetch(t,e);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(t,e={}){let n=this.#S;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=e,a=this.get(t,s);if(!i&&a!==void 0)return a;let c=n(t,a,{options:s,context:o});return this.set(t,c,s),c}get(t,e={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=e,a=this.#n.get(t);if(a!==void 0){let c=this.#e[a],l=this.#a(c);return s&&this.#B(s,a),this.#v(a)?(s&&(s.get="stale"),l?(s&&n&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.#T(t,"expire"),s&&n&&(s.returnedStale=!0),n?c:void 0)):(s&&(s.get="hit"),l?c.__staleWhileFetching:(this.#N(a),o&&this.#A(a),c))}else s&&(s.get="miss")}#M(t,e){this.#l[e]=t,this.#h[t]=e}#N(t){t!==this.#u&&(t===this.#d?this.#d=this.#h[t]:this.#M(this.#l[t],this.#h[t]),this.#M(this.#u,t),this.#u=t)}delete(t){return this.#T(t,"delete")}#T(t,e){let n=!1;if(this.#i!==0){let o=this.#n.get(t);if(o!==void 0)if(n=!0,this.#i===1)this.#V(e);else{this.#R(o);let i=this.#e[o];if(this.#a(i)?i.__abortController.abort(new Error("deleted")):(this.#w||this.#p)&&(this.#w&&this.#o?.(i,t,e),this.#p&&this.#f?.push([i,t,e])),this.#n.delete(t),this.#s[o]=void 0,this.#e[o]=void 0,o===this.#u)this.#u=this.#l[o];else if(o===this.#d)this.#d=this.#h[o];else{let s=this.#l[o];this.#h[s]=this.#h[o];let a=this.#h[o];this.#l[a]=this.#l[o]}this.#i--,this.#b.push(o)}}if(this.#p&&this.#f?.length){let o=this.#f,i;for(;i=o?.shift();)this.#c?.(...i)}return n}clear(){return this.#V("delete")}#V(t){for(let e of this.#k({allowStale:!0})){let n=this.#e[e];if(this.#a(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#s[e];this.#w&&this.#o?.(n,o,t),this.#p&&this.#f?.push([n,o,t])}}if(this.#n.clear(),this.#e.fill(void 0),this.#s.fill(void 0),this.#m&&this.#E&&(this.#m.fill(0),this.#E.fill(0)),this.#x&&this.#x.fill(0),this.#d=0,this.#u=0,this.#b.length=0,this.#y=0,this.#i=0,this.#p&&this.#f){let e=this.#f,n;for(;n=e?.shift();)this.#c?.(...n)}}};var Se=class extends Error{static name="InvalidRangeError";constructor(t="Invalid range request"){super(t),this.name="InvalidRangeError"}},Dl=class extends Error{static name="NoContentError";constructor(t="No content found"){super(t),this.name="NoContentError"}},Ol=class extends Error{static name="SubdomainNotSupportedError";constructor(t="Subdomain not supported"){super(t),this.name="SubdomainNotSupportedError"}};function db(r,t){if(r==null)return;if(r instanceof Headers)return r.get(t)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===t.toLowerCase())?.[1];let e=Object.keys(r).find(n=>n.toLowerCase()===t.toLowerCase());if(e!=null)return r[e]}function pb(r,t,e){if((r??0)>(t??1/0))throw new Se("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(t??0)>=(e??1/0))throw new Se("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(t??0)>(e??1/0))throw new Se("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Se("Invalid range: Range-start index cannot be negative.");if(r!=null&&t!=null)return{byteSize:t-r+1,start:r,end:t};if(r==null&&t!=null)return e==null?{end:t}:t===e?{byteSize:e,start:0,end:e-1}:{byteSize:t,start:e-t,end:e-1};if(r!=null&&t==null){if(e==null)return{start:r};let n=e-1;return{byteSize:e-r,start:r,end:n}}return{byteSize:e,start:0,end:e!=null?e-1:0}}function mb({ttl:r,protocol:t,response:e}){let n;t==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,e.headers.set("cache-control",n)}function gb({byteStart:r,byteEnd:t,byteSize:e}){let n=e??"*";if((t??0)>=(e??1/0))throw new Se("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(e??1/0))throw new Se("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&t==null)return e==null?`bytes */${n}`:`bytes ${r}-${e-1}/${e}`;if(r==null&&t!=null){if(e==null)return`bytes */${n}`;let o=e-1;return`bytes ${o-t+1}-${o}/${e}`}return r==null&&t==null?`bytes */${n}`:`bytes ${r}-${t}/${n}`}function xd(r,t){t!=null&&r.headers.set("X-Ipfs-Roots",t.map(e=>e.toV1().toString()).join(","))}function oI(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function iI(r){let t=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(t?.groups==null)throw new Se("Invalid range request");let{start:e,end:n}=t.groups;return{start:e,end:n}}var ls=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(t,e){if(this.headers=e,this.log=t.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=db(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=iI(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=o!=null?parseInt(o):null}catch(n){this.log.error("error parsing range request header: %o",n),this.requestRangeStart=null,this.requestRangeEnd=null}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1,this.requestRangeStart=null,this.requestRangeEnd=null}setBody(t){this._body=t,this.setFileSize(this._fileSize??oI(t)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let t=this._body;if(t==null)return this.log.trace("body is null"),t;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),t;let e=this.byteStart,n=this.byteEnd,o=this.byteSize;return e!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",e,n,o),t instanceof ReadableStream?t:this.getSlicedBody(t)):(this.log.error("returning unmodified body for valid range request"),t)}getSlicedBody(t){let e=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",e,n),t.slice(e,n)}setFileSize(t){this._fileSize=t!=null?Number(t):null,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(){return!(this.byteStart!=null&&(this.byteStart<0||this._fileSize!=null&&this.byteStart>=this._fileSize||this.byteEnd!=null&&this.byteStart>this.byteEnd))}isValidByteEnd(){return!(this.byteEnd!=null&&(this.byteEnd<0||this._fileSize!=null&&this.byteEnd>=this._fileSize||this.byteStart!=null&&this.byteEnd<this.byteStart))}get isValidRangeRequest(){if(!this.isRangeRequest)return!1;if(this.requestRangeStart==null&&this.requestRangeEnd==null)return this.log.trace("invalid range request, range request values not provided"),!1;if(!this.isValidByteStart())return this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1;if(!this.isValidByteEnd())return this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1;if(this.requestRangeEnd!=null&&this.requestRangeStart!=null){if(this.requestRangeStart>this.requestRangeEnd)return this.log.trace("invalid range request, start is greater than end"),!1;if(this.requestRangeStart<0)return this.log.trace("invalid range request, start is less than 0"),!1;if(this.requestRangeEnd<0)return this.log.trace("invalid range request, end is less than 0"),!1}return this.byteEnd==null&&this.byteStart==null&&this.byteSize==null?(this.log.trace("invalid range request, could not calculate byteStart, byteEnd, or byteSize"),!1):!0}get offset(){return this.byteStart??0}get length(){return this.byteEnd!=null&&this.byteStart!=null&&this.byteStart===this.byteEnd?1:this.byteEnd!=null?this.byteEnd+1:this.byteSize!=null?this.byteSize-1:void 0}setOffsetDetails(){if(this.requestRangeStart==null&&this.requestRangeEnd==null){this.log.trace("requestRangeStart and requestRangeEnd are null");return}try{let{start:t,end:e,byteSize:n}=pb(this.requestRangeStart??void 0,this.requestRangeEnd??void 0,this._fileSize??void 0);this.log.trace("set byteStart to %o, byteEnd to %o, byteSize to %o",t,e,n),this.byteStart=t,this.byteEnd=e,this.byteSize=n}catch(t){this.log.error("error setting offset details: %o",t),this.byteStart=void 0,this.byteEnd=void 0,this.byteSize=void 0}}get contentRangeHeaderValue(){if(!this.isValidRangeRequest)throw this.log.error("cannot get contentRangeHeaderValue for invalid range request"),new Se("Invalid range request");return gb({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function yb(r){let t=Ht(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(Oi(t))}function wb(r){let t=sI(r);return t===r?`filename="${r}"`:`filename="${t}"; filename*=UTF-8''${encodeURIComponent(r)}`}function sI(r){return r.replace(/[^\x00-\x7F]/g,"_")}function bb({cid:r,reqFormat:t,weak:e,rangeStart:n,rangeEnd:o}){let i=e===!0?"W/":"",s=t==null?"":`.${t}`;return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}var aI={[Cr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Rr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[hr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Be]:["application/octet-stream","application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","application/x-tar"],[ae]:["application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.dag-json","application/vnd.ipld.car","application/x-tar"]};function xb(r,t){let e=aI[r.code];if(t!=null)return cI(t,e)}function cI(r,t){let e=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:lI(o[1])}}).sort((n,o)=>n.weight===o.weight?0:n.weight>o.weight?-1:1).map(n=>n.mimeType);for(let n of e)for(let o of t)if(n.includes(o)||n==="*/*"||n.startsWith("*/")&&o.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&o.split("/")[0]===n.split("/")[0])return o}function lI(r){if(r!=null&&(r=r.trim()),r?.startsWith("q=")!==!0)return 1;let t=parseFloat(r.replace("q=",""));return isNaN(t)?0:t}var Ul={raw:"application/vnd.ipld.raw",car:"application/vnd.ipld.car","dag-json":"application/vnd.ipld.dag-json","dag-cbor":"application/vnd.ipld.dag-cbor",json:"application/json",cbor:"application/cbor","ipns-record":"application/vnd.ipfs.ipns-record",tar:"application/x-tar"};function Eb(r){if(r!=null)return Ul[r]}function Ed(r){let t=r.get("accept");return!!(t!=null&&Object.values(Ul).includes(t))}function vd(r){let t=r?.format;return!!(t!=null&&Object.keys(Ul).includes(t))}function vb({query:r,headers:t}){return Ed(t)||vd(r)}function Sb({query:r,headers:t,logger:e}){let n=e.forComponent("helia:verified-fetch:get-resolved-accept-header"),o=new Headers(t),i=o.get("accept")??void 0;if(i!=null&&n('incoming accept header "%s"',i),!vb({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=Eb(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=i;return!Ed(o)&&vd(r)&&(n("accept header not recognized, but query format provided, setting accept header to %s",s),a=s),n('resolved accept header to "%s"',a),a}async function _b(r,t,e,n){let o=e.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),i=r[Symbol.asyncIterator](),{value:s,done:a}=await i.next();if(a===!0)throw o.error("no content found for path",t),new Dl;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new H("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await i.next();if(n?.signal?.aborted===!0){l.error(new Ne(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new H("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new H("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var Fl=class extends Error{name;code;constructor(t,e,n){super(t),this.name=e,this.code=n}},us=class extends Fl{constructor(t="not a Unixfs node"){super(t,"NotUnixFSError","ERR_NOT_UNIXFS")}};var Ml=class extends Fl{constructor(t="path does not exist"){super(t,"DoesNotExistError","ERR_DOES_NOT_EXIST")}};var wH=L("ustar\0","binary"),bH=L("ustar ","binary"),xH=L(" \0","binary");var Bb=Ut(Ib(),1);function fI(r){return r[Symbol.asyncIterator]!=null}function hI(r){if(fI(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=ut([n,o],n.length+o.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return ut(t,e)}var kb=hI;var dI="0000000000000000000",pI="7777777777777777777",mI=48,gI=L("ustar\0","binary"),yI=L("00","binary"),wI=parseInt("7777",8),bI=257,xI=263,EI=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},vI=function(r){let t=256;for(let e=0;e<148;e++)t+=r[e];for(let e=156;e<512;e++)t+=r[e];return t},dn=function(r,t){let e=r.toString(8);return e.length>t?L(pI.slice(0,t)+" "):L(dI.slice(0,t-e.length)+e+" ")},Sd=function(r){let t=L(r).byteLength,e=Math.floor(Math.log(t)/Math.log(10))+1;return t+e>=Math.pow(10,e)&&e++,`${t+e}${r}`};function Tb(r){let t="";r.name!=null&&(t+=Sd(" path="+r.name+`
|
|
19
|
+
`)),r.linkname!=null&&(t+=Sd(" linkpath="+r.linkname+`
|
|
20
|
+
`));let e=r.pax;if(e!=null)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t+=Sd(" "+n+"="+e[n]+`
|
|
21
|
+
`));return L(t)}function Vl(r){let t=new Uint8Array(512),e=r.name,n="";if(r.typeflag===5&&e[e.length-1]!=="/"&&(e+="/"),L(e).byteLength!==e.length)return null;for(;L(e).byteLength>100;){let o=e.indexOf("/");if(o===-1)return null;n+=n!==""?"/"+e.slice(0,o):e.slice(0,o),e=e.slice(o+1)}return L(e).byteLength>100||L(n).byteLength>155||r.linkname!=null&&L(r.linkname).byteLength>100?null:(t.set(L(e),0),t.set(dn(r.mode&wI,6),100),t.set(dn(r.uid,6),108),t.set(dn(r.gid,6),116),t.set(dn(r.size,11),124),t.set(dn(r.mtime.getTime()/1e3|0,11),136),t[156]=mI+EI(r.type),r.linkname!=null&&t.set(L(r.linkname),157),t.set(gI,bI),t.set(yI,xI),r.uname!=null&&t.set(L(r.uname),265),r.gname!=null&&t.set(L(r.gname),297),t.set(dn(r.devmajor??0,6),329),t.set(dn(r.devminor??0,6),337),n!=null&&t.set(L(n),345),t.set(dn(vI(t),6),148),t)}var{S_IFMT:_I,S_IFBLK:AI,S_IFCHR:II,S_IFDIR:kI,S_IFIFO:TI,S_IFLNK:BI}=Bb.default,CI=parseInt("755",8),RI=parseInt("644",8),Cb=new Uint8Array(1024);function NI(r=0){switch(r&_I){case AI:return"block-device";case II:return"character-device";case kI:return"directory";case TI:return"fifo";case BI:return"symlink";default:return"file"}}function Ad(r){return r&=511,r!==0?Cb.subarray(0,512-r):new Uint8Array(0)}function _d(r){if(r.pax==null){let t=Vl(r);if(t!=null)return t}return PI(r)}function PI(r){let t=Tb(r),e={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:t.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new gn(Vl(e)??new Uint8Array(0),t,Ad(t.length),Vl({...e,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function Hl(){return async function*(r){for await(let{header:t,body:e}of r){let n={...t,size:t.type==="symlink"?0:t.size??0,type:t.type??NI(t.mode),mode:t.mode??(t.type==="directory"?CI:RI),uid:t.uid??0,gid:t.gid??0,mtime:t.mtime??new Date};if(typeof e=="string"&&(e=L(e)),e instanceof Uint8Array||Ye(e)){n.size=e.length,yield _d(n),yield Ye(e)?e.subarray():e,yield Ad(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(e==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=G(await kb(e)),yield _d(n);continue}if(yield _d(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of e??[])o+=i.length,yield Ye(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield Ad(n.size)}yield Cb}}var LI=["file","raw","directory"];function DI(r){let t,e;return(r.type==="file"||r.type==="directory")&&(t=r.unixfs.mode,e=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:t,mtime:e,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function Rb(r){if(!LI.includes(r.type))throw new us(`${r.type} is not a UnixFS node`);let t={header:DI(r)};return(r.type==="file"||r.type==="raw")&&(t.body=r.content()),t}async function*Nb(r,t,e){let n=await Ko(r,t,e);if(n.type==="file"||n.type==="raw"){yield*Xe([Rb(n)],Hl());return}if(n.type==="directory"){yield*Xe(ab(r,t,e),o=>qt(o,i=>Rb(i)),Hl());return}throw new us("Not a UnixFS node")}var Pb=Ut(Nf(),1),$l=class{lru;constructor(t){this.lru=(0,Pb.default)(t)}get(t){let e=this.lru.get(t);if(e!=null){if(e.expire!=null&&e.expire<Date.now()){this.lru.remove(t);return}return e.value}}set(t,e,n){this.lru.set(t,{value:e,expire:Date.now()+n})}has(t){return this.get(t)!=null}remove(t){this.lru.remove(t)}clear(){this.lru.clear()}};var Lb=new $l(1e3),OI=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,UI=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,FI=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,MI=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function VI(r){let t=r?.protocol;if(t==null)return!1;let e=r?.cidOrPeerIdOrDnsLink;if(e==null)return!1;let n=r?.path,o=r?.queryString;return["ipns","ipfs"].includes(t)&&typeof e=="string"&&(n==null||typeof n=="string")&&(o==null||typeof o=="string")}function fs(r){for(let t of[MI,OI,FI,UI]){let e=r.match(t);if(VI(e?.groups))return e.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function HI(r){if(r==null)return;let t=r.answer?.TTL,e=r.record?.ttl,n=e!=null?Number(e/BigInt(1e9)):void 0;return t??n}var $I=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function zI(r){return $I.test(r)&&r.includes("-")&&!r.includes(".")}function qI(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function Db({urlString:r,ipns:t,logger:e},n){let o=e.forComponent("helia:verified-fetch:parse-url-string"),{protocol:i,cidOrPeerIdOrDnsLink:s,path:a,queryString:c}=fs(r),l,u,f=[],d;if(i==="ipfs")try{l=P.parse(s)}catch(p){o.error(p),f.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(d=Lb.get(s),d!=null)l=d.cid,u=d.path,o.trace("resolved %s to %c from cache",s,l);else{o.trace("Attempting to resolve PeerId for %s",s);let p;try{if(s.charAt(0)==="1"||s.charAt(0)==="Q"?p=wo(s):p=bo(P.parse(s)),p.publicKey==null)throw new TypeError("cidOrPeerIdOrDnsLink contains no public key");d=await t.resolve(p.publicKey,n),l=d?.cid,u=d?.path,o.trace("resolved %s to %c",s,l)}catch(y){n?.signal?.throwIfAborted(),p==null?(o.error('could not parse PeerId string "%s"',s,y),f.push(new TypeError(`Could not parse PeerId in ipns url "${s}", ${y.message}`))):(o.error("could not resolve PeerId %c",p,y),f.push(new TypeError(`Could not resolve PeerId "${s}", ${y.message}`)))}if(l==null){let y=s;zI(s)&&(y=qI(s),o.trace('decoded dnslink from "%s" to "%s"',s,y)),o.trace("Attempting to resolve DNSLink for %s",y);try{d=await t.resolveDNSLink(y,n),l=d?.cid,u=d?.path,o.trace("resolved %s to %c",y,l)}catch(g){n?.signal?.throwIfAborted(),o.error('could not resolve DnsLink for "%s"',s,g),f.push(g)}}}if(l==null)throw f.length===1?f[0]:new AggregateError(f,`Invalid resource. Cannot determine CID from URL "${r}"`);let h=HI(d);d!=null&&(h=h??60*2,o.trace("caching %s resolved to %s with TTL: %s",s,l,h),Lb.set(s,d,h*1e3));let m={};if(c!=null&&c.length>0){let p=c.split("&");for(let y of p){let[g,x]=y.split("=");m[g]=decodeURIComponent(x)}m.download!=null&&(m.download=m.download==="true"),m.filename!=null&&(m.filename=m.filename.toString())}return{protocol:i,cid:l,path:KI(u,a??""),query:m,ttl:h,ipfsPath:`/${i}/${s}${a!=null&&a!==""?`/${a}`:""}`}}function KI(r,t){let e="";return r!=null&&(e+=r),t.length>0&&(e=`${e.length>0?`${e}/`:e}${t}`),e=e.replace(/\/(\/)+/g,"/"),e.startsWith("/")&&(e=e.substring(1)),e.split("/").map(decodeURIComponent).join("/")}function Id(r,t,e){Object.defineProperty(r,t,{enumerable:!0,configurable:!1,set:()=>{},get:()=>e})}function Fr(r,t){Id(r,"type",t)}function Mr(r,t){Id(r,"url",t)}function Ob(r){Id(r,"redirected",!0)}function Kn(r,t,e){let n=new Response(t,{...e??{},status:200,statusText:"OK"});return e?.redirected===!0&&Ob(n),Fr(n,"basic"),Mr(n,r),n.headers.set("Accept-Ranges","bytes"),n}function ql(r,t,e){let n=new Response(t,{...e??{},status:502,statusText:"Bad Gateway"});return Fr(n,"basic"),Mr(n,r),n}function Kl(r,t,e){let n=new Response(t,{...e??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Fr(n,"basic"),Mr(n,r),n}function jo(r,t,e){let n=new Response(t,{...e??{},status:406,statusText:"Not Acceptable"});return Fr(n,"basic"),Mr(n,r),n}function Gl(r,t,e){let n=new Response(t,{...e??{},status:404,statusText:"Not Found"});return Fr(n,"basic"),Mr(n,r),n}function hs(r,t,e){t instanceof Error&&(t=t.message);let n=new Response(t,{...e??{},status:400,statusText:"Bad Request"});return Fr(n,"basic"),Mr(n,r),n}function ds(r,t,e){let n=new Response(null,{...e??{},status:301,statusText:"Moved Permanently",headers:{...e?.headers??{},location:t}});return Fr(n,"basic"),Mr(n,r),n}function kd(r,t,{byteRangeContext:e,log:n},o){if(!e.isRangeRequest)return Kn(r,t,o);if(!e.isValidRangeRequest)return zl(r,t,o);let i;try{i=new Response(t,{...o??{},status:206,statusText:"Partial Content",headers:{...o?.headers??{},"content-range":e.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),zl(r,t,o)}return o?.redirected===!0&&Ob(i),Fr(i,"basic"),Mr(i,r),i.headers.set("Accept-Ranges","bytes"),i}function zl(r,t,e){let n=new Response(t,{...e??{},status:416,statusText:"Requested Range Not Satisfiable"});return Fr(n,"basic"),Mr(n,r),n}function Ub(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function Fb({resource:r,options:t,logger:e,cid:n,fetch:o=globalThis.fetch}){let i=e.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||t==null||["ipfs://","ipns://"].some(u=>r.startsWith(u)))return null;let s=new Headers(t?.headers),a=s.get("x-forwarded-host"),c=s.get("host");if(s.get("x-forwarded-for")==null&&a==null&&c==null)return i.trace("no redirect info found in headers"),null;i.trace("checking for redirect info");try{let u=fs(r),f=new URL(r),d=a??f.host,h=new URL(f);if(u.protocol==="ipfs"&&n.version===0?h.host=`${n.toV1()}.ipfs.${d}`:h.host=`${u.cidOrPeerIdOrDnsLink}.${u.protocol}.${d}`,c?.includes(u.protocol)===!0&&h.host.includes(c))return i.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!h.host.includes(c))return i.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(f.host===h.host)return i.trace("req url is the same as the subdomain url, not setting location header"),null;h.pathname=Ub(f.pathname.replace(`/${u.cidOrPeerIdOrDnsLink}`,"").replace(`/${u.protocol}`,"")),i.trace("subdomain url %s",h.href);let m=new URL(f,`${f.protocol}//${d}`);m.pathname=Ub(f.pathname),i.trace("path url %s",m.href);try{let p=await o(h,{method:"HEAD"});if(p.ok)return i("subdomain supported, redirecting to subdomain"),ds(r.toString(),h.href);throw i("subdomain not supported, subdomain failed with status %s %s",p.status,p.statusText),new Ol("subdomain not supported")}catch(p){return i("subdomain not supported",p),m.href===f.href?(i("path url is the same as the request url, not setting location header"),null):ds(r.toString(),m.href)}}catch(u){i.error("error setting location header for x-forwarded-host",u)}return null}async function Mb(r,{ipns:t,logger:e},n){if(typeof r=="string")return Db({urlString:r,ipns:t,logger:e},n);let o=P.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function Vb(r){let t=P.asCID(r);if(t!=null)return`ipfs://${t}`;try{return`ipfs://${P.parse(r.toString())}`}catch{}let{protocol:e,cidOrPeerIdOrDnsLink:n}=fs(r.toString());return`${e}://${n}`}async function GI(r,t,e){let n=[],o;for await(let i of yd(t,r,e))n.push(i.cid),o=i;if(o==null)throw new Ml("No terminal element found");return{ipfsRoots:n,terminalElement:o}}function Hb(r){return r.type==="object"}async function Td({cid:r,path:t,resource:e,options:n,blockstore:o,log:i}){try{return await GI(o,`${r.toString()}/${t}`,n)}catch(s){return n?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?Gl(e):(i.error("error walking path %s",t,s),ql(e,"Error walking path"))}}var WI=100,jI=60*1e3;function YI(r){if(r==null)return;let t;return r?.signal===null?t=void 0:t=r?.signal,{...r,signal:t}}var XI=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function ZI({headers:r,accept:t}){let n=(t??new Headers(r).get("accept")??"").split(",").map(o=>o.split(";")[0]).map(o=>o.trim());for(let o of n){if(o==="*/*")return;if(XI.includes(o??""))return o}}var Wl=class{helia;ipns;log;contentTypeParser;blockstoreSessions;constructor({helia:t,ipns:e},n){this.helia=t,this.log=t.logger.forComponent("helia:verified-fetch"),this.ipns=e??Rw(t),this.contentTypeParser=n?.contentTypeParser,this.blockstoreSessions=new Ll({max:n?.sessionCacheSize??WI,ttl:n?.sessionTTLms??jI,dispose:o=>{o.close()}}),this.log.trace("created VerifiedFetch instance")}getBlockstore(t,e,n,o){let i=Vb(e);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(i);return s==null&&(s=this.helia.blockstore.createSession(t,o),this.blockstoreSessions.set(i,s)),s}async handleIPNSRecord({resource:t,cid:e,path:n,options:o}){if(n!==""||!(t.startsWith("ipns://")||t.includes(".ipns.")))return this.log.error('invalid request for IPNS name "%s" and path "%s"',t,n),hs(t,"Invalid IPNS name");let i;try{if(t.startsWith("ipns://")){let f=t.replace("ipns://","");this.log.trace('trying to parse peer id from "%s"',f),i=wo(f)}else{let f=t.split(".ipns.")[0].split("://")[1];this.log.trace('trying to parse peer id from "%s"',f);let d;try{d=P.parse(f)}catch(h){return this.log.error('could not construct CID from peerId string "%s"',t,h),hs(t,h)}i=bo(d)}}catch(f){return this.log.error("could not parse peer id from IPNS url %s",t,f),hs(t,f)}let s=ut([L("/ipns/"),i.toMultihash().bytes]),a=new _t("/dht/record/"+G(s,"base32"),!1),c=await this.helia.datastore.get(a,o),l=cr.deserialize(c),u=Kn(t,l.value);return u.headers.set("content-type","application/vnd.ipfs.ipns-record"),u}async handleCar({resource:t,cid:e,session:n,options:o}){let i=this.getBlockstore(e,t,n,o),s=sw({blockstore:i,getCodec:this.helia.getCodec}),a=Nl(s.stream(e,o)),c=Kn(t,a);return c.headers.set("content-type","application/vnd.ipld.car; version=1"),c}async handleTar({resource:t,cid:e,path:n,session:o,options:i}){if(e.code!==Be&&e.code!==ae)return jo("only UnixFS data can be returned in a TAR file");let s=this.getBlockstore(e,t,o,i),a=Nl(Nb(`/ipfs/${e}/${n}`,s,i)),c=Kn(t,a);return c.headers.set("content-type","application/x-tar"),c}async handleJson({resource:t,cid:e,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",e,n);let c=await this.getBlockstore(e,t,i,s).get(e,s),l;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let f=Co(c);l=To(f)}catch(f){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",f),jo(t)}else l=c;let u=Kn(t,l);return u.headers.set("content-type",o??"application/json"),u}async handleDagCbor({resource:t,cid:e,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",e,n);let a,c=this.getBlockstore(e,t,i,s),l=await Td({cid:e,path:n,resource:t,options:s,blockstore:c,log:this.log});if(l instanceof Response)return l;let u=l.ipfsRoots;if(Hb(l.terminalElement))a=l.terminalElement;else return this.log.error("terminal element is not a dag-cbor node"),Kl(t,"Terminal element is not a dag-cbor node");let f=a.node,d;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")d=f;else if(o==="application/vnd.ipld.dag-json")try{let m=cn(f);d=wc(m)}catch(m){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",m),jo(t)}else try{d=yb(f)}catch(m){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',m),jo(t);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",m),d=f}let h=Kn(t,d);return o==null&&(o=d instanceof Uint8Array?"application/octet-stream":"application/json"),h.headers.set("content-type",o),xd(h,u),h}async handleDagPb({cid:t,path:e,resource:n,session:o,options:i}){let s=!1,a=new ls(this.helia.logger,i?.headers),c=this.getBlockstore(t,n,o,i),l=await Td({cid:t,path:e,resource:n,options:i,blockstore:c,log:this.log});if(l instanceof Response)return l;let u=l.ipfsRoots,f=l.terminalElement,d=f.cid;if(f?.type==="directory"){let p=f.cid;if(e===""?!n.toString().endsWith("/"):!e.endsWith("/")){if(i?.redirect==="error")throw this.log('could not redirect to %s/ as redirect option was set to "error"',n),new TypeError("Failed to fetch");if(i?.redirect==="manual")return this.log("returning 301 permanent redirect to %s/",n),ds(n,`${n}/`);n=`${n}/`,s=!0}let g="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",t,e);let x=await Ko(`/ipfs/${p}/${g}`,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress});this.log.trace("found root file at %c/%s with cid %c",p,g,x.cid),e=g,d=x.cid}catch(x){return i?.signal?.throwIfAborted(),this.log("error loading path %c/%s",p,g,x),Kl("Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented")}finally{i?.onProgress?.(new H("verified-fetch:request:end",{cid:p,path:g}))}}a.isRangeRequest&&a.isValidRangeRequest&&f.type==="file"&&(a.setFileSize(f.unixfs.fileSize()),this.log.trace("fileSize for rangeRequest %d",a.getFileSize()));let h=a.offset,m=a.length;this.log.trace("calling exporter for %c/%s with offset=%o & length=%o",d,e,h,m);try{let y=(await Ko(d,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress})).content({signal:i?.signal,onProgress:i?.onProgress,offset:h,length:m});this.log("got async iterator for %c/%s",t,e);let{stream:g,firstChunk:x}=await _b(y,e??"",this.helia.logger,{onProgress:i?.onProgress,signal:i?.signal});a.setBody(g);let b=kd(n,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:s});return await this.setContentType(x,e,b),xd(b,u),b}catch(p){return i?.signal?.throwIfAborted(),this.log.error("error streaming %c/%s",t,e,p),a.isRangeRequest&&p.code==="ERR_INVALID_PARAMS"?zl(n):ql(n.toString(),"Unable to stream content")}}async handleRaw({resource:t,cid:e,path:n,session:o,options:i,accept:s}){if(n!=="")return this.log.trace("404-ing raw codec request for %c/%s",e,n),Gl(t,"Raw codec does not support paths");let a=new ls(this.helia.logger,i?.headers),l=await this.getBlockstore(e,t,o,i).get(e,i);a.setBody(l);let u=kd(t,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:!1});return await this.setContentType(l,n,u,ZI({headers:i?.headers,accept:s})),u}async setContentType(t,e,n,o="application/octet-stream"){let i;if(this.contentTypeParser!=null)try{let s=e.split("/").pop()?.trim();s=s===""?void 0:s;let a=this.contentTypeParser(t,s);if(JI(a)){let c=await a;c!=null&&(i=c)}else a!=null&&(i=a)}catch(s){this.log.error("error parsing content type",s)}this.log.trace('setting content type to "%s"',i??o),n.headers.set("content-type",i??o)}codecHandlers={[Be]:this.handleDagPb,[Rr]:this.handleJson,[hr]:this.handleJson,[Cr]:this.handleDagCbor,[ae]:this.handleRaw,[bt.code]:this.handleRaw};async fetch(t,e){this.log("fetch %s",t);let n=YI(e);n?.onProgress?.(new H("verified-fetch:request:start",{resource:t}));let o,i,s,a,c,l;try{let g=await Mb(t,{ipns:this.ipns,logger:this.helia.logger},n);o=g.cid,i=g.path,s=g.query,a=g.ttl,c=g.protocol,l=g.ipfsPath}catch(g){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",t,g),hs(t.toString(),g)}n?.onProgress?.(new H("verified-fetch:request:resolve",{cid:o,path:i}));let u=Sb({query:s,headers:n?.headers,logger:this.helia.logger}),f=xb(o,u);if(this.log("output type %s",f),u!=null&&f==null)return jo(t.toString());let d,h,m=await Fb({resource:t,options:n,logger:this.helia.logger,cid:o});if(m!=null)return m;let p={resource:t.toString(),cid:o,path:i,accept:f,session:n?.session??!0,options:n};if(f==="application/vnd.ipfs.ipns-record")h="ipns-record",d=await this.handleIPNSRecord(p);else if(f==="application/vnd.ipld.car")h="car",s.download=!0,s.filename=s.filename??`${o.toString()}.car`,d=await this.handleCar(p);else if(f==="application/vnd.ipld.raw")h="raw",s.download=!0,s.filename=s.filename??`${o.toString()}.bin`,d=await this.handleRaw(p);else if(f==="application/x-tar")h="tar",s.download=!0,s.filename=s.filename??`${o.toString()}.tar`,d=await this.handleTar(p);else{this.log.trace('finding handler for cid code "%s" and output type "%s"',o.code,f);let g=this.codecHandlers[o.code];if(g==null)return Kl(`Support for codec with code ${o.code} is not yet implemented. Please open an issue at https://github.com/ipfs/helia-verified-fetch/issues/new`);this.log.trace('calling handler "%s"',g.name),d=await g.call(this,p)}d.headers.set("etag",bb({cid:o,reqFormat:h,weak:!1})),mb({response:d,ttl:a,protocol:c}),d.headers.set("X-Ipfs-Path",l);let y;return s.download===!0&&(y="attachment"),s.filename!=null&&(y==null&&(y="inline"),y=`${y}; ${wb(s.filename)}`),y!=null&&d.headers.set("Content-Disposition",y),n?.onProgress?.(new H("verified-fetch:request:end",{cid:o,path:i})),d}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function JI(r){return r?.then!=null}var ps,jl=async function(t,e){return ps==null&&(ps=await Bd()),ps(t,e)};jl.start=async function(){await ps?.start()};jl.stop=async function(){await ps?.stop()};async function Bd(r,t){QI(r)||(r=await qy({blockBrokers:[Gi({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})],routers:[...(r?.routers??["https://delegated-ipfs.dev"]).map(o=>Xi(o)),Zi({gateways:r?.gateways??["https://trustless-gateway.link"]})],dns:t8(r?.dnsResolvers)}));let e=new Wl({helia:r},t);async function n(o,i){return e.fetch(o,i)}return n.stop=e.stop.bind(e),n.start=e.start.bind(e),n}function QI(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function t8(r){if(r!=null)return Array.isArray(r)?Ti({resolvers:{".":r}}):Ti({resolvers:r})}return ex(e8);})();
|
|
22
22
|
/*! Bundled license information:
|
|
23
23
|
|
|
24
24
|
pvtsutils/build/index.js:
|