@helia/verified-fetch 1.3.7 → 1.3.9
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,14 +1,14 @@
|
|
|
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 Db=Object.create;var Bs=Object.defineProperty;var Pb=Object.getOwnPropertyDescriptor;var Ob=Object.getOwnPropertyNames;var Ub=Object.getPrototypeOf,Fb=Object.prototype.hasOwnProperty;var Le=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),xe=(r,e)=>{for(var t in e)Bs(r,t,{get:e[t],enumerable:!0})},Jd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ob(e))!Fb.call(r,o)&&o!==t&&Bs(r,o,{get:()=>e[o],enumerable:!(n=Pb(e,o))||n.enumerable});return r};var J=(r,e,t)=>(t=r!=null?Db(Ub(r)):{},Jd(e||!r||!r.__esModule?Bs(t,"default",{value:r,enumerable:!0}):t,r)),Vb=r=>Jd(Bs({},"__esModule",{value:!0}),r);var yh=Le((EB,mh)=>{var oo=1e3,io=oo*60,so=io*60,kn=so*24,Rx=kn*7,Tx=kn*365.25;mh.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Nx(r);if(t==="number"&&isFinite(r))return e.long?Lx(r):Cx(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Nx(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Tx;case"weeks":case"week":case"w":return t*Rx;case"days":case"day":case"d":return t*kn;case"hours":case"hour":case"hrs":case"hr":case"h":return t*so;case"minutes":case"minute":case"mins":case"min":case"m":return t*io;case"seconds":case"second":case"secs":case"sec":case"s":return t*oo;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Cx(r){var e=Math.abs(r);return e>=kn?Math.round(r/kn)+"d":e>=so?Math.round(r/so)+"h":e>=io?Math.round(r/io)+"m":e>=oo?Math.round(r/oo)+"s":r+"ms"}function Lx(r){var e=Math.abs(r);return e>=kn?Ts(r,e,kn,"day"):e>=so?Ts(r,e,so,"hour"):e>=io?Ts(r,e,io,"minute"):e>=oo?Ts(r,e,oo,"second"):r+" ms"}function Ts(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var wh=Le((vB,gh)=>{function Dx(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=yh(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let m=0;m<l.length;m++)f=(f<<5)-f+l.charCodeAt(m),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l){let f,m=null,d,p;function h(...y){if(!h.enabled)return;let g=h,b=Number(new Date),x=b-(f||b);g.diff=x,g.prev=f,g.curr=b,f=b,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let v=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(I,_)=>{if(I==="%%")return"%";v++;let E=t.formatters[_];if(typeof E=="function"){let P=y[v];I=E.call(g,P),y.splice(v,1),v--}return I}),t.formatArgs.call(g,y),(g.log||t.log).apply(g,y)}return h.namespace=l,h.useColors=t.useColors(),h.color=t.selectColor(l),h.extend=n,h.destroy=t.destroy,Object.defineProperty(h,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(d!==t.namespaces&&(d=t.namespaces,p=t.enabled(l)),p),set:y=>{m=y}}),typeof t.init=="function"&&t.init(h),h}function n(l,f){let m=t(this.namespace+(typeof f>"u"?":":f)+l);return m.log=this.log,m}function o(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,m=(typeof l=="string"?l:"").split(/[\s,]+/),d=m.length;for(f=0;f<d;f++)m[f]&&(l=m[f].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.slice(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function i(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let f,m;for(f=0,m=t.skips.length;f<m;f++)if(t.skips[f].test(l))return!1;for(f=0,m=t.names.length;f<m;f++)if(t.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}gh.exports=Dx});var bh=Le((pt,Ns)=>{pt.formatArgs=Ox;pt.save=Ux;pt.load=Fx;pt.useColors=Px;pt.storage=Vx();pt.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();pt.colors=["#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 Px(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Ox(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ns.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}pt.log=console.debug||console.log||(()=>{});function Ux(r){try{r?pt.storage.setItem("debug",r):pt.storage.removeItem("debug")}catch{}}function Fx(){let r;try{r=pt.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Vx(){try{return localStorage}catch{}}Ns.exports=wh()(pt);var{formatters:Hx}=Ns.exports;Hx.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Sh=Le((RB,vh)=>{vh.exports=$l;var Eh=128,qx=127,Gx=~qx,Wx=Math.pow(2,31);function $l(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw $l.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=Wx;)e[t++]=r&255|Eh,r/=128;for(;r&Gx;)e[t++]=r&255|Eh,r>>>=7;return e[t]=r|0,$l.bytes=t-n+1,e}});var kh=Le((TB,Ah)=>{Ah.exports=Kl;var jx=128,_h=127;function Kl(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw Kl.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&_h)<<o:(s&_h)*Math.pow(2,o),o+=7}while(s>=jx);return Kl.bytes=i-n,t}});var Ih=Le((NB,Bh)=>{var Yx=Math.pow(2,7),Xx=Math.pow(2,14),Zx=Math.pow(2,21),Jx=Math.pow(2,28),Qx=Math.pow(2,35),e1=Math.pow(2,42),t1=Math.pow(2,49),r1=Math.pow(2,56),n1=Math.pow(2,63);Bh.exports=function(r){return r<Yx?1:r<Xx?2:r<Zx?3:r<Jx?4:r<Qx?5:r<e1?6:r<t1?7:r<r1?8:r<n1?9:10}});var Cs=Le((CB,Rh)=>{Rh.exports={encode:Sh(),decode:kh(),encodingLength:Ih()}});var Ie=Le((YI,jh)=>{"use strict";function Wh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function F1(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return Wh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),Wh(new o,t)}}jh.exports=F1});var qp=Le(Ro=>{"use strict";var Iv="[object ArrayBuffer]",vr=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Iv}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let i=0;i<n.length;i++)if(n[i]!==o[i])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let s of t)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of t){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},Zu="string",Rv=/^[0-9a-f]+$/i,Tv=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Nv=/^[a-zA-Z0-9-_]+$/,ca=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=vr.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},Lt=class{static toString(e,t=!1){let n=vr.toArrayBuffer(e),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let i=0;i<e.length;i++)o.setUint16(i*2,e.charCodeAt(i),t);return n}},la=class r{static isHex(e){return typeof e===Zu&&Rv.test(e)}static isBase64(e){return typeof e===Zu&&Tv.test(e)}static isBase64Url(e){return typeof e===Zu&&Nv.test(e)}static ToString(e,t="utf8"){let n=vr.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Lt.toString(n,!0);case"utf16":case"utf16be":return Lt.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Lt.fromString(e,!0);case"utf16":case"utf16be":return Lt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=vr.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return ca.fromString(e);case"utf16":case"utf16be":return Lt.fromString(e);case"utf16le":case"usc2":return Lt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return ca.toString(e);case"utf16":case"utf16be":return Lt.toString(e);case"utf16le":case"usc2":return Lt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=vr.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=vr.toUint8Array(e),n="",o=t.length;for(let i=0;i<o;i++){let s=t[i];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let i=t.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(e,t=!1){return Lt.toString(e,t)}static FromUtf16String(e,t=!1){return Lt.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};la.DEFAULT_UTF8_ENCODING="utf8";function Cv(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)t[i]=o[i]}return t}function Lv(...r){let e=r.map(o=>o.byteLength).reduce((o,i)=>o+i),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)t[n++]=i}),t.buffer}function Dv(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Ro.BufferSourceConverter=vr;Ro.Convert=la;Ro.assign=Cv;Ro.combine=Lv;Ro.isEqual=Dv});var Ja=Le((pC,hf)=>{var hC=function(){typeof hf<"u"&&(hf.exports=h);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",u=Math.trunc||function(E){var P=E-E%1;return P==0&&(E<0||E===0&&1/E!=1/0)?-0:P},l=h.prototype,f=(h.fromDate=function(E){return new h(+E)},h.fromInt64BE=v(0,1,2,3,0,4),h.fromInt64LE=v(3,2,1,0,4,0),h.fromString=function(L){var P,V=new h,L=(L+="").replace(/^\s*[+\-]?\d+/,function(C){var C=+C,ne=1970+(C-1970)%400;return V.year=C-ne,ne}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function($,C,ne){return C<0&&(ne*=-1),P=6e4*(60*+C+ +ne),""}).replace(/\.\d+$/,function($){return V.nano=+($+c).substr(1,9),""}).split(/\D+/);if(1<L.length?L[1]--:L[1]=0,V.time=P=Date.UTC.apply(Date,L)-(P||0),isNaN(P))throw new TypeError("Invalid Date");return y(V)},h.fromTimeT=function(E){return b(E,0)},l.year=0,l.time=0,l.nano=0,l.addNano=function(E){return this.nano+=+E||0,this},l.getNano=function(){var E=y(this);return(E.time%1e3*a+ +E.nano+1e9)%1e9},l.getTimeT=function(){var P=y(this),E=Math.floor(P.time/1e3),P=P.year;return P&&(E+=P*t*r/e),E},l.getYear=function(){return this.toDate().getUTCFullYear()+this.year},l.toDate=function(){return g(y(this).time)},l.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},l.toString=function(E){var P=this,V=P.toDate(),L={H:function(){return I(V.getUTCHours())},L:function(){return _(V.getUTCMilliseconds(),3)},M:function(){return I(V.getUTCMinutes())},N:function(){return _(P.getNano(),9)},S:function(){return I(V.getUTCSeconds())},Y:function(){var $=P.getYear();return 999999<$?"+"+$:9999<$?"+"+_($,6):0<=$?_($,4):-999999<=$?"-"+_(-$,6):$},a:function(){return d[V.getUTCDay()]},b:function(){return m[V.getUTCMonth()]},d:function(){return I(V.getUTCDate())},e:function(){return function($){return(9<$?"":" ")+(0|$)}(V.getUTCDate())},m:function(){return I(V.getUTCMonth()+1)}};return function $(C){return C.replace(/%./g,function(ne){var T=ne[1],B=p[T],T=L[T];return B?$(B):T?T():ne})}(E||f)},l.writeInt64BE=x(0,1,2,3,0,4),l.writeInt64LE=x(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),m=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p={"%":"%",F:"%Y-%m-%d",n:`
|
|
3
|
-
`,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return h;function h(E,P,V){var L=this;if(!(L instanceof h))return new h(E,P,V);L.time=+E||0,L.nano=+P||0,L.year=+V||0,y(L)}function y(E){var P,V,L,$=E.year,C=E.time,ne=E.nano,B=((ne<0||a<=ne)&&(ne-=(V=Math.floor(ne/a))*a,C+=V,V=1),$%e);return(C<-i||i<C||B)&&((P=u(C/o))&&($+=P*e,C-=P*o),(L=g(C)).setUTCFullYear(B+L.getUTCFullYear()),L=(C=+L)+(P=u(($-=B)/e))*o,P&&-i<=L&&L<=i&&($-=P*e,C=L),V=1),V&&(E.year=$,E.time=C,E.nano=ne),E}function g(E){var P=new Date(0);return P.setTime(E),P}function b($,L){$=+$||0;var V=u((L=(L|0)*s)/n)+u($/n),L=L%n+$%n,$=u(L/n);return $&&(V+=$,L-=$*n),new h(1e3*L,0,V*e)}function x(E,P,V,L,$,C){return function(B,T){var R=y(this);B=B||new Array(8),S(B,T|=0);var A=Math.floor(R.time/1e3),R=R.year*(t*r/e),G=u(R/s)+u(A/s),R=R%s+A%s,A=Math.floor(R/s);return A&&(G+=A,R-=A*s),ne(B,T+$,G),ne(B,T+C,R),B};function ne(B,T,G){B[T+E]=G>>24&255,B[T+P]=G>>16&255,B[T+V]=G>>8&255,B[T+L]=255&G}}function v(E,P,V,L,$,C){return function(B,T){S(B,T|=0);var G=ne(B,T+$);return b(ne(B,T+C),G)};function ne(B,T){return 16777216*B[T+E]+(B[T+P]<<16|B[T+V]<<8|B[T+L])}}function S(E,P){if(E=E&&E.length,E==null)throw new TypeError("Invalid Buffer");if(E<P+8)throw new RangeError("Out of range")}function I(E){return(9<E?"":"0")+(0|E)}function _(E,P){return(c+(0|E)).substr(-P)}}()});var xg=Le((Z6,If)=>{"use strict";var ZS=Object.prototype.hasOwnProperty,nt="~";function Ki(){}Object.create&&(Ki.prototype=Object.create(null),new Ki().__proto__||(nt=!1));function JS(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function bg(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new JS(t,n||r,o),s=nt?nt+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function pc(r,e){--r._eventsCount===0?r._events=new Ki:delete r._events[e]}function Xe(){this._events=new Ki,this._eventsCount=0}Xe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ZS.call(t,n)&&e.push(nt?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Xe.prototype.listeners=function(e){var t=nt?nt+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};Xe.prototype.listenerCount=function(e){var t=nt?nt+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Xe.prototype.emit=function(e,t,n,o,i,s){var a=nt?nt+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,i),!0;case 6:return c.fn.call(c.context,t,n,o,i,s),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var m=c.length,d;for(f=0;f<m;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c[f].fn.apply(c[f].context,l)}}return!0};Xe.prototype.on=function(e,t,n){return bg(this,e,t,n,!1)};Xe.prototype.once=function(e,t,n){return bg(this,e,t,n,!0)};Xe.prototype.removeListener=function(e,t,n,o){var i=nt?nt+e:e;if(!this._events[i])return this;if(!t)return pc(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&pc(this,i);else{for(var a=0,c=[],u=s.length;a<u;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:pc(this,i)}return this};Xe.prototype.removeAllListeners=function(e){var t;return e?(t=nt?nt+e:e,this._events[t]&&pc(this,t)):(this._events=new Ki,this._eventsCount=0),this};Xe.prototype.off=Xe.prototype.removeListener;Xe.prototype.addListener=Xe.prototype.on;Xe.prefixed=nt;Xe.EventEmitter=Xe;typeof If<"u"&&(If.exports=Xe)});var Of=Le((eL,Tg)=>{Tg.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var V0=Le((gs,qc)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(d){if(!Array.isArray(d)&&!ArrayBuffer.isView(d))return!1;for(var p=0;p<d.length;p++)if(!Number.isInteger(d[p])||d[p]<0||d[p]>255)return!1;return!0}function o(d,p){return(d&65535)*p+(((d>>>16)*p&65535)<<16)}function i(d,p){return d<<p|d>>>32-p}function s(d){return d^=d>>>16,d=o(d,2246822507),d^=d>>>13,d=o(d,3266489909),d^=d>>>16,d}function a(d,p){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var h=[0,0,0,0];return h[3]+=d[3]+p[3],h[2]+=h[3]>>>16,h[3]&=65535,h[2]+=d[2]+p[2],h[1]+=h[2]>>>16,h[2]&=65535,h[1]+=d[1]+p[1],h[0]+=h[1]>>>16,h[1]&=65535,h[0]+=d[0]+p[0],h[0]&=65535,[h[0]<<16|h[1],h[2]<<16|h[3]]}function c(d,p){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var h=[0,0,0,0];return h[3]+=d[3]*p[3],h[2]+=h[3]>>>16,h[3]&=65535,h[2]+=d[2]*p[3],h[1]+=h[2]>>>16,h[2]&=65535,h[2]+=d[3]*p[2],h[1]+=h[2]>>>16,h[2]&=65535,h[1]+=d[1]*p[3],h[0]+=h[1]>>>16,h[1]&=65535,h[1]+=d[2]*p[2],h[0]+=h[1]>>>16,h[1]&=65535,h[1]+=d[3]*p[1],h[0]+=h[1]>>>16,h[1]&=65535,h[0]+=d[0]*p[3]+d[1]*p[2]+d[2]*p[1]+d[3]*p[0],h[0]&=65535,[h[0]<<16|h[1],h[2]<<16|h[3]]}function u(d,p){return p%=64,p===32?[d[1],d[0]]:p<32?[d[0]<<p|d[1]>>>32-p,d[1]<<p|d[0]>>>32-p]:(p-=32,[d[1]<<p|d[0]>>>32-p,d[0]<<p|d[1]>>>32-p])}function l(d,p){return p%=64,p===0?d:p<32?[d[0]<<p|d[1]>>>32-p,d[1]<<p]:[d[1]<<p-32,0]}function f(d,p){return[d[0]^p[0],d[1]^p[1]]}function m(d){return d=f(d,[0,d[0]>>>1]),d=c(d,[4283543511,3981806797]),d=f(d,[0,d[0]>>>1]),d=c(d,[3301882366,444984403]),d=f(d,[0,d[0]>>>1]),d}t.x86.hash32=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var h=d.length%4,y=d.length-h,g=p,b=0,x=3432918353,v=461845907,S=0;S<y;S=S+4)b=d[S]|d[S+1]<<8|d[S+2]<<16|d[S+3]<<24,b=o(b,x),b=i(b,15),b=o(b,v),g^=b,g=i(g,13),g=o(g,5)+3864292196;switch(b=0,h){case 3:b^=d[S+2]<<16;case 2:b^=d[S+1]<<8;case 1:b^=d[S],b=o(b,x),b=i(b,15),b=o(b,v),g^=b}return g^=d.length,g=s(g),g>>>0},t.x86.hash128=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var h=d.length%16,y=d.length-h,g=p,b=p,x=p,v=p,S=0,I=0,_=0,E=0,P=597399067,V=2869860233,L=951274213,$=2716044179,C=0;C<y;C=C+16)S=d[C]|d[C+1]<<8|d[C+2]<<16|d[C+3]<<24,I=d[C+4]|d[C+5]<<8|d[C+6]<<16|d[C+7]<<24,_=d[C+8]|d[C+9]<<8|d[C+10]<<16|d[C+11]<<24,E=d[C+12]|d[C+13]<<8|d[C+14]<<16|d[C+15]<<24,S=o(S,P),S=i(S,15),S=o(S,V),g^=S,g=i(g,19),g+=b,g=o(g,5)+1444728091,I=o(I,V),I=i(I,16),I=o(I,L),b^=I,b=i(b,17),b+=x,b=o(b,5)+197830471,_=o(_,L),_=i(_,17),_=o(_,$),x^=_,x=i(x,15),x+=v,x=o(x,5)+2530024501,E=o(E,$),E=i(E,18),E=o(E,P),v^=E,v=i(v,13),v+=g,v=o(v,5)+850148119;switch(S=0,I=0,_=0,E=0,h){case 15:E^=d[C+14]<<16;case 14:E^=d[C+13]<<8;case 13:E^=d[C+12],E=o(E,$),E=i(E,18),E=o(E,P),v^=E;case 12:_^=d[C+11]<<24;case 11:_^=d[C+10]<<16;case 10:_^=d[C+9]<<8;case 9:_^=d[C+8],_=o(_,L),_=i(_,17),_=o(_,$),x^=_;case 8:I^=d[C+7]<<24;case 7:I^=d[C+6]<<16;case 6:I^=d[C+5]<<8;case 5:I^=d[C+4],I=o(I,V),I=i(I,16),I=o(I,L),b^=I;case 4:S^=d[C+3]<<24;case 3:S^=d[C+2]<<16;case 2:S^=d[C+1]<<8;case 1:S^=d[C],S=o(S,P),S=i(S,15),S=o(S,V),g^=S}return g^=d.length,b^=d.length,x^=d.length,v^=d.length,g+=b,g+=x,g+=v,b+=g,x+=g,v+=g,g=s(g),b=s(b),x=s(x),v=s(v),g+=b,g+=x,g+=v,b+=g,x+=g,v+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)},t.x64.hash128=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var h=d.length%16,y=d.length-h,g=[0,p],b=[0,p],x=[0,0],v=[0,0],S=[2277735313,289559509],I=[1291169091,658871167],_=0;_<y;_=_+16)x=[d[_+4]|d[_+5]<<8|d[_+6]<<16|d[_+7]<<24,d[_]|d[_+1]<<8|d[_+2]<<16|d[_+3]<<24],v=[d[_+12]|d[_+13]<<8|d[_+14]<<16|d[_+15]<<24,d[_+8]|d[_+9]<<8|d[_+10]<<16|d[_+11]<<24],x=c(x,S),x=u(x,31),x=c(x,I),g=f(g,x),g=u(g,27),g=a(g,b),g=a(c(g,[0,5]),[0,1390208809]),v=c(v,I),v=u(v,33),v=c(v,S),b=f(b,v),b=u(b,31),b=a(b,g),b=a(c(b,[0,5]),[0,944331445]);switch(x=[0,0],v=[0,0],h){case 15:v=f(v,l([0,d[_+14]],48));case 14:v=f(v,l([0,d[_+13]],40));case 13:v=f(v,l([0,d[_+12]],32));case 12:v=f(v,l([0,d[_+11]],24));case 11:v=f(v,l([0,d[_+10]],16));case 10:v=f(v,l([0,d[_+9]],8));case 9:v=f(v,[0,d[_+8]]),v=c(v,I),v=u(v,33),v=c(v,S),b=f(b,v);case 8:x=f(x,l([0,d[_+7]],56));case 7:x=f(x,l([0,d[_+6]],48));case 6:x=f(x,l([0,d[_+5]],40));case 5:x=f(x,l([0,d[_+4]],32));case 4:x=f(x,l([0,d[_+3]],24));case 3:x=f(x,l([0,d[_+2]],16));case 2:x=f(x,l([0,d[_+1]],8));case 1:x=f(x,[0,d[_]]),x=c(x,S),x=u(x,31),x=c(x,I),g=f(g,x)}return g=f(g,[0,d.length]),b=f(b,[0,d.length]),g=a(g,b),b=a(b,g),g=m(g),b=m(b),g=a(g,b),b=a(b,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof gs<"u"?(typeof qc<"u"&&qc.exports&&(gs=qc.exports=t),gs.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(gs)});var M0=Le((v5,H0)=>{H0.exports=V0()});var Wc=Le((R5,$0)=>{"use strict";$0.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let o=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):o=!0,this._setInternalPos(n,e,t,o),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,o=t;for(;n<this.length;){let i=this.get(n);o=e(o,i,n),n++}return o}find(e){let t=0,n,o;for(;t<this.length&&!n;)o=this.get(t),n=e(o),t++;return n?o:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let o=this._bitArrays[n],i=e-n*7;if(!((o&1<<i)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(B_,0),c=~(4294967295<<i+1),u=z0(o&c);return a+u-1}_bytePosFor(e,t){let n=Math.floor(e/7),o=n+1;for(;!t&&this._bitArrays.length<o;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,o){let i=this._data,s=[t,n];if(o)this._sortData(),i[e]=s;else{if(i.length)if(i[i.length-1][0]>=t)i.push(s);else if(i[0][0]<=t)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(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(I_),this._changedData=!1}bitField(){let e=[],t=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,t),u=~(255<<c),l=i&u;o|=l<<8-t,i=i>>>c,n-=c,t-=c,(!t||!n&&!s.length)&&(e.push(o),o=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(R_)}};function B_(r,e){return r+z0(e)}function z0(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function I_(r,e){return r[0]-e[0]}function R_(r){return r[1]}});var Iw=Le((I7,Bw)=>{"use strict";Bw.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Dw=Le((Cw,Lw)=>{"use strict";var Qc=Iw(),{hasOwnProperty:Tw}=Object.prototype,{propertyIsEnumerable:fA}=Object,Xo=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),dA=Cw,Rw={concatArrays:!1,ignoreUndefined:!1},el=r=>{let e=[];for(let t in r)Tw.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)fA.call(r,n)&&e.push(n)}return e};function Zo(r){return Array.isArray(r)?hA(r):Qc(r)?pA(r):r}function hA(r){let e=r.slice(0,0);return el(r).forEach(t=>{Xo(e,t,Zo(r[t]))}),e}function pA(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return el(r).forEach(t=>{Xo(e,t,Zo(r[t]))}),e}var Nw=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Xo(r,o,Id(r[o],e[o],n)):Xo(r,o,Zo(e[o])))}),r),mA=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(i=>{let s=[];for(let a=0;a<i.length;a++)Tw.call(i,a)&&(s.push(String(a)),i===r?Xo(n,o++,i[a]):Xo(n,o++,Zo(i[a])));n=Nw(n,i,el(i).filter(a=>!s.includes(a)),t)}),n};function Id(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?mA(r,e,t):!Qc(e)||!Qc(r)?Zo(e):Nw(r,e,el(e),t)}Lw.exports=function(...r){let e=Id(Zo(Rw),this!==dA&&this||{},Rw),t={_:{}};for(let n of r)if(n!==void 0){if(!Qc(n))throw new TypeError("`"+n+"` is not an Option Object");t=Id(t,{_:n},e)}return t._}});var db=Le((s9,fb)=>{"use strict";fb.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 Gk={};xe(Gk,{createVerifiedFetch:()=>$d,verifiedFetch:()=>Sl});function _n(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}function Hb(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Zn=Hb;function Mb(r){return r[Symbol.asyncIterator]!=null}function Qd(r){return r?.then!=null}function zb(r,e){if(Mb(r))return async function*(){for await(let a of r){let c=e(a);Qd(c)&&await c,yield a}}();let t=Zn(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();if(typeof e(n)?.then=="function")return async function*(){yield n;for await(let a of t){let c=e(a);Qd(c)&&await c,yield a}}();let s=e;return function*(){yield n;for(let a of t)s(a),yield a}()}var Al=zb;var Ll={};xe(Ll,{base32:()=>Fe,base32hex:()=>Qb,base32hexpad:()=>tx,base32hexpadupper:()=>rx,base32hexupper:()=>ex,base32pad:()=>Zb,base32padupper:()=>Jb,base32upper:()=>nh,base32z:()=>nx});var Jn={};xe(Jn,{coerce:()=>_t,empty:()=>eh,equals:()=>kl,fromHex:()=>Kb,fromString:()=>Bl,isBinary:()=>qb,toHex:()=>$b,toString:()=>Il});var eh=new Uint8Array(0);function $b(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function Kb(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):eh}function kl(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _t(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function qb(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function Bl(r){return new TextEncoder().encode(r)}function Il(r){return new TextDecoder().decode(r)}function Gb(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var h=0,y=0,g=0,b=p.length;g!==b&&p[g]===0;)g++,h++;for(var x=(b-g)*l+1>>>0,v=new Uint8Array(x);g!==b;){for(var S=p[g],I=0,_=x-1;(S!==0||I<y)&&_!==-1;_--,I++)S+=256*v[_]>>>0,v[_]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=I,g++}for(var E=x-y;E!==x&&v[E]===0;)E++;for(var P=c.repeat(h);E<x;++E)P+=r.charAt(v[E]);return P}function m(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var h=0;if(p[h]!==" "){for(var y=0,g=0;p[h]===c;)y++,h++;for(var b=(p.length-h)*u+1>>>0,x=new Uint8Array(b);p[h];){var v=t[p.charCodeAt(h)];if(v===255)return;for(var S=0,I=b-1;(v!==0||S<g)&&I!==-1;I--,S++)v+=a*x[I]>>>0,x[I]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,h++}if(p[h]!==" "){for(var _=b-g;_!==b&&x[_]===0;)_++;for(var E=new Uint8Array(y+(b-_)),P=y;_!==b;)E[P++]=x[_++];return E}}}function d(p){var h=m(p);if(h)return h;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:m,decode:d}}var Wb=Gb,jb=Wb,th=jb;var Rl=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Tl=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return rh(this,e)}},Nl=class{decoders;constructor(e){this.decoders=e}or(e){return rh(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function rh(r,e){return new Nl({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Cl=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Rl(e,t,n),this.decoder=new Tl(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Qn({name:r,prefix:e,encode:t,decode:n}){return new Cl(r,e,t,n)}function zr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=th(t,r);return Qn({prefix:e,name:r,encode:n,decode:i=>_t(o(i))})}function Yb(r,e,t,n){let o={};for(let l=0;l<e.length;++l)o[e[l]]=l;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),a=0,c=0,u=0;for(let l=0;l<i;++l){let f=o[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function Xb(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;i.length*t&7;)i+="=";return i}function Ee({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Qn({prefix:e,name:r,encode(o){return Xb(o,n,t)},decode(o){return Yb(o,n,t,r)}})}var Fe=Ee({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nh=Ee({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Zb=Ee({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Jb=Ee({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Qb=Ee({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ex=Ee({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tx=Ee({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rx=Ee({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nx=Ee({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Dl={};xe(Dl,{base58btc:()=>Ae,base58flickr:()=>ox});var Ae=zr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ox=zr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ix=sh,oh=128,sx=127,ax=~sx,cx=Math.pow(2,31);function sh(r,e,t){e=e||[],t=t||0;for(var n=t;r>=cx;)e[t++]=r&255|oh,r/=128;for(;r&ax;)e[t++]=r&255|oh,r>>>=7;return e[t]=r|0,sh.bytes=t-n+1,e}var lx=Pl,ux=128,ih=127;function Pl(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Pl.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&ih)<<o:(s&ih)*Math.pow(2,o),o+=7}while(s>=ux);return Pl.bytes=i-n,t}var fx=Math.pow(2,7),dx=Math.pow(2,14),hx=Math.pow(2,21),px=Math.pow(2,28),mx=Math.pow(2,35),yx=Math.pow(2,42),gx=Math.pow(2,49),wx=Math.pow(2,56),bx=Math.pow(2,63),xx=function(r){return r<fx?1:r<dx?2:r<hx?3:r<px?4:r<mx?5:r<yx?6:r<gx?7:r<wx?8:r<bx?9:10},Ex={encode:ix,decode:lx,encodingLength:xx},vx=Ex,ii=vx;function si(r,e=0){return[ii.decode(r,e),ii.decode.bytes]}function eo(r,e,t=0){return ii.encode(r,e,t),e}function to(r){return ii.encodingLength(r)}function Jt(r,e){let t=e.byteLength,n=to(r),o=n+to(t),i=new Uint8Array(o+t);return eo(r,i,0),eo(t,i,n),i.set(e,o),new ro(r,t,e,i)}function Je(r){let e=_t(r),[t,n]=si(e),[o,i]=si(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new ro(t,o,s,e)}function ah(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&kl(r.bytes,t.bytes)}}var ro=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function ch(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return _x(t,Ol(r),e??Ae.encoder);default:return Ax(t,Ol(r),e??Fe.encoder)}}var lh=new WeakMap;function Ol(r){let e=lh.get(r);if(e==null){let t=new Map;return lh.set(r,t),t}return e}var O=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==ai)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==kx)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Jt(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&ah(e.multihash,n.multihash)}toString(e){return ch(this,e)}toJSON(){return{"/":ch(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??uh(n,o,i.bytes))}else if(t[Bx]===!0){let{version:n,multihash:o,code:i}=t,s=Je(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ai)throw new Error(`Version 0 CID must use dag-pb (code: ${ai}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=uh(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ai,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_t(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new ro(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,m]=si(e.subarray(t));return t+=m,f},o=n(),i=ai;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Sx(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ol(i).set(n,e),i}};function Sx(r,e){switch(r[0]){case"Q":{let t=e??Ae;return[Ae.prefix,t.decode(`${Ae.prefix}${r}`)]}case Ae.prefix:{let t=e??Ae;return[Ae.prefix,t.decode(r)]}case Fe.prefix:{let t=e??Fe;return[Fe.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function _x(r,e,t){let{prefix:n}=t;if(n!==Ae.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function Ax(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var ai=112,kx=18;function uh(r,e,t){let n=to(r),o=n+to(e),i=new Uint8Array(o+t.byteLength);return eo(r,i,0),eo(e,i,n),i.set(t,o),i}var Bx=Symbol.for("@ipld/js-cid/CID");var ci=Symbol.for("@libp2p/content-routing");var Ul=Symbol.for("@libp2p/peer-id");function fh(r){return r!=null&&!!r[Ul]}var li=Symbol.for("@libp2p/peer-routing");var Qt=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},N=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var no=(r,...e)=>{try{[...e]}catch{}};var Rs=class extends EventTarget{#e=new Map;constructor(){super(),no(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Ix(e,t))}},Fl=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Ix=globalThis.CustomEvent??Fl;function dh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function $r(...r){let e=[];for(let t of r)dh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Kr(...r){let e=[];for(let t of r)dh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Ml={};xe(Ml,{sha256:()=>ce,sha512:()=>Hl});function An({name:r,code:e,encode:t}){return new Vl(r,e,t)}var Vl=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Jt(this.code,t):t.then(n=>Jt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ph(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ce=An({name:"sha2-256",code:18,encode:ph("SHA-256")}),Hl=An({name:"sha2-512",code:19,encode:ph("SHA-512")});var mt=J(bh(),1);var zl={};xe(zl,{base64:()=>er,base64pad:()=>Mx,base64url:()=>zx,base64urlpad:()=>$x});var er=Ee({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Mx=Ee({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),zx=Ee({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$x=Ee({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});mt.default.formatters.b=r=>r==null?"undefined":Ae.baseEncode(r);mt.default.formatters.t=r=>r==null?"undefined":Fe.baseEncode(r);mt.default.formatters.m=r=>r==null?"undefined":er.baseEncode(r);mt.default.formatters.p=r=>r==null?"undefined":r.toString();mt.default.formatters.c=r=>r==null?"undefined":r.toString();mt.default.formatters.k=r=>r==null?"undefined":r.toString();mt.default.formatters.a=r=>r==null?"undefined":r.toString();function Kx(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function xh(){return{forComponent(r){return Q(r)}}}function Q(r){let e=Kx(`${r}:trace`);return mt.default.enabled(`${r}:trace`)&&mt.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,mt.default)(`${r}:trace`)),Object.assign((0,mt.default)(r),{error:(0,mt.default)(`${r}:error`),trace:e})}function ie(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function kt(r=0){return new Uint8Array(r)}function it(r=0){return new Uint8Array(r)}var o1=Math.pow(2,7),i1=Math.pow(2,14),s1=Math.pow(2,21),ql=Math.pow(2,28),Gl=Math.pow(2,35),Wl=Math.pow(2,42),jl=Math.pow(2,49),le=128,Ke=127;function st(r){if(r<o1)return 1;if(r<i1)return 2;if(r<s1)return 3;if(r<ql)return 4;if(r<Gl)return 5;if(r<Wl)return 6;if(r<jl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Yl(r,e,t=0){switch(st(r)){case 8:e[t++]=r&255|le,r/=128;case 7:e[t++]=r&255|le,r/=128;case 6:e[t++]=r&255|le,r/=128;case 5:e[t++]=r&255|le,r/=128;case 4:e[t++]=r&255|le,r>>>=7;case 3:e[t++]=r&255|le,r>>>=7;case 2:e[t++]=r&255|le,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function a1(r,e,t=0){switch(st(r)){case 8:e.set(t++,r&255|le),r/=128;case 7:e.set(t++,r&255|le),r/=128;case 6:e.set(t++,r&255|le),r/=128;case 5:e.set(t++,r&255|le),r/=128;case 4:e.set(t++,r&255|le),r>>>=7;case 3:e.set(t++,r&255|le),r>>>=7;case 2:e.set(t++,r&255|le),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Xl(r,e){let t=r[e],n=0;if(n+=t&Ke,t<le||(t=r[e+1],n+=(t&Ke)<<7,t<le)||(t=r[e+2],n+=(t&Ke)<<14,t<le)||(t=r[e+3],n+=(t&Ke)<<21,t<le)||(t=r[e+4],n+=(t&Ke)*ql,t<le)||(t=r[e+5],n+=(t&Ke)*Gl,t<le)||(t=r[e+6],n+=(t&Ke)*Wl,t<le)||(t=r[e+7],n+=(t&Ke)*jl,t<le))return n;throw new RangeError("Could not decode varint")}function c1(r,e){let t=r.get(e),n=0;if(n+=t&Ke,t<le||(t=r.get(e+1),n+=(t&Ke)<<7,t<le)||(t=r.get(e+2),n+=(t&Ke)<<14,t<le)||(t=r.get(e+3),n+=(t&Ke)<<21,t<le)||(t=r.get(e+4),n+=(t&Ke)*ql,t<le)||(t=r.get(e+5),n+=(t&Ke)*Gl,t<le)||(t=r.get(e+6),n+=(t&Ke)*Wl,t<le)||(t=r.get(e+7),n+=(t&Ke)*jl,t<le))return n;throw new RangeError("Could not decode varint")}function ao(r,e,t=0){return e==null&&(e=it(st(r))),e instanceof Uint8Array?Yl(r,e,t):a1(r,e,t)}function Bn(r,e=0){return r instanceof Uint8Array?Xl(r,e):c1(r,e)}var Zl=new Float32Array([-0]),qr=new Uint8Array(Zl.buffer);function Nh(r,e,t){Zl[0]=r,e[t]=qr[0],e[t+1]=qr[1],e[t+2]=qr[2],e[t+3]=qr[3]}function Ch(r,e){return qr[0]=r[e],qr[1]=r[e+1],qr[2]=r[e+2],qr[3]=r[e+3],Zl[0]}var Jl=new Float64Array([-0]),qe=new Uint8Array(Jl.buffer);function Lh(r,e,t){Jl[0]=r,e[t]=qe[0],e[t+1]=qe[1],e[t+2]=qe[2],e[t+3]=qe[3],e[t+4]=qe[4],e[t+5]=qe[5],e[t+6]=qe[6],e[t+7]=qe[7]}function Dh(r,e){return qe[0]=r[e],qe[1]=r[e+1],qe[2]=r[e+2],qe[3]=r[e+3],qe[4]=r[e+4],qe[5]=r[e+5],qe[6]=r[e+6],qe[7]=r[e+7],Jl[0]}var l1=BigInt(Number.MAX_SAFE_INTEGER),u1=BigInt(Number.MIN_SAFE_INTEGER),yt=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return In;if(e<l1&&e>u1)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Ph&&(o=0n,++n>Ph&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return In;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):In}},In=new yt(0,0);In.toBigInt=function(){return 0n};In.zzEncode=In.zzDecode=function(){return this};In.length=function(){return 1};var Ph=4294967296n;function Oh(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Uh(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function Ql(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Ut(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ls(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var eu=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ut(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ut(this,4);return Ls(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ut(this,4);return Ls(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ut(this,4);let e=Ch(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ut(this,4);let e=Dh(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Ut(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Uh(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ut(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ut(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new yt(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ut(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ut(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ut(this,8);let e=Ls(this.buf,this.pos+=4),t=Ls(this.buf,this.pos+=4);return new yt(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Xl(this.buf,this.pos);return this.pos+=st(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function tu(r){return new eu(r instanceof Uint8Array?r:r.subarray())}function Bt(r,e,t){let n=tu(r);return e.decode(n,void 0,t)}var ru={};xe(ru,{base10:()=>f1});var f1=zr({prefix:"9",name:"base10",alphabet:"0123456789"});var nu={};xe(nu,{base16:()=>d1,base16upper:()=>h1});var d1=Ee({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),h1=Ee({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ou={};xe(ou,{base2:()=>p1});var p1=Ee({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var iu={};xe(iu,{base256emoji:()=>b1});var Vh=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}"),m1=Vh.reduce((r,e,t)=>(r[t]=e,r),[]),y1=Vh.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function g1(r){return r.reduce((e,t)=>(e+=m1[t],e),"")}function w1(r){let e=[];for(let t of r){let n=y1[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var b1=Qn({prefix:"\u{1F680}",name:"base256emoji",encode:g1,decode:w1});var su={};xe(su,{base36:()=>Gr,base36upper:()=>x1});var Gr=zr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),x1=zr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var au={};xe(au,{base8:()=>E1});var E1=Ee({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var cu={};xe(cu,{identity:()=>v1});var v1=Qn({prefix:"\0",name:"identity",encode:r=>Il(r),decode:r=>Bl(r)});var ZB=new TextEncoder,S1=new TextDecoder;var Wr=512;function Hh(r){return JSON.parse(S1.decode(r))}var It={};xe(It,{code:()=>ge,decode:()=>k1,encode:()=>A1,name:()=>_1});var _1="raw",ge=85;function A1(r){return _t(r)}function k1(r){return _t(r)}var lu={};xe(lu,{identity:()=>Ge});var Mh=0,B1="identity",zh=_t;function I1(r){return Jt(Mh,zh(r))}var Ge={code:Mh,name:B1,encode:zh,digest:I1};var jr={...cu,...ou,...au,...ru,...nu,...Ll,...su,...Dl,...zl,...iu},lI={...Ml,...lu};function Kh(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var $h=Kh("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),uu=Kh("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=it(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),R1={utf8:$h,"utf-8":$h,hex:jr.base16,latin1:uu,ascii:uu,binary:uu,...jr},Ps=R1;function U(r,e="utf8"){let t=Ps[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function fu(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return it(s);o+s>e&&(n=it(e),o=0);let a=n.subarray(o,o+=s);return o&7&&(o=(o|7)+1),a}}var Rn=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function du(){}var pu=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},T1=fu();function N1(r){return globalThis.Buffer!=null?it(r):T1(r)}var fi=class{len;head;tail;states;constructor(){this.len=0,this.head=new Rn(du,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Rn(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new mu((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Os,10,yt.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=yt.fromBigInt(e);return this._push(Os,t.length(),t)}uint64Number(e){return this._push(Yl,st(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=yt.fromBigInt(e).zzEncode();return this._push(Os,t.length(),t)}sint64Number(e){let t=yt.fromNumber(e).zzEncode();return this._push(Os,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(hu,1,e?1:0)}fixed32(e){return this._push(ui,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=yt.fromBigInt(e);return this._push(ui,4,t.lo)._push(ui,4,t.hi)}fixed64Number(e){let t=yt.fromNumber(e);return this._push(ui,4,t.lo)._push(ui,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Nh,4,e)}double(e){return this._push(Lh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(hu,1,0):this.uint32(t)._push(L1,t,e)}string(e){let t=Oh(e);return t!==0?this.uint32(t)._push(Ql,t,e):this._push(hu,1,0)}fork(){return this.states=new pu(this),this.head=this.tail=new Rn(du,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 Rn(du,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=N1(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function hu(r,e,t){e[t]=r&255}function C1(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var mu=class extends Rn{next;constructor(e,t){super(C1,e,t),this.next=void 0}};function Os(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function ui(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function L1(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(fi.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(D1,e,r),this},fi.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(P1,e,r),this});function D1(r,e,t){e.set(r,t)}function P1(r,e,t){r.length<40?Ql(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(U(r),t)}function yu(){return new fi}function Rt(r,e){let t=yu();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var co;(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"})(co||(co={}));function Us(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Tn(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,s){let a=e(i);s.int32(a)},n=function(i){let s=i.int32();return e(s)};return Us("enum",co.VARINT,t,n)}function Tt(r,e){return Us("message",co.LENGTH_DELIMITED,r,e)}function O1(r){return r[Symbol.asyncIterator]!=null}function U1(r){if(O1(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ft=U1;function ue(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=it(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Gh=Symbol.for("@achingbrain/uint8arraylist");function qh(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function tr(r){return!!r?.[Gh]}var Vt=class r{bufs;length;[Gh]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(tr(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(tr(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=qh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=qh(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(tr(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return ue(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:ue(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!tr(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let 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,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let m=u;m>=0;m--){let d=this.get(f+m);if(n[m]!==d){l=Math.max(1,m-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=kt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=kt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=kt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=kt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=kt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=kt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=kt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=kt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,i)=>o+i.byteLength,0)),n.length=t,n}};function V1(r){return r[Symbol.asyncIterator]!=null}function H1(r,e){if(V1(r))return async function*(){for await(let a of r)yield e(a)}();let t=Zn(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let a of t)yield e(a)}();let s=e;return function*(){yield i;for(let a of t)yield s(a)}()}var We=H1;function ve(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Fs=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},lo=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Fs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Fs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var gu=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Nt(r={}){return M1(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function M1(r,e){e=e??{};let t=e.onEnd,n=new lo,o,i,s,a=ve(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{i=b=>{i=null,n.push(b);try{y(r(n))}catch(x){g(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ve()})}},u=y=>i!=null?i(y):(n.push(y),o),l=y=>(n=new lo,i!=null?i({error:y}):(n.push({error:y}),o)),f=y=>{if(s)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},m=y=>s?o:(s=!0,y!=null?l(y):u({done:!0})),d=()=>(n=new lo,m(),{done:!0}),p=y=>(m(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:m,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,x;g!=null&&(b=new Promise((v,S)=>{x=()=>{S(new gu)},g.addEventListener("abort",x)}));try{await Promise.race([a.promise,b])}finally{x!=null&&g!=null&&g?.removeEventListener("abort",x)}}},t==null)return o;let h=o;return o={[Symbol.asyncIterator](){return this},next(){return h.next()},throw(y){return h.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return h.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(y){return h.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return h.readableLength},onEmpty:y=>h.onEmpty(y)},o}function z1(r){return r[Symbol.asyncIterator]!=null}function $1(...r){let e=[];for(let t of r)z1(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Nt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var mr=$1;function at(r,...e){if(r==null)throw new Error("Empty pipeline");if(wu(r)){let n=r;r=()=>n.source}else if(Xh(r)||Yh(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&wu(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)wu(t[n])&&(t[n]=q1(t[n]));return K1(...t)}var K1=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Yh=r=>r?.[Symbol.asyncIterator]!=null,Xh=r=>r?.[Symbol.iterator]!=null,wu=r=>r==null?!1:r.sink!=null&&r.source!=null,q1=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Nt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Yh(i))o=async function*(){yield*i,n.end()};else if(Xh(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return mr(n,o())}return r.source};function G1(r){return r[Symbol.asyncIterator]!=null}function W1(r,e){return G1(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var Vs=W1;var F=class extends Event{constructor(e,t){super(e),this.detail=t}};function W(r,e="utf8"){let t=Ps[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Hs=class{url;#e=0;#t=0;#r=0;#s=0;constructor(e){this.url=e instanceof URL?e:new URL(e)}async getRawBlock(e,t){let n=this.url;if(n.pathname=`/ipfs/${e.toString()}`,n.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);try{this.#e++;let o=await fetch(n.toString(),{signal:t,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"});if(!o.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#s++,new Uint8Array(await o.arrayBuffer())}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#s/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}};var Ms=class{gateways;log;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.gateways=(t.gateways??Zh).map(n=>new Hs(n))}async retrieve(e,t={}){let n=this.gateways.sort((i,s)=>s.reliability()-i.reliability()),o=[];for(let i of n){this.log("getting block for %c from %s",e,i.url);try{let s=await i.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,i.url);try{await t.validateFn?.(s)}catch(a){throw this.log.error("failed to validate block for %c from %s",e,i.url,a),i.incrementInvalidBlocks(),new Error(`unable to validate block for CID ${e} from gateway ${i.url}`)}return s}catch(s){if(this.log.error("failed to get block for %c from %s",e,i.url,s),s instanceof Error?o.push(s):o.push(new Error(`unable to fetch raw block for CID ${e} from gateway ${i.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,i.url);break}}}throw new AggregateError(o,`unable to fetch raw block for CID ${e} from any gateway`)}};var Zh=["https://trustless-gateway.link","https://cloudflare-ipfs.com","https://4everland.io"];function di(r={}){return e=>new Ms(e,r)}var j1=Symbol.for("nodejs.util.inspect.custom"),Jh=Object.values(jr).map(r=>r.decoder).reduce((r,e)=>r.or(e),jr.identity.decoder),Qh=114,bu=36,xu=37,hi=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ul]=!0;toString(){return this.string==null&&(this.string=Ae.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return O.createV1(Qh,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ie(this.multihash.bytes,e);if(typeof e=="string")return Qe(e).equals(this);if(e?.multihash?.bytes!=null)return ie(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[j1](){return`PeerId(${this.toString()})`}},uo=class extends hi{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},fo=class extends hi{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},ho=class extends hi{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function Qe(r,e){if(e=e??Jh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Je(Ae.decode(`z${r}`));return r.startsWith("12D")?new fo({multihash:t}):r.startsWith("16U")?new ho({multihash:t}):new uo({multihash:t})}return pi(Jh.decode(r))}function pi(r){try{let e=Je(r);if(e.code===Ge.code){if(e.digest.length===bu)return new fo({multihash:e});if(e.digest.length===xu)return new ho({multihash:e})}if(e.code===ce.code)return new uo({multihash:e})}catch{return Y1(O.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Y1(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Qh)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===ce.code)return new uo({multihash:r.multihash});if(e.code===Ge.code){if(e.digest.length===bu)return new fo({multihash:r.multihash});if(e.digest.length===xu)return new ho({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function ep(r,e){return r.length===bu?new fo({multihash:Jt(Ge.code,r),privateKey:e}):r.length===xu?new ho({multihash:Jt(Ge.code,r),privateKey:e}):new uo({multihash:await ce.digest(r),publicKey:r,privateKey:e})}var zs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let m=Number.parseInt(f,e);if(!Number.isNaN(m))return m});if(l===void 0)break;if(i*=e,i+=l,i>u||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var tp=45,X1=15,po=new zs;function Eu(r){if(!(r.length>X1))return po.new(r).parseWith(()=>po.readIPv4Addr())}function vu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>tp))return po.new(r).parseWith(()=>po.readIPv6Addr())}function $s(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>tp))return po.new(r).parseWith(()=>po.readIPAddr())}var HR=parseInt("0xFFFF",16),MR=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function op(r){return!!Eu(r)}function ip(r){return!!vu(r)}function Ks(r){return!!$s(r)}var sp=op,tE=ip,Su=function(r){let e=0;if(r=r.toString().trim(),sp(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(tE(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=sp(t[n]),s;i&&(s=Su(t[n]),t[n]=W(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,W(s.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let i=parseInt(t[n],16);o[e++]=i>>8&255,o[e++]=i&255}return o}throw new Error("invalid ip address")},ap=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let i=0;i<t;i++)o.push(r[e+i]);return o.join(".")}if(t===16){let o=[];for(let i=0;i<t;i+=2)o.push(n.getUint16(e+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var mo={},_u={},nE=[[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"],[777,-1,"memory"]];nE.forEach(r=>{let e=oE(...r);_u[e.code]=e,mo[e.name]=e});function oE(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function de(r){if(typeof r=="number"){if(_u[r]!=null)return _u[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(mo[r]!=null)return mo[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var _T=de("ip4"),AT=de("ip6"),kT=de("ipcidr");function ku(r,e){switch(de(r).code){case 4:case 41:return sE(e);case 42:return up(e);case 6:case 273:case 33:case 132:return dp(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return up(e);case 421:return uE(e);case 444:return fp(e);case 445:return fp(e);case 466:return lE(e);default:return W(e,"base16")}}function Bu(r,e){switch(de(r).code){case 4:return cp(e);case 41:return cp(e);case 42:return lp(e);case 6:case 273:case 33:case 132:return Iu(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return lp(e);case 421:return aE(e);case 444:return fE(e);case 445:return dE(e);case 466:return cE(e);default:return U(e,"base16")}}var Au=Object.values(jr).map(r=>r.decoder),iE=function(){let r=Au[0].or(Au[1]);return Au.slice(2).forEach(e=>r=r.or(e)),r}();function cp(r){if(!Ks(r))throw new Error("invalid ip address");return Su(r)}function sE(r){let e=ap(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Ks(e))throw new Error("invalid ip address");return e}function Iu(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function dp(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function lp(r){let e=U(r),t=Uint8Array.from(ao(e.length));return ue([t,e],t.length+e.length)}function up(r){let e=Bn(r);if(r=r.slice(st(e)),r.length!==e)throw new Error("inconsistent lengths");return W(r)}function aE(r){let e;r[0]==="Q"||r[0]==="1"?e=Je(Ae.decode(`z${r}`)).bytes:e=O.parse(r).multihash.bytes;let t=Uint8Array.from(ao(e.length));return ue([t,e],t.length+e.length)}function cE(r){let e=iE.decode(r),t=Uint8Array.from(ao(e.length));return ue([t,e],t.length+e.length)}function lE(r){let e=Bn(r),t=r.slice(st(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+W(t,"base64url")}function uE(r){let e=Bn(r),t=r.slice(st(e));if(t.length!==e)throw new Error("inconsistent lengths");return W(t,"base58btc")}function fE(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Fe.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Iu(n);return ue([t,o],t.length+o.length)}function dE(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Fe.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Iu(n);return ue([t,o],t.length+o.length)}function fp(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=W(e,"base32"),o=dp(t);return`${n}:${o}`}function hp(r){r=Ru(r);let e=[],t=[],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=de(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw mp("invalid address: "+r);if(a.path===!0){n=Ru(o.slice(i).join("/")),e.push([a.code,Bu(a.code,n)]),t.push([a.code,n]);break}let c=Bu(a.code,o[i]);e.push([a.code,c]),t.push([a.code,ku(a.code,c)])}return{string:pp(t),bytes:Nu(e),tuples:e,stringTuples:t,path:n}}function Tu(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=Bn(r,o),s=st(i),a=de(i),c=hE(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let u=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw mp("Invalid address Uint8Array: "+W(r,"base16"));e.push([i,u]);let l=ku(i,u);if(t.push([i,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:pp(t),tuples:e,stringTuples:t,path:n}}function pp(r){let e=[];return r.map(t=>{let n=de(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Ru(e.join("/"))}function Nu(r){return ue(r.map(e=>{let t=de(e[0]),n=Uint8Array.from(ao(t.code));return e.length>1&&e[1]!=null&&(n=ue([n,e[1]])),n}))}function hE(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Bn(e instanceof Uint8Array?e:Uint8Array.from(e));return t+st(t)}}function Ru(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function mp(r){return new Error("Error parsing address: "+r)}var pE=Symbol.for("nodejs.util.inspect.custom"),Cu=Symbol.for("@multiformats/js-multiaddr/multiaddr"),mE=[de("dns").code,de("dns4").code,de("dns6").code,de("dnsaddr").code],qs=class r{bytes;#e;#t;#r;#s;[Cu]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Tu(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=hp(e)}else if(gp(e))t=Tu(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#s=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,i="",s=de("tcp"),a=de("udp"),c=de("ip4"),u=de("ip6"),l=de("dns6"),f=de("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(i=`%${p??""}`),mE.includes(d)&&(t=s.name,o=443,n=`${p??""}${i}`,e=d===l.code?6:4),(d===s.code||d===a.code)&&(t=de(d).name,o=parseInt(p??"")),(d===c.code||d===u.code)&&(t=de(d).name,n=`${p??""}${i}`,e=d===u.code?6:4);if(e==null||t==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:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},de(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>de(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Nu(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===mo.p2p.code&&e.push([n,o]),n===mo["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?W(Ae.decode(`z${n}`),"base58btc"):W(O.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#s}equals(e){return ie(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=yp.get(t.name);if(n==null)throw new N(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(i=>mi(i))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[pE](){return`Multiaddr(${this.#e})`}};var yp=new Map;function gp(r){return!!r?.[Cu]}function mi(r){return new qs(r)}async function*Gs(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var Yu={};xe(Yu,{Ed25519PrivateKey:()=>Dn,Ed25519PublicKey:()=>wi,generateKeyPair:()=>Av,generateKeyPairFromSeed:()=>Kp,unmarshalEd25519PrivateKey:()=>Sv,unmarshalEd25519PublicKey:()=>_v});function Ct(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function yo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function yE(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function go(r,...e){if(!yE(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function Ws(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");yo(r.outputLen),yo(r.blockLen)}function wo(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function wp(r,e){go(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var js=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var xo=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Ht=(r,e)=>r<<32-e|r>>>e;var i8=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var gE=async()=>{};async function bp(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-n;i>=0&&i<e||(await gE(),n+=i)}}function Lu(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Yr(r){return typeof r=="string"&&(r=Lu(r)),go(r),r}function Ys(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];go(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}var bo=class{clone(){return this._cloneInto()}},wE={}.toString;function xp(r,e){if(e!==void 0&&wE.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Xs(r){let e=n=>r().update(Yr(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Eo(r=32){if(js&&typeof js.getRandomValues=="function")return js.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function bE(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(t>>o&i),a=Number(t&i),c=n?4:0,u=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+u,a,n)}var Ep=(r,e,t)=>r&e^~r&t,vp=(r,e,t)=>r&e^r&t^e&t,vo=class extends bo{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=xo(this.buffer)}update(e){wo(this);let{view:t,buffer:n,blockLen:o}=this;e=Yr(e);let i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=xo(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){wo(this),wp(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[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++)t[f]=0;bE(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=xo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return e.length=o,e.pos=a,e.finished=i,e.destroyed=s,o%t&&e.buffer.set(n),e}};var Zs=BigInt(4294967295),Du=BigInt(32);function Sp(r,e=!1){return e?{h:Number(r&Zs),l:Number(r>>Du&Zs)}:{h:Number(r>>Du&Zs)|0,l:Number(r&Zs)|0}}function xE(r,e=!1){let t=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],e);[t[o],n[o]]=[i,s]}return[t,n]}var EE=(r,e)=>BigInt(r>>>0)<<Du|BigInt(e>>>0),vE=(r,e,t)=>r>>>t,SE=(r,e,t)=>r<<32-t|e>>>t,_E=(r,e,t)=>r>>>t|e<<32-t,AE=(r,e,t)=>r<<32-t|e>>>t,kE=(r,e,t)=>r<<64-t|e>>>t-32,BE=(r,e,t)=>r>>>t-32|e<<64-t,IE=(r,e)=>e,RE=(r,e)=>r,TE=(r,e,t)=>r<<t|e>>>32-t,NE=(r,e,t)=>e<<t|r>>>32-t,CE=(r,e,t)=>e<<t-32|r>>>64-t,LE=(r,e,t)=>r<<t-32|e>>>64-t;function DE(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var PE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),OE=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,UE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),FE=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,VE=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),HE=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var ME={fromBig:Sp,split:xE,toBig:EE,shrSH:vE,shrSL:SE,rotrSH:_E,rotrSL:AE,rotrBH:kE,rotrBL:BE,rotr32H:IE,rotr32L:RE,rotlSH:TE,rotlSL:NE,rotlBH:CE,rotlBL:LE,add:DE,add3L:PE,add3H:OE,add4L:UE,add4H:FE,add5H:HE,add5L:VE},Y=ME;var[zE,$E]=Y.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))),Xr=new Uint32Array(80),Zr=new Uint32Array(80),Pu=class extends vo{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:m,Gh:d,Gl:p,Hh:h,Hl:y}=this;return[e,t,n,o,i,s,a,c,u,l,f,m,d,p,h,y]}set(e,t,n,o,i,s,a,c,u,l,f,m,d,p,h,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=m|0,this.Gh=d|0,this.Gl=p|0,this.Hh=h|0,this.Hl=y|0}process(e,t){for(let x=0;x<16;x++,t+=4)Xr[x]=e.getUint32(t),Zr[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let v=Xr[x-15]|0,S=Zr[x-15]|0,I=Y.rotrSH(v,S,1)^Y.rotrSH(v,S,8)^Y.shrSH(v,S,7),_=Y.rotrSL(v,S,1)^Y.rotrSL(v,S,8)^Y.shrSL(v,S,7),E=Xr[x-2]|0,P=Zr[x-2]|0,V=Y.rotrSH(E,P,19)^Y.rotrBH(E,P,61)^Y.shrSH(E,P,6),L=Y.rotrSL(E,P,19)^Y.rotrBL(E,P,61)^Y.shrSL(E,P,6),$=Y.add4L(_,L,Zr[x-7],Zr[x-16]),C=Y.add4H($,I,V,Xr[x-7],Xr[x-16]);Xr[x]=C|0,Zr[x]=$|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:m,Fh:d,Fl:p,Gh:h,Gl:y,Hh:g,Hl:b}=this;for(let x=0;x<80;x++){let v=Y.rotrSH(f,m,14)^Y.rotrSH(f,m,18)^Y.rotrBH(f,m,41),S=Y.rotrSL(f,m,14)^Y.rotrSL(f,m,18)^Y.rotrBL(f,m,41),I=f&d^~f&h,_=m&p^~m&y,E=Y.add5L(b,S,_,$E[x],Zr[x]),P=Y.add5H(E,g,v,I,zE[x],Xr[x]),V=E|0,L=Y.rotrSH(n,o,28)^Y.rotrBH(n,o,34)^Y.rotrBH(n,o,39),$=Y.rotrSL(n,o,28)^Y.rotrBL(n,o,34)^Y.rotrBL(n,o,39),C=n&i^n&a^i&a,ne=o&s^o&c^s&c;g=h|0,b=y|0,h=d|0,y=p|0,d=f|0,p=m|0,{h:f,l:m}=Y.add(u|0,l|0,P|0,V|0),u=a|0,l=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let B=Y.add3L(V,$,ne);n=Y.add3H(B,P,L,C),o=B|0}({h:n,l:o}=Y.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Y.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Y.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:m}=Y.add(this.Eh|0,this.El|0,f|0,m|0),{h:d,l:p}=Y.add(this.Fh|0,this.Fl|0,d|0,p|0),{h,l:y}=Y.add(this.Gh|0,this.Gl|0,h|0,y|0),{h:g,l:b}=Y.add(this.Hh|0,this.Hl|0,g|0,b|0),this.set(n,o,i,s,a,c,u,l,f,m,d,p,h,y,g,b)}roundClean(){Xr.fill(0),Zr.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 So=Xs(()=>new Pu);var Qs={};xe(Qs,{abytes:()=>_o,bitGet:()=>XE,bitLen:()=>YE,bitMask:()=>yi,bitSet:()=>ZE,bytesToHex:()=>gr,bytesToNumberBE:()=>wr,bytesToNumberLE:()=>Qr,concatBytes:()=>br,createHmacDrbg:()=>Fu,ensureBytes:()=>Se,equalBytes:()=>WE,hexToBytes:()=>Nn,hexToNumber:()=>Uu,isBytes:()=>Jr,numberToBytesBE:()=>en,numberToBytesLE:()=>Cn,numberToHexUnpadded:()=>Bp,numberToVarBytesBE:()=>GE,utf8ToBytes:()=>jE,validateObject:()=>rr});var kp=BigInt(0),Js=BigInt(1),KE=BigInt(2);function Jr(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function _o(r){if(!Jr(r))throw new Error("Uint8Array expected")}var qE=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function gr(r){_o(r);let e="";for(let t=0;t<r.length;t++)e+=qE[r[t]];return e}function Bp(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Uu(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var yr={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function _p(r){if(r>=yr._0&&r<=yr._9)return r-yr._0;if(r>=yr._A&&r<=yr._F)return r-(yr._A-10);if(r>=yr._a&&r<=yr._f)return r-(yr._a-10)}function Nn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,i=0;o<t;o++,i+=2){let s=_p(r.charCodeAt(i)),a=_p(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 wr(r){return Uu(gr(r))}function Qr(r){return _o(r),Uu(gr(Uint8Array.from(r).reverse()))}function en(r,e){return Nn(r.toString(16).padStart(e*2,"0"))}function Cn(r,e){return en(r,e).reverse()}function GE(r){return Nn(Bp(r))}function Se(r,e,t){let n;if(typeof e=="string")try{n=Nn(e)}catch(i){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${i}`)}else if(Jr(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function br(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];_o(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function WE(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function jE(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function YE(r){let e;for(e=0;r>kp;r>>=Js,e+=1);return e}function XE(r,e){return r>>BigInt(e)&Js}function ZE(r,e,t){return r|(t?Js:kp)<<BigInt(e)}var yi=r=>(KE<<BigInt(r-1))-Js,Ou=r=>new Uint8Array(r),Ap=r=>Uint8Array.from(r);function Fu(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Ou(r),o=Ou(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>t(o,n,...f),c=(f=Ou())=>{o=a(Ap([0]),f),n=a(),f.length!==0&&(o=a(Ap([1]),f),n=a())},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,m=[];for(;f<e;){n=a();let d=n.slice();m.push(d),f+=n.length}return br(...m)};return(f,m)=>{s(),c(f);let d;for(;!(d=m(u()));)c();return s(),d}}var JE={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"||Jr(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function rr(r,e,t={}){let n=(o,i,s)=>{let a=JE[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(e))n(o,i,!1);for(let[o,i]of Object.entries(t))n(o,i,!0);return r}var Ce=BigInt(0),he=BigInt(1),Ln=BigInt(2),QE=BigInt(3),Vu=BigInt(4),Ip=BigInt(5),Rp=BigInt(8),ev=BigInt(9),tv=BigInt(16);function fe(r,e){let t=r%e;return t>=Ce?t:e+t}function rv(r,e,t){if(t<=Ce||e<Ce)throw new Error("Expected power/modulo > 0");if(t===he)return Ce;let n=he;for(;e>Ce;)e&he&&(n=n*r%t),r=r*r%t,e>>=he;return n}function pe(r,e,t){let n=r;for(;e-- >Ce;)n*=n,n%=t;return n}function ea(r,e){if(r===Ce||e<=Ce)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=fe(r,e),n=e,o=Ce,i=he,s=he,a=Ce;for(;t!==Ce;){let u=n/t,l=n%t,f=o-s*u,m=i-a*u;n=t,t=l,o=s,i=a,s=f,a=m}if(n!==he)throw new Error("invert: does not exist");return fe(o,e)}function nv(r){let e=(r-he)/Ln,t,n,o;for(t=r-he,n=0;t%Ln===Ce;t/=Ln,n++);for(o=Ln;o<r&&rv(o,e,r)!==r-he;o++);if(n===1){let s=(r+he)/Vu;return function(c,u){let l=c.pow(u,s);if(!c.eql(c.sqr(l),u))throw new Error("Cannot find square root");return l}}let i=(t+he)/Ln;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,l=a.pow(a.mul(a.ONE,o),t),f=a.pow(c,i),m=a.pow(c,t);for(;!a.eql(m,a.ONE);){if(a.eql(m,a.ZERO))return a.ZERO;let d=1;for(let h=a.sqr(m);d<u&&!a.eql(h,a.ONE);d++)h=a.sqr(h);let p=a.pow(l,he<<BigInt(u-d-1));l=a.sqr(p),f=a.mul(f,p),m=a.mul(m,l),u=d}return f}}function ov(r){if(r%Vu===QE){let e=(r+he)/Vu;return function(n,o){let i=n.pow(o,e);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%Rp===Ip){let e=(r-Ip)/Rp;return function(n,o){let i=n.mul(o,Ln),s=n.pow(i,e),a=n.mul(o,s),c=n.mul(n.mul(a,Ln),s),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%tv,nv(r)}var Tp=(r,e)=>(fe(r,e)&he)===he,iv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Hu(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=iv.reduce((n,o)=>(n[o]="function",n),e);return rr(r,t)}function sv(r,e,t){if(t<Ce)throw new Error("Expected power > 0");if(t===Ce)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>Ce;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function av(r,e){let t=new Array(e.length),n=e.reduce((i,s,a)=>r.is0(s)?i:(t[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return e.reduceRight((i,s,a)=>r.is0(s)?i:(t[a]=r.mul(i,t[a]),r.mul(i,s)),o),t}function Mu(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function ta(r,e,t=!1,n={}){if(r<=Ce)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:i}=Mu(r,e);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=ov(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:i,MASK:yi(o),ZERO:Ce,ONE:he,create:c=>fe(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Ce<=c&&c<r},is0:c=>c===Ce,isOdd:c=>(c&he)===he,neg:c=>fe(-c,r),eql:(c,u)=>c===u,sqr:c=>fe(c*c,r),add:(c,u)=>fe(c+u,r),sub:(c,u)=>fe(c-u,r),mul:(c,u)=>fe(c*u,r),pow:(c,u)=>sv(a,c,u),div:(c,u)=>fe(c*ea(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>ea(c,r),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>av(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>t?Cn(c,i):en(c,i),fromBytes:c=>{if(c.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);return t?Qr(c):wr(c)}});return Object.freeze(a)}function Np(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function Cp(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function zu(r){let e=Cp(r);return e+Math.ceil(e/2)}function Lp(r,e,t=!1){let n=r.length,o=Cp(e),i=zu(e);if(n<16||n<i||n>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);let s=t?wr(r):Qr(r),a=fe(s,e-he)+he;return t?Cn(a,o):en(a,o)}var lv=BigInt(0),$u=BigInt(1);function ra(r,e){let t=(o,i)=>{let s=i.negate();return o?s:i},n=o=>{let i=Math.ceil(e/o)+1,s=2**(o-1);return{windows:i,windowSize:s}};return{constTimeNegate:t,unsafeLadder(o,i){let s=r.ZERO,a=o;for(;i>lv;)i&$u&&(s=s.add(a)),a=a.double(),i>>=$u;return s},precomputeWindow(o,i){let{windows:s,windowSize:a}=n(i),c=[],u=o,l=u;for(let f=0;f<s;f++){l=u,c.push(l);for(let m=1;m<a;m++)l=l.add(u),c.push(l);u=l.double()}return c},wNAF(o,i,s){let{windows:a,windowSize:c}=n(o),u=r.ZERO,l=r.BASE,f=BigInt(2**o-1),m=2**o,d=BigInt(o);for(let p=0;p<a;p++){let h=p*c,y=Number(s&f);s>>=d,y>c&&(y-=m,s+=$u);let g=h,b=h+Math.abs(y)-1,x=p%2!==0,v=y<0;y===0?l=l.add(t(x,i[g])):u=u.add(t(v,i[b]))}return{p:u,f:l}},wNAFCached(o,i,s,a){let c=o._WINDOW_SIZE||1,u=i.get(o);return u||(u=this.precomputeWindow(o,c),c!==1&&i.set(o,a(u))),this.wNAF(c,u,s)}}}function gi(r){return Hu(r.Fp),rr(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Mu(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Mt=BigInt(0),gt=BigInt(1),na=BigInt(2),uv=BigInt(8),fv={zip215:!0};function dv(r){let e=gi(r);return rr(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function oa(r){let e=dv(r),{Fp:t,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=e,u=na<<BigInt(a*8)-gt,l=t.create,f=e.uvRatio||((R,A)=>{try{return{isValid:!0,value:t.sqrt(R*t.inv(A))}}catch{return{isValid:!1,value:Mt}}}),m=e.adjustScalarBytes||(R=>R),d=e.domain||((R,A,M)=>{if(A.length||M)throw new Error("Contexts/pre-hash are not supported");return R}),p=R=>typeof R=="bigint"&&Mt<R,h=(R,A)=>p(R)&&p(A)&&R<A,y=R=>R===Mt||h(R,u);function g(R,A){if(h(R,A))return R;throw new Error(`Expected valid scalar < ${A}, got ${typeof R} ${R}`)}function b(R){return R===Mt?R:g(R,n)}let x=new Map;function v(R){if(!(R instanceof S))throw new Error("ExtendedPoint expected")}class S{constructor(A,M,K,j){if(this.ex=A,this.ey=M,this.ez=K,this.et=j,!y(A))throw new Error("x required");if(!y(M))throw new Error("y required");if(!y(K))throw new Error("z required");if(!y(j))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof S)throw new Error("extended point not allowed");let{x:M,y:K}=A||{};if(!y(M)||!y(K))throw new Error("invalid affine point");return new S(M,K,gt,l(M*K))}static normalizeZ(A){let M=t.invertBatch(A.map(K=>K.ez));return A.map((K,j)=>K.toAffine(M[j])).map(S.fromAffine)}_setWindowSize(A){this._WINDOW_SIZE=A,x.delete(this)}assertValidity(){let{a:A,d:M}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:K,ey:j,ez:X,et:Z}=this,ae=l(K*K),te=l(j*j),oe=l(X*X),Be=l(oe*oe),be=l(ae*A),Oe=l(oe*l(be+te)),Ue=l(Be+l(M*l(ae*te)));if(Oe!==Ue)throw new Error("bad point: equation left != right (1)");let Ne=l(K*j),$e=l(X*Z);if(Ne!==$e)throw new Error("bad point: equation left != right (2)")}equals(A){v(A);let{ex:M,ey:K,ez:j}=this,{ex:X,ey:Z,ez:ae}=A,te=l(M*ae),oe=l(X*j),Be=l(K*ae),be=l(Z*j);return te===oe&&Be===be}is0(){return this.equals(S.ZERO)}negate(){return new S(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:A}=e,{ex:M,ey:K,ez:j}=this,X=l(M*M),Z=l(K*K),ae=l(na*l(j*j)),te=l(A*X),oe=M+K,Be=l(l(oe*oe)-X-Z),be=te+Z,Oe=be-ae,Ue=te-Z,Ne=l(Be*Oe),$e=l(be*Ue),pr=l(Be*Ue),Sn=l(Oe*be);return new S(Ne,$e,Sn,pr)}add(A){v(A);let{a:M,d:K}=e,{ex:j,ey:X,ez:Z,et:ae}=this,{ex:te,ey:oe,ez:Be,et:be}=A;if(M===BigInt(-1)){let qd=l((X-j)*(oe+te)),Gd=l((X+j)*(oe-te)),_l=l(Gd-qd);if(_l===Mt)return this.double();let Wd=l(Z*na*be),jd=l(ae*na*Be),Yd=jd+Wd,Xd=Gd+qd,Zd=jd-Wd,Tb=l(Yd*_l),Nb=l(Xd*Zd),Cb=l(Yd*Zd),Lb=l(_l*Xd);return new S(Tb,Nb,Lb,Cb)}let Oe=l(j*te),Ue=l(X*oe),Ne=l(ae*K*be),$e=l(Z*Be),pr=l((j+X)*(te+oe)-Oe-Ue),Sn=$e-Ne,oi=$e+Ne,Kd=l(Ue-M*Oe),kb=l(pr*Sn),Bb=l(oi*Kd),Ib=l(pr*Kd),Rb=l(Sn*oi);return new S(kb,Bb,Rb,Ib)}subtract(A){return this.add(A.negate())}wNAF(A){return E.wNAFCached(this,x,A,S.normalizeZ)}multiply(A){let{p:M,f:K}=this.wNAF(g(A,n));return S.normalizeZ([M,K])[0]}multiplyUnsafe(A){let M=b(A);return M===Mt?_:this.equals(_)||M===gt?this:this.equals(I)?this.wNAF(M).p:E.unsafeLadder(this,M)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return E.unsafeLadder(this,n).is0()}toAffine(A){let{ex:M,ey:K,ez:j}=this,X=this.is0();A==null&&(A=X?uv:t.inv(j));let Z=l(M*A),ae=l(K*A),te=l(j*A);if(X)return{x:Mt,y:gt};if(te!==gt)throw new Error("invZ was invalid");return{x:Z,y:ae}}clearCofactor(){let{h:A}=e;return A===gt?this:this.multiplyUnsafe(A)}static fromHex(A,M=!1){let{d:K,a:j}=e,X=t.BYTES;A=Se("pointHex",A,X);let Z=A.slice(),ae=A[X-1];Z[X-1]=ae&-129;let te=Qr(Z);te===Mt||(M?g(te,u):g(te,t.ORDER));let oe=l(te*te),Be=l(oe-gt),be=l(K*oe-j),{isValid:Oe,value:Ue}=f(Be,be);if(!Oe)throw new Error("Point.fromHex: invalid y coordinate");let Ne=(Ue>)===gt,$e=(ae&128)!==0;if(!M&&Ue===Mt&&$e)throw new Error("Point.fromHex: x=0 and x_0=1");return $e!==Ne&&(Ue=l(-Ue)),S.fromAffine({x:Ue,y:te})}static fromPrivateKey(A){return L(A).point}toRawBytes(){let{x:A,y:M}=this.toAffine(),K=Cn(M,t.BYTES);return K[K.length-1]|=A>?128:0,K}toHex(){return gr(this.toRawBytes())}}S.BASE=new S(e.Gx,e.Gy,gt,l(e.Gx*e.Gy)),S.ZERO=new S(Mt,gt,gt,Mt);let{BASE:I,ZERO:_}=S,E=ra(S,a*8);function P(R){return fe(R,n)}function V(R){return P(Qr(R))}function L(R){let A=a;R=Se("private key",R,A);let M=Se("hashed private key",i(R),2*A),K=m(M.slice(0,A)),j=M.slice(A,2*A),X=V(K),Z=I.multiply(X),ae=Z.toRawBytes();return{head:K,prefix:j,scalar:X,point:Z,pointBytes:ae}}function $(R){return L(R).pointBytes}function C(R=new Uint8Array,...A){let M=br(...A);return V(i(d(M,Se("context",R),!!o)))}function ne(R,A,M={}){R=Se("message",R),o&&(R=o(R));let{prefix:K,scalar:j,pointBytes:X}=L(A),Z=C(M.context,K,R),ae=I.multiply(Z).toRawBytes(),te=C(M.context,ae,X,R),oe=P(Z+te*j);b(oe);let Be=br(ae,Cn(oe,t.BYTES));return Se("result",Be,a*2)}let B=fv;function T(R,A,M,K=B){let{context:j,zip215:X}=K,Z=t.BYTES;R=Se("signature",R,2*Z),A=Se("message",A),o&&(A=o(A));let ae=Qr(R.slice(Z,2*Z)),te,oe,Be;try{te=S.fromHex(M,X),oe=S.fromHex(R.slice(0,Z),X),Be=I.multiplyUnsafe(ae)}catch{return!1}if(!X&&te.isSmallOrder())return!1;let be=C(j,oe.toRawBytes(),te.toRawBytes(),A);return oe.add(te.multiplyUnsafe(be)).subtract(Be).clearCofactor().equals(S.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:$,sign:ne,verify:T,ExtendedPoint:S,utils:{getExtendedPublicKey:L,randomPrivateKey:()=>s(t.BYTES),precompute(R=8,A=S.BASE){return A._setWindowSize(R),A.multiply(BigInt(3)),A}}}}var qu=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Dp=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),B8=BigInt(0),hv=BigInt(1),Ku=BigInt(2),pv=BigInt(5),Pp=BigInt(10),mv=BigInt(20),yv=BigInt(40),Op=BigInt(80);function gv(r){let e=qu,n=r*r%e*r%e,o=pe(n,Ku,e)*n%e,i=pe(o,hv,e)*r%e,s=pe(i,pv,e)*i%e,a=pe(s,Pp,e)*s%e,c=pe(a,mv,e)*a%e,u=pe(c,yv,e)*c%e,l=pe(u,Op,e)*u%e,f=pe(l,Op,e)*u%e,m=pe(f,Pp,e)*s%e;return{pow_p_5_8:pe(m,Ku,e)*r%e,b2:n}}function wv(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function bv(r,e){let t=qu,n=fe(e*e*e,t),o=fe(n*n*e,t),i=gv(r*o).pow_p_5_8,s=fe(r*n*i,t),a=fe(e*s*s,t),c=s,u=fe(s*Dp,t),l=a===r,f=a===fe(-r,t),m=a===fe(-r*Dp,t);return l&&(s=c),(f||m)&&(s=u),Tp(s,t)&&(s=fe(-s,t)),{isValid:l||f,value:s}}var xr=ta(qu,void 0,!0),Gu={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:xr,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:So,randomBytes:Eo,adjustScalarBytes:wv,uvRatio:bv},Ao=oa(Gu);function Up(r,e,t){if(e.length>255)throw new Error("Context is too big");return Ys(Lu("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var I8=oa({...Gu,domain:Up}),R8=oa({...Gu,domain:Up,prehash:So});var xv=(xr.ORDER+BigInt(3))/BigInt(8),T8=xr.pow(Ku,xv),N8=xr.sqrt(xr.neg(xr.ONE)),C8=(xr.ORDER-BigInt(5))/BigInt(8),L8=BigInt(486662);var D8=Np(xr,xr.neg(BigInt(486664)));var P8=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),O8=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),U8=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),F8=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var V8=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ko=32,Er=64,ia=32;function Fp(){let r=Ao.utils.randomPrivateKey(),e=Ao.getPublicKey(r);return{privateKey:zp(r,e),publicKey:e}}function Vp(r){if(r.length!==ia)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=Ao.getPublicKey(e);return{privateKey:zp(e,t),publicKey:t}}function Hp(r,e){let t=r.subarray(0,ia);return Ao.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Mp(r,e,t){return Ao.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function zp(r,e){let t=new Uint8Array(Er);for(let n=0;n<ia;n++)t[n]=r[n],t[ia+n]=e[n];return t}var et={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var Wu={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function $p(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",i=r?.saltLength??16,s=r?.iterations??32767,a=et.get();t*=8;async function c(f,m){let d=a.getRandomValues(new Uint8Array(i)),p=a.getRandomValues(new Uint8Array(n)),h={name:e,iv:p};typeof m=="string"&&(m=U(m));let y;if(m.length===0){y=await a.subtle.importKey("jwk",Wu,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:d,iterations:s,hash:{name:o}},x=await a.subtle.importKey("raw",m,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Wu,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:d,iterations:s,hash:{name:o}},x=await a.subtle.importKey("raw",m,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(h,y,f);return ue([d,h.iv,new Uint8Array(g)])}async function u(f,m){let d=f.subarray(0,i),p=f.subarray(i,i+n),h=f.subarray(i+n),y={name:e,iv:p};typeof m=="string"&&(m=U(m));let g;if(m.length===0)try{let x={name:"PBKDF2",salt:d,iterations:s,hash:{name:o}},v=await a.subtle.importKey("raw",m,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,v,{name:e,length:t},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",Wu,{name:"AES-GCM"},!0,["decrypt"])}else{let x={name:"PBKDF2",salt:d,iterations:s,hash:{name:o}},v=await a.subtle.importKey("raw",m,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,v,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(y,g,h);return new Uint8Array(b)}return{encrypt:c,decrypt:u}}async function Bo(r,e){let n=await $p().encrypt(r,e);return er.encode(n)}var me;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(me||(me={}));var ju;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(ju||(ju={}));(function(r){r.codec=()=>Tn(ju)})(me||(me={}));var nr;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),me.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Type=me.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>Rt(t,r.codec()),r.decode=t=>Bt(t,r.codec())})(nr||(nr={}));var or;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),me.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Type=me.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>Rt(t,r.codec()),r.decode=t=>Bt(t,r.codec())})(or||(or={}));var wi=class{_key;constructor(e){this._key=Io(e,ko)}verify(e,t){return Mp(this._key,t,e)}marshal(){return this._key}get bytes(){return nr.encode({Type:me.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=ce.digest(this.bytes);return Ct(e)?e.then(({bytes:t})=>t):e.bytes}},Dn=class{_key;_publicKey;constructor(e,t){this._key=Io(e,Er),this._publicKey=Io(t,ko)}sign(e){return Hp(this._key,e)}get public(){return new wi(this._publicKey)}marshal(){return this._key}get bytes(){return or.encode({Type:me.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=ce.digest(this.bytes),t;return Ct(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Ge.digest(this.public.bytes);return Ae.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Bo(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Sv(r){if(r.length>Er){r=Io(r,Er+ko);let n=r.subarray(0,Er),o=r.subarray(Er,r.length);return new Dn(n,o)}r=Io(r,Er);let e=r.subarray(0,Er),t=r.subarray(ko);return new Dn(e,t)}function _v(r){return r=Io(r,ko),new wi(r)}async function Av(){let{privateKey:r,publicKey:e}=Fp();return new Dn(r,e)}async function Kp(r){let{privateKey:e,publicKey:t}=Vp(r);return new Dn(e,t)}function Io(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new N(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var sf={};xe(sf,{MAX_RSA_KEY_SIZE:()=>Ti,RsaPrivateKey:()=>Lo,RsaPublicKey:()=>Ri,fromJwk:()=>Jv,generateKeyPair:()=>Qv,unmarshalRsaPrivateKey:()=>nf,unmarshalRsaPublicKey:()=>Zv});function Pn(r){if(isNaN(r)||r<=0)throw new N("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Eo(r)}var on={};xe(on,{exportToPem:()=>Gv,importFromPem:()=>Wv,jwkToPkcs1:()=>zv,jwkToPkix:()=>Kv,pkcs1ToJwk:()=>Mv,pkixToJwk:()=>$v});var aa=class extends bo{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ws(e);let n=Yr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(e){return wo(this),this.iHash.update(e),this}digestInto(e){wo(this),go(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},bi=(r,e,t)=>new aa(r,e).update(t).digest();bi.create=(r,e)=>new aa(r,e);function kv(r,e,t,n){Ws(r);let o=xp({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(yo(i),yo(s),yo(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Yr(e),u=Yr(t),l=new Uint8Array(s),f=bi.create(r,c),m=f._cloneInto().update(u);return{c:i,dkLen:s,asyncTick:a,DK:l,PRF:f,PRFSalt:m}}function Bv(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function Xu(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:u}=kv(r,e,t,n),l,f=new Uint8Array(4),m=xo(f),d=new Uint8Array(c.outputLen);for(let p=1,h=0;h<i;p++,h+=c.outputLen){let y=a.subarray(h,h+c.outputLen);m.setInt32(0,p,!1),(l=u._cloneInto(l)).update(f).digestInto(d),y.set(d.subarray(0,y.length)),await bp(o-1,s,()=>{c._cloneInto(l).update(d).digestInto(d);for(let g=0;g<y.length;g++)y[g]^=d[g]})}return Bv(c,u,a,l,d)}var ee=J(qp());function On(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function tn(r,e,t=-1){let n=t,o=r,i=0,s=Math.pow(2,e);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 u=new Uint8Array(c);for(let l=a-1;l>=0;l--){let f=Math.pow(2,l*e);u[i-l-1]=Math.floor(o/f),o-=u[i-l-1]*f}return c}s*=Math.pow(2,e)}return new ArrayBuffer(0)}function ua(...r){let e=0,t=0;for(let i of r)e+=i.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let i of r)o.set(i,t),t+=i.length;return o}function Ju(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=On(t,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,On(i,8)-n}function Gp(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let s=t-e,a=tn(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=tn(e,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}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Wp(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function ct(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(t)}var hN=Math.log(2);function fa(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Qu(r){let e=0,t=0;for(let o=0;o<r.length;o++){let i=r[o];e+=i.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let i=r[o];n.set(new Uint8Array(i),t),t+=i.byteLength}return n.buffer}function kr(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Ei=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Qu(this.items)}},xi=[new Uint8Array([1])],jp="0123456789";var No="",$t=new ArrayBuffer(0),ef=new Uint8Array(0),vi="EndOfContent",Xp="OCTET STRING",Zp="BIT STRING";function Br(r){var e;return e=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?ee.BufferSourceConverter.toUint8Array(i.valueHex):ef}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(!kr(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",$t)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ee.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Sr=class{constructor({blockLength:e=0,error:t=No,warnings:n=[],valueBeforeDecode:o=ef}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=ee.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ee.Convert.ToHex(this.valueBeforeDecodeView)}}};Sr.NAME="baseBlock";var je=class extends Sr{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};je.NAME="valueBlock";var da=class extends Br(Sr){constructor({idBlock:e={}}={}){var t,n,o,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?ee.BufferSourceConverter.toUint8Array(e.valueHex):ef,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",$t}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=tn(this.tagNumber,7),i=new Uint8Array(o),s=o.byteLength,a=new Uint8Array(s+1);if(a[0]=t|31,!e){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]=t|31,!e){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(e,t,n){let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;let i=o.subarray(t,t+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,u=this.valueHexView=new Uint8Array(255),l=255;for(;i[c]&128;){if(u[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===l){l+=255;let m=new Uint8Array(l);for(let d=0;d<u.length;d++)m[d]=u[d];u=this.valueHexView=new Uint8Array(l)}}this.blockLength=c+1,u[c-1]=i[c]&127;let f=new Uint8Array(c);for(let m=0;m<c;m++)f[m]=u[m];u=this.valueHexView=new Uint8Array(c),u.set(f),this.blockLength<=9?this.tagNumber=On(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};da.NAME="identificationBlock";var ha=class extends Sr{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;let i=o.subarray(t,t+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,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+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=t+1,c=o.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=On(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=tn(this.length,8);if(o.byteLength>127)return this.error="Too big length",$t;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let i=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let s=0;s<o.byteLength;s++)n[s+1]=i[s];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};ha.NAME="lengthBlock";var H={},Ve=class extends Sr{constructor({name:e=No,optional:t=!1,primitiveSchema:n,...o}={},i){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new da(o),this.lenBlock=new ha(o),this.valueBlock=i?new i(o):new je(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,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(e,t){let n=t||new Ei;t||Jp(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let s=this.lenBlock.toBER(e);n.write(s),n.write(i)}return t?$t:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():ee.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${ee.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Wp(t,n)}};Ve.NAME="BaseBlock";function Jp(r){if(r instanceof H.Constructed)for(let e of r.valueBlock.value)Jp(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var pa=class extends Ve{constructor({value:e=No,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,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}'`}};pa.NAME="BaseStringBlock";var ma=class extends Br(je){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};ma.NAME="PrimitiveValueBlock";var Qp,ya=class extends Ve{constructor(e={}){super(e,ma),this.idBlock.isConstructed=!1}};Qp=ya;H.Primitive=Qp;ya.NAME="PRIMITIVE";function Ov(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Ya(r,e=0,t=r.length){let n=e,o=new Ve({},je),i=new Sr;if(!kr(i,r,e,t))return o.error=i.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=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=Ve;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=H.EndOfContent;break;case 1:c=H.Boolean;break;case 2:c=H.Integer;break;case 3:c=H.BitString;break;case 4:c=H.OctetString;break;case 5:c=H.Null;break;case 6:c=H.ObjectIdentifier;break;case 10:c=H.Enumerated;break;case 12:c=H.Utf8String;break;case 13:c=H.RelativeObjectIdentifier;break;case 14:c=H.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=H.Sequence;break;case 17:c=H.Set;break;case 18:c=H.NumericString;break;case 19:c=H.PrintableString;break;case 20:c=H.TeletexString;break;case 21:c=H.VideotexString;break;case 22:c=H.IA5String;break;case 23:c=H.UTCTime;break;case 24:c=H.GeneralizedTime;break;case 25:c=H.GraphicString;break;case 26:c=H.VisibleString;break;case 27:c=H.GeneralString;break;case 28:c=H.UniversalString;break;case 29:c=H.CharacterString;break;case 30:c=H.BmpString;break;case 31:c=H.DATE;break;case 32:c=H.TimeOfDay;break;case 33:c=H.DateTime;break;case 34:c=H.Duration;break;default:{let u=o.idBlock.isConstructed?new H.Constructed:new H.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?H.Constructed:H.Primitive}return o=Ov(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Co(r){if(!r.byteLength){let e=new Ve({},je);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ya(ee.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Uv(r,e){return r?1:e}var ir=class extends je{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let i=t;for(;Uv(this.isIndefiniteForm,n)>0;){let s=Ya(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===vi)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===vi?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){let n=t||new Ei;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?$t:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};ir.NAME="ConstructedValueBlock";var em,rn=class extends Ve{constructor(e={}){super(e,ir),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,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 e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
2
|
+
"use strict";var HeliaVerifiedFetch=(()=>{var Pb=Object.create;var Bs=Object.defineProperty;var Ob=Object.getOwnPropertyDescriptor;var Ub=Object.getOwnPropertyNames;var Fb=Object.getPrototypeOf,Vb=Object.prototype.hasOwnProperty;var Le=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),xe=(r,e)=>{for(var t in e)Bs(r,t,{get:e[t],enumerable:!0})},Qd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ub(e))!Vb.call(r,o)&&o!==t&&Bs(r,o,{get:()=>e[o],enumerable:!(n=Ob(e,o))||n.enumerable});return r};var J=(r,e,t)=>(t=r!=null?Pb(Fb(r)):{},Qd(e||!r||!r.__esModule?Bs(t,"default",{value:r,enumerable:!0}):t,r)),Hb=r=>Qd(Bs({},"__esModule",{value:!0}),r);var gh=Le((vB,yh)=>{var ro=1e3,no=ro*60,oo=no*60,An=oo*24,Tx=An*7,Nx=An*365.25;yh.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Cx(r);if(t==="number"&&isFinite(r))return e.long?Dx(r):Lx(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Cx(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Nx;case"weeks":case"week":case"w":return t*Tx;case"days":case"day":case"d":return t*An;case"hours":case"hour":case"hrs":case"hr":case"h":return t*oo;case"minutes":case"minute":case"mins":case"min":case"m":return t*no;case"seconds":case"second":case"secs":case"sec":case"s":return t*ro;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Lx(r){var e=Math.abs(r);return e>=An?Math.round(r/An)+"d":e>=oo?Math.round(r/oo)+"h":e>=no?Math.round(r/no)+"m":e>=ro?Math.round(r/ro)+"s":r+"ms"}function Dx(r){var e=Math.abs(r);return e>=An?Ts(r,e,An,"day"):e>=oo?Ts(r,e,oo,"hour"):e>=no?Ts(r,e,no,"minute"):e>=ro?Ts(r,e,ro,"second"):r+" ms"}function Ts(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var bh=Le((SB,wh)=>{function Px(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=gh(),t.destroy=u,Object.keys(r).forEach(l=>{t[l]=r[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let f=0;for(let m=0;m<l.length;m++)f=(f<<5)-f+l.charCodeAt(m),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(l){let f,m=null,d,p;function h(...y){if(!h.enabled)return;let g=h,b=Number(new Date),x=b-(f||b);g.diff=x,g.prev=f,g.curr=b,f=b,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let v=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(I,_)=>{if(I==="%%")return"%";v++;let E=t.formatters[_];if(typeof E=="function"){let P=y[v];I=E.call(g,P),y.splice(v,1),v--}return I}),t.formatArgs.call(g,y),(g.log||t.log).apply(g,y)}return h.namespace=l,h.useColors=t.useColors(),h.color=t.selectColor(l),h.extend=n,h.destroy=t.destroy,Object.defineProperty(h,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(d!==t.namespaces&&(d=t.namespaces,p=t.enabled(l)),p),set:y=>{m=y}}),typeof t.init=="function"&&t.init(h),h}function n(l,f){let m=t(this.namespace+(typeof f>"u"?":":f)+l);return m.log=this.log,m}function o(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let f,m=(typeof l=="string"?l:"").split(/[\s,]+/),d=m.length;for(f=0;f<d;f++)m[f]&&(l=m[f].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.slice(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function i(){let l=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let f,m;for(f=0,m=t.skips.length;f<m;f++)if(t.skips[f].test(l))return!1;for(f=0,m=t.names.length;f<m;f++)if(t.names[f].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}wh.exports=Px});var xh=Le((pt,Ns)=>{pt.formatArgs=Ux;pt.save=Fx;pt.load=Vx;pt.useColors=Ox;pt.storage=Hx();pt.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();pt.colors=["#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 Ox(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Ux(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ns.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}pt.log=console.debug||console.log||(()=>{});function Fx(r){try{r?pt.storage.setItem("debug",r):pt.storage.removeItem("debug")}catch{}}function Vx(){let r;try{r=pt.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Hx(){try{return localStorage}catch{}}Ns.exports=bh()(pt);var{formatters:Mx}=Ns.exports;Mx.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var _h=Le((TB,Sh)=>{Sh.exports=Kl;var vh=128,Gx=127,Wx=~Gx,jx=Math.pow(2,31);function Kl(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Kl.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=jx;)e[t++]=r&255|vh,r/=128;for(;r&Wx;)e[t++]=r&255|vh,r>>>=7;return e[t]=r|0,Kl.bytes=t-n+1,e}});var Bh=Le((NB,kh)=>{kh.exports=ql;var Yx=128,Ah=127;function ql(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw ql.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&Ah)<<o:(s&Ah)*Math.pow(2,o),o+=7}while(s>=Yx);return ql.bytes=i-n,t}});var Rh=Le((CB,Ih)=>{var Xx=Math.pow(2,7),Zx=Math.pow(2,14),Jx=Math.pow(2,21),Qx=Math.pow(2,28),e1=Math.pow(2,35),t1=Math.pow(2,42),r1=Math.pow(2,49),n1=Math.pow(2,56),o1=Math.pow(2,63);Ih.exports=function(r){return r<Xx?1:r<Zx?2:r<Jx?3:r<Qx?4:r<e1?5:r<t1?6:r<r1?7:r<n1?8:r<o1?9:10}});var Cs=Le((LB,Th)=>{Th.exports={encode:_h(),decode:Bh(),encodingLength:Rh()}});var Ie=Le((XI,Yh)=>{"use strict";function jh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function V1(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return jh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),jh(new o,t)}}Yh.exports=V1});var Gp=Le(Bo=>{"use strict";var Rv="[object ArrayBuffer]",vr=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Rv}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let i=0;i<n.length;i++)if(n[i]!==o[i])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let s of t)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of t){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},Ju="string",Tv=/^[0-9a-f]+$/i,Nv=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Cv=/^[a-zA-Z0-9-_]+$/,ca=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=vr.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},Lt=class{static toString(e,t=!1){let n=vr.toArrayBuffer(e),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let i=0;i<e.length;i++)o.setUint16(i*2,e.charCodeAt(i),t);return n}},la=class r{static isHex(e){return typeof e===Ju&&Tv.test(e)}static isBase64(e){return typeof e===Ju&&Nv.test(e)}static isBase64Url(e){return typeof e===Ju&&Cv.test(e)}static ToString(e,t="utf8"){let n=vr.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Lt.toString(n,!0);case"utf16":case"utf16be":return Lt.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Lt.fromString(e,!0);case"utf16":case"utf16be":return Lt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=vr.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return ca.fromString(e);case"utf16":case"utf16be":return Lt.fromString(e);case"utf16le":case"usc2":return Lt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return ca.toString(e);case"utf16":case"utf16be":return Lt.toString(e);case"utf16le":case"usc2":return Lt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=vr.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=vr.toUint8Array(e),n="",o=t.length;for(let i=0;i<o;i++){let s=t[i];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let i=t.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(e,t=!1){return Lt.toString(e,t)}static FromUtf16String(e,t=!1){return Lt.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};la.DEFAULT_UTF8_ENCODING="utf8";function Lv(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)t[i]=o[i]}return t}function Dv(...r){let e=r.map(o=>o.byteLength).reduce((o,i)=>o+i),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)t[n++]=i}),t.buffer}function Pv(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Bo.BufferSourceConverter=vr;Bo.Convert=la;Bo.assign=Lv;Bo.combine=Dv;Bo.isEqual=Pv});var Ja=Le((mC,pf)=>{var pC=function(){typeof pf<"u"&&(pf.exports=h);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",u=Math.trunc||function(E){var P=E-E%1;return P==0&&(E<0||E===0&&1/E!=1/0)?-0:P},l=h.prototype,f=(h.fromDate=function(E){return new h(+E)},h.fromInt64BE=v(0,1,2,3,0,4),h.fromInt64LE=v(3,2,1,0,4,0),h.fromString=function(L){var P,V=new h,L=(L+="").replace(/^\s*[+\-]?\d+/,function(C){var C=+C,ne=1970+(C-1970)%400;return V.year=C-ne,ne}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function($,C,ne){return C<0&&(ne*=-1),P=6e4*(60*+C+ +ne),""}).replace(/\.\d+$/,function($){return V.nano=+($+c).substr(1,9),""}).split(/\D+/);if(1<L.length?L[1]--:L[1]=0,V.time=P=Date.UTC.apply(Date,L)-(P||0),isNaN(P))throw new TypeError("Invalid Date");return y(V)},h.fromTimeT=function(E){return b(E,0)},l.year=0,l.time=0,l.nano=0,l.addNano=function(E){return this.nano+=+E||0,this},l.getNano=function(){var E=y(this);return(E.time%1e3*a+ +E.nano+1e9)%1e9},l.getTimeT=function(){var P=y(this),E=Math.floor(P.time/1e3),P=P.year;return P&&(E+=P*t*r/e),E},l.getYear=function(){return this.toDate().getUTCFullYear()+this.year},l.toDate=function(){return g(y(this).time)},l.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},l.toString=function(E){var P=this,V=P.toDate(),L={H:function(){return I(V.getUTCHours())},L:function(){return _(V.getUTCMilliseconds(),3)},M:function(){return I(V.getUTCMinutes())},N:function(){return _(P.getNano(),9)},S:function(){return I(V.getUTCSeconds())},Y:function(){var $=P.getYear();return 999999<$?"+"+$:9999<$?"+"+_($,6):0<=$?_($,4):-999999<=$?"-"+_(-$,6):$},a:function(){return d[V.getUTCDay()]},b:function(){return m[V.getUTCMonth()]},d:function(){return I(V.getUTCDate())},e:function(){return function($){return(9<$?"":" ")+(0|$)}(V.getUTCDate())},m:function(){return I(V.getUTCMonth()+1)}};return function $(C){return C.replace(/%./g,function(ne){var T=ne[1],B=p[T],T=L[T];return B?$(B):T?T():ne})}(E||f)},l.writeInt64BE=x(0,1,2,3,0,4),l.writeInt64LE=x(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),m=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p={"%":"%",F:"%Y-%m-%d",n:`
|
|
3
|
+
`,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return h;function h(E,P,V){var L=this;if(!(L instanceof h))return new h(E,P,V);L.time=+E||0,L.nano=+P||0,L.year=+V||0,y(L)}function y(E){var P,V,L,$=E.year,C=E.time,ne=E.nano,B=((ne<0||a<=ne)&&(ne-=(V=Math.floor(ne/a))*a,C+=V,V=1),$%e);return(C<-i||i<C||B)&&((P=u(C/o))&&($+=P*e,C-=P*o),(L=g(C)).setUTCFullYear(B+L.getUTCFullYear()),L=(C=+L)+(P=u(($-=B)/e))*o,P&&-i<=L&&L<=i&&($-=P*e,C=L),V=1),V&&(E.year=$,E.time=C,E.nano=ne),E}function g(E){var P=new Date(0);return P.setTime(E),P}function b($,L){$=+$||0;var V=u((L=(L|0)*s)/n)+u($/n),L=L%n+$%n,$=u(L/n);return $&&(V+=$,L-=$*n),new h(1e3*L,0,V*e)}function x(E,P,V,L,$,C){return function(B,T){var R=y(this);B=B||new Array(8),S(B,T|=0);var A=Math.floor(R.time/1e3),R=R.year*(t*r/e),G=u(R/s)+u(A/s),R=R%s+A%s,A=Math.floor(R/s);return A&&(G+=A,R-=A*s),ne(B,T+$,G),ne(B,T+C,R),B};function ne(B,T,G){B[T+E]=G>>24&255,B[T+P]=G>>16&255,B[T+V]=G>>8&255,B[T+L]=255&G}}function v(E,P,V,L,$,C){return function(B,T){S(B,T|=0);var G=ne(B,T+$);return b(ne(B,T+C),G)};function ne(B,T){return 16777216*B[T+E]+(B[T+P]<<16|B[T+V]<<8|B[T+L])}}function S(E,P){if(E=E&&E.length,E==null)throw new TypeError("Invalid Buffer");if(E<P+8)throw new RangeError("Out of range")}function I(E){return(9<E?"":"0")+(0|E)}function _(E,P){return(c+(0|E)).substr(-P)}}()});var Eg=Le((J6,Rf)=>{"use strict";var JS=Object.prototype.hasOwnProperty,nt="~";function Ki(){}Object.create&&(Ki.prototype=Object.create(null),new Ki().__proto__||(nt=!1));function QS(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function xg(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new QS(t,n||r,o),s=nt?nt+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function pc(r,e){--r._eventsCount===0?r._events=new Ki:delete r._events[e]}function Xe(){this._events=new Ki,this._eventsCount=0}Xe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)JS.call(t,n)&&e.push(nt?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Xe.prototype.listeners=function(e){var t=nt?nt+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};Xe.prototype.listenerCount=function(e){var t=nt?nt+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Xe.prototype.emit=function(e,t,n,o,i,s){var a=nt?nt+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,i),!0;case 6:return c.fn.call(c.context,t,n,o,i,s),!0}for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];c.fn.apply(c.context,l)}else{var m=c.length,d;for(f=0;f<m;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),u){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c[f].fn.apply(c[f].context,l)}}return!0};Xe.prototype.on=function(e,t,n){return xg(this,e,t,n,!1)};Xe.prototype.once=function(e,t,n){return xg(this,e,t,n,!0)};Xe.prototype.removeListener=function(e,t,n,o){var i=nt?nt+e:e;if(!this._events[i])return this;if(!t)return pc(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&pc(this,i);else{for(var a=0,c=[],u=s.length;a<u;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:pc(this,i)}return this};Xe.prototype.removeAllListeners=function(e){var t;return e?(t=nt?nt+e:e,this._events[t]&&pc(this,t)):(this._events=new Ki,this._eventsCount=0),this};Xe.prototype.off=Xe.prototype.removeListener;Xe.prototype.addListener=Xe.prototype.on;Xe.prefixed=nt;Xe.EventEmitter=Xe;typeof Rf<"u"&&(Rf.exports=Xe)});var Uf=Le((tL,Ng)=>{Ng.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var H0=Le((gs,Gc)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(d){if(!Array.isArray(d)&&!ArrayBuffer.isView(d))return!1;for(var p=0;p<d.length;p++)if(!Number.isInteger(d[p])||d[p]<0||d[p]>255)return!1;return!0}function o(d,p){return(d&65535)*p+(((d>>>16)*p&65535)<<16)}function i(d,p){return d<<p|d>>>32-p}function s(d){return d^=d>>>16,d=o(d,2246822507),d^=d>>>13,d=o(d,3266489909),d^=d>>>16,d}function a(d,p){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var h=[0,0,0,0];return h[3]+=d[3]+p[3],h[2]+=h[3]>>>16,h[3]&=65535,h[2]+=d[2]+p[2],h[1]+=h[2]>>>16,h[2]&=65535,h[1]+=d[1]+p[1],h[0]+=h[1]>>>16,h[1]&=65535,h[0]+=d[0]+p[0],h[0]&=65535,[h[0]<<16|h[1],h[2]<<16|h[3]]}function c(d,p){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var h=[0,0,0,0];return h[3]+=d[3]*p[3],h[2]+=h[3]>>>16,h[3]&=65535,h[2]+=d[2]*p[3],h[1]+=h[2]>>>16,h[2]&=65535,h[2]+=d[3]*p[2],h[1]+=h[2]>>>16,h[2]&=65535,h[1]+=d[1]*p[3],h[0]+=h[1]>>>16,h[1]&=65535,h[1]+=d[2]*p[2],h[0]+=h[1]>>>16,h[1]&=65535,h[1]+=d[3]*p[1],h[0]+=h[1]>>>16,h[1]&=65535,h[0]+=d[0]*p[3]+d[1]*p[2]+d[2]*p[1]+d[3]*p[0],h[0]&=65535,[h[0]<<16|h[1],h[2]<<16|h[3]]}function u(d,p){return p%=64,p===32?[d[1],d[0]]:p<32?[d[0]<<p|d[1]>>>32-p,d[1]<<p|d[0]>>>32-p]:(p-=32,[d[1]<<p|d[0]>>>32-p,d[0]<<p|d[1]>>>32-p])}function l(d,p){return p%=64,p===0?d:p<32?[d[0]<<p|d[1]>>>32-p,d[1]<<p]:[d[1]<<p-32,0]}function f(d,p){return[d[0]^p[0],d[1]^p[1]]}function m(d){return d=f(d,[0,d[0]>>>1]),d=c(d,[4283543511,3981806797]),d=f(d,[0,d[0]>>>1]),d=c(d,[3301882366,444984403]),d=f(d,[0,d[0]>>>1]),d}t.x86.hash32=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var h=d.length%4,y=d.length-h,g=p,b=0,x=3432918353,v=461845907,S=0;S<y;S=S+4)b=d[S]|d[S+1]<<8|d[S+2]<<16|d[S+3]<<24,b=o(b,x),b=i(b,15),b=o(b,v),g^=b,g=i(g,13),g=o(g,5)+3864292196;switch(b=0,h){case 3:b^=d[S+2]<<16;case 2:b^=d[S+1]<<8;case 1:b^=d[S],b=o(b,x),b=i(b,15),b=o(b,v),g^=b}return g^=d.length,g=s(g),g>>>0},t.x86.hash128=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var h=d.length%16,y=d.length-h,g=p,b=p,x=p,v=p,S=0,I=0,_=0,E=0,P=597399067,V=2869860233,L=951274213,$=2716044179,C=0;C<y;C=C+16)S=d[C]|d[C+1]<<8|d[C+2]<<16|d[C+3]<<24,I=d[C+4]|d[C+5]<<8|d[C+6]<<16|d[C+7]<<24,_=d[C+8]|d[C+9]<<8|d[C+10]<<16|d[C+11]<<24,E=d[C+12]|d[C+13]<<8|d[C+14]<<16|d[C+15]<<24,S=o(S,P),S=i(S,15),S=o(S,V),g^=S,g=i(g,19),g+=b,g=o(g,5)+1444728091,I=o(I,V),I=i(I,16),I=o(I,L),b^=I,b=i(b,17),b+=x,b=o(b,5)+197830471,_=o(_,L),_=i(_,17),_=o(_,$),x^=_,x=i(x,15),x+=v,x=o(x,5)+2530024501,E=o(E,$),E=i(E,18),E=o(E,P),v^=E,v=i(v,13),v+=g,v=o(v,5)+850148119;switch(S=0,I=0,_=0,E=0,h){case 15:E^=d[C+14]<<16;case 14:E^=d[C+13]<<8;case 13:E^=d[C+12],E=o(E,$),E=i(E,18),E=o(E,P),v^=E;case 12:_^=d[C+11]<<24;case 11:_^=d[C+10]<<16;case 10:_^=d[C+9]<<8;case 9:_^=d[C+8],_=o(_,L),_=i(_,17),_=o(_,$),x^=_;case 8:I^=d[C+7]<<24;case 7:I^=d[C+6]<<16;case 6:I^=d[C+5]<<8;case 5:I^=d[C+4],I=o(I,V),I=i(I,16),I=o(I,L),b^=I;case 4:S^=d[C+3]<<24;case 3:S^=d[C+2]<<16;case 2:S^=d[C+1]<<8;case 1:S^=d[C],S=o(S,P),S=i(S,15),S=o(S,V),g^=S}return g^=d.length,b^=d.length,x^=d.length,v^=d.length,g+=b,g+=x,g+=v,b+=g,x+=g,v+=g,g=s(g),b=s(b),x=s(x),v=s(v),g+=b,g+=x,g+=v,b+=g,x+=g,v+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)},t.x64.hash128=function(d,p){if(t.inputValidation&&!n(d))return e;p=p||0;for(var h=d.length%16,y=d.length-h,g=[0,p],b=[0,p],x=[0,0],v=[0,0],S=[2277735313,289559509],I=[1291169091,658871167],_=0;_<y;_=_+16)x=[d[_+4]|d[_+5]<<8|d[_+6]<<16|d[_+7]<<24,d[_]|d[_+1]<<8|d[_+2]<<16|d[_+3]<<24],v=[d[_+12]|d[_+13]<<8|d[_+14]<<16|d[_+15]<<24,d[_+8]|d[_+9]<<8|d[_+10]<<16|d[_+11]<<24],x=c(x,S),x=u(x,31),x=c(x,I),g=f(g,x),g=u(g,27),g=a(g,b),g=a(c(g,[0,5]),[0,1390208809]),v=c(v,I),v=u(v,33),v=c(v,S),b=f(b,v),b=u(b,31),b=a(b,g),b=a(c(b,[0,5]),[0,944331445]);switch(x=[0,0],v=[0,0],h){case 15:v=f(v,l([0,d[_+14]],48));case 14:v=f(v,l([0,d[_+13]],40));case 13:v=f(v,l([0,d[_+12]],32));case 12:v=f(v,l([0,d[_+11]],24));case 11:v=f(v,l([0,d[_+10]],16));case 10:v=f(v,l([0,d[_+9]],8));case 9:v=f(v,[0,d[_+8]]),v=c(v,I),v=u(v,33),v=c(v,S),b=f(b,v);case 8:x=f(x,l([0,d[_+7]],56));case 7:x=f(x,l([0,d[_+6]],48));case 6:x=f(x,l([0,d[_+5]],40));case 5:x=f(x,l([0,d[_+4]],32));case 4:x=f(x,l([0,d[_+3]],24));case 3:x=f(x,l([0,d[_+2]],16));case 2:x=f(x,l([0,d[_+1]],8));case 1:x=f(x,[0,d[_]]),x=c(x,S),x=u(x,31),x=c(x,I),g=f(g,x)}return g=f(g,[0,d.length]),b=f(b,[0,d.length]),g=a(g,b),b=a(b,g),g=m(g),b=m(b),g=a(g,b),b=a(b,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof gs<"u"?(typeof Gc<"u"&&Gc.exports&&(gs=Gc.exports=t),gs.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(gs)});var z0=Le((S5,M0)=>{M0.exports=H0()});var jc=Le((T5,K0)=>{"use strict";K0.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let o=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):o=!0,this._setInternalPos(n,e,t,o),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,o=t;for(;n<this.length;){let i=this.get(n);o=e(o,i,n),n++}return o}find(e){let t=0,n,o;for(;t<this.length&&!n;)o=this.get(t),n=e(o),t++;return n?o:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let o=this._bitArrays[n],i=e-n*7;if(!((o&1<<i)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(I_,0),c=~(4294967295<<i+1),u=$0(o&c);return a+u-1}_bytePosFor(e,t){let n=Math.floor(e/7),o=n+1;for(;!t&&this._bitArrays.length<o;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,o){let i=this._data,s=[t,n];if(o)this._sortData(),i[e]=s;else{if(i.length)if(i[i.length-1][0]>=t)i.push(s);else if(i[0][0]<=t)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(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(R_),this._changedData=!1}bitField(){let e=[],t=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,t),u=~(255<<c),l=i&u;o|=l<<8-t,i=i>>>c,n-=c,t-=c,(!t||!n&&!s.length)&&(e.push(o),o=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(T_)}};function I_(r,e){return r+$0(e)}function $0(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function R_(r,e){return r[0]-e[0]}function T_(r){return r[1]}});var Rw=Le((R7,Iw)=>{"use strict";Iw.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var Pw=Le((Lw,Dw)=>{"use strict";var el=Rw(),{hasOwnProperty:Nw}=Object.prototype,{propertyIsEnumerable:dA}=Object,Xo=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),hA=Lw,Tw={concatArrays:!1,ignoreUndefined:!1},tl=r=>{let e=[];for(let t in r)Nw.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)dA.call(r,n)&&e.push(n)}return e};function Zo(r){return Array.isArray(r)?pA(r):el(r)?mA(r):r}function pA(r){let e=r.slice(0,0);return tl(r).forEach(t=>{Xo(e,t,Zo(r[t]))}),e}function mA(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return tl(r).forEach(t=>{Xo(e,t,Zo(r[t]))}),e}var Cw=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Xo(r,o,Rd(r[o],e[o],n)):Xo(r,o,Zo(e[o])))}),r),yA=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(i=>{let s=[];for(let a=0;a<i.length;a++)Nw.call(i,a)&&(s.push(String(a)),i===r?Xo(n,o++,i[a]):Xo(n,o++,Zo(i[a])));n=Cw(n,i,tl(i).filter(a=>!s.includes(a)),t)}),n};function Rd(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?yA(r,e,t):!el(e)||!el(r)?Zo(e):Cw(r,e,tl(e),t)}Dw.exports=function(...r){let e=Rd(Zo(Tw),this!==hA&&this||{},Tw),t={_:{}};for(let n of r)if(n!==void 0){if(!el(n))throw new TypeError("`"+n+"` is not an Option Object");t=Rd(t,{_:n},e)}return t._}});var hb=Le((a9,db)=>{"use strict";db.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 Wk={};xe(Wk,{createVerifiedFetch:()=>Kd,verifiedFetch:()=>_l});function Sn(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}function Mb(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Yn=Mb;function zb(r){return r[Symbol.asyncIterator]!=null}function eh(r){return r?.then!=null}function $b(r,e){if(zb(r))return async function*(){for await(let a of r){let c=e(a);eh(c)&&await c,yield a}}();let t=Yn(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();if(typeof e(n)?.then=="function")return async function*(){yield n;for await(let a of t){let c=e(a);eh(c)&&await c,yield a}}();let s=e;return function*(){yield n;for(let a of t)s(a),yield a}()}var kl=$b;var Dl={};xe(Dl,{base32:()=>Fe,base32hex:()=>ex,base32hexpad:()=>rx,base32hexpadupper:()=>nx,base32hexupper:()=>tx,base32pad:()=>Jb,base32padupper:()=>Qb,base32upper:()=>oh,base32z:()=>ox});var Xn={};xe(Xn,{coerce:()=>_t,empty:()=>th,equals:()=>Bl,fromHex:()=>qb,fromString:()=>Il,isBinary:()=>Gb,toHex:()=>Kb,toString:()=>Rl});var th=new Uint8Array(0);function Kb(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function qb(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):th}function Bl(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function _t(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Gb(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function Il(r){return new TextEncoder().encode(r)}function Rl(r){return new TextDecoder().decode(r)}function Wb(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var h=0,y=0,g=0,b=p.length;g!==b&&p[g]===0;)g++,h++;for(var x=(b-g)*l+1>>>0,v=new Uint8Array(x);g!==b;){for(var S=p[g],I=0,_=x-1;(S!==0||I<y)&&_!==-1;_--,I++)S+=256*v[_]>>>0,v[_]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=I,g++}for(var E=x-y;E!==x&&v[E]===0;)E++;for(var P=c.repeat(h);E<x;++E)P+=r.charAt(v[E]);return P}function m(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var h=0;if(p[h]!==" "){for(var y=0,g=0;p[h]===c;)y++,h++;for(var b=(p.length-h)*u+1>>>0,x=new Uint8Array(b);p[h];){var v=t[p.charCodeAt(h)];if(v===255)return;for(var S=0,I=b-1;(v!==0||S<g)&&I!==-1;I--,S++)v+=a*x[I]>>>0,x[I]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");g=S,h++}if(p[h]!==" "){for(var _=b-g;_!==b&&x[_]===0;)_++;for(var E=new Uint8Array(y+(b-_)),P=y;_!==b;)E[P++]=x[_++];return E}}}function d(p){var h=m(p);if(h)return h;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:m,decode:d}}var jb=Wb,Yb=jb,rh=Yb;var Tl=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Nl=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return nh(this,e)}},Cl=class{decoders;constructor(e){this.decoders=e}or(e){return nh(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function nh(r,e){return new Cl({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ll=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Tl(e,t,n),this.decoder=new Nl(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Zn({name:r,prefix:e,encode:t,decode:n}){return new Ll(r,e,t,n)}function zr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=rh(t,r);return Zn({prefix:e,name:r,encode:n,decode:i=>_t(o(i))})}function Xb(r,e,t,n){let o={};for(let l=0;l<e.length;++l)o[e[l]]=l;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),a=0,c=0,u=0;for(let l=0;l<i;++l){let f=o[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function Zb(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;i.length*t&7;)i+="=";return i}function Ee({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Zn({prefix:e,name:r,encode(o){return Zb(o,n,t)},decode(o){return Xb(o,n,t,r)}})}var Fe=Ee({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),oh=Ee({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Jb=Ee({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Qb=Ee({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ex=Ee({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),tx=Ee({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rx=Ee({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),nx=Ee({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ox=Ee({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Pl={};xe(Pl,{base58btc:()=>Ae,base58flickr:()=>ix});var Ae=zr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ix=zr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var sx=ah,ih=128,ax=127,cx=~ax,lx=Math.pow(2,31);function ah(r,e,t){e=e||[],t=t||0;for(var n=t;r>=lx;)e[t++]=r&255|ih,r/=128;for(;r&cx;)e[t++]=r&255|ih,r>>>=7;return e[t]=r|0,ah.bytes=t-n+1,e}var ux=Ol,fx=128,sh=127;function Ol(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Ol.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&sh)<<o:(s&sh)*Math.pow(2,o),o+=7}while(s>=fx);return Ol.bytes=i-n,t}var dx=Math.pow(2,7),hx=Math.pow(2,14),px=Math.pow(2,21),mx=Math.pow(2,28),yx=Math.pow(2,35),gx=Math.pow(2,42),wx=Math.pow(2,49),bx=Math.pow(2,56),xx=Math.pow(2,63),Ex=function(r){return r<dx?1:r<hx?2:r<px?3:r<mx?4:r<yx?5:r<gx?6:r<wx?7:r<bx?8:r<xx?9:10},vx={encode:sx,decode:ux,encodingLength:Ex},Sx=vx,ii=Sx;function si(r,e=0){return[ii.decode(r,e),ii.decode.bytes]}function Jn(r,e,t=0){return ii.encode(r,e,t),e}function Qn(r){return ii.encodingLength(r)}function Jt(r,e){let t=e.byteLength,n=Qn(r),o=n+Qn(t),i=new Uint8Array(o+t);return Jn(r,i,0),Jn(t,i,n),i.set(e,o),new eo(r,t,e,i)}function Je(r){let e=_t(r),[t,n]=si(e),[o,i]=si(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new eo(t,o,s,e)}function ch(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Bl(r.bytes,t.bytes)}}var eo=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function lh(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ax(t,Ul(r),e??Ae.encoder);default:return kx(t,Ul(r),e??Fe.encoder)}}var uh=new WeakMap;function Ul(r){let e=uh.get(r);if(e==null){let t=new Map;return uh.set(r,t),t}return e}var O=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==ai)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Bx)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Jt(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&ch(e.multihash,n.multihash)}toString(e){return lh(this,e)}toJSON(){return{"/":lh(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??fh(n,o,i.bytes))}else if(t[Ix]===!0){let{version:n,multihash:o,code:i}=t,s=Je(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ai)throw new Error(`Version 0 CID must use dag-pb (code: ${ai}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=fh(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ai,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=_t(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new eo(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,m]=si(e.subarray(t));return t+=m,f},o=n(),i=ai;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),u=t+c,l=u-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,o]=_x(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ul(i).set(n,e),i}};function _x(r,e){switch(r[0]){case"Q":{let t=e??Ae;return[Ae.prefix,t.decode(`${Ae.prefix}${r}`)]}case Ae.prefix:{let t=e??Ae;return[Ae.prefix,t.decode(r)]}case Fe.prefix:{let t=e??Fe;return[Fe.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ax(r,e,t){let{prefix:n}=t;if(n!==Ae.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function kx(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var ai=112,Bx=18;function fh(r,e,t){let n=Qn(r),o=n+Qn(e),i=new Uint8Array(o+t.byteLength);return Jn(r,i,0),Jn(e,i,n),i.set(t,o),i}var Ix=Symbol.for("@ipld/js-cid/CID");var ci=Symbol.for("@libp2p/content-routing");var Fl=Symbol.for("@libp2p/peer-id");function dh(r){return r!=null&&!!r[Fl]}var li=Symbol.for("@libp2p/peer-routing");var Qt=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},N=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var to=(r,...e)=>{try{[...e]}catch{}};var Rs=class extends EventTarget{#e=new Map;constructor(){super(),to(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Rx(e,t))}},Vl=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Rx=globalThis.CustomEvent??Vl;function hh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function $r(...r){let e=[];for(let t of r)hh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Kr(...r){let e=[];for(let t of r)hh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var zl={};xe(zl,{sha256:()=>ce,sha512:()=>Ml});function _n({name:r,code:e,encode:t}){return new Hl(r,e,t)}var Hl=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Jt(this.code,t):t.then(n=>Jt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function mh(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ce=_n({name:"sha2-256",code:18,encode:mh("SHA-256")}),Ml=_n({name:"sha2-512",code:19,encode:mh("SHA-512")});var mt=J(xh(),1);var $l={};xe($l,{base64:()=>er,base64pad:()=>zx,base64url:()=>$x,base64urlpad:()=>Kx});var er=Ee({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),zx=Ee({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$x=Ee({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Kx=Ee({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});mt.default.formatters.b=r=>r==null?"undefined":Ae.baseEncode(r);mt.default.formatters.t=r=>r==null?"undefined":Fe.baseEncode(r);mt.default.formatters.m=r=>r==null?"undefined":er.baseEncode(r);mt.default.formatters.p=r=>r==null?"undefined":r.toString();mt.default.formatters.c=r=>r==null?"undefined":r.toString();mt.default.formatters.k=r=>r==null?"undefined":r.toString();mt.default.formatters.a=r=>r==null?"undefined":r.toString();function qx(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Eh(){return{forComponent(r){return Q(r)}}}function Q(r){let e=qx(`${r}:trace`);return mt.default.enabled(`${r}:trace`)&&mt.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,mt.default)(`${r}:trace`)),Object.assign((0,mt.default)(r),{error:(0,mt.default)(`${r}:error`),trace:e})}function ie(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function kt(r=0){return new Uint8Array(r)}function it(r=0){return new Uint8Array(r)}var i1=Math.pow(2,7),s1=Math.pow(2,14),a1=Math.pow(2,21),Gl=Math.pow(2,28),Wl=Math.pow(2,35),jl=Math.pow(2,42),Yl=Math.pow(2,49),le=128,Ke=127;function st(r){if(r<i1)return 1;if(r<s1)return 2;if(r<a1)return 3;if(r<Gl)return 4;if(r<Wl)return 5;if(r<jl)return 6;if(r<Yl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Xl(r,e,t=0){switch(st(r)){case 8:e[t++]=r&255|le,r/=128;case 7:e[t++]=r&255|le,r/=128;case 6:e[t++]=r&255|le,r/=128;case 5:e[t++]=r&255|le,r/=128;case 4:e[t++]=r&255|le,r>>>=7;case 3:e[t++]=r&255|le,r>>>=7;case 2:e[t++]=r&255|le,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function c1(r,e,t=0){switch(st(r)){case 8:e.set(t++,r&255|le),r/=128;case 7:e.set(t++,r&255|le),r/=128;case 6:e.set(t++,r&255|le),r/=128;case 5:e.set(t++,r&255|le),r/=128;case 4:e.set(t++,r&255|le),r>>>=7;case 3:e.set(t++,r&255|le),r>>>=7;case 2:e.set(t++,r&255|le),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Zl(r,e){let t=r[e],n=0;if(n+=t&Ke,t<le||(t=r[e+1],n+=(t&Ke)<<7,t<le)||(t=r[e+2],n+=(t&Ke)<<14,t<le)||(t=r[e+3],n+=(t&Ke)<<21,t<le)||(t=r[e+4],n+=(t&Ke)*Gl,t<le)||(t=r[e+5],n+=(t&Ke)*Wl,t<le)||(t=r[e+6],n+=(t&Ke)*jl,t<le)||(t=r[e+7],n+=(t&Ke)*Yl,t<le))return n;throw new RangeError("Could not decode varint")}function l1(r,e){let t=r.get(e),n=0;if(n+=t&Ke,t<le||(t=r.get(e+1),n+=(t&Ke)<<7,t<le)||(t=r.get(e+2),n+=(t&Ke)<<14,t<le)||(t=r.get(e+3),n+=(t&Ke)<<21,t<le)||(t=r.get(e+4),n+=(t&Ke)*Gl,t<le)||(t=r.get(e+5),n+=(t&Ke)*Wl,t<le)||(t=r.get(e+6),n+=(t&Ke)*jl,t<le)||(t=r.get(e+7),n+=(t&Ke)*Yl,t<le))return n;throw new RangeError("Could not decode varint")}function io(r,e,t=0){return e==null&&(e=it(st(r))),e instanceof Uint8Array?Xl(r,e,t):c1(r,e,t)}function kn(r,e=0){return r instanceof Uint8Array?Zl(r,e):l1(r,e)}var Jl=new Float32Array([-0]),qr=new Uint8Array(Jl.buffer);function Ch(r,e,t){Jl[0]=r,e[t]=qr[0],e[t+1]=qr[1],e[t+2]=qr[2],e[t+3]=qr[3]}function Lh(r,e){return qr[0]=r[e],qr[1]=r[e+1],qr[2]=r[e+2],qr[3]=r[e+3],Jl[0]}var Ql=new Float64Array([-0]),qe=new Uint8Array(Ql.buffer);function Dh(r,e,t){Ql[0]=r,e[t]=qe[0],e[t+1]=qe[1],e[t+2]=qe[2],e[t+3]=qe[3],e[t+4]=qe[4],e[t+5]=qe[5],e[t+6]=qe[6],e[t+7]=qe[7]}function Ph(r,e){return qe[0]=r[e],qe[1]=r[e+1],qe[2]=r[e+2],qe[3]=r[e+3],qe[4]=r[e+4],qe[5]=r[e+5],qe[6]=r[e+6],qe[7]=r[e+7],Ql[0]}var u1=BigInt(Number.MAX_SAFE_INTEGER),f1=BigInt(Number.MIN_SAFE_INTEGER),yt=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Bn;if(e<u1&&e>f1)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Oh&&(o=0n,++n>Oh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Bn;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Bn}},Bn=new yt(0,0);Bn.toBigInt=function(){return 0n};Bn.zzEncode=Bn.zzDecode=function(){return this};Bn.length=function(){return 1};var Oh=4294967296n;function Uh(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Fh(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function eu(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Ut(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ls(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var tu=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ut(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ut(this,4);return Ls(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ut(this,4);return Ls(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ut(this,4);let e=Lh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ut(this,4);let e=Ph(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Ut(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Fh(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ut(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ut(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new yt(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ut(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ut(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ut(this,8);let e=Ls(this.buf,this.pos+=4),t=Ls(this.buf,this.pos+=4);return new yt(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Zl(this.buf,this.pos);return this.pos+=st(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ru(r){return new tu(r instanceof Uint8Array?r:r.subarray())}function Bt(r,e,t){let n=ru(r);return e.decode(n,void 0,t)}var nu={};xe(nu,{base10:()=>d1});var d1=zr({prefix:"9",name:"base10",alphabet:"0123456789"});var ou={};xe(ou,{base16:()=>h1,base16upper:()=>p1});var h1=Ee({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),p1=Ee({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var iu={};xe(iu,{base2:()=>m1});var m1=Ee({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var su={};xe(su,{base256emoji:()=>x1});var Hh=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}"),y1=Hh.reduce((r,e,t)=>(r[t]=e,r),[]),g1=Hh.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function w1(r){return r.reduce((e,t)=>(e+=y1[t],e),"")}function b1(r){let e=[];for(let t of r){let n=g1[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var x1=Zn({prefix:"\u{1F680}",name:"base256emoji",encode:w1,decode:b1});var au={};xe(au,{base36:()=>Gr,base36upper:()=>E1});var Gr=zr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),E1=zr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var cu={};xe(cu,{base8:()=>v1});var v1=Ee({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var lu={};xe(lu,{identity:()=>S1});var S1=Zn({prefix:"\0",name:"identity",encode:r=>Rl(r),decode:r=>Il(r)});var JB=new TextEncoder,_1=new TextDecoder;var Wr=512;function Mh(r){return JSON.parse(_1.decode(r))}var It={};xe(It,{code:()=>ge,decode:()=>B1,encode:()=>k1,name:()=>A1});var A1="raw",ge=85;function k1(r){return _t(r)}function B1(r){return _t(r)}var uu={};xe(uu,{identity:()=>Ge});var zh=0,I1="identity",$h=_t;function R1(r){return Jt(zh,$h(r))}var Ge={code:zh,name:I1,encode:$h,digest:R1};var jr={...lu,...iu,...cu,...nu,...ou,...Dl,...au,...Pl,...$l,...su},uI={...zl,...uu};function qh(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Kh=qh("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),fu=qh("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=it(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),T1={utf8:Kh,"utf-8":Kh,hex:jr.base16,latin1:fu,ascii:fu,binary:fu,...jr},Ps=T1;function U(r,e="utf8"){let t=Ps[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function du(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return it(s);o+s>e&&(n=it(e),o=0);let a=n.subarray(o,o+=s);return o&7&&(o=(o|7)+1),a}}var In=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function hu(){}var mu=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},N1=du();function C1(r){return globalThis.Buffer!=null?it(r):N1(r)}var fi=class{len;head;tail;states;constructor(){this.len=0,this.head=new In(hu,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new In(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new yu((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Os,10,yt.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=yt.fromBigInt(e);return this._push(Os,t.length(),t)}uint64Number(e){return this._push(Xl,st(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=yt.fromBigInt(e).zzEncode();return this._push(Os,t.length(),t)}sint64Number(e){let t=yt.fromNumber(e).zzEncode();return this._push(Os,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(pu,1,e?1:0)}fixed32(e){return this._push(ui,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=yt.fromBigInt(e);return this._push(ui,4,t.lo)._push(ui,4,t.hi)}fixed64Number(e){let t=yt.fromNumber(e);return this._push(ui,4,t.lo)._push(ui,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Ch,4,e)}double(e){return this._push(Dh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(pu,1,0):this.uint32(t)._push(D1,t,e)}string(e){let t=Uh(e);return t!==0?this.uint32(t)._push(eu,t,e):this._push(pu,1,0)}fork(){return this.states=new mu(this),this.head=this.tail=new In(hu,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 In(hu,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=C1(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function pu(r,e,t){e[t]=r&255}function L1(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var yu=class extends In{next;constructor(e,t){super(L1,e,t),this.next=void 0}};function Os(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function ui(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function D1(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(fi.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(P1,e,r),this},fi.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(O1,e,r),this});function P1(r,e,t){e.set(r,t)}function O1(r,e,t){r.length<40?eu(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(U(r),t)}function gu(){return new fi}function Rt(r,e){let t=gu();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var so;(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"})(so||(so={}));function Us(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Rn(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,s){let a=e(i);s.int32(a)},n=function(i){let s=i.int32();return e(s)};return Us("enum",so.VARINT,t,n)}function Tt(r,e){return Us("message",so.LENGTH_DELIMITED,r,e)}function U1(r){return r[Symbol.asyncIterator]!=null}function F1(r){if(U1(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ft=F1;function ue(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=it(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Wh=Symbol.for("@achingbrain/uint8arraylist");function Gh(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function tr(r){return!!r?.[Wh]}var Vt=class r{bufs;length;[Wh]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(tr(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(tr(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Gh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Gh(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(tr(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return ue(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:ue(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(u){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(l){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!tr(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let 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,u=n.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let m=u;m>=0;m--){let d=this.get(f+m);if(n[m]!==d){l=Math.max(1,m-a[d]);break}}if(l===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=kt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=kt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=kt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=kt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=kt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=kt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=kt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=kt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ie(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,i)=>o+i.byteLength,0)),n.length=t,n}};function H1(r){return r[Symbol.asyncIterator]!=null}function M1(r,e){if(H1(r))return async function*(){for await(let a of r)yield e(a)}();let t=Yn(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let a of t)yield e(a)}();let s=e;return function*(){yield i;for(let a of t)yield s(a)}()}var We=M1;function ve(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Fs=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},ao=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Fs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Fs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var wu=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Nt(r={}){return z1(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function z1(r,e){e=e??{};let t=e.onEnd,n=new ao,o,i,s,a=ve(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{i=b=>{i=null,n.push(b);try{y(r(n))}catch(x){g(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ve()})}},u=y=>i!=null?i(y):(n.push(y),o),l=y=>(n=new ao,i!=null?i({error:y}):(n.push({error:y}),o)),f=y=>{if(s)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:y})},m=y=>s?o:(s=!0,y!=null?l(y):u({done:!0})),d=()=>(n=new ao,m(),{done:!0}),p=y=>(m(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:p,push:f,end:m,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,x;g!=null&&(b=new Promise((v,S)=>{x=()=>{S(new wu)},g.addEventListener("abort",x)}));try{await Promise.race([a.promise,b])}finally{x!=null&&g!=null&&g?.removeEventListener("abort",x)}}},t==null)return o;let h=o;return o={[Symbol.asyncIterator](){return this},next(){return h.next()},throw(y){return h.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return h.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(y){return h.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return h.readableLength},onEmpty:y=>h.onEmpty(y)},o}function $1(r){return r[Symbol.asyncIterator]!=null}function K1(...r){let e=[];for(let t of r)$1(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Nt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var mr=K1;function at(r,...e){if(r==null)throw new Error("Empty pipeline");if(bu(r)){let n=r;r=()=>n.source}else if(Zh(r)||Xh(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&bu(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)bu(t[n])&&(t[n]=G1(t[n]));return q1(...t)}var q1=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Xh=r=>r?.[Symbol.asyncIterator]!=null,Zh=r=>r?.[Symbol.iterator]!=null,bu=r=>r==null?!1:r.sink!=null&&r.source!=null,G1=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Nt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Xh(i))o=async function*(){yield*i,n.end()};else if(Zh(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return mr(n,o())}return r.source};function W1(r){return r[Symbol.asyncIterator]!=null}function j1(r,e){return W1(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var Vs=j1;var F=class extends Event{constructor(e,t){super(e),this.detail=t}};function W(r,e="utf8"){let t=Ps[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Hs=class{url;#e=0;#t=0;#r=0;#s=0;constructor(e){this.url=e instanceof URL?e:new URL(e)}async getRawBlock(e,t){let n=this.url;if(n.pathname=`/ipfs/${e.toString()}`,n.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);try{this.#e++;let o=await fetch(n.toString(),{signal:t,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"});if(!o.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#s++,new Uint8Array(await o.arrayBuffer())}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#s/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}};var Ms=class{gateways;log;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.gateways=(t.gateways??Jh).map(n=>new Hs(n))}async retrieve(e,t={}){let n=this.gateways.sort((i,s)=>s.reliability()-i.reliability()),o=[];for(let i of n){this.log("getting block for %c from %s",e,i.url);try{let s=await i.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,i.url);try{await t.validateFn?.(s)}catch(a){throw this.log.error("failed to validate block for %c from %s",e,i.url,a),i.incrementInvalidBlocks(),new Error(`unable to validate block for CID ${e} from gateway ${i.url}`)}return s}catch(s){if(this.log.error("failed to get block for %c from %s",e,i.url,s),s instanceof Error?o.push(s):o.push(new Error(`unable to fetch raw block for CID ${e} from gateway ${i.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,i.url);break}}}throw new AggregateError(o,`unable to fetch raw block for CID ${e} from any gateway`)}};var Jh=["https://trustless-gateway.link","https://cloudflare-ipfs.com","https://4everland.io"];function di(r={}){return e=>new Ms(e,r)}var Y1=Symbol.for("nodejs.util.inspect.custom"),Qh=Object.values(jr).map(r=>r.decoder).reduce((r,e)=>r.or(e),jr.identity.decoder),ep=114,xu=36,Eu=37,hi=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Fl]=!0;toString(){return this.string==null&&(this.string=Ae.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return O.createV1(ep,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ie(this.multihash.bytes,e);if(typeof e=="string")return Qe(e).equals(this);if(e?.multihash?.bytes!=null)return ie(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Y1](){return`PeerId(${this.toString()})`}},co=class extends hi{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},lo=class extends hi{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},uo=class extends hi{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function Qe(r,e){if(e=e??Qh,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Je(Ae.decode(`z${r}`));return r.startsWith("12D")?new lo({multihash:t}):r.startsWith("16U")?new uo({multihash:t}):new co({multihash:t})}return pi(Qh.decode(r))}function pi(r){try{let e=Je(r);if(e.code===Ge.code){if(e.digest.length===xu)return new lo({multihash:e});if(e.digest.length===Eu)return new uo({multihash:e})}if(e.code===ce.code)return new co({multihash:e})}catch{return X1(O.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function X1(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==ep)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===ce.code)return new co({multihash:r.multihash});if(e.code===Ge.code){if(e.digest.length===xu)return new lo({multihash:r.multihash});if(e.digest.length===Eu)return new uo({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function tp(r,e){return r.length===xu?new lo({multihash:Jt(Ge.code,r),privateKey:e}):r.length===Eu?new uo({multihash:Jt(Ge.code,r),privateKey:e}):new co({multihash:await ce.digest(r),publicKey:r,privateKey:e})}var zs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let m=Number.parseInt(f,e);if(!Number.isNaN(m))return m});if(l===void 0)break;if(i*=e,i+=l,i>u||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var rp=45,Z1=15,fo=new zs;function vu(r){if(!(r.length>Z1))return fo.new(r).parseWith(()=>fo.readIPv4Addr())}function Su(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>rp))return fo.new(r).parseWith(()=>fo.readIPv6Addr())}function $s(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>rp))return fo.new(r).parseWith(()=>fo.readIPAddr())}var MR=parseInt("0xFFFF",16),zR=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ip(r){return!!vu(r)}function sp(r){return!!Su(r)}function Ks(r){return!!$s(r)}var ap=ip,rE=sp,_u=function(r){let e=0;if(r=r.toString().trim(),ap(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(rE(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=ap(t[n]),s;i&&(s=_u(t[n]),t[n]=W(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,W(s.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let i=parseInt(t[n],16);o[e++]=i>>8&255,o[e++]=i&255}return o}throw new Error("invalid ip address")},cp=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let i=0;i<t;i++)o.push(r[e+i]);return o.join(".")}if(t===16){let o=[];for(let i=0;i<t;i+=2)o.push(n.getUint16(e+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var ho={},Au={},oE=[[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"],[777,-1,"memory"]];oE.forEach(r=>{let e=iE(...r);Au[e.code]=e,ho[e.name]=e});function iE(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function de(r){if(typeof r=="number"){if(Au[r]!=null)return Au[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(ho[r]!=null)return ho[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var AT=de("ip4"),kT=de("ip6"),BT=de("ipcidr");function Bu(r,e){switch(de(r).code){case 4:case 41:return aE(e);case 42:return fp(e);case 6:case 273:case 33:case 132:return hp(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return fp(e);case 421:return fE(e);case 444:return dp(e);case 445:return dp(e);case 466:return uE(e);default:return W(e,"base16")}}function Iu(r,e){switch(de(r).code){case 4:return lp(e);case 41:return lp(e);case 42:return up(e);case 6:case 273:case 33:case 132:return Ru(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return up(e);case 421:return cE(e);case 444:return dE(e);case 445:return hE(e);case 466:return lE(e);default:return U(e,"base16")}}var ku=Object.values(jr).map(r=>r.decoder),sE=function(){let r=ku[0].or(ku[1]);return ku.slice(2).forEach(e=>r=r.or(e)),r}();function lp(r){if(!Ks(r))throw new Error("invalid ip address");return _u(r)}function aE(r){let e=cp(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Ks(e))throw new Error("invalid ip address");return e}function Ru(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function hp(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function up(r){let e=U(r),t=Uint8Array.from(io(e.length));return ue([t,e],t.length+e.length)}function fp(r){let e=kn(r);if(r=r.slice(st(e)),r.length!==e)throw new Error("inconsistent lengths");return W(r)}function cE(r){let e;r[0]==="Q"||r[0]==="1"?e=Je(Ae.decode(`z${r}`)).bytes:e=O.parse(r).multihash.bytes;let t=Uint8Array.from(io(e.length));return ue([t,e],t.length+e.length)}function lE(r){let e=sE.decode(r),t=Uint8Array.from(io(e.length));return ue([t,e],t.length+e.length)}function uE(r){let e=kn(r),t=r.slice(st(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+W(t,"base64url")}function fE(r){let e=kn(r),t=r.slice(st(e));if(t.length!==e)throw new Error("inconsistent lengths");return W(t,"base58btc")}function dE(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=Fe.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ru(n);return ue([t,o],t.length+o.length)}function hE(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=Fe.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ru(n);return ue([t,o],t.length+o.length)}function dp(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=W(e,"base32"),o=hp(t);return`${n}:${o}`}function pp(r){r=Tu(r);let e=[],t=[],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=de(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw yp("invalid address: "+r);if(a.path===!0){n=Tu(o.slice(i).join("/")),e.push([a.code,Iu(a.code,n)]),t.push([a.code,n]);break}let c=Iu(a.code,o[i]);e.push([a.code,c]),t.push([a.code,Bu(a.code,c)])}return{string:mp(t),bytes:Cu(e),tuples:e,stringTuples:t,path:n}}function Nu(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=kn(r,o),s=st(i),a=de(i),c=pE(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let u=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw yp("Invalid address Uint8Array: "+W(r,"base16"));e.push([i,u]);let l=Bu(i,u);if(t.push([i,l]),a.path===!0){n=l;break}}return{bytes:Uint8Array.from(r),string:mp(t),tuples:e,stringTuples:t,path:n}}function mp(r){let e=[];return r.map(t=>{let n=de(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Tu(e.join("/"))}function Cu(r){return ue(r.map(e=>{let t=de(e[0]),n=Uint8Array.from(io(t.code));return e.length>1&&e[1]!=null&&(n=ue([n,e[1]])),n}))}function pE(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=kn(e instanceof Uint8Array?e:Uint8Array.from(e));return t+st(t)}}function Tu(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function yp(r){return new Error("Error parsing address: "+r)}var mE=Symbol.for("nodejs.util.inspect.custom"),Lu=Symbol.for("@multiformats/js-multiaddr/multiaddr"),yE=[de("dns").code,de("dns4").code,de("dns6").code,de("dnsaddr").code],qs=class r{bytes;#e;#t;#r;#s;[Lu]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Nu(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=pp(e)}else if(wp(e))t=Nu(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#s=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,i="",s=de("tcp"),a=de("udp"),c=de("ip4"),u=de("ip6"),l=de("dns6"),f=de("ip6zone");for(let[d,p]of this.stringTuples())d===f.code&&(i=`%${p??""}`),yE.includes(d)&&(t=s.name,o=443,n=`${p??""}${i}`,e=d===l.code?6:4),(d===s.code||d===a.code)&&(t=de(d).name,o=parseInt(p??"")),(d===c.code||d===u.code)&&(t=de(d).name,n=`${p??""}${i}`,e=d===u.code?6:4);if(e==null||t==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:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},de(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>de(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(Cu(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===ho.p2p.code&&e.push([n,o]),n===ho["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?W(Ae.decode(`z${n}`),"base58btc"):W(O.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#s}equals(e){return ie(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=gp.get(t.name);if(n==null)throw new N(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(i=>mi(i))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[mE](){return`Multiaddr(${this.#e})`}};var gp=new Map;function wp(r){return!!r?.[Lu]}function mi(r){return new qs(r)}async function*Gs(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var Xu={};xe(Xu,{Ed25519PrivateKey:()=>Ln,Ed25519PublicKey:()=>wi,generateKeyPair:()=>kv,generateKeyPairFromSeed:()=>qp,unmarshalEd25519PrivateKey:()=>_v,unmarshalEd25519PublicKey:()=>Av});function Ct(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function po(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function gE(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function mo(r,...e){if(!gE(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function Ws(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");po(r.outputLen),po(r.blockLen)}function yo(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function bp(r,e){mo(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var js=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var wo=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Ht=(r,e)=>r<<32-e|r>>>e;var s8=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var wE=async()=>{};async function xp(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-n;i>=0&&i<e||(await wE(),n+=i)}}function Du(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Yr(r){return typeof r=="string"&&(r=Du(r)),mo(r),r}function Ys(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];mo(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}var go=class{clone(){return this._cloneInto()}},bE={}.toString;function Ep(r,e){if(e!==void 0&&bE.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Xs(r){let e=n=>r().update(Yr(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function bo(r=32){if(js&&typeof js.getRandomValues=="function")return js.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function xE(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(t>>o&i),a=Number(t&i),c=n?4:0,u=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+u,a,n)}var vp=(r,e,t)=>r&e^~r&t,Sp=(r,e,t)=>r&e^r&t^e&t,xo=class extends go{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=wo(this.buffer)}update(e){yo(this);let{view:t,buffer:n,blockLen:o}=this;e=Yr(e);let i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=wo(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){yo(this),bp(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[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++)t[f]=0;xE(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=wo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return e.length=o,e.pos=a,e.finished=i,e.destroyed=s,o%t&&e.buffer.set(n),e}};var Zs=BigInt(4294967295),Pu=BigInt(32);function _p(r,e=!1){return e?{h:Number(r&Zs),l:Number(r>>Pu&Zs)}:{h:Number(r>>Pu&Zs)|0,l:Number(r&Zs)|0}}function EE(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=_p(r[o],e);[t[o],n[o]]=[i,s]}return[t,n]}var vE=(r,e)=>BigInt(r>>>0)<<Pu|BigInt(e>>>0),SE=(r,e,t)=>r>>>t,_E=(r,e,t)=>r<<32-t|e>>>t,AE=(r,e,t)=>r>>>t|e<<32-t,kE=(r,e,t)=>r<<32-t|e>>>t,BE=(r,e,t)=>r<<64-t|e>>>t-32,IE=(r,e,t)=>r>>>t-32|e<<64-t,RE=(r,e)=>e,TE=(r,e)=>r,NE=(r,e,t)=>r<<t|e>>>32-t,CE=(r,e,t)=>e<<t|r>>>32-t,LE=(r,e,t)=>e<<t-32|r>>>64-t,DE=(r,e,t)=>r<<t-32|e>>>64-t;function PE(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var OE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),UE=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,FE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),VE=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,HE=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),ME=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var zE={fromBig:_p,split:EE,toBig:vE,shrSH:SE,shrSL:_E,rotrSH:AE,rotrSL:kE,rotrBH:BE,rotrBL:IE,rotr32H:RE,rotr32L:TE,rotlSH:NE,rotlSL:CE,rotlBH:LE,rotlBL:DE,add:PE,add3L:OE,add3H:UE,add4L:FE,add4H:VE,add5H:ME,add5L:HE},Y=zE;var[$E,KE]=Y.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))),Xr=new Uint32Array(80),Zr=new Uint32Array(80),Ou=class extends xo{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:m,Gh:d,Gl:p,Hh:h,Hl:y}=this;return[e,t,n,o,i,s,a,c,u,l,f,m,d,p,h,y]}set(e,t,n,o,i,s,a,c,u,l,f,m,d,p,h,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=m|0,this.Gh=d|0,this.Gl=p|0,this.Hh=h|0,this.Hl=y|0}process(e,t){for(let x=0;x<16;x++,t+=4)Xr[x]=e.getUint32(t),Zr[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let v=Xr[x-15]|0,S=Zr[x-15]|0,I=Y.rotrSH(v,S,1)^Y.rotrSH(v,S,8)^Y.shrSH(v,S,7),_=Y.rotrSL(v,S,1)^Y.rotrSL(v,S,8)^Y.shrSL(v,S,7),E=Xr[x-2]|0,P=Zr[x-2]|0,V=Y.rotrSH(E,P,19)^Y.rotrBH(E,P,61)^Y.shrSH(E,P,6),L=Y.rotrSL(E,P,19)^Y.rotrBL(E,P,61)^Y.shrSL(E,P,6),$=Y.add4L(_,L,Zr[x-7],Zr[x-16]),C=Y.add4H($,I,V,Xr[x-7],Xr[x-16]);Xr[x]=C|0,Zr[x]=$|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:m,Fh:d,Fl:p,Gh:h,Gl:y,Hh:g,Hl:b}=this;for(let x=0;x<80;x++){let v=Y.rotrSH(f,m,14)^Y.rotrSH(f,m,18)^Y.rotrBH(f,m,41),S=Y.rotrSL(f,m,14)^Y.rotrSL(f,m,18)^Y.rotrBL(f,m,41),I=f&d^~f&h,_=m&p^~m&y,E=Y.add5L(b,S,_,KE[x],Zr[x]),P=Y.add5H(E,g,v,I,$E[x],Xr[x]),V=E|0,L=Y.rotrSH(n,o,28)^Y.rotrBH(n,o,34)^Y.rotrBH(n,o,39),$=Y.rotrSL(n,o,28)^Y.rotrBL(n,o,34)^Y.rotrBL(n,o,39),C=n&i^n&a^i&a,ne=o&s^o&c^s&c;g=h|0,b=y|0,h=d|0,y=p|0,d=f|0,p=m|0,{h:f,l:m}=Y.add(u|0,l|0,P|0,V|0),u=a|0,l=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let B=Y.add3L(V,$,ne);n=Y.add3H(B,P,L,C),o=B|0}({h:n,l:o}=Y.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Y.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Y.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:m}=Y.add(this.Eh|0,this.El|0,f|0,m|0),{h:d,l:p}=Y.add(this.Fh|0,this.Fl|0,d|0,p|0),{h,l:y}=Y.add(this.Gh|0,this.Gl|0,h|0,y|0),{h:g,l:b}=Y.add(this.Hh|0,this.Hl|0,g|0,b|0),this.set(n,o,i,s,a,c,u,l,f,m,d,p,h,y,g,b)}roundClean(){Xr.fill(0),Zr.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 Eo=Xs(()=>new Ou);var Qs={};xe(Qs,{abytes:()=>vo,bitGet:()=>ZE,bitLen:()=>XE,bitMask:()=>yi,bitSet:()=>JE,bytesToHex:()=>gr,bytesToNumberBE:()=>wr,bytesToNumberLE:()=>Qr,concatBytes:()=>br,createHmacDrbg:()=>Vu,ensureBytes:()=>Se,equalBytes:()=>jE,hexToBytes:()=>Tn,hexToNumber:()=>Fu,isBytes:()=>Jr,numberToBytesBE:()=>en,numberToBytesLE:()=>Nn,numberToHexUnpadded:()=>Ip,numberToVarBytesBE:()=>WE,utf8ToBytes:()=>YE,validateObject:()=>rr});var Bp=BigInt(0),Js=BigInt(1),qE=BigInt(2);function Jr(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function vo(r){if(!Jr(r))throw new Error("Uint8Array expected")}var GE=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function gr(r){vo(r);let e="";for(let t=0;t<r.length;t++)e+=GE[r[t]];return e}function Ip(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Fu(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var yr={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Ap(r){if(r>=yr._0&&r<=yr._9)return r-yr._0;if(r>=yr._A&&r<=yr._F)return r-(yr._A-10);if(r>=yr._a&&r<=yr._f)return r-(yr._a-10)}function Tn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,i=0;o<t;o++,i+=2){let s=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 wr(r){return Fu(gr(r))}function Qr(r){return vo(r),Fu(gr(Uint8Array.from(r).reverse()))}function en(r,e){return Tn(r.toString(16).padStart(e*2,"0"))}function Nn(r,e){return en(r,e).reverse()}function WE(r){return Tn(Ip(r))}function Se(r,e,t){let n;if(typeof e=="string")try{n=Tn(e)}catch(i){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${i}`)}else if(Jr(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function br(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];vo(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function jE(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function YE(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function XE(r){let e;for(e=0;r>Bp;r>>=Js,e+=1);return e}function ZE(r,e){return r>>BigInt(e)&Js}function JE(r,e,t){return r|(t?Js:Bp)<<BigInt(e)}var yi=r=>(qE<<BigInt(r-1))-Js,Uu=r=>new Uint8Array(r),kp=r=>Uint8Array.from(r);function Vu(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Uu(r),o=Uu(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>t(o,n,...f),c=(f=Uu())=>{o=a(kp([0]),f),n=a(),f.length!==0&&(o=a(kp([1]),f),n=a())},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,m=[];for(;f<e;){n=a();let d=n.slice();m.push(d),f+=n.length}return br(...m)};return(f,m)=>{s(),c(f);let d;for(;!(d=m(u()));)c();return s(),d}}var QE={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"||Jr(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function rr(r,e,t={}){let n=(o,i,s)=>{let a=QE[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(e))n(o,i,!1);for(let[o,i]of Object.entries(t))n(o,i,!0);return r}var Ce=BigInt(0),he=BigInt(1),Cn=BigInt(2),ev=BigInt(3),Hu=BigInt(4),Rp=BigInt(5),Tp=BigInt(8),tv=BigInt(9),rv=BigInt(16);function fe(r,e){let t=r%e;return t>=Ce?t:e+t}function nv(r,e,t){if(t<=Ce||e<Ce)throw new Error("Expected power/modulo > 0");if(t===he)return Ce;let n=he;for(;e>Ce;)e&he&&(n=n*r%t),r=r*r%t,e>>=he;return n}function pe(r,e,t){let n=r;for(;e-- >Ce;)n*=n,n%=t;return n}function ea(r,e){if(r===Ce||e<=Ce)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=fe(r,e),n=e,o=Ce,i=he,s=he,a=Ce;for(;t!==Ce;){let u=n/t,l=n%t,f=o-s*u,m=i-a*u;n=t,t=l,o=s,i=a,s=f,a=m}if(n!==he)throw new Error("invert: does not exist");return fe(o,e)}function ov(r){let e=(r-he)/Cn,t,n,o;for(t=r-he,n=0;t%Cn===Ce;t/=Cn,n++);for(o=Cn;o<r&&nv(o,e,r)!==r-he;o++);if(n===1){let s=(r+he)/Hu;return function(c,u){let l=c.pow(u,s);if(!c.eql(c.sqr(l),u))throw new Error("Cannot find square root");return l}}let i=(t+he)/Cn;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,l=a.pow(a.mul(a.ONE,o),t),f=a.pow(c,i),m=a.pow(c,t);for(;!a.eql(m,a.ONE);){if(a.eql(m,a.ZERO))return a.ZERO;let d=1;for(let h=a.sqr(m);d<u&&!a.eql(h,a.ONE);d++)h=a.sqr(h);let p=a.pow(l,he<<BigInt(u-d-1));l=a.sqr(p),f=a.mul(f,p),m=a.mul(m,l),u=d}return f}}function iv(r){if(r%Hu===ev){let e=(r+he)/Hu;return function(n,o){let i=n.pow(o,e);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%Tp===Rp){let e=(r-Rp)/Tp;return function(n,o){let i=n.mul(o,Cn),s=n.pow(i,e),a=n.mul(o,s),c=n.mul(n.mul(a,Cn),s),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),o))throw new Error("Cannot find square root");return u}}return r%rv,ov(r)}var Np=(r,e)=>(fe(r,e)&he)===he,sv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Mu(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=sv.reduce((n,o)=>(n[o]="function",n),e);return rr(r,t)}function av(r,e,t){if(t<Ce)throw new Error("Expected power > 0");if(t===Ce)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>Ce;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function cv(r,e){let t=new Array(e.length),n=e.reduce((i,s,a)=>r.is0(s)?i:(t[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return e.reduceRight((i,s,a)=>r.is0(s)?i:(t[a]=r.mul(i,t[a]),r.mul(i,s)),o),t}function zu(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function ta(r,e,t=!1,n={}){if(r<=Ce)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:i}=zu(r,e);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=iv(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:i,MASK:yi(o),ZERO:Ce,ONE:he,create:c=>fe(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Ce<=c&&c<r},is0:c=>c===Ce,isOdd:c=>(c&he)===he,neg:c=>fe(-c,r),eql:(c,u)=>c===u,sqr:c=>fe(c*c,r),add:(c,u)=>fe(c+u,r),sub:(c,u)=>fe(c-u,r),mul:(c,u)=>fe(c*u,r),pow:(c,u)=>av(a,c,u),div:(c,u)=>fe(c*ea(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>ea(c,r),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>cv(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>t?Nn(c,i):en(c,i),fromBytes:c=>{if(c.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);return t?Qr(c):wr(c)}});return Object.freeze(a)}function Cp(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function Lp(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function $u(r){let e=Lp(r);return e+Math.ceil(e/2)}function Dp(r,e,t=!1){let n=r.length,o=Lp(e),i=$u(e);if(n<16||n<i||n>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);let s=t?wr(r):Qr(r),a=fe(s,e-he)+he;return t?Nn(a,o):en(a,o)}var uv=BigInt(0),Ku=BigInt(1);function ra(r,e){let t=(o,i)=>{let s=i.negate();return o?s:i},n=o=>{let i=Math.ceil(e/o)+1,s=2**(o-1);return{windows:i,windowSize:s}};return{constTimeNegate:t,unsafeLadder(o,i){let s=r.ZERO,a=o;for(;i>uv;)i&Ku&&(s=s.add(a)),a=a.double(),i>>=Ku;return s},precomputeWindow(o,i){let{windows:s,windowSize:a}=n(i),c=[],u=o,l=u;for(let f=0;f<s;f++){l=u,c.push(l);for(let m=1;m<a;m++)l=l.add(u),c.push(l);u=l.double()}return c},wNAF(o,i,s){let{windows:a,windowSize:c}=n(o),u=r.ZERO,l=r.BASE,f=BigInt(2**o-1),m=2**o,d=BigInt(o);for(let p=0;p<a;p++){let h=p*c,y=Number(s&f);s>>=d,y>c&&(y-=m,s+=Ku);let g=h,b=h+Math.abs(y)-1,x=p%2!==0,v=y<0;y===0?l=l.add(t(x,i[g])):u=u.add(t(v,i[b]))}return{p:u,f:l}},wNAFCached(o,i,s,a){let c=o._WINDOW_SIZE||1,u=i.get(o);return u||(u=this.precomputeWindow(o,c),c!==1&&i.set(o,a(u))),this.wNAF(c,u,s)}}}function gi(r){return Mu(r.Fp),rr(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...zu(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Mt=BigInt(0),gt=BigInt(1),na=BigInt(2),fv=BigInt(8),dv={zip215:!0};function hv(r){let e=gi(r);return rr(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function oa(r){let e=hv(r),{Fp:t,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=e,u=na<<BigInt(a*8)-gt,l=t.create,f=e.uvRatio||((R,A)=>{try{return{isValid:!0,value:t.sqrt(R*t.inv(A))}}catch{return{isValid:!1,value:Mt}}}),m=e.adjustScalarBytes||(R=>R),d=e.domain||((R,A,M)=>{if(A.length||M)throw new Error("Contexts/pre-hash are not supported");return R}),p=R=>typeof R=="bigint"&&Mt<R,h=(R,A)=>p(R)&&p(A)&&R<A,y=R=>R===Mt||h(R,u);function g(R,A){if(h(R,A))return R;throw new Error(`Expected valid scalar < ${A}, got ${typeof R} ${R}`)}function b(R){return R===Mt?R:g(R,n)}let x=new Map;function v(R){if(!(R instanceof S))throw new Error("ExtendedPoint expected")}class S{constructor(A,M,K,j){if(this.ex=A,this.ey=M,this.ez=K,this.et=j,!y(A))throw new Error("x required");if(!y(M))throw new Error("y required");if(!y(K))throw new Error("z required");if(!y(j))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof S)throw new Error("extended point not allowed");let{x:M,y:K}=A||{};if(!y(M)||!y(K))throw new Error("invalid affine point");return new S(M,K,gt,l(M*K))}static normalizeZ(A){let M=t.invertBatch(A.map(K=>K.ez));return A.map((K,j)=>K.toAffine(M[j])).map(S.fromAffine)}_setWindowSize(A){this._WINDOW_SIZE=A,x.delete(this)}assertValidity(){let{a:A,d:M}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:K,ey:j,ez:X,et:Z}=this,ae=l(K*K),te=l(j*j),oe=l(X*X),Be=l(oe*oe),be=l(ae*A),Oe=l(oe*l(be+te)),Ue=l(Be+l(M*l(ae*te)));if(Oe!==Ue)throw new Error("bad point: equation left != right (1)");let Ne=l(K*j),$e=l(X*Z);if(Ne!==$e)throw new Error("bad point: equation left != right (2)")}equals(A){v(A);let{ex:M,ey:K,ez:j}=this,{ex:X,ey:Z,ez:ae}=A,te=l(M*ae),oe=l(X*j),Be=l(K*ae),be=l(Z*j);return te===oe&&Be===be}is0(){return this.equals(S.ZERO)}negate(){return new S(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:A}=e,{ex:M,ey:K,ez:j}=this,X=l(M*M),Z=l(K*K),ae=l(na*l(j*j)),te=l(A*X),oe=M+K,Be=l(l(oe*oe)-X-Z),be=te+Z,Oe=be-ae,Ue=te-Z,Ne=l(Be*Oe),$e=l(be*Ue),pr=l(Be*Ue),vn=l(Oe*be);return new S(Ne,$e,vn,pr)}add(A){v(A);let{a:M,d:K}=e,{ex:j,ey:X,ez:Z,et:ae}=this,{ex:te,ey:oe,ez:Be,et:be}=A;if(M===BigInt(-1)){let Gd=l((X-j)*(oe+te)),Wd=l((X+j)*(oe-te)),Al=l(Wd-Gd);if(Al===Mt)return this.double();let jd=l(Z*na*be),Yd=l(ae*na*Be),Xd=Yd+jd,Zd=Wd+Gd,Jd=Yd-jd,Nb=l(Xd*Al),Cb=l(Zd*Jd),Lb=l(Xd*Jd),Db=l(Al*Zd);return new S(Nb,Cb,Db,Lb)}let Oe=l(j*te),Ue=l(X*oe),Ne=l(ae*K*be),$e=l(Z*Be),pr=l((j+X)*(te+oe)-Oe-Ue),vn=$e-Ne,oi=$e+Ne,qd=l(Ue-M*Oe),Bb=l(pr*vn),Ib=l(oi*qd),Rb=l(pr*qd),Tb=l(vn*oi);return new S(Bb,Ib,Tb,Rb)}subtract(A){return this.add(A.negate())}wNAF(A){return E.wNAFCached(this,x,A,S.normalizeZ)}multiply(A){let{p:M,f:K}=this.wNAF(g(A,n));return S.normalizeZ([M,K])[0]}multiplyUnsafe(A){let M=b(A);return M===Mt?_:this.equals(_)||M===gt?this:this.equals(I)?this.wNAF(M).p:E.unsafeLadder(this,M)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return E.unsafeLadder(this,n).is0()}toAffine(A){let{ex:M,ey:K,ez:j}=this,X=this.is0();A==null&&(A=X?fv:t.inv(j));let Z=l(M*A),ae=l(K*A),te=l(j*A);if(X)return{x:Mt,y:gt};if(te!==gt)throw new Error("invZ was invalid");return{x:Z,y:ae}}clearCofactor(){let{h:A}=e;return A===gt?this:this.multiplyUnsafe(A)}static fromHex(A,M=!1){let{d:K,a:j}=e,X=t.BYTES;A=Se("pointHex",A,X);let Z=A.slice(),ae=A[X-1];Z[X-1]=ae&-129;let te=Qr(Z);te===Mt||(M?g(te,u):g(te,t.ORDER));let oe=l(te*te),Be=l(oe-gt),be=l(K*oe-j),{isValid:Oe,value:Ue}=f(Be,be);if(!Oe)throw new Error("Point.fromHex: invalid y coordinate");let Ne=(Ue>)===gt,$e=(ae&128)!==0;if(!M&&Ue===Mt&&$e)throw new Error("Point.fromHex: x=0 and x_0=1");return $e!==Ne&&(Ue=l(-Ue)),S.fromAffine({x:Ue,y:te})}static fromPrivateKey(A){return L(A).point}toRawBytes(){let{x:A,y:M}=this.toAffine(),K=Nn(M,t.BYTES);return K[K.length-1]|=A>?128:0,K}toHex(){return gr(this.toRawBytes())}}S.BASE=new S(e.Gx,e.Gy,gt,l(e.Gx*e.Gy)),S.ZERO=new S(Mt,gt,gt,Mt);let{BASE:I,ZERO:_}=S,E=ra(S,a*8);function P(R){return fe(R,n)}function V(R){return P(Qr(R))}function L(R){let A=a;R=Se("private key",R,A);let M=Se("hashed private key",i(R),2*A),K=m(M.slice(0,A)),j=M.slice(A,2*A),X=V(K),Z=I.multiply(X),ae=Z.toRawBytes();return{head:K,prefix:j,scalar:X,point:Z,pointBytes:ae}}function $(R){return L(R).pointBytes}function C(R=new Uint8Array,...A){let M=br(...A);return V(i(d(M,Se("context",R),!!o)))}function ne(R,A,M={}){R=Se("message",R),o&&(R=o(R));let{prefix:K,scalar:j,pointBytes:X}=L(A),Z=C(M.context,K,R),ae=I.multiply(Z).toRawBytes(),te=C(M.context,ae,X,R),oe=P(Z+te*j);b(oe);let Be=br(ae,Nn(oe,t.BYTES));return Se("result",Be,a*2)}let B=dv;function T(R,A,M,K=B){let{context:j,zip215:X}=K,Z=t.BYTES;R=Se("signature",R,2*Z),A=Se("message",A),o&&(A=o(A));let ae=Qr(R.slice(Z,2*Z)),te,oe,Be;try{te=S.fromHex(M,X),oe=S.fromHex(R.slice(0,Z),X),Be=I.multiplyUnsafe(ae)}catch{return!1}if(!X&&te.isSmallOrder())return!1;let be=C(j,oe.toRawBytes(),te.toRawBytes(),A);return oe.add(te.multiplyUnsafe(be)).subtract(Be).clearCofactor().equals(S.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:$,sign:ne,verify:T,ExtendedPoint:S,utils:{getExtendedPublicKey:L,randomPrivateKey:()=>s(t.BYTES),precompute(R=8,A=S.BASE){return A._setWindowSize(R),A.multiply(BigInt(3)),A}}}}var Gu=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Pp=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),I8=BigInt(0),pv=BigInt(1),qu=BigInt(2),mv=BigInt(5),Op=BigInt(10),yv=BigInt(20),gv=BigInt(40),Up=BigInt(80);function wv(r){let e=Gu,n=r*r%e*r%e,o=pe(n,qu,e)*n%e,i=pe(o,pv,e)*r%e,s=pe(i,mv,e)*i%e,a=pe(s,Op,e)*s%e,c=pe(a,yv,e)*a%e,u=pe(c,gv,e)*c%e,l=pe(u,Up,e)*u%e,f=pe(l,Up,e)*u%e,m=pe(f,Op,e)*s%e;return{pow_p_5_8:pe(m,qu,e)*r%e,b2:n}}function bv(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function xv(r,e){let t=Gu,n=fe(e*e*e,t),o=fe(n*n*e,t),i=wv(r*o).pow_p_5_8,s=fe(r*n*i,t),a=fe(e*s*s,t),c=s,u=fe(s*Pp,t),l=a===r,f=a===fe(-r,t),m=a===fe(-r*Pp,t);return l&&(s=c),(f||m)&&(s=u),Np(s,t)&&(s=fe(-s,t)),{isValid:l||f,value:s}}var xr=ta(Gu,void 0,!0),Wu={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:xr,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Eo,randomBytes:bo,adjustScalarBytes:bv,uvRatio:xv},So=oa(Wu);function Fp(r,e,t){if(e.length>255)throw new Error("Context is too big");return Ys(Du("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var R8=oa({...Wu,domain:Fp}),T8=oa({...Wu,domain:Fp,prehash:Eo});var Ev=(xr.ORDER+BigInt(3))/BigInt(8),N8=xr.pow(qu,Ev),C8=xr.sqrt(xr.neg(xr.ONE)),L8=(xr.ORDER-BigInt(5))/BigInt(8),D8=BigInt(486662);var P8=Cp(xr,xr.neg(BigInt(486664)));var O8=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),U8=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),F8=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),V8=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var H8=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var _o=32,Er=64,ia=32;function Vp(){let r=So.utils.randomPrivateKey(),e=So.getPublicKey(r);return{privateKey:$p(r,e),publicKey:e}}function Hp(r){if(r.length!==ia)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=So.getPublicKey(e);return{privateKey:$p(e,t),publicKey:t}}function Mp(r,e){let t=r.subarray(0,ia);return So.sign(e instanceof Uint8Array?e:e.subarray(),t)}function zp(r,e,t){return So.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function $p(r,e){let t=new Uint8Array(Er);for(let n=0;n<ia;n++)t[n]=r[n],t[ia+n]=e[n];return t}var et={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var ju={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Kp(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",i=r?.saltLength??16,s=r?.iterations??32767,a=et.get();t*=8;async function c(f,m){let d=a.getRandomValues(new Uint8Array(i)),p=a.getRandomValues(new Uint8Array(n)),h={name:e,iv:p};typeof m=="string"&&(m=U(m));let y;if(m.length===0){y=await a.subtle.importKey("jwk",ju,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:d,iterations:s,hash:{name:o}},x=await a.subtle.importKey("raw",m,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",ju,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:d,iterations:s,hash:{name:o}},x=await a.subtle.importKey("raw",m,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(h,y,f);return ue([d,h.iv,new Uint8Array(g)])}async function u(f,m){let d=f.subarray(0,i),p=f.subarray(i,i+n),h=f.subarray(i+n),y={name:e,iv:p};typeof m=="string"&&(m=U(m));let g;if(m.length===0)try{let x={name:"PBKDF2",salt:d,iterations:s,hash:{name:o}},v=await a.subtle.importKey("raw",m,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,v,{name:e,length:t},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",ju,{name:"AES-GCM"},!0,["decrypt"])}else{let x={name:"PBKDF2",salt:d,iterations:s,hash:{name:o}},v=await a.subtle.importKey("raw",m,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,v,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(y,g,h);return new Uint8Array(b)}return{encrypt:c,decrypt:u}}async function Ao(r,e){let n=await Kp().encrypt(r,e);return er.encode(n)}var me;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(me||(me={}));var Yu;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(Yu||(Yu={}));(function(r){r.codec=()=>Rn(Yu)})(me||(me={}));var nr;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),me.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Type=me.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>Rt(t,r.codec()),r.decode=t=>Bt(t,r.codec())})(nr||(nr={}));var or;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),me.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Type=me.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>Rt(t,r.codec()),r.decode=t=>Bt(t,r.codec())})(or||(or={}));var wi=class{_key;constructor(e){this._key=ko(e,_o)}verify(e,t){return zp(this._key,t,e)}marshal(){return this._key}get bytes(){return nr.encode({Type:me.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=ce.digest(this.bytes);return Ct(e)?e.then(({bytes:t})=>t):e.bytes}},Ln=class{_key;_publicKey;constructor(e,t){this._key=ko(e,Er),this._publicKey=ko(t,_o)}sign(e){return Mp(this._key,e)}get public(){return new wi(this._publicKey)}marshal(){return this._key}get bytes(){return or.encode({Type:me.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=ce.digest(this.bytes),t;return Ct(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Ge.digest(this.public.bytes);return Ae.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Ao(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function _v(r){if(r.length>Er){r=ko(r,Er+_o);let n=r.subarray(0,Er),o=r.subarray(Er,r.length);return new Ln(n,o)}r=ko(r,Er);let e=r.subarray(0,Er),t=r.subarray(_o);return new Ln(e,t)}function Av(r){return r=ko(r,_o),new wi(r)}async function kv(){let{privateKey:r,publicKey:e}=Vp();return new Ln(r,e)}async function qp(r){let{privateKey:e,publicKey:t}=Hp(r);return new Ln(e,t)}function ko(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new N(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var af={};xe(af,{MAX_RSA_KEY_SIZE:()=>Ti,RsaPrivateKey:()=>No,RsaPublicKey:()=>Ri,fromJwk:()=>Qv,generateKeyPair:()=>eS,unmarshalRsaPrivateKey:()=>of,unmarshalRsaPublicKey:()=>Jv});function Dn(r){if(isNaN(r)||r<=0)throw new N("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return bo(r)}var on={};xe(on,{exportToPem:()=>Wv,importFromPem:()=>jv,jwkToPkcs1:()=>$v,jwkToPkix:()=>qv,pkcs1ToJwk:()=>zv,pkixToJwk:()=>Kv});var aa=class extends go{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ws(e);let n=Yr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(e){return yo(this),this.iHash.update(e),this}digestInto(e){yo(this),mo(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},bi=(r,e,t)=>new aa(r,e).update(t).digest();bi.create=(r,e)=>new aa(r,e);function Bv(r,e,t,n){Ws(r);let o=Ep({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(po(i),po(s),po(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Yr(e),u=Yr(t),l=new Uint8Array(s),f=bi.create(r,c),m=f._cloneInto().update(u);return{c:i,dkLen:s,asyncTick:a,DK:l,PRF:f,PRFSalt:m}}function Iv(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function Zu(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:u}=Bv(r,e,t,n),l,f=new Uint8Array(4),m=wo(f),d=new Uint8Array(c.outputLen);for(let p=1,h=0;h<i;p++,h+=c.outputLen){let y=a.subarray(h,h+c.outputLen);m.setInt32(0,p,!1),(l=u._cloneInto(l)).update(f).digestInto(d),y.set(d.subarray(0,y.length)),await xp(o-1,s,()=>{c._cloneInto(l).update(d).digestInto(d);for(let g=0;g<y.length;g++)y[g]^=d[g]})}return Iv(c,u,a,l,d)}var ee=J(Gp());function Pn(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function tn(r,e,t=-1){let n=t,o=r,i=0,s=Math.pow(2,e);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 u=new Uint8Array(c);for(let l=a-1;l>=0;l--){let f=Math.pow(2,l*e);u[i-l-1]=Math.floor(o/f),o-=u[i-l-1]*f}return c}s*=Math.pow(2,e)}return new ArrayBuffer(0)}function ua(...r){let e=0,t=0;for(let i of r)e+=i.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let i of r)o.set(i,t),t+=i.length;return o}function Qu(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Pn(t,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,Pn(i,8)-n}function Wp(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let s=t-e,a=tn(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=tn(e,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}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function jp(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function ct(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(t)}var pN=Math.log(2);function fa(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function ef(r){let e=0,t=0;for(let o=0;o<r.length;o++){let i=r[o];e+=i.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let i=r[o];n.set(new Uint8Array(i),t),t+=i.byteLength}return n.buffer}function kr(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Ei=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return ef(this.items)}},xi=[new Uint8Array([1])],Yp="0123456789";var Ro="",$t=new ArrayBuffer(0),tf=new Uint8Array(0),vi="EndOfContent",Zp="OCTET STRING",Jp="BIT STRING";function Br(r){var e;return e=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?ee.BufferSourceConverter.toUint8Array(i.valueHex):tf}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(!kr(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",$t)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ee.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Sr=class{constructor({blockLength:e=0,error:t=Ro,warnings:n=[],valueBeforeDecode:o=tf}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=ee.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ee.Convert.ToHex(this.valueBeforeDecodeView)}}};Sr.NAME="baseBlock";var je=class extends Sr{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};je.NAME="valueBlock";var da=class extends Br(Sr){constructor({idBlock:e={}}={}){var t,n,o,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?ee.BufferSourceConverter.toUint8Array(e.valueHex):tf,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",$t}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=tn(this.tagNumber,7),i=new Uint8Array(o),s=o.byteLength,a=new Uint8Array(s+1);if(a[0]=t|31,!e){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]=t|31,!e){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(e,t,n){let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;let i=o.subarray(t,t+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,u=this.valueHexView=new Uint8Array(255),l=255;for(;i[c]&128;){if(u[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===l){l+=255;let m=new Uint8Array(l);for(let d=0;d<u.length;d++)m[d]=u[d];u=this.valueHexView=new Uint8Array(l)}}this.blockLength=c+1,u[c-1]=i[c]&127;let f=new Uint8Array(c);for(let m=0;m<c;m++)f[m]=u[m];u=this.valueHexView=new Uint8Array(c),u.set(f),this.blockLength<=9?this.tagNumber=Pn(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};da.NAME="identificationBlock";var ha=class extends Sr{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;let i=o.subarray(t,t+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,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+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=t+1,c=o.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Pn(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=tn(this.length,8);if(o.byteLength>127)return this.error="Too big length",$t;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let i=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let s=0;s<o.byteLength;s++)n[s+1]=i[s];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};ha.NAME="lengthBlock";var H={},Ve=class extends Sr{constructor({name:e=Ro,optional:t=!1,primitiveSchema:n,...o}={},i){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new da(o),this.lenBlock=new ha(o),this.valueBlock=i?new i(o):new je(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,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(e,t){let n=t||new Ei;t||Qp(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let s=this.lenBlock.toBER(e);n.write(s),n.write(i)}return t?$t:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():ee.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${ee.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return jp(t,n)}};Ve.NAME="BaseBlock";function Qp(r){if(r instanceof H.Constructed)for(let e of r.valueBlock.value)Qp(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var pa=class extends Ve{constructor({value:e=Ro,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,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}'`}};pa.NAME="BaseStringBlock";var ma=class extends Br(je){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};ma.NAME="PrimitiveValueBlock";var em,ya=class extends Ve{constructor(e={}){super(e,ma),this.idBlock.isConstructed=!1}};em=ya;H.Primitive=em;ya.NAME="PRIMITIVE";function Uv(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function Ya(r,e=0,t=r.length){let n=e,o=new Ve({},je),i=new Sr;if(!kr(i,r,e,t))return o.error=i.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=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=Ve;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=H.EndOfContent;break;case 1:c=H.Boolean;break;case 2:c=H.Integer;break;case 3:c=H.BitString;break;case 4:c=H.OctetString;break;case 5:c=H.Null;break;case 6:c=H.ObjectIdentifier;break;case 10:c=H.Enumerated;break;case 12:c=H.Utf8String;break;case 13:c=H.RelativeObjectIdentifier;break;case 14:c=H.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=H.Sequence;break;case 17:c=H.Set;break;case 18:c=H.NumericString;break;case 19:c=H.PrintableString;break;case 20:c=H.TeletexString;break;case 21:c=H.VideotexString;break;case 22:c=H.IA5String;break;case 23:c=H.UTCTime;break;case 24:c=H.GeneralizedTime;break;case 25:c=H.GraphicString;break;case 26:c=H.VisibleString;break;case 27:c=H.GeneralString;break;case 28:c=H.UniversalString;break;case 29:c=H.CharacterString;break;case 30:c=H.BmpString;break;case 31:c=H.DATE;break;case 32:c=H.TimeOfDay;break;case 33:c=H.DateTime;break;case 34:c=H.Duration;break;default:{let u=o.idBlock.isConstructed?new H.Constructed:new H.Primitive;u.idBlock=o.idBlock,u.lenBlock=o.lenBlock,u.warnings=o.warnings,o=u}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?H.Constructed:H.Primitive}return o=Uv(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function To(r){if(!r.byteLength){let e=new Ve({},je);return e.error="Input buffer has zero length",{offset:-1,result:e}}return Ya(ee.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Fv(r,e){return r?1:e}var ir=class extends je{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let i=t;for(;Fv(this.isIndefiniteForm,n)>0;){let s=Ya(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===vi)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===vi?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){let n=t||new Ei;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?$t:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};ir.NAME="ConstructedValueBlock";var tm,rn=class extends Ve{constructor(e={}){super(e,ir),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,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 e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
4
4
|
`).map(o=>` ${o}`).join(`
|
|
5
5
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
6
6
|
${e.join(`
|
|
7
|
-
`)}`:`${t} :`}};em=rn;H.Constructed=em;rn.NAME="CONSTRUCTED";var ga=class extends je{fromBER(e,t,n){return t}toBER(e){return $t}};ga.override="EndOfContentValueBlock";var tm,wa=class extends Ve{constructor(e={}){super(e,ga),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};tm=wa;H.EndOfContent=tm;wa.NAME=vi;var rm,nn=class extends Ve{constructor(e={}){super(e,je),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};rm=nn;H.Null=rm;nn.NAME="NULL";var ba=class extends Br(je){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=ee.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=ee.BufferSourceConverter.toUint8Array(e);return kr(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Ju.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ba.NAME="BooleanValueBlock";var nm,xa=class extends Ve{constructor(e={}){super(e,ba),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};nm=xa;H.Boolean=nm;xa.NAME="BOOLEAN";var Ea=class extends Br(ir){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=ir.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===vi){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==Xp)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?ir.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Ea.NAME="OctetStringValueBlock";var om,_r=class r extends Ve{constructor({idBlock:e={},lenBlock:t={},...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,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ea),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let s=Ya(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?rn.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${ee.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return ee.BufferSourceConverter.concat(e)}};om=_r;H.OctetString=om;_r.NAME=Xp;var va=class extends Br(ir){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=ir.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===vi){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Zp)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let i=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,i,t,n))return-1;let s=i.subarray(t,t+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=Ya(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,t+n}toBER(e,t){if(this.isConstructed)return ir.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return $t;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}}};va.NAME="BitStringValueBlock";var im,To=class extends Ve{constructor({idBlock:e={},lenBlock:t={},...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,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},va),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return rn.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};im=To;H.BitString=im;To.NAME=Zp;var sm;function Fv(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,u=0,l=c<s?s:c,f=0;for(let m=l;m>=0;m--,f++){switch(!0){case f<a.length:u=i[s-f]+a[c-f]+t[0];break;default:u=i[s-f]+t[0]}switch(t[0]=u/10,!0){case f>=i.length:i=ua(new Uint8Array([u%10]),i);break;default:i[s-f]=u%10}}return t[0]>0&&(i=ua(t,i)),i}function Yp(r){if(r>=xi.length)for(let e=xi.length;e<=r;e++){let t=new Uint8Array([0]),n=xi[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=i[0]/10,n[o]=i[0]%10}t[0]>0&&(n=ua(t,n)),xi.push(n)}return xi[r]}function Vv(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,u,l=0;for(let f=c;f>=0;f--,l++)switch(u=i[s-l]-a[c-l]-t,!0){case u<0:t=1,i[s-l]=u+10;break;default:t=0,i[s-l]=u}if(t>0)for(let f=s-c+1;f>=0;f--,l++)if(u=i[s-l]-t,u<0)t=1,i[s-l]=u+10;else{t=0,i[s-l]=u;break}return i.slice()}var Si=class extends Br(je){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Ju.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Gp(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let i=this.fromBER(e,t,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(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=Vv(Yp(n),t),s="-";break;default:t=Fv(t,Yp(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=jp.charAt(t[c]));return a===!1&&(s+=jp.charAt(0)),s}};sm=Si;Si.NAME="IntegerValueBlock";Object.defineProperty(sm.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var am,Re=class r extends Ve{constructor(e={}){super(e,Si),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return fa(),BigInt(this.valueBlock.toString())}static fromBigInt(e){fa();let t=BigInt(e),n=new Ei,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(ee.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${ee.Convert.ToHex(a)}`)+t,l=ee.BufferSourceConverter.toUint8Array(ee.Convert.FromHex(u.toString(16)));l[0]|=128,n.write(l)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};am=Re;H.Integer=am;Re.NAME="INTEGER";var cm,Sa=class extends Re{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};cm=Sa;H.Enumerated=cm;Sa.NAME="ENUMERATED";var _i=class extends Br(je){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;let i=o.subarray(t,t+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=On(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){fa();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let 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 t=tn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",$t;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let e="";if(this.isHexOnly)e=ee.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};_i.NAME="sidBlock";var _a=class extends je{constructor({value:e=No,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new _i;if(o=i.fromBER(e,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(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,$t;t.push(o)}return Qu(t)}fromString(e){this.value=[];let t=0,n=0,o="",i=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=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 _i;if(o>Number.MAX_SAFE_INTEGER){fa();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 e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};_a.NAME="ObjectIdentifierValueBlock";var lm,zt=class extends Ve{constructor(e={}){super(e,_a),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};lm=zt;H.ObjectIdentifier=lm;zt.NAME="OBJECT IDENTIFIER";var Ai=class extends Br(Sr){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;let i=o.subarray(t,t+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=On(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let 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 t=tn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",$t;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ee.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ai.NAME="relativeSidBlock";var Aa=class extends je{constructor({value:e=No,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Ai;if(o=i.fromBER(e,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(e,t){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(e);if(i.byteLength===0)return this.error=this.value[o].error,$t;n.push(i)}return Qu(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let i=new Ai;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Aa.NAME="RelativeObjectIdentifierValueBlock";var um,ka=class extends Ve{constructor(e={}){super(e,Aa),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};um=ka;H.RelativeObjectIdentifier=um;ka.NAME="RelativeObjectIdentifier";var fm,De=class extends rn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};fm=De;H.Sequence=fm;De.NAME="SEQUENCE";var dm,Ba=class extends rn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};dm=Ba;H.Set=dm;Ba.NAME="SET";var Ia=class extends Br(je){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=No}toJSON(){return{...super.toJSON(),value:this.value}}};Ia.NAME="StringValueBlock";var Ra=class extends Ia{};Ra.NAME="SimpleStringValueBlock";var tt=class extends pa{constructor({...e}={}){super(e,Ra)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,ee.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};tt.NAME="SIMPLE STRING";var Ta=class extends tt{fromBuffer(e){this.valueBlock.valueHexView=ee.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=ee.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=ee.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ee.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Ta.NAME="Utf8StringValueBlock";var hm,Ar=class extends Ta{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};hm=Ar;H.Utf8String=hm;Ar.NAME="UTF8String";var Na=class extends tt{fromBuffer(e){this.valueBlock.value=ee.Convert.ToUtf16String(e),this.valueBlock.valueHexView=ee.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ee.Convert.FromUtf16String(e))}};Na.NAME="BmpStringValueBlock";var pm,Ca=class extends Na{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};pm=Ca;H.BmpString=pm;Ca.NAME="BMPString";var La=class extends tt{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);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(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let i=tn(e.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=e}};La.NAME="UniversalStringValueBlock";var mm,Da=class extends La{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};mm=Da;H.UniversalString=mm;Da.NAME="UniversalString";var ym,Pa=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};ym=Pa;H.NumericString=ym;Pa.NAME="NumericString";var gm,Oa=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};gm=Oa;H.PrintableString=gm;Oa.NAME="PrintableString";var wm,Ua=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};wm=Ua;H.TeletexString=wm;Ua.NAME="TeletexString";var bm,Fa=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};bm=Fa;H.VideotexString=bm;Fa.NAME="VideotexString";var xm,Va=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};xm=Va;H.IA5String=xm;Va.NAME="IA5String";var Em,Ha=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Em=Ha;H.GraphicString=Em;Ha.NAME="GraphicString";var vm,ki=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};vm=ki;H.VisibleString=vm;ki.NAME="VisibleString";var Sm,Ma=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Sm=Ma;H.GeneralString=Sm;Ma.NAME="GeneralString";var _m,za=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};_m=za;H.CharacterString=_m;za.NAME="CharacterString";var Am,Bi=class extends ki{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,ee.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let 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(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=ct(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=ct(this.month,2),t[2]=ct(this.day,2),t[3]=ct(this.hour,2),t[4]=ct(this.minute,2),t[5]=ct(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Am=Bi;H.UTCTime=Am;Bi.NAME="UTCTime";var km,$a=class extends Bi{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",i=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,m=n.indexOf("+"),d="";if(m===-1&&(m=n.indexOf("-"),f=-1),m!==-1){if(d=n.substring(m+1),n=n.substring(0,m),d.length!==2&&d.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(d.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*p,d.length===4){if(p=parseInt(d.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=f*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let f=new Number(`0${n.substring(u)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");i=f.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,u!==-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,u!==-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,u!==-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,u!==-1){let f=1e3*i;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let l=s.exec(o);if(l===null)throw new Error("Wrong input string for conversion");for(let f=1;f<l.length;f++)switch(f){case 1:this.year=parseInt(l[f],10);break;case 2:this.month=parseInt(l[f],10);break;case 3:this.day=parseInt(l[f],10);break;case 4:this.hour=parseInt(l[f],10)+a;break;case 5:this.minute=parseInt(l[f],10)+c;break;case 6:this.second=parseInt(l[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(ct(this.year,4)),t.push(ct(this.month,2)),t.push(ct(this.day,2)),t.push(ct(this.hour,2)),t.push(ct(this.minute,2)),t.push(ct(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(ct(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};km=$a;H.GeneralizedTime=km;$a.NAME="GeneralizedTime";var Bm,Ka=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Bm=Ka;H.DATE=Bm;Ka.NAME="DATE";var Im,qa=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Im=qa;H.TimeOfDay=Im;qa.NAME="TimeOfDay";var Rm,Ga=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Rm=Ga;H.DateTime=Rm;Ga.NAME="DateTime";var Tm,Wa=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Tm=Wa;H.Duration=Tm;Wa.NAME="Duration";var Nm,ja=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Nm=ja;H.TIME=Nm;ja.NAME="TIME";function Mv(r){let{result:e}=Co(r),t=e.valueBlock.value;return{n:W(sr(t[1].toBigInt()),"base64url"),e:W(sr(t[2].toBigInt()),"base64url"),d:W(sr(t[3].toBigInt()),"base64url"),p:W(sr(t[4].toBigInt()),"base64url"),q:W(sr(t[5].toBigInt()),"base64url"),dp:W(sr(t[6].toBigInt()),"base64url"),dq:W(sr(t[7].toBigInt()),"base64url"),qi:W(sr(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function zv(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 N("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new De({value:[new Re({value:0}),Re.fromBigInt(ar(U(r.n,"base64url"))),Re.fromBigInt(ar(U(r.e,"base64url"))),Re.fromBigInt(ar(U(r.d,"base64url"))),Re.fromBigInt(ar(U(r.p,"base64url"))),Re.fromBigInt(ar(U(r.q,"base64url"))),Re.fromBigInt(ar(U(r.dp,"base64url"))),Re.fromBigInt(ar(U(r.dq,"base64url"))),Re.fromBigInt(ar(U(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function $v(r){let{result:e}=Co(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:W(sr(t[0].toBigInt()),"base64url"),e:W(sr(t[1].toBigInt()),"base64url")}}function Kv(r){if(r.n==null||r.e==null)throw new N("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new De({value:[new De({value:[new zt({value:"1.2.840.113549.1.1.1"}),new nn]}),new To({valueHex:new De({value:[Re.fromBigInt(ar(U(r.n,"base64url"))),Re.fromBigInt(ar(U(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function sr(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,i=0;for(;o<t;)n[o]=parseInt(e.slice(i,i+2),16),o+=1,i+=2;return n}function ar(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var qv=16,tf=32,rf=1e4;async function Gv(r,e){let t=et.get(),o=new De({value:[new Re({value:0}),new De({value:[new zt({value:"1.2.840.113549.1.1.1"}),new nn]}),new _r({valueHex:r.marshal()})]}).toBER(),i=new Uint8Array(o,0,o.byteLength),s=Pn(qv),a=await Xu(So,e,s,{c:rf,dkLen:tf}),c=Pn(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),l=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,i),f=new De({value:[new _r({valueHex:s}),new Re({value:rf}),new Re({value:tf}),new De({value:[new zt({value:"1.2.840.113549.2.11"}),new nn]})]}),m=new De({value:[new zt({value:"1.2.840.113549.1.5.13"}),new De({value:[new De({value:[new zt({value:"1.2.840.113549.1.5.12"}),f]}),new De({value:[new zt({value:"2.16.840.1.101.3.4.1.42"}),new _r({valueHex:c})]})]})]}),p=new De({value:[m,new _r({valueHex:l})]}).toBER(),h=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...W(h,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
8
|
-
`)}async function Wv(r,e){let t=et.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=U(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Co(o),{iv:s,salt:a,iterations:c,keySize:u,cipherText:l}=jv(i),f=await Xu(So,e,a,{c,dkLen:u}),m=await t.subtle.importKey("raw",f,"AES-CBC",!1,["decrypt"]),d=Ii(await t.subtle.decrypt({name:"AES-CBC",iv:s},m,l)),{result:p}=Co(d);n=Cm(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=U(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Co(o);n=Cm(i)}else throw new N("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return nf(n)}function jv(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new N("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new N("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let i=n.valueBlock.value[1],s=Ii(i.valueBlock.value[0].getValue()),a=rf,c=tf;if(i.valueBlock.value.length===3)a=Number(i.valueBlock.value[1].toBigInt()),c=Number(i.valueBlock.value[2].toBigInt());else if(i.valueBlock.value.length===2)throw new N("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],l=u.valueBlock.value[0].toString();if(l!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(l!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(l!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(l!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(l!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new N("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let f=Ii(u.valueBlock.value[1].getValue());return{cipherText:Ii(r.valueBlock.value[1].getValue()),salt:s,iterations:a,keySize:c,iv:f}}function Cm(r){return Ii(r.valueBlock.value[2].getValue())}function Ii(r){return new Uint8Array(r,0,r.byteLength)}async function Lm(r){let e=await et.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Om(e);return{privateKey:t[0],publicKey:t[1]}}async function of(r){let t=[await et.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Yv(r)],n=await Om({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Dm(r,e){let t=await et.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await et.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Pm(r,e,t){let n=await et.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return et.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Om(r){if(r.privateKey==null||r.publicKey==null)throw new N("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([et.get().subtle.exportKey("jwk",r.privateKey),et.get().subtle.exportKey("jwk",r.publicKey)])}async function Yv(r){return et.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Xa(r){if(r.kty!=="RSA")throw new N("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new N("invalid key modulus","ERR_INVALID_KEY_MODULUS");return U(r.n,"base64url").length*8}var Ti=8192,Ri=class{_key;constructor(e){this._key=e}verify(e,t){return Pm(this._key,t,e)}marshal(){return on.jwkToPkix(this._key)}get bytes(){return nr.encode({Type:me.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=ce.digest(this.bytes);return Ct(e)?e.then(({bytes:t})=>t):e.bytes}},Lo=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Pn(16)}sign(e){return Dm(this._key,e)}get public(){if(this._publicKey==null)throw new N("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ri(this._publicKey)}marshal(){return on.jwkToPkcs1(this._key)}get bytes(){return or.encode({Type:me.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=ce.digest(this.bytes);return Ct(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return W(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return on.exportToPem(this,e);if(t==="libp2p-key")return Bo(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function nf(r){let e=on.pkcs1ToJwk(r);if(Xa(e)>Ti)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await of(e);return new Lo(t.privateKey,t.publicKey)}function Zv(r){let e=on.pkixToJwk(r);if(Xa(e)>Ti)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Ri(e)}async function Jv(r){if(Xa(r)>Ti)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await of(r);return new Lo(e.privateKey,e.publicKey)}async function Qv(r){if(r>Ti)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Lm(r);return new Lo(e.privateKey,e.publicKey)}var ff={};xe(ff,{Secp256k1PrivateKey:()=>Ci,Secp256k1PublicKey:()=>Ni,generateKeyPair:()=>dS,unmarshalSecp256k1PrivateKey:()=>uS,unmarshalSecp256k1PublicKey:()=>fS});var eS=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]),sn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),an=new Uint32Array(64),af=class extends vo{constructor(){super(64,32,8,!1),this.A=sn[0]|0,this.B=sn[1]|0,this.C=sn[2]|0,this.D=sn[3]|0,this.E=sn[4]|0,this.F=sn[5]|0,this.G=sn[6]|0,this.H=sn[7]|0}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)an[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let m=an[f-15],d=an[f-2],p=Ht(m,7)^Ht(m,18)^m>>>3,h=Ht(d,17)^Ht(d,19)^d>>>10;an[f]=h+an[f-7]+p+an[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let m=Ht(a,6)^Ht(a,11)^Ht(a,25),d=l+m+Ep(a,c,u)+eS[f]+an[f]|0,h=(Ht(n,2)^Ht(n,13)^Ht(n,22))+vp(n,o,i)|0;l=u,u=c,c=a,a=s+d|0,s=i,i=o,o=n,n=d+h|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,u=u+this.G|0,l=l+this.H|0,this.set(n,o,i,s,a,c,u,l)}roundClean(){an.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Um=Xs(()=>new af);function tS(r){let e=gi(r);rr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:rS,hexToBytes:nS}=Qs,Un={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=Un;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:rS(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=Un,t=typeof r=="string"?nS(r):r;_o(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:i}=Un._parseInt(t.subarray(2)),{d:s,l:a}=Un._parseInt(i);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let l=u.toString(16);return l.length&1?`0${l}`:l},n=e(t(r.s)),o=e(t(r.r)),i=n.length/2,s=o.length/2,a=t(i),c=t(s);return`30${t(s+i+4)}02${c}${o}02${a}${n}`}},Ir=BigInt(0),Dt=BigInt(1),VN=BigInt(2),Fm=BigInt(3),HN=BigInt(4);function oS(r){let e=tS(r),{Fp:t}=e,n=e.toBytes||((p,h,y)=>{let g=h.toAffine();return br(Uint8Array.from([4]),t.toBytes(g.x),t.toBytes(g.y))}),o=e.fromBytes||(p=>{let h=p.subarray(1),y=t.fromBytes(h.subarray(0,t.BYTES)),g=t.fromBytes(h.subarray(t.BYTES,2*t.BYTES));return{x:y,y:g}});function i(p){let{a:h,b:y}=e,g=t.sqr(p),b=t.mul(g,p);return t.add(t.add(b,t.mul(p,h)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function s(p){return typeof p=="bigint"&&Ir<p&&p<e.n}function a(p){if(!s(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:h,nByteLength:y,wrapPrivateKey:g,n:b}=e;if(h&&typeof p!="bigint"){if(Jr(p)&&(p=gr(p)),typeof p!="string"||!h.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let x;try{x=typeof p=="bigint"?p:wr(Se("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return g&&(x=fe(x,b)),a(x),x}let u=new Map;function l(p){if(!(p instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(h,y,g){if(this.px=h,this.py=y,this.pz=g,h==null||!t.isValid(h))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(g==null||!t.isValid(g))throw new Error("z required")}static fromAffine(h){let{x:y,y:g}=h||{};if(!h||!t.isValid(y)||!t.isValid(g))throw new Error("invalid affine point");if(h instanceof f)throw new Error("projective point not allowed");let b=x=>t.eql(x,t.ZERO);return b(y)&&b(g)?f.ZERO:new f(y,g,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let y=t.invertBatch(h.map(g=>g.pz));return h.map((g,b)=>g.toAffine(y[b])).map(f.fromAffine)}static fromHex(h){let y=f.fromAffine(o(Se("pointHex",h)));return y.assertValidity(),y}static fromPrivateKey(h){return f.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:h,y}=this.toAffine();if(!t.isValid(h)||!t.isValid(y))throw new Error("bad point: x or y not FE");let g=t.sqr(y),b=i(h);if(!t.eql(g,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:h}=this.toAffine();if(t.isOdd)return!t.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:y,py:g,pz:b}=this,{px:x,py:v,pz:S}=h,I=t.eql(t.mul(y,S),t.mul(x,b)),_=t.eql(t.mul(g,S),t.mul(v,b));return I&&_}negate(){return new f(this.px,t.neg(this.py),this.pz)}double(){let{a:h,b:y}=e,g=t.mul(y,Fm),{px:b,py:x,pz:v}=this,S=t.ZERO,I=t.ZERO,_=t.ZERO,E=t.mul(b,b),P=t.mul(x,x),V=t.mul(v,v),L=t.mul(b,x);return L=t.add(L,L),_=t.mul(b,v),_=t.add(_,_),S=t.mul(h,_),I=t.mul(g,V),I=t.add(S,I),S=t.sub(P,I),I=t.add(P,I),I=t.mul(S,I),S=t.mul(L,S),_=t.mul(g,_),V=t.mul(h,V),L=t.sub(E,V),L=t.mul(h,L),L=t.add(L,_),_=t.add(E,E),E=t.add(_,E),E=t.add(E,V),E=t.mul(E,L),I=t.add(I,E),V=t.mul(x,v),V=t.add(V,V),E=t.mul(V,L),S=t.sub(S,E),_=t.mul(V,P),_=t.add(_,_),_=t.add(_,_),new f(S,I,_)}add(h){l(h);let{px:y,py:g,pz:b}=this,{px:x,py:v,pz:S}=h,I=t.ZERO,_=t.ZERO,E=t.ZERO,P=e.a,V=t.mul(e.b,Fm),L=t.mul(y,x),$=t.mul(g,v),C=t.mul(b,S),ne=t.add(y,g),B=t.add(x,v);ne=t.mul(ne,B),B=t.add(L,$),ne=t.sub(ne,B),B=t.add(y,b);let T=t.add(x,S);return B=t.mul(B,T),T=t.add(L,C),B=t.sub(B,T),T=t.add(g,b),I=t.add(v,S),T=t.mul(T,I),I=t.add($,C),T=t.sub(T,I),E=t.mul(P,B),I=t.mul(V,C),E=t.add(I,E),I=t.sub($,E),E=t.add($,E),_=t.mul(I,E),$=t.add(L,L),$=t.add($,L),C=t.mul(P,C),B=t.mul(V,B),$=t.add($,C),C=t.sub(L,C),C=t.mul(P,C),B=t.add(B,C),L=t.mul($,B),_=t.add(_,L),L=t.mul(T,B),I=t.mul(ne,I),I=t.sub(I,L),L=t.mul(ne,$),E=t.mul(T,E),E=t.add(E,L),new f(I,_,E)}subtract(h){return this.add(h.negate())}is0(){return this.equals(f.ZERO)}wNAF(h){return d.wNAFCached(this,u,h,y=>{let g=t.invertBatch(y.map(b=>b.pz));return y.map((b,x)=>b.toAffine(g[x])).map(f.fromAffine)})}multiplyUnsafe(h){let y=f.ZERO;if(h===Ir)return y;if(a(h),h===Dt)return this;let{endo:g}=e;if(!g)return d.unsafeLadder(this,h);let{k1neg:b,k1:x,k2neg:v,k2:S}=g.splitScalar(h),I=y,_=y,E=this;for(;x>Ir||S>Ir;)x&Dt&&(I=I.add(E)),S&Dt&&(_=_.add(E)),E=E.double(),x>>=Dt,S>>=Dt;return b&&(I=I.negate()),v&&(_=_.negate()),_=new f(t.mul(_.px,g.beta),_.py,_.pz),I.add(_)}multiply(h){a(h);let y=h,g,b,{endo:x}=e;if(x){let{k1neg:v,k1:S,k2neg:I,k2:_}=x.splitScalar(y),{p:E,f:P}=this.wNAF(S),{p:V,f:L}=this.wNAF(_);E=d.constTimeNegate(v,E),V=d.constTimeNegate(I,V),V=new f(t.mul(V.px,x.beta),V.py,V.pz),g=E.add(V),b=P.add(L)}else{let{p:v,f:S}=this.wNAF(y);g=v,b=S}return f.normalizeZ([g,b])[0]}multiplyAndAddUnsafe(h,y,g){let b=f.BASE,x=(S,I)=>I===Ir||I===Dt||!S.equals(b)?S.multiplyUnsafe(I):S.multiply(I),v=x(this,y).add(x(h,g));return v.is0()?void 0:v}toAffine(h){let{px:y,py:g,pz:b}=this,x=this.is0();h==null&&(h=x?t.ONE:t.inv(b));let v=t.mul(y,h),S=t.mul(g,h),I=t.mul(b,h);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:v,y:S}}isTorsionFree(){let{h,isTorsionFree:y}=e;if(h===Dt)return!0;if(y)return y(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:y}=e;return h===Dt?this:y?y(f,this):this.multiplyUnsafe(e.h)}toRawBytes(h=!0){return this.assertValidity(),n(f,this,h)}toHex(h=!0){return gr(this.toRawBytes(h))}}f.BASE=new f(e.Gx,e.Gy,t.ONE),f.ZERO=new f(t.ZERO,t.ONE,t.ZERO);let m=e.nBitLength,d=ra(f,e.endo?Math.ceil(m/2):m);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:s}}function iS(r){let e=gi(r);return rr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Vm(r){let e=iS(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(B){return Ir<B&&B<t.ORDER}function a(B){return fe(B,n)}function c(B){return ea(B,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:l,weierstrassEquation:f,isWithinCurveOrder:m}=oS({...e,toBytes(B,T,G){let R=T.toAffine(),A=t.toBytes(R.x),M=br;return G?M(Uint8Array.from([T.hasEvenY()?2:3]),A):M(Uint8Array.from([4]),A,t.toBytes(R.y))},fromBytes(B){let T=B.length,G=B[0],R=B.subarray(1);if(T===o&&(G===2||G===3)){let A=wr(R);if(!s(A))throw new Error("Point is not on curve");let M=f(A),K;try{K=t.sqrt(M)}catch(Z){let ae=Z instanceof Error?": "+Z.message:"";throw new Error("Point is not on curve"+ae)}let j=(K&Dt)===Dt;return(G&1)===1!==j&&(K=t.neg(K)),{x:A,y:K}}else if(T===i&&G===4){let A=t.fromBytes(R.subarray(0,t.BYTES)),M=t.fromBytes(R.subarray(t.BYTES,2*t.BYTES));return{x:A,y:M}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),d=B=>gr(en(B,e.nByteLength));function p(B){let T=n>>Dt;return B>T}function h(B){return p(B)?a(-B):B}let y=(B,T,G)=>wr(B.slice(T,G));class g{constructor(T,G,R){this.r=T,this.s=G,this.recovery=R,this.assertValidity()}static fromCompact(T){let G=e.nByteLength;return T=Se("compactSignature",T,G*2),new g(y(T,0,G),y(T,G,2*G))}static fromDER(T){let{r:G,s:R}=Un.toSig(Se("DER",T));return new g(G,R)}assertValidity(){if(!m(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!m(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(T){return new g(this.r,this.s,T)}recoverPublicKey(T){let{r:G,s:R,recovery:A}=this,M=_(Se("msgHash",T));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let K=A===2||A===3?G+e.n:G;if(K>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let j=A&1?"03":"02",X=u.fromHex(j+d(K)),Z=c(K),ae=a(-M*Z),te=a(R*Z),oe=u.BASE.multiplyAndAddUnsafe(X,ae,te);if(!oe)throw new Error("point at infinify");return oe.assertValidity(),oe}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Nn(this.toDERHex())}toDERHex(){return Un.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Nn(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let b={isValidPrivateKey(B){try{return l(B),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let B=zu(e.n);return Lp(e.randomBytes(B),e.n)},precompute(B=8,T=u.BASE){return T._setWindowSize(B),T.multiply(BigInt(3)),T}};function x(B,T=!0){return u.fromPrivateKey(B).toRawBytes(T)}function v(B){let T=Jr(B),G=typeof B=="string",R=(T||G)&&B.length;return T?R===o||R===i:G?R===2*o||R===2*i:B instanceof u}function S(B,T,G=!0){if(v(B))throw new Error("first arg must be private key");if(!v(T))throw new Error("second arg must be public key");return u.fromHex(T).multiply(l(B)).toRawBytes(G)}let I=e.bits2int||function(B){let T=wr(B),G=B.length*8-e.nBitLength;return G>0?T>>BigInt(G):T},_=e.bits2int_modN||function(B){return a(I(B))},E=yi(e.nBitLength);function P(B){if(typeof B!="bigint")throw new Error("bigint expected");if(!(Ir<=B&&B<E))throw new Error(`bigint expected < 2^${e.nBitLength}`);return en(B,e.nByteLength)}function V(B,T,G=L){if(["recovered","canonical"].some(be=>be in G))throw new Error("sign() legacy options not supported");let{hash:R,randomBytes:A}=e,{lowS:M,prehash:K,extraEntropy:j}=G;M==null&&(M=!0),B=Se("msgHash",B),K&&(B=Se("prehashed msgHash",R(B)));let X=_(B),Z=l(T),ae=[P(Z),P(X)];if(j!=null&&j!==!1){let be=j===!0?A(t.BYTES):j;ae.push(Se("extraEntropy",be))}let te=br(...ae),oe=X;function Be(be){let Oe=I(be);if(!m(Oe))return;let Ue=c(Oe),Ne=u.BASE.multiply(Oe).toAffine(),$e=a(Ne.x);if($e===Ir)return;let pr=a(Ue*a(oe+$e*Z));if(pr===Ir)return;let Sn=(Ne.x===$e?0:2)|Number(Ne.y&Dt),oi=pr;return M&&p(pr)&&(oi=h(pr),Sn^=1),new g($e,oi,Sn)}return{seed:te,k2sig:Be}}let L={lowS:e.lowS,prehash:!1},$={lowS:e.lowS,prehash:!1};function C(B,T,G=L){let{seed:R,k2sig:A}=V(B,T,G),M=e;return Fu(M.hash.outputLen,M.nByteLength,M.hmac)(R,A)}u.BASE._setWindowSize(8);function ne(B,T,G,R=$){let A=B;if(T=Se("msgHash",T),G=Se("publicKey",G),"strict"in R)throw new Error("options.strict was renamed to lowS");let{lowS:M,prehash:K}=R,j,X;try{if(typeof A=="string"||Jr(A))try{j=g.fromDER(A)}catch(Ne){if(!(Ne instanceof Un.Err))throw Ne;j=g.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:Ne,s:$e}=A;j=new g(Ne,$e)}else throw new Error("PARSE");X=u.fromHex(G)}catch(Ne){if(Ne.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(M&&j.hasHighS())return!1;K&&(T=e.hash(T));let{r:Z,s:ae}=j,te=_(T),oe=c(ae),Be=a(te*oe),be=a(Z*oe),Oe=u.BASE.multiplyAndAddUnsafe(X,Be,be)?.toAffine();return Oe?a(Oe.x)===Z:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:S,sign:C,verify:ne,ProjectivePoint:u,Signature:g,utils:b}}function sS(r){return{hash:r,hmac:(e,...t)=>bi(r,e,Ys(...t)),randomBytes:Eo}}function Hm(r,e){let t=n=>Vm({...r,...sS(n)});return Object.freeze({...t(e),create:t})}var $m=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Mm=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),aS=BigInt(1),cf=BigInt(2),zm=(r,e)=>(r+e/cf)/e;function cS(r){let e=$m,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=pe(l,t,e)*l%e,m=pe(f,t,e)*l%e,d=pe(m,cf,e)*u%e,p=pe(d,o,e)*d%e,h=pe(p,i,e)*p%e,y=pe(h,a,e)*h%e,g=pe(y,c,e)*y%e,b=pe(g,a,e)*h%e,x=pe(b,t,e)*l%e,v=pe(x,s,e)*p%e,S=pe(v,n,e)*u%e,I=pe(S,cf,e);if(!lf.eql(lf.sqr(I),r))throw new Error("Cannot find square root");return I}var lf=ta($m,void 0,void 0,{sqrt:cS}),Kt=Hm({a:BigInt(0),b:BigInt(7),Fp:lf,n:Mm,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Mm,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-aS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=zm(i*r,e),c=zm(-n*r,e),u=fe(r-a*t-c*o,e),l=fe(-a*n-c*i,e),f=u>s,m=l>s;if(f&&(u=e-u),m&&(l=e-l),u>s||l>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:m,k2:l}}}},Um),YN=BigInt(0);var XN=Kt.ProjectivePoint;function Km(){return Kt.utils.randomPrivateKey()}function qm(r,e){let t=ce.digest(e instanceof Uint8Array?e:e.subarray());if(Ct(t))return t.then(({digest:n})=>Kt.sign(n,r).toDERRawBytes()).catch(n=>{throw new N(String(n),"ERR_INVALID_INPUT")});try{return Kt.sign(t.digest,r).toDERRawBytes()}catch(n){throw new N(String(n),"ERR_INVALID_INPUT")}}function Gm(r,e,t){let n=ce.digest(t instanceof Uint8Array?t:t.subarray());if(Ct(n))return n.then(({digest:o})=>Kt.verify(e,o,r)).catch(o=>{throw new N(String(o),"ERR_INVALID_INPUT")});try{return Kt.verify(e,n.digest,r)}catch(o){throw new N(String(o),"ERR_INVALID_INPUT")}}function Wm(r){return Kt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function jm(r){try{Kt.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}function uf(r){try{Kt.ProjectivePoint.fromHex(r)}catch(e){throw new N(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Ym(r){try{return Kt.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Ni=class{_key;constructor(e){uf(e),this._key=e}verify(e,t){return Gm(this._key,t,e)}marshal(){return Wm(this._key)}get bytes(){return nr.encode({Type:me.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=ce.digest(this.bytes),t;return Ct(e)?{bytes:t}=await e:t=e.bytes,t}},Ci=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Ym(e),jm(this._key),uf(this._publicKey)}sign(e){return qm(this._key,e)}get public(){return new Ni(this._publicKey)}marshal(){return this._key}get bytes(){return or.encode({Type:me.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=ce.digest(this.bytes);return Ct(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return W(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Bo(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function uS(r){return new Ci(r)}function fS(r){return new Ni(r)}async function dS(){let r=Km();return new Ci(r)}var Fn={rsa:sf,ed25519:Yu,secp256k1:ff};function Xm(r){let e=Object.keys(Fn).join(" / ");return new N(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function df(r){let e=nr.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case me.RSA:return Fn.rsa.unmarshalRsaPublicKey(t);case me.Ed25519:return Fn.ed25519.unmarshalEd25519PublicKey(t);case me.Secp256k1:return Fn.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Xm(e.Type??"unknown")}}async function Zm(r){let e=or.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case me.RSA:return Fn.rsa.unmarshalRsaPrivateKey(t);case me.Ed25519:return Fn.ed25519.unmarshalEd25519PrivateKey(t);case me.Secp256k1:return Fn.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Xm(e.Type??"RSA")}}var Bf=J(Ie(),1);var Rr="/",Jm=new TextEncoder().encode(Rr),Za=Jm[0],ke=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=U(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Za)throw new Error("Invalid key")}toString(e="utf8"){return W(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Rr))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Jm),this._buf[0]!==Za){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Za,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Za;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Rr).slice(1)}type(){return hS(this.baseNamespace())}name(){return pS(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Rr)||(e+=Rr),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Rr):new r(e.slice(0,-1).join(Rr))}child(e){return this.toString()===Rr?e:e.toString()===Rr?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...mS(e.map(t=>t.namespaces()))])}};function hS(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function pS(r){let e=r.split(":");return e[e.length-1]}function mS(r){return[].concat(...r)}var pg=J(Ja(),1);var Qm="ERR_IPNS_EXPIRED_RECORD",Li="ERR_UNRECOGNIZED_VALIDITY",ey="ERR_SIGNATURE_CREATION",Tr="ERR_SIGNATURE_VERIFICATION";var pf="ERR_UNDEFINED_PARAMETER",ty="ERR_INVALID_RECORD_DATA",ry="ERR_INVALID_VALUE",ny="ERR_INVALID_EMBEDDED_KEY",oy="ERR_MISSING_PRIVATE_KEY",iy="ERR_RECORD_TOO_LARGE";var He;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),function(o){o.codec=()=>Tn(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=Tt((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)=>{let s={},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.value=o.bytes();break;case 2:s.signatureV1=o.bytes();break;case 3:s.validityType=r.ValidityType.codec().decode(o);break;case 4:s.validity=o.bytes();break;case 5:s.sequence=o.uint64();break;case 6:s.ttl=o.uint64();break;case 7:s.pubKey=o.bytes();break;case 8:s.signatureV2=o.bytes();break;case 9:s.data=o.bytes();break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>Rt(o,r.codec()),r.decode=o=>Bt(o,r.codec())})(He||(He={}));var yS=["string","number","bigint","symbol"],gS=["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 sy(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(yS.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(wS(r))return"Buffer";let t=bS(r);return t||"Object"}function wS(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function bS(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(gS.includes(e))return e}var w=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};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 k=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Do=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",xS=new TextDecoder,ES=new TextEncoder;function Qa(r){return Do&&globalThis.Buffer.isBuffer(r)}function Di(r){return r instanceof Uint8Array?Qa(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var uy=Do?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):cy(r,e,t):(r,e,t)=>t-e>64?xS.decode(r.subarray(e,t)):cy(r,e,t),ec=Do?r=>r.length>64?globalThis.Buffer.from(r):ay(r):r=>r.length>64?ES.encode(r):ay(r),cr=r=>Uint8Array.from(r),Po=Do?(r,e,t)=>Qa(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),fy=Do?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Di(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},dy=Do?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function hy(r,e){if(Qa(r)&&Qa(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function ay(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function cy(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(l=(o&31)<<6|a&63,l>127&&(i=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(o&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(i=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(o&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(i=l))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return yf(n)}var ly=4096;function yf(r){let e=r.length;if(e<=ly)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=ly));return t}var vS=256,Pi=class{constructor(e=vS){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=dy(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Po(n,0,this.cursor)}else t=fy(this.chunks,this.cursor);return e&&this.reset(),t}};var z="CBOR decode error:",Nr="CBOR encode error:",Oi=[];Oi[23]=1;Oi[24]=2;Oi[25]=3;Oi[26]=5;Oi[27]=9;function Cr(r,e,t){if(r.length-e<t)throw new Error(`${z} not enough data for type`)}var Pe=[24,256,65536,4294967296,BigInt("18446744073709551616")];function wt(r,e,t){Cr(r,e,1);let n=r[e];if(t.strict===!0&&n<Pe[0])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return n}function bt(r,e,t){Cr(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Pe[1])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return n}function xt(r,e,t){Cr(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Pe[2])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return n}function Et(r,e,t){Cr(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<Pe[3])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${z} integers outside of the safe integer range are not supported`)}function py(r,e,t,n){return new k(w.uint,wt(r,e+1,n),2)}function my(r,e,t,n){return new k(w.uint,bt(r,e+1,n),3)}function yy(r,e,t,n){return new k(w.uint,xt(r,e+1,n),5)}function gy(r,e,t,n){return new k(w.uint,Et(r,e+1,n),9)}function Pt(r,e){return Me(r,0,e.value)}function Me(r,e,t){if(t<Pe[0]){let n=Number(t);r.push([e|n])}else if(t<Pe[1]){let n=Number(t);r.push([e|24,n])}else if(t<Pe[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Pe[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<Pe[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${z} encountered BigInt larger than allowable range`)}}Pt.encodedSize=function(e){return Me.encodedSize(e.value)};Me.encodedSize=function(e){return e<Pe[0]?1:e<Pe[1]?2:e<Pe[2]?3:e<Pe[3]?5:9};Pt.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function wy(r,e,t,n){return new k(w.negint,-1-wt(r,e+1,n),2)}function by(r,e,t,n){return new k(w.negint,-1-bt(r,e+1,n),3)}function xy(r,e,t,n){return new k(w.negint,-1-xt(r,e+1,n),5)}var gf=BigInt(-1),Ey=BigInt(1);function vy(r,e,t,n){let o=Et(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new k(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${z} integers outside of the safe integer range are not supported`);return new k(w.negint,gf-BigInt(o),9)}function tc(r,e){let t=e.value,n=typeof t=="bigint"?t*gf-Ey:t*-1-1;Me(r,e.type.majorEncoded,n)}tc.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*gf-Ey:t*-1-1;return n<Pe[0]?1:n<Pe[1]?2:n<Pe[2]?3:n<Pe[3]?5:9};tc.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Ui(r,e,t,n){Cr(r,e,t+n);let o=Po(r,e+t,e+t+n);return new k(w.bytes,o,t+n)}function Sy(r,e,t,n){return Ui(r,e,1,t)}function _y(r,e,t,n){return Ui(r,e,2,wt(r,e+1,n))}function Ay(r,e,t,n){return Ui(r,e,3,bt(r,e+1,n))}function ky(r,e,t,n){return Ui(r,e,5,xt(r,e+1,n))}function By(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer bytes lengths not supported`);return Ui(r,e,9,o)}function rc(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===w.string?ec(r.value):r.value),r.encodedBytes}function Oo(r,e){let t=rc(e);Me(r,e.type.majorEncoded,t.length),r.push(t)}Oo.encodedSize=function(e){let t=rc(e);return Me.encodedSize(t.length)+t.length};Oo.compareTokens=function(e,t){return _S(rc(e),rc(t))};function _S(r,e){return r.length<e.length?-1:r.length>e.length?1:hy(r,e)}function Fi(r,e,t,n,o){let i=t+n;Cr(r,e,i);let s=new k(w.string,uy(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Po(r,e+t,e+i)),s}function Iy(r,e,t,n){return Fi(r,e,1,t,n)}function Ry(r,e,t,n){return Fi(r,e,2,wt(r,e+1,n),n)}function Ty(r,e,t,n){return Fi(r,e,3,bt(r,e+1,n),n)}function Ny(r,e,t,n){return Fi(r,e,5,xt(r,e+1,n),n)}function Cy(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer string lengths not supported`);return Fi(r,e,9,o,n)}var Ly=Oo;function Uo(r,e,t,n){return new k(w.array,n,t)}function Dy(r,e,t,n){return Uo(r,e,1,t)}function Py(r,e,t,n){return Uo(r,e,2,wt(r,e+1,n))}function Oy(r,e,t,n){return Uo(r,e,3,bt(r,e+1,n))}function Uy(r,e,t,n){return Uo(r,e,5,xt(r,e+1,n))}function Fy(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer array lengths not supported`);return Uo(r,e,9,o)}function Vy(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return Uo(r,e,1,1/0)}function nc(r,e){Me(r,w.array.majorEncoded,e.value)}nc.compareTokens=Pt.compareTokens;nc.encodedSize=function(e){return Me.encodedSize(e.value)};function Fo(r,e,t,n){return new k(w.map,n,t)}function Hy(r,e,t,n){return Fo(r,e,1,t)}function My(r,e,t,n){return Fo(r,e,2,wt(r,e+1,n))}function zy(r,e,t,n){return Fo(r,e,3,bt(r,e+1,n))}function $y(r,e,t,n){return Fo(r,e,5,xt(r,e+1,n))}function Ky(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer map lengths not supported`);return Fo(r,e,9,o)}function qy(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return Fo(r,e,1,1/0)}function oc(r,e){Me(r,w.map.majorEncoded,e.value)}oc.compareTokens=Pt.compareTokens;oc.encodedSize=function(e){return Me.encodedSize(e.value)};function Gy(r,e,t,n){return new k(w.tag,t,1)}function Wy(r,e,t,n){return new k(w.tag,wt(r,e+1,n),2)}function jy(r,e,t,n){return new k(w.tag,bt(r,e+1,n),3)}function Yy(r,e,t,n){return new k(w.tag,xt(r,e+1,n),5)}function Xy(r,e,t,n){return new k(w.tag,Et(r,e+1,n),9)}function ic(r,e){Me(r,w.tag.majorEncoded,e.value)}ic.compareTokens=Pt.compareTokens;ic.encodedSize=function(e){return Me.encodedSize(e.value)};var TS=20,NS=21,CS=22,LS=23;function Zy(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${z} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new k(w.null,null,1):new k(w.undefined,void 0,1)}function Jy(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return new k(w.break,void 0,1)}function wf(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${z} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${z} Infinity values are not supported`)}return new k(w.float,r,e)}function Qy(r,e,t,n){return wf(bf(r,e+1),3,n)}function eg(r,e,t,n){return wf(xf(r,e+1),5,n)}function tg(r,e,t,n){return wf(ig(r,e+1),9,n)}function sc(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|TS]);else if(n===!0)r.push([w.float.majorEncoded|NS]);else if(n===null)r.push([w.float.majorEncoded|CS]);else if(n===void 0)r.push([w.float.majorEncoded|LS]);else{let o,i=!1;(!t||t.float64!==!0)&&(ng(n),o=bf(qt,1),n===o||Number.isNaN(n)?(qt[0]=249,r.push(qt.slice(0,3)),i=!0):(og(n),o=xf(qt,1),n===o&&(qt[0]=250,r.push(qt.slice(0,5)),i=!0))),i||(DS(n),o=ig(qt,1),qt[0]=251,r.push(qt.slice(0,9)))}}sc.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){ng(n);let o=bf(qt,1);if(n===o||Number.isNaN(n))return 3;if(og(n),o=xf(qt,1),n===o)return 5}return 9};var rg=new ArrayBuffer(9),Ot=new DataView(rg,1),qt=new Uint8Array(rg,0);function ng(r){if(r===1/0)Ot.setUint16(0,31744,!1);else if(r===-1/0)Ot.setUint16(0,64512,!1);else if(Number.isNaN(r))Ot.setUint16(0,32256,!1);else{Ot.setFloat32(0,r);let e=Ot.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Ot.setUint16(0,31744,!1);else if(t===0)Ot.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Ot.setUint16(0,0):o<-14?Ot.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Ot.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function bf(r,e){if(r.length-e<2)throw new Error(`${z} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function og(r){Ot.setFloat32(0,r,!1)}function xf(r,e){if(r.length-e<4)throw new Error(`${z} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function DS(r){Ot.setFloat64(0,r,!1)}function ig(r,e){if(r.length-e<8)throw new Error(`${z} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}sc.compareTokens=Pt.compareTokens;function se(r,e,t){throw new Error(`${z} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function ac(r){return()=>{throw new Error(`${z} ${r}`)}}var D=[];for(let r=0;r<=23;r++)D[r]=se;D[24]=py;D[25]=my;D[26]=yy;D[27]=gy;D[28]=se;D[29]=se;D[30]=se;D[31]=se;for(let r=32;r<=55;r++)D[r]=se;D[56]=wy;D[57]=by;D[58]=xy;D[59]=vy;D[60]=se;D[61]=se;D[62]=se;D[63]=se;for(let r=64;r<=87;r++)D[r]=Sy;D[88]=_y;D[89]=Ay;D[90]=ky;D[91]=By;D[92]=se;D[93]=se;D[94]=se;D[95]=ac("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)D[r]=Iy;D[120]=Ry;D[121]=Ty;D[122]=Ny;D[123]=Cy;D[124]=se;D[125]=se;D[126]=se;D[127]=ac("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)D[r]=Dy;D[152]=Py;D[153]=Oy;D[154]=Uy;D[155]=Fy;D[156]=se;D[157]=se;D[158]=se;D[159]=Vy;for(let r=160;r<=183;r++)D[r]=Hy;D[184]=My;D[185]=zy;D[186]=$y;D[187]=Ky;D[188]=se;D[189]=se;D[190]=se;D[191]=qy;for(let r=192;r<=215;r++)D[r]=Gy;D[216]=Wy;D[217]=jy;D[218]=Yy;D[219]=Xy;D[220]=se;D[221]=se;D[222]=se;D[223]=se;for(let r=224;r<=243;r++)D[r]=ac("simple values are not supported");D[244]=se;D[245]=se;D[246]=se;D[247]=Zy;D[248]=ac("simple values are not supported");D[249]=Qy;D[250]=eg;D[251]=tg;D[252]=se;D[253]=se;D[254]=se;D[255]=Jy;var Gt=[];for(let r=0;r<24;r++)Gt[r]=new k(w.uint,r,1);for(let r=-1;r>=-24;r--)Gt[31-r]=new k(w.negint,r,1);Gt[64]=new k(w.bytes,new Uint8Array(0),1);Gt[96]=new k(w.string,"",1);Gt[128]=new k(w.array,0,1);Gt[160]=new k(w.map,0,1);Gt[244]=new k(w.false,!1,1);Gt[245]=new k(w.true,!0,1);Gt[246]=new k(w.null,null,1);function Ef(r){switch(r.type){case w.false:return cr([244]);case w.true:return cr([245]);case w.null:return cr([246]);case w.bytes:return r.value.length?void 0:cr([64]);case w.string:return r.value===""?cr([96]):void 0;case w.array:return r.value===0?cr([128]):void 0;case w.map:return r.value===0?cr([160]):void 0;case w.uint:return r.value<24?cr([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return cr([31-Number(r.value)])}}var OS={float64:!1,mapSorter:FS,quickEncodeToken:Ef};function Sf(){let r=[];return r[w.uint.major]=Pt,r[w.negint.major]=tc,r[w.bytes.major]=Oo,r[w.string.major]=Ly,r[w.array.major]=nc,r[w.map.major]=oc,r[w.tag.major]=ic,r[w.float.major]=sc,r}var sg=Sf(),vf=new Pi,cc=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Nr} object contains circular references`);return new r(t,e)}},cn={null:new k(w.null,null),undefined:new k(w.undefined,void 0),true:new k(w.true,!0),false:new k(w.false,!1),emptyArray:new k(w.array,0),emptyMap:new k(w.map,0)},ln={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new k(w.float,r):r>=0?new k(w.uint,r):new k(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new k(w.uint,r):new k(w.negint,r)},Uint8Array(r,e,t,n){return new k(w.bytes,r)},string(r,e,t,n){return new k(w.string,r)},boolean(r,e,t,n){return r?cn.true:cn.false},null(r,e,t,n){return cn.null},undefined(r,e,t,n){return cn.undefined},ArrayBuffer(r,e,t,n){return new k(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new k(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[cn.emptyArray,new k(w.break)]:cn.emptyArray;n=cc.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Vi(s,t,n);return t.addBreakTokens?[new k(w.array,r.length),o,new k(w.break)]:[new k(w.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[cn.emptyMap,new k(w.break)]:cn.emptyMap;n=cc.createCheck(n,r);let a=[],c=0;for(let u of i)a[c++]=[Vi(u,t,n),Vi(o?r.get(u):r[u],t,n)];return US(a,t),t.addBreakTokens?[new k(w.map,s),a,new k(w.break)]:[new k(w.map,s),a]}};ln.Map=ln.Object;ln.Buffer=ln.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ln[`${r}Array`]=ln.DataView;function Vi(r,e={},t){let n=sy(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||ln[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=ln[n];if(!i)throw new Error(`${Nr} unsupported type: ${n}`);return i(r,n,e,t)}function US(r,e){e.mapSorter&&r.sort(e.mapSorter)}function FS(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=sg[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function ag(r,e,t,n){if(Array.isArray(e))for(let o of e)ag(r,o,t,n);else t[e.type.major](r,e,n)}function _f(r,e,t){let n=Vi(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new Pi(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Di(a.chunks[0])}}return vf.reset(),ag(vf,n,e,t),vf.toBytes(!0)}function un(r,e){return e=Object.assign({},OS,e),_f(r,sg,e)}var VS={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},lc=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Gt[e];if(t===void 0){let n=D[e];if(!n)throw new Error(`${z} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},Hi=Symbol.for("DONE"),uc=Symbol.for("BREAK");function HS(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Vo(e,t);if(i===uc){if(r.value===1/0)break;throw new Error(`${z} got unexpected break to lengthed array`)}if(i===Hi)throw new Error(`${z} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function MS(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=Vo(e,t);if(a===uc){if(r.value===1/0)break;throw new Error(`${z} got unexpected break to lengthed map`)}if(a===Hi)throw new Error(`${z} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${z} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${z} found repeat map key "${a}"`);let c=Vo(e,t);if(c===Hi)throw new Error(`${z} 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 Vo(r,e){if(r.done())return Hi;let t=r.next();if(t.type===w.break)return uc;if(t.type.terminal)return t.value;if(t.type===w.array)return HS(t,r,e);if(t.type===w.map)return MS(t,r,e);if(t.type===w.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Vo(r,e);return e.tags[t.value](n)}throw new Error(`${z} tag not supported (${t.value})`)}throw new Error("unsupported")}function Af(r,e){if(!(r instanceof Uint8Array))throw new Error(`${z} data to decode must be a Uint8Array`);e=Object.assign({},VS,e);let t=e.tokenizer||new lc(r,e),n=Vo(t,e);if(n===Hi)throw new Error(`${z} did not find any content to decode`);if(n===uc)throw new Error(`${z} got unexpected break`);return[n,r.subarray(t.pos())]}function rt(r,e){let[t,n]=Af(r,e);if(n.length>0)throw new Error(`${z} too many terminals, data makes no sense`);return t}var lt=J(Ie(),1);var cg=Q("ipns:utils"),lg=U("/ipns/"),zS=114,ug=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw cg.error(n),(0,lt.default)(n,pf)}let t;if(e.pubKey!=null){try{t=df(e.pubKey)}catch(o){throw cg.error(o),o}if(!(await ep(e.pubKey)).equals(r))throw(0,lt.default)(new Error("Embedded public key did not match PeerID"),ny)}else r.publicKey!=null&&(t=df(r.publicKey));if(t!=null)return t;throw(0,lt.default)(new Error("no public key is available"),pf)},fg=(r,e,t)=>{let n=U(e);return ue([r,t,n])},dc=r=>{let e=U("ipns-signature:");return ue([e,r])},Lr=r=>"signatureV1"in r?He.encode({value:U(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:U(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):He.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data});function Ye(r){let e=He.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw(0,lt.default)(new Error("missing data or signatureV2"),Tr);let t=hg(e.data),n=kf(t.Value),o=W(t.Validity);if(e.value!=null&&e.signatureV1!=null)return $S(e),{value:n,validityType:He.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:He.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}var Ho=r=>ue([lg,r.toBytes()]),Mo=r=>pi(r.slice(lg.length)),dg=(r,e,t,n,o)=>{let i;if(e===He.ValidityType.EOL)i=0;else throw(0,lt.default)(new Error("Unknown validity type"),Li);return un({Value:r,Validity:t,ValidityType:i,Sequence:n,TTL:o})},hg=r=>{let e=rt(r);if(e.ValidityType===0)e.ValidityType=He.ValidityType.EOL;else throw(0,lt.default)(new Error("Unknown validity type"),Li);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e},kf=r=>{if(r!=null){if(fh(r))return`/ipns/${r.toCID().toString(Gr)}`;if(r instanceof Uint8Array){let n=W(r);n.startsWith("/")&&(r=n)}let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e;let t=O.asCID(r);if(t!=null)return t.code===zS?`/ipns/${t.toString(Gr)}`:`/ipfs/${t.toV1().toString()}`;try{return r instanceof Uint8Array?`/ipfs/${O.decode(r).toV1().toString()}`:`/ipfs/${O.parse(e).toV1().toString()}`}catch{}}throw(0,lt.default)(new Error("Value must be a valid content path starting with /"),ry)},$S=r=>{if(r.data==null)throw(0,lt.default)(new Error("Record data is missing"),ty);let e=hg(r.data);if(!ie(e.Value,r.value??new Uint8Array(0)))throw(0,lt.default)(new Error('Field "value" did not match between protobuf and CBOR'),Tr);if(!ie(e.Validity,r.validity??new Uint8Array(0)))throw(0,lt.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Tr);if(e.ValidityType!==r.validityType)throw(0,lt.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Tr);if(e.Sequence!==r.sequence)throw(0,lt.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Tr);if(e.TTL!==r.ttl)throw(0,lt.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Tr)};var KS=Q("ipns"),qS=Ge.code,mg=60*60*1e9,GS="/ipns/",P6=GS.length,yg={v1Compatible:!0,ttlNs:mg};async function gg(r,e,t,n,o=yg){let i=new pg.default(Date.now()+Number(n)),s=He.ValidityType.EOL,a=BigInt(o.ttlNs!=null?o.ttlNs:mg);return WS(r,e,t,s,i.toString(),a,o)}var WS=async(r,e,t,n,o,i,s=yg)=>{t=BigInt(t);let a=U(o),c=kf(e),u=U(c);if(r.privateKey==null)throw(0,Bf.default)(new Error("Missing private key"),oy);let l=await Zm(r.privateKey),f=dg(u,n,a,t,i),m=dc(f),d=await l.sign(m),p;if(r.publicKey!=null){let h=Je(r.toBytes());(h.code!==qS||!ie(r.publicKey,h.digest))&&(p=r.publicKey)}if(s.v1Compatible===!0){let h=await jS(l,u,n,a),y={value:c,signatureV1:h,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:d,data:f};return p!=null&&(y.pubKey=p),y}else{let h={value:c,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:d,data:f};return p!=null&&(h.pubKey=p),h}};var jS=async(r,e,t,n)=>{try{let o=fg(e,t,n);return await r.sign(o)}catch(o){throw KS.error("record signature creation failed",o),(0,Bf.default)(new Error("record signature creation failed"),ey)}};var Mi=J(Ie(),1),wg=J(Ja(),1);var hc=Q("ipns:validator"),YS=1024*10,XS=async(r,e)=>{let t=Ye(e),n;try{let o=dc(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw hc.error("record signature verification failed"),(0,Mi.default)(new Error("record signature verification failed"),Tr);if(t.validityType===He.ValidityType.EOL){if(wg.default.fromString(t.validity).toDate().getTime()<Date.now())throw hc.error("record has expired"),(0,Mi.default)(new Error("record has expired"),Qm)}else if(t.validityType!=null)throw hc.error("unrecognized validity type"),(0,Mi.default)(new Error("unrecognized validity type"),Li);hc("ipns record for %s is valid",t.value)};async function zi(r,e){if(e.byteLength>YS)throw(0,Mi.default)(new Error("record too large"),iy);let t=Mo(r),n=Ye(e),o=await ug(t,n);await XS(o,e)}async function*$i(r){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=t.decode(o,{stream:!0});let i=n.split(e);n=i.pop()??"";for(let s=0;s<i.length;s++)yield JSON.parse(i[s])}n+=t.decode(),n!==""&&(yield JSON.parse(n))}var Rf=J(xg(),1);var qi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Tf=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Eg=r=>globalThis.DOMException===void 0?new Tf(r):new DOMException(r),vg=r=>{let e=r.reason===void 0?Eg("This operation was aborted."):r.reason;return e instanceof Error?e:Eg(e)};function Gi(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,c=new Promise((u,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:m}=e;m.aborted&&l(vg(m)),m.addEventListener("abort",()=>{l(vg(m))})}if(t===Number.POSITIVE_INFINITY){r.then(u,l);return}let f=new qi;s=i.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){l(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?l(o):(f.message=o??`Promise timed out after ${t} milliseconds`,l(f))},t),(async()=>{try{u(await r)}catch(m){l(m)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function Nf(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var Wi=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Nf(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var ut=class extends Rf.default{#e;#t;#r=0;#s;#c;#p=0;#o;#l;#n;#m;#i=0;#u;#a;#y;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Wi,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#s=e.intervalCap,this.#c=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#a=e.autoStart===!1}get#b(){return this.#t||this.#r<this.#s}get#x(){return this.#i<this.#u}#E(){this.#i--,this.#f(),this.emit("next")}#v(){this.#w(),this.#g(),this.#l=void 0}get#S(){let e=Date.now();if(this.#o===void 0){let t=this.#p-e;if(t<0)this.#r=this.#e?this.#i:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#i===0&&this.emit("idle"),!1;if(!this.#a){let e=!this.#S;if(this.#b&&this.#x){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#g(),!0):!1}}return!1}#g(){this.#t||this.#o!==void 0||(this.#o=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#r===0&&this.#i===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#r=this.#e?this.#i:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#d()}async#_(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#y,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#i++,this.#r++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=Gi(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#_(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof qi&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#E()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#a?(this.#a=!1,this.#d(),this):this}pause(){this.#a=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#h("next",()=>this.#n.size<e)}async onIdle(){this.#i===0&&this.#n.size===0||await this.#h("idle")}async#h(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#i}get isPaused(){return this.#a}};function QS(r){return r[Symbol.asyncIterator]!=null}function e2(r){if(QS(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Hn=e2;var Cf=U("/ipns/");function Sg(r){return ie(r.subarray(0,Cf.byteLength),Cf)}var _g=r=>pi(r.slice(Cf.length)),mc=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*We(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!Sg(e))return;let o=_g(e),i=Ye(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!Sg(e))throw new N("Not found","ERR_NOT_FOUND");let n=_g(e);try{let o=await this.client.getIPNS(n,t);return Lr(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}},yc=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await Hn(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new N("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){}};var ft=Q("delegated-routing-v1-http-api-client"),Ag={concurrentRequests:4,timeout:3e4},gc=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,no(1/0,this.shutDownController.signal),this.httpQueue=new ut({concurrency:t.concurrentRequests??Ag.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??Ag.timeout,this.contentRouting=new mc(this),this.peerRouting=new yc(this)}get[ci](){return this.contentRouting}get[li](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(e,t={}){ft("getProviders starts: %c",e);let n=_n([this.shutDownController.signal,t.signal,AbortSignal.timeout(this.timeout)]),o=ve(),i=ve();this.httpQueue.add(async()=>(o.resolve(),i.promise));try{await o.promise;let s=`${this.clientUrl}routing/v1/providers/${e.toString()}`,c=await fetch(s,{headers:{Accept:"application/x-ndjson"},signal:n});if(c.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(c.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(c.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(c.headers.get("Content-Type")==="application/json"){let l=await c.json();for(let f of l.Providers){let m=this.#e(f);m!=null&&(yield m)}}else for await(let l of $i(Gs(c.body))){let f=this.#e(l);f!=null&&(yield f)}}catch(s){ft.error("getProviders errored:",s)}finally{n.clear(),i.resolve(),ft("getProviders finished: %c",e)}}async*getPeers(e,t={}){ft("getPeers starts: %c",e);let n=_n([this.shutDownController.signal,t.signal,AbortSignal.timeout(this.timeout)]),o=ve(),i=ve();this.httpQueue.add(async()=>(o.resolve(),i.promise));try{await o.promise;let s=`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`,c=await fetch(s,{headers:{Accept:"application/x-ndjson"},signal:n});if(c.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(c.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(c.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(c.headers.get("Content-Type")==="application/json"){let l=await c.json();for(let f of l.Peers){let m=this.#e(f);m!=null&&(yield m)}}else for await(let l of $i(Gs(c.body))){let f=this.#e(l);f!=null&&(yield f)}}catch(s){ft.error("getPeers errored:",s)}finally{n.clear(),i.resolve(),ft("getPeers finished: %c",e)}}async getIPNS(e,t={}){ft("getIPNS starts: %c",e);let n=_n([this.shutDownController.signal,t.signal,AbortSignal.timeout(this.timeout)]),o=ve(),i=ve();this.httpQueue.add(async()=>(o.resolve(),i.promise));let s=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await o.promise;let c=await fetch(s,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:n});if(ft("getIPNS GET %s %d",s,c.status),c.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(c.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(c.body==null)throw new N("GET ipns response had no body","ERR_BAD_RESPONSE");let u=await c.arrayBuffer(),l=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await zi(Ho(e),l),Ye(l)}catch(a){throw ft.error("getIPNS GET %s error:",s,a),a}finally{n.clear(),i.resolve(),ft("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){ft("putIPNS starts: %c",e);let o=_n([this.shutDownController.signal,n.signal,AbortSignal.timeout(this.timeout)]),i=ve(),s=ve();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await i.promise;let c=Lr(t),l=await fetch(a,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:c,signal:o});if(ft("putIPNS PUT %s %d",a,l.status),l.status!==200)throw new N("PUT ipns response had status other than 200","ERR_BAD_RESPONSE")}catch(c){throw ft.error("putIPNS PUT %s error:",a,c.stack),c}finally{o.clear(),s.resolve(),ft("putIPNS finished: %c",e)}}#e(e){let t=[],n=e.Addrs?.map(mi)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Qe(e.ID),Addrs:n,Protocols:t}}};function kg(r,e={}){return new gc(new URL(r),e)}var Bg=U("/ipns/");function Ig(r){return ie(r.subarray(0,Bg.byteLength),Bg)}var Lf=class{client;constructor(e){this.client=kg(e)}async provide(e,t){}async*findProviders(e,t){yield*We(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols}))}async put(e,t,n){if(!Ig(e))return;let o=Mo(e),i=Ye(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!Ig(e))throw new N("Not found","ERR_NOT_FOUND");let n=Mo(e);try{let o=await this.client.getIPNS(n,t);return Lr(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}async findPeer(e,t){let n=await Hn(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new N("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t){}};function ji(r){return new Lf(new URL(r))}function wc(r){let e=[dt.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Df=60;function bc(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:dt[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:dt[e.type],TTL:e.TTL??e.ttl??Df,data:e.data instanceof Uint8Array?W(e.data):e.data}))}}var t2=4;function Pf(r,e={}){let t=new ut({concurrency:e.queryConcurrency??t2});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),wc(o.types).forEach(a=>{i.append("type",dt[a])}),o.onProgress?.(new F("dns:query",{detail:n}));let s=await t.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=bc(await a.json());return o.onProgress?.(new F("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Rg(){return[Pf("https://cloudflare-dns.com/dns-query"),Pf("https://dns.google/resolve")]}var Ng=J(Of(),1);var Uf=class{lru;constructor(e){this.lru=(0,Ng.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return bc({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:dt[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Df)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Cg(r){return new Uf(r)}var r2=1e3,xc=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Cg(e.cacheSize??r2),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Rg())}async query(e,t={}){let n=wc(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new F("dns:cache",{detail:o})),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new F("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var dt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(dt||(dt={}));function Yi(r={}){return new xc(r)}var Ff=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Ec(r,e,t,n){let o=new Ff(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{let a=u=>{try{if(n?.filter?.(u)===!1)return}catch(l){r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(l);return}r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(u)},c=()=>{r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(o)};r.addEventListener(e,a),t?.addEventListener("abort",c)})}var vc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Lg(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new vc(t?.errorMessage,t?.errorCode));let n,o=new vc(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Sc=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=ve(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new Qt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function n2(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var _c=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=n2(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,no(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&this.controller.abort(new Qt)}async join(e={}){let t=new Sc(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Lg(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.signal?.removeEventListener("abort",this.onAbort)})}};function o2(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var Xi=class extends Rs{concurrency;queue;pending;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=o2(this.queue,e,(n,o)=>o.priority-n.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let n=new _c(e,t,t?.priority),o=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),i)).catch(i=>{throw this.safeDispatchEvent("error",{detail:i}),i});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Qt)}),this.clear()}async onEmpty(e){this.size!==0&&await Ec(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ec(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ec(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Nt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new N("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var Ug="/pin/",Dg="/pinned-block/",Vf=Gr,Pg=1;function Og(r){return r.version===0&&(r=r.toV1()),new ke(`${Ug}${r.toString(Vf)}`)}var Ac=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers=n}async*add(e,t={}){let n=Og(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new Xi({concurrency:Pg});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(u=>ie(u,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,un(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=this.dagWalkers[e.code];if(o==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let i=await this.blockstore.get(e,n);yield e;for await(let s of o.walk(i))yield*await t.add(async()=>this.#e(s,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new ke(`${Dg}${Vf.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=rt(await this.datastore.get(o,n))}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,un(i),n),n.onProgress?.(new F("helia:pin:add",e))}}async*rm(e,t={}){let n=Og(e),o=await this.datastore.get(n,t),i=rt(o);await this.datastore.delete(n,t);let s=new Xi({concurrency:Pg});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(u=>ie(u,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Ug+(e.cid!=null?`${e.cid.toString(Gr)}`:"")},e)){let o=O.parse(t.toString().substring(5),Gr),i=rt(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new ke(`${Dg}${Vf.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};function Hf(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var zo=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Hf(this.set.entries(),e=>{let t=Qe(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Qe(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Hf(this.set.values(),e=>Qe(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var kc=class{log;routers;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[]}async start(){await $r(...this.routers)}async stop(){await Kr(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new N("No content routers available","ERR_NO_ROUTERS_AVAILABLE");let n=new zo;for await(let o of mr(...$o(this.routers,"findProviders").map(i=>i.findProviders(e,t))))o!=null&&(n.has(o.id)||(n.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new N("No content routers available","ERR_NO_ROUTERS_AVAILABLE");await Promise.all($o(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all($o(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any($o(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new N("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");let n=this,o=mr(...$o(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new N("Could not find peer in routing","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new N("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");let n=new zo;for await(let o of mr(...$o(this.routers,"getClosestPeers").map(i=>i.getClosestPeers(e,t))))o!=null&&(n.has(o.id)||(n.add(o.id),yield o))}};function $o(r,e){return r.filter(t=>t[e]!=null)}var fn={},Ko=r=>{r.addEventListener("message",e=>{Ko.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Ko.dispatchEvent("message",r,e)})};Ko.addEventListener=(r,e)=>{fn[r]==null&&(fn[r]=[]),fn[r].push(e)};Ko.removeEventListener=(r,e)=>{fn[r]!=null&&(fn[r]=fn[r].filter(t=>t===e))};Ko.dispatchEvent=function(r,e,t){fn[r]!=null&&fn[r].forEach(n=>n(e,t))};var Mf=Ko;var zf="lock:worker:request-read",$f="lock:worker:release-read",Kf="lock:master:grant-read",qf="lock:worker:request-write",Gf="lock:worker:release-write",Wf="lock:master:grant-write";var Fg=(r=21)=>Math.random().toString().substring(2);var Vg=(r,e,t,n,o)=>(i,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(i.removeEventListener("message",u),c())};i.addEventListener("message",u)})}}}))},Hg=(r,e,t,n)=>async()=>{let o=Fg();return globalThis.postMessage({type:e,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===t&&c.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},i2={singleProcess:!1},Mg=r=>{if(r=Object.assign({},i2,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Mf.addEventListener("message",Vg(t,"requestReadLock",zf,$f,Kf)),Mf.addEventListener("message",Vg(t,"requestWriteLock",qf,Gf,Wf)),t}return{isWorker:!0,readLock:t=>Hg(t,zf,Kf,$f),writeLock:t=>Hg(t,qf,Wf,Gf)}};var Mn={},dn;async function jf(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Gi((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var s2=(r,e)=>{if(dn.isWorker===!0)return{readLock:dn.readLock(r,e),writeLock:dn.writeLock(r,e)};let t=new ut({concurrency:1}),n;return{async readLock(){if(n!=null)return jf(n,e);n=new ut({concurrency:e.concurrency,autoStart:!1});let o=n,i=jf(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,jf(t,e)}}},a2={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Yf(r){let e=Object.assign({},a2,r);return dn==null&&(dn=Mg(e),dn.isWorker!==!0&&(dn.addEventListener("requestReadLock",t=>{Mn[t.data.name]!=null&&Mn[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),dn.addEventListener("requestWriteLock",async t=>{Mn[t.data.name]!=null&&Mn[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Mn[e.name]==null&&(Mn[e.name]=s2(e.name,e)),Mn[e.name]}var Bc=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Yf({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await $r(this.child),this.started=!0}async stop(){await Kr(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),t)}finally{n()}}async has(e,t={}){let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}};var zg=42;function c2(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function l2(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=O.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new k(w.tag,zg),new k(w.bytes,t)]}function u2(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function f2(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 Xf={float64:!0,typeEncoders:{Object:l2,undefined:u2,number:f2}},s4={...Xf,typeEncoders:{...Xf.typeEncoders}};function d2(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return O.decode(r.subarray(1))}var Ic={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Ic.tags[zg]=d2;var a4={...Ic,tags:Ic.tags.slice()};var hn=113,Zi=r=>un(r,Xf),zn=r=>rt(c2(r),Ic);var Zf=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===w.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===w.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[w.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[w.negint.major](e,t){this[w.uint.major](e,t)}[w.bytes.major](e,t){throw new Error(`${Nr} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=ec(JSON.stringify(t.value));e.push(n.length>32?Di(n):n)}[w.array.major](e,t){this.prefix(e),this.inRecursive.push({type:w.array,elements:0}),e.push([91])}[w.map.major](e,t){this.prefix(e),this.inRecursive.push({type:w.map,elements:0}),e.push([123])}[w.tag.major](e,t){}[w.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===w.array)e.push([93]);else if(s.type===w.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Nr} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.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)),e.push(o)}};function h2(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Nr} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==w.string||n.type!==w.string)throw new Error(`${Nr} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Nr} unexpected duplicate map keys, this is not supported`)}var p2={addBreakTokens:!0,mapSorter:h2};function Qi(r,e){return e=Object.assign({},p2,e),_f(r,new Zf,e)}var pn=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,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 e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${z} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${z} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new k(w.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${z} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${z} 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(e,this._pos)),s=parseFloat(i);return n?new k(w.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new k(s>=0?w.uint:w.negint,s,this._pos-e):new k(s>=0?w.uint:w.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${z} 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 k(w.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${z} 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(`${z} 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(`${z} unexpected unicode sequence at position ${this._pos}`);let c,u,l,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],u=this.data[this._pos+2],(c&192)===128&&(u&192)===128&&(f=(i&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],u=this.data[this._pos+2],l=this.data[this._pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(f=(i&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.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(`${z} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${z} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new k(w.string,yf(t),this._pos-e);default:if(i<32)throw new Error(`${z} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${z} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new k(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new k(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new k(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new k(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new k(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(`${z} 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 k(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${z} 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 k(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 k(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${z} 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 k(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${z} 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"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${z} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function es(r,e){return e=Object.assign({tokenizer:new pn(r,e)},e),rt(r,e)}function m2(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function y2(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=O.asCID(r);if(!e)return null;let t=e.toString();return[new k(w.map,1/0,1),new k(w.string,"/",1),new k(w.string,t,t.length),new k(w.break,void 0,1)]}function Rc(r){let e=er.encode(r).slice(1);return[new k(w.map,1/0,1),new k(w.string,"/",1),new k(w.map,1/0,1),new k(w.string,"bytes",5),new k(w.string,e,e.length),new k(w.break,void 0,1),new k(w.break,void 0,1)]}function Wt(r){return Rc(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function g2(r){return Rc(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:y2,Buffer:Rc,Uint8Array:Rc,Int8Array:Wt,Uint16Array:Wt,Int16Array:Wt,Uint32Array:Wt,Int32Array:Wt,Float32Array:Wt,Float64Array:Wt,Uint8ClampedArray:Wt,BigInt64Array:Wt,BigUint64Array:Wt,DataView:Wt,ArrayBuffer:g2,undefined:w2,number:b2}},Jf=class extends pn{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===w.map){let t=this._next();if(t.type===w.string&&t.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 k(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=er.decode(`m${i.value}`);return new k(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Qf={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Qf.tags[42]=O.parse;var mn=297,Kg=r=>Qi(r,x2),Tc=r=>{let e=m2(r),t=Object.assign(Qf,{tokenizer:new Jf(e,Qf)});return es(e,t)};var _4=new TextDecoder;var A4=new TextEncoder;var Te={};xe(Te,{code:()=>ye,createLink:()=>e0,createNode:()=>Qg,decode:()=>we,encode:()=>re,name:()=>N2,prepare:()=>_e,validate:()=>rd});var E2=new TextDecoder;function ed(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Cc(r,e){let t;[t,e]=ed(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function qg(r,e){let t;return[t,e]=ed(r,e),[t&7,t>>3,e]}function v2(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=qg(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Cc(r,n)}else if(i===2){if(e.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(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=Cc(r,n),e.Name=E2.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=ed(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Gg(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=qg(r,t),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,t]=Cc(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,t]=Cc(r,t),n.push(v2(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var jg=new TextEncoder,Wg=2**32,S2=2**31;function _2(r,e){let t=e.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");t=ts(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=jg.encode(r.Name);t-=n.length,e.set(n,t),t=ts(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=ts(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Yg(r){let e=k2(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=ts(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=_2(r.Links[o],t.subarray(0,n));n-=i,n=ts(t,n,i)-1,t[n]=18}return t}function A2(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+qo(t)}if(typeof r.Name=="string"){let t=jg.encode(r.Name).length;e+=1+t+qo(t)}return typeof r.Tsize=="number"&&(e+=1+qo(r.Tsize)),e}function k2(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+qo(t)}if(r.Links)for(let t of r.Links){let n=A2(t);e+=1+n+qo(n)}return e}function ts(r,e,t){e-=qo(t);let n=e;for(;t>=S2;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function qo(r){return r%2===0&&r++,Math.floor((B2(r)+6)/7)}function B2(r){let e=0;return r>=Wg&&(r=Math.floor(r/Wg),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+I2[r]}var I2=[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 R2=["Data","Links"],T2=["Hash","Name","Tsize"],td=new TextEncoder;function Zg(r,e){if(r===e)return 0;let t=r.Name?td.encode(r.Name):[],n=e.Name?td.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function Xg(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Jg(r){if(typeof r.asCID=="object"){let t=O.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=O.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=O.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=O.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function _e(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 e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=td.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(Jg),e.Links.sort(Zg);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function rd(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Xg(r,R2))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 e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Xg(t,T2))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&Zg(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Qg(r,e=[]){return _e({Data:r,Links:e})}function e0(r,e,t){return Jg({Hash:t,Name:r,Tsize:e})}function t0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var N2="dag-pb",ye=112;function re(r){rd(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),Yg(e)}function we(r){let e=t0(r),t=Gg(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=O.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}var C2={codec:ye,*walk(r){yield*we(r).Links.map(t=>t.Hash)}},L2={codec:ge,*walk(){}},r0=42,D2={codec:hn,*walk(r){let e=[],t=[];t[r0]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let o=O.decode(n.subarray(1));return e.push(o),o},rt(r,{tags:t}),yield*e}},nd=class extends pn{tokenBuffer;constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===w.map){let t=this._next();if(t.type===w.string&&t.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 k(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=er.decode(`m${i.value}`);return new k(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},P2={codec:mn,*walk(r){let e=[],t=[];t[r0]=n=>{let o=O.parse(n);return e.push(o),o},es(r,{tags:t,tokenizer:new nd(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}},O2={codec:Wr,*walk(){}};function n0(r=[]){let e={};return[C2,L2,D2,P2,O2,...r].forEach(t=>{e[t.codec]=t}),e}var od=new ke("/version"),o0=1;async function i0(r){if(!await r.has(od)){await r.put(od,U(`${o0}`));return}let e=await r.get(od),t=W(e);if(parseInt(t,10)!==o0)throw new Error("Unknown datastore version, a datastore migration may be required")}function s0(r=[]){let e={};return[ce,Hl,Ge,...r].forEach(t=>{e[t.code]=t}),e}var lr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var $n={};xe($n,{abortedError:()=>M2,closeFailedError:()=>F2,deleteFailedError:()=>sd,getFailedError:()=>V2,hasFailedError:()=>H2,notFoundError:()=>yn,openFailedError:()=>U2,putFailedError:()=>id});var Dr=J(Ie(),1);function U2(r){return r=r??new Error("Open failed"),(0,Dr.default)(r,"ERR_OPEN_FAILED")}function F2(r){return r=r??new Error("Close failed"),(0,Dr.default)(r,"ERR_CLOSE_FAILED")}function id(r){return r=r??new Error("Put failed"),(0,Dr.default)(r,"ERR_PUT_FAILED")}function V2(r){return r=r??new Error("Get failed"),(0,Dr.default)(r,"ERR_GET_FAILED")}function sd(r){return r=r??new Error("Delete failed"),(0,Dr.default)(r,"ERR_DELETE_FAILED")}function H2(r){return r=r??new Error("Has failed"),(0,Dr.default)(r,"ERR_HAS_FAILED")}function yn(r){return r=r??new Error("Not Found"),(0,Dr.default)(r,"ERR_NOT_FOUND")}function M2(r){return r=r??new Error("Aborted"),(0,Dr.default)(r,"ERR_ABORTED")}var a0=0,Lc=class extends lr{put(e){return e}get(e){if(e.code===a0)return e.multihash.digest;throw yn()}has(e){return e.code===a0}delete(){}*getAll(){}};function z2(r){return r[Symbol.asyncIterator]!=null}function $2(r,e){if(z2(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Zn(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){await i&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let s=e;return function*(){i===!0&&(yield n);for(let a of t)s(a)&&(yield a)}()}var ht=$2;var K2=Q("blockstore:core:tiered"),rs=class extends lr{stores;constructor(e){super(),this.stores=e.slice()}async put(e,t,n){try{return await Promise.all(this.stores.map(async o=>{await o.put(e,t,n)})),e}catch(o){throw id(o)}}async get(e,t){for(let n of this.stores)try{let o=await n.get(e,t);if(o!=null)return o}catch(o){K2.error(o)}throw yn()}async has(e,t){for(let n of this.stores)if(await n.has(e,t))return!0;return!1}async delete(e,t){try{await Promise.all(this.stores.map(async n=>{await n.delete(e,t)}))}catch(n){throw sd(n)}}async*putMany(e,t={}){let n,o=this.stores.map(i=>{let s=Nt({objectMode:!0});return Ft(i.putMany(s,t)).catch(a=>{n=a}),s});try{for await(let i of e){if(n!=null)throw n;o.forEach(s=>s.push(i)),yield i.cid}}finally{o.forEach(i=>i.end())}}async*deleteMany(e,t={}){let n,o=this.stores.map(i=>{let s=Nt({objectMode:!0});return Ft(i.deleteMany(s,t)).catch(a=>{n=a}),s});try{for await(let i of e){if(n!=null)throw n;o.forEach(s=>s.push(i)),yield i}}finally{o.forEach(i=>i.end())}}async*getAll(e){let t=new Set;yield*ht(mr(...this.stores.map(n=>n.getAll(e))),n=>{let o=n.cid.toString();return t.has(o)?!1:(t.add(o),!0)})}};function q2(r){return typeof r.retrieve=="function"}function G2(r){return typeof r.announce=="function"}var Dc=class{child;blockRetrievers;blockAnnouncers;hashers;started;log;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.child=new rs([new Lc,e.blockstore]),this.blockRetrievers=(e.blockBrokers??[]).filter(q2),this.blockAnnouncers=(e.blockBrokers??[]).filter(G2),this.hashers=e.hashers??{},this.started=!1}isStarted(){return this.started}async start(){await $r(this.child,...new Set([...this.blockRetrievers,...this.blockAnnouncers])),this.started=!0}async stop(){await Kr(this.child,...new Set([...this.blockRetrievers,...this.blockAnnouncers])),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){return await this.child.has(e)?(n.onProgress?.(new F("blocks:put:duplicate",e)),e):(n.onProgress?.(new F("blocks:put:providers:notify",e)),this.blockAnnouncers.forEach(o=>{o.announce(e,t,n)}),n.onProgress?.(new F("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=ht(e,async({cid:i})=>{let s=await this.child.has(i);return s&&t.onProgress?.(new F("blocks:put-many:duplicate",i)),!s}),o=Al(n,({cid:i,block:s})=>{t.onProgress?.(new F("blocks:put-many:providers:notify",i)),this.blockAnnouncers.forEach(a=>{a.announce(i,s,t)})});t.onProgress?.(new F("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e)){t.onProgress?.(new F("blocks:get:providers:get",e));let n=await c0(e,this.blockRetrievers,this.hashers[e.multihash.code],{...t,log:this.log});return t.onProgress?.(new F("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),t.onProgress?.(new F("blocks:get:providers:notify",e)),this.blockAnnouncers.forEach(o=>{o.announce(e,n,t)}),n}return t.onProgress?.(new F("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new F("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Al(e,async n=>{if(t.offline!==!0&&!await this.child.has(n)){t.onProgress?.(new F("blocks:get-many:providers:get",n));let o=await c0(n,this.blockRetrievers,this.hashers[n.multihash.code],{...t,log:this.log});t.onProgress?.(new F("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new F("blocks:get-many:providers:notify",n)),this.blockAnnouncers.forEach(i=>{i.announce(n,o,t)})}}))}async delete(e,t={}){t.onProgress?.(new F("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new F("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new F("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},W2=(r,e)=>{if(e==null)throw new N(`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`,"ERR_UNKNOWN_HASH_ALG");return async t=>{let n=await e.digest(t);if(!ie(n.digest,r.multihash.digest))throw new N("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function c0(r,e,t,n){let o=W2(r,t),i=new AbortController,s=_n([i.signal,n.signal]);try{return await Promise.any(e.map(async a=>{try{let c=!1,u=await a.retrieve(r,{...n,signal:s,validateFn:async l=>{await o(l),c=!0}});return c||await o(u),u}catch(c){throw n.log.error("could not retrieve verified block for %c",r,c),c}}))}finally{s.clear()}}var Pc=class{blockstore;datastore;pins;logger;routing;dagWalkers;hashers;dns;log;constructor(e){this.logger=e.logger??xh(),this.log=this.logger.forComponent("helia"),this.hashers=s0(e.hashers),this.dagWalkers=n0(e.dagWalkers),this.dns=e.dns??Yi();let t={blockstore:e.blockstore,datastore:e.datastore,hashers:this.hashers,dagWalkers:this.dagWalkers,logger:this.logger,blockBrokers:[],dns:this.dns,...e.components??{}};t.blockBrokers=e.blockBrokers.map(o=>o(t));let n=new Dc(t);this.pins=new Ac(e.datastore,n,this.dagWalkers),this.blockstore=new Bc(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,this.routing=new kc(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[ci]!=null&&i.push(o[ci]),o[li]!=null&&i.push(o[li]),i})})}async start(){await i0(this.datastore),await $r(this.blockstore,this.datastore,this.routing)}async stop(){await Kr(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Ft(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new F("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new F("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};var ns=class extends lr{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(Fe.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(Fe.encode(e.multihash.bytes));if(t==null)throw yn();return t}has(e){return this.data.has(Fe.encode(e.multihash.bytes))}async delete(e){this.data.delete(Fe.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:O.createV1(ge,Je(Fe.decode(e))),block:t}}};var CD={...$n};var l0=J(Ie(),1);function Oc(r){return r=r??new Error("Not Found"),(0,l0.default)(r,"ERR_NOT_FOUND")}var u0="SHARDING";function Y2(r){return r[Symbol.asyncIterator]!=null}function X2(r){if(Y2(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var is=X2;function Z2(r){return r[Symbol.asyncIterator]!=null}function J2(r,e){return Z2(r)?async function*(){yield*(await is(r)).sort(e)}():function*(){yield*is(r).sort(e)}()}var Uc=J2;var Pr=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Ft(this.putMany(e,n)),e=[],await Ft(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=ht(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>ht(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>Uc(o,i),n)),e.offset!=null){let o=0,i=e.offset;n=ht(n,()=>o++>=i)}return e.limit!=null&&(n=Vs(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=ht(n,i=>i.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>ht(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>Uc(o,i),n)),e.offset!=null){let o=e.offset,i=0;n=ht(n,()=>i++>=o)}return e.limit!=null&&(n=Vs(n,e.limit)),n}};var ss=class extends Pr{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw Oc();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new ke(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new ke(e)}};var sP=new ke(u0);var wP=Q("datastore:core:tiered");async function d0(r={}){let e=r.datastore??new ss,t=r.blockstore??new ns,n=new Pc({...r,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[di()],routers:r.routers??[ji("https://delegated-ipfs.dev")]});return r.start!==!1&&await n.start(),n}var ad=J(Cs(),1);var cd=40;function ld(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=ad.default.decode(r);return e.seek(ad.default.decode.bytes),t}function ud(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var gn={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},as={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":gn.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(gn.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=as["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=as["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:gn.Int,CarV1HeaderOrV2Pragma:r=>{if(gn.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=as["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=as.Int(r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},cs={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":gn.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(gn.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=cs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=cs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:gn.Int,CarV1HeaderOrV2Pragma:r=>{if(gn.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=cs["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=cs.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},fd={toTyped:as.CarV1HeaderOrV2Pragma,toRepresentation:cs.CarV1HeaderOrV2Pragma};var rO=Sf();var o_=J(Cs(),1);var aO=[new k(w.map,2),new k(w.string,"version"),new k(w.uint,1),new k(w.string,"roots")],cO=new k(w.tag,42);async function dd(r,e){let t=ld(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=zn(n);if(fd.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);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=ud(await r.exactly(cd,!0));r.seek(i.dataOffset-r.pos);let s=await dd(r,1);return Object.assign(s,i)}function ls(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let o=r.subarray(e,e+t);return n&&(e+=t),o},seek(t){e+=t},get pos(){return e}}}var hd=J(Cs(),1),m0=1;function pd(r){let e=Zi({version:m0,roots:r}),t=hd.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function y0(r){return{async setRoots(e){let t=pd(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(hd.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return m0}}}function Fc(){}function g0(){let r=[],e=null,t=Fc,n=!1,o=null,i=Fc,s=()=>(e||(e=new Promise(u=>{t=()=>{e=null,t=Fc,u()}})),e),a={write(u){r.push(u);let l=s();return i(),l},async end(){n=!0;let u=s();i(),await u}},c={async next(){let u=r.shift();return u?(r.length===0&&t(),{done:!1,value:u}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(l=>{i=()=>(o=null,i=Fc,l(c.next()))})),o)}};return{writer:a,iterator:c}}var us=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=O.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.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(e){e=c_(e);let{encoder:t,iterator:n}=w0(),o=new r(e,t),i=new Vc(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=w0();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new Vc(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=ls(e);await dd(n);let o=pd(t);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 e.set(o,0),e}},Vc=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function w0(){let r=g0(),{writer:e,iterator:t}=r;return{encoder:y0(e),iterator:t}}function c_(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=O.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=O.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var l_=1,md=class{components;constructor(e,t){this.components=e}async import(e,t){await Ft(this.components.blockstore.putMany(We(e.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),t))}async export(e,t,n){let o=ve(),i=Array.isArray(e)?e:[e],s=new ut({concurrency:l_});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#e(a,s,async(c,u)=>{await t.put({cid:c,bytes:u})},n)}).catch(()=>{});try{await o.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:o}=us.create(e);this.export(e,n,t).catch(()=>{});for await(let i of o)yield i}async#e(e,t,n,o){let i=this.components.dagWalkers[e.code];if(i==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.components.blockstore.get(e,o);await n(e,s);for await(let a of i.walk(s))t.add(async()=>{await this.#e(a,t,n,o)})}};function b0(r,e={}){return new md(r,e)}var yd=J(Ja(),1);function x0(r,e){let t=e.map((n,o)=>({record:Ye(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===He.ValidityType.EOL&&o.record.validityType===He.ValidityType.EOL){let a=yd.default.fromString(n.record.validity).toDate(),c=yd.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var u_=32;async function E0(r,e,t,n,o={}){if(e===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=(await t.query(r,{...o,types:[dt.TXT]})).Answer.sort((u,l)=>u.data.localeCompare(l.data));n("found %d TXT records for %s",s.length,r);for(let u of s)try{let l=u.data;if(l.startsWith('"')&&l.endsWith('"')&&(l=l.substring(1,l.length-1)),!l.startsWith("dnslink="))continue;n("%s TXT %s",u.name,l),l=l.replace("dnslink=","");let[,f,m,...d]=l.split("/");if(f==="ipfs")try{return{value:`/ipfs/${O.parse(m)}${d.length>0?`/${d.join("/")}`:""}`,answer:u}}catch{}else if(f==="ipns"){try{return{value:`/ipns/${Qe(m)}${d.length>0?`/${d.join("/")}`:""}`,answer:u}}catch{}return await Hc(m,e-1,t,n,o)}else{if(f==="dnslink")return await Hc(m,e-1,t,n,o);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(l){n.error("could not parse DNS link record for domain %s, %s",r,u.data,l)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=(await t.query(r,{...o,types:[dt.CNAME]})).Answer.sort((u,l)=>u.data.localeCompare(l.data));n("found %d CNAME records for %s",c.length,r);for(let u of c)try{return await Hc(u.data,e-1,t,n,o)}catch(l){n.error("domain %s cname %s had no DNSLink records",r,u.data,l)}throw new N(`No DNSLink records found for domain: ${r}`,"ERR_DNSLINK_NOT_FOUND")}async function Hc(r,e,t,n,o={}){if(e===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await E0(r,e,t,n,o)}catch(i){if(i.code!=="ENOTFOUND"&&i.code!=="ERR_DNSLINK_NOT_FOUND"&&i.code!=="ENODATA")throw i;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,await E0(r,e,t,n,o)}}async function v0(r,e,t,n={}){return Hc(r,n.maxRecursiveDepth??u_,e,t,n)}var gd=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(o){n.onProgress?.(new F("ipns:routing:helia:error",o))}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){t.onProgress?.(new F("ipns:routing:helia:error",n))}throw new Error("Not found")}};function S0(r){return new gd(r)}var fs;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.key!=null&&t.key.byteLength>0&&(n.uint32(10),n.bytes(t.key)),t.value!=null&&t.value.byteLength>0&&(n.uint32(18),n.bytes(t.value)),t.timeReceived!=null&&t.timeReceived!==""&&(n.uint32(42),n.string(t.timeReceived)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={key:kt(0),value:kt(0),timeReceived:""},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.key=t.bytes();break}case 2:{i.value=t.bytes();break}case 5:{i.timeReceived=t.string();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Rt(t,r.codec()),r.decode=(t,n)=>Bt(t,r.codec(),n)})(fs||(fs={}));function _0(r){let e=r.getUTCFullYear(),t=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`${e}-${t}-${n}T${o}:${i}:${s}.${c}Z`}function A0(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),o=parseInt(t[2],10)-1,i=parseInt(t[3],10),s=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),u=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,u))}var Or=class r{key;value;timeReceived;constructor(e,t,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return fs.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:_0(this.timeReceived)}}static deserialize(e){let t=fs.decode(e);return new r(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=A0(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new r(e.key,e.value,t)}};var Mc=globalThis.CustomEvent??Event;async function*Kn(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,i=[],s=ve(),a=ve(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(i.length===t&&(s=ve(),await s.promise),l)break;let h={done:!1};i.push(h),p().then(y=>{h.done=!0,h.ok=!0,h.value=y,o.dispatchEvent(new Mc("task-complete"))},y=>{h.done=!0,h.err=y,o.dispatchEvent(new Mc("task-complete"))})}c=!0,o.dispatchEvent(new Mc("task-complete"))}catch(p){u=p,o.dispatchEvent(new Mc("task-complete"))}});function f(){return n?i[0]?.done:!!i.find(p=>p.done)}function*m(){for(;i.length>0&&i[0].done;){let p=i[0];if(i.shift(),p.ok)yield p.value;else throw l=!0,s.resolve(),p.err;s.resolve()}}function*d(){for(;f();)for(let p=0;p<i.length;p++)if(i[p].done){let h=i[p];if(i.splice(p,1),p--,h.ok)yield h.value;else throw l=!0,s.resolve(),h.err;s.resolve()}}for(;;){if(f()||(a=ve(),await a.promise),u!=null)throw u;if(n?yield*m():yield*d(),c&&i.length===0)break}}var k0;(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"})(k0||(k0={}));function zc(r){return new ke("/dht/record/"+W(r,"base32"),!1)}function B0(r){return{async put(e,t,n={}){try{let o=zc(e);try{let s=await r.get(o),a=Or.deserialize(s);if(ie(a.value,t))return}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}let i=new Or(e,t,new Date);n.onProgress?.(new F("ipns:routing:datastore:put")),await r.put(o,i.serialize(),n)}catch(o){throw n.onProgress?.(new F("ipns:routing:datastore:error",o)),o}},async get(e,t={}){try{let n=zc(e);t.onProgress?.(new F("ipns:routing:datastore:get"));let o=await r.get(n,t),i=Or.deserialize(o);return{record:i.value,created:i.timeReceived}}catch(n){throw t.onProgress?.(new F("ipns:routing:datastore:error",n)),n}},async has(e,t={}){let n=zc(e);return r.has(n,t)},async delete(e,t){let n=zc(e);return r.delete(n,t)}}}var Ur=Q("helia:ipns"),d_=60*1e3,xd=60*d_,h_=24*xd,wd=23*xd,p_=BigInt(xd)*1000000n,bd=class{routers;localStore;timeout;dns;log;constructor(e,t=[]){this.routers=[S0(e.routing),...t],this.localStore=B0(e.datastore),this.dns=e.dns,this.log=e.logger.forComponent("helia:ipns")}async publish(e,t,n={}){try{let o=1n,i=Ho(e);if(await this.localStore.has(i,n)){let{record:c}=await this.localStore.get(i,n);o=Ye(c).sequence+1n}let s=await gg(e,t,o,n.lifetime??h_,n),a=Lr(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 F("ipns:publish:error",o)),o}}async resolve(e,t={}){let n=Ho(e),o=await this.#t(n,t);return{...await this.#e(o.value,t),record:o}}async resolveDNSLink(e,t={}){let n=await v0(e,this.dns,this.log,t);return{...await this.#e(n.value,t),answer:n.answer}}republish(e={}){if(this.timeout!=null)throw new Error("Republish is already running");e.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function t(){let n=Date.now();e.onProgress?.(new F("ipns:republish:start"));let i=Date.now()-n,s=wd-i;s<0&&(s=e.interval??wd),setTimeout(()=>{t().catch(a=>{Ur.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{t().catch(n=>{Ur.error("error republishing",n)})},e.interval??wd)}async#e(e,t={}){let n=e.split("/");try{let o=n[1];if(o==="ipns"){let{cid:i}=await this.resolve(Qe(n[2]),t),s=n.slice(3).join("/");return{cid:i,path:s}}else if(o==="ipfs"){let i=O.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",e),new Error("Invalid value")}async#t(e,t={}){let n=[];if(await this.localStore.has(e,t))if(Ur("record is present in the cache"),t.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await zi(e,a),this.log("record was valid");let u=Ye(a),l=Number((u.ttl??p_)/1000000n);if(c.getTime()+l>Date.now())return this.log("record TTL was valid"),u;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),u;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(e,t)}else Ur("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new N("Record was not present in the cache or has expired","ERR_NOT_FOUND");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(e,{...t,validate:!1})}catch(u){Ur.error("error finding IPNS record",u);return}try{await zi(e,c),n.push(c)}catch(u){i++,Ur.error("error finding IPNS record",u)}})),n.length===0)throw i>0?new N(`${i>1?`${i} records`:"Record"} found for routing key ${i>1?"were":"was"} invalid`,"ERR_RECORDS_FAILED_VALIDATION"):new N("Could not find record for routing key","ERR_NOT_FOUND");let s=n[x0(e,n)];return await this.localStore.put(e,s,t),Ye(s)}};function I0(r,{routers:e=[]}={}){return new bd(r,e)}var kd=J(Ie(),1);function m_(r){return r[Symbol.asyncIterator]!=null}function y_(r,e=1){return e=Number(e),m_(r)?async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}():function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}()}var $c=y_;async function*ds(r,e=1){for await(let t of $c(r,e)){let n=t.map(async o=>o().then(i=>({ok:!0,value:i}),i=>({ok:!1,err:i})));for(let o=0;o<n.length;o++){let i=await n[o];if(i.ok)yield i.value;else throw i.err}}}var g_=262144,hs=(r={})=>{let e=r.chunkSize??g_;return async function*(n){let o=new Vt,i=0,s=!1;for await(let a of n)for(o.append(a),i+=a.length;i>=e;)if(yield o.slice(0,e),s=!0,e===o.length)o=new Vt,i=0;else{let c=new Vt;c.append(o.sublist(e)),o=c,i-=e}(!s||i>0)&&(yield o.subarray(0,i))}};var Ed=J(Ie(),1);var jt;(function(r){let e;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(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"})(t||(t={})),function(o){o.codec=()=>Tn(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=Tt((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),Kc.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=Kc.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>Rt(o,r.codec()),r.decode=o=>Bt(o,r.codec())})(jt||(jt={}));var Kc;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>Rt(t,r.codec()),r.decode=t=>Bt(t,r.codec())})(Kc||(Kc={}));var R0;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.MimeType=t.string();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>Rt(t,r.codec()),r.decode=t=>Bt(t,r.codec())})(R0||(R0={}));var T0={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},w_=["directory","hamt-sharded-directory"],N0=parseInt("0644",8),C0=parseInt("0755",8),q=class r{static unmarshal(e){let t=jt.decode(e),n=new r({type:T0[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(T0).includes(t))throw(0,Ed.default)(new Error("Type: "+t+" is not valid"),"ERR_INVALID_TYPE");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?C0:N0:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return w_.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=jt.DataType.Raw;break;case"directory":e=jt.DataType.Directory;break;case"file":e=jt.DataType.File;break;case"metadata":e=jt.DataType.Metadata;break;case"symlink":e=jt.DataType.Symlink;break;case"hamt-sharded-directory":e=jt.DataType.HAMTShard;break;default:throw(0,Ed.default)(new Error(`Type: ${e} is not valid`),"ERR_INVALID_TYPE")}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===N0&&!this.isDirectory()&&(n=void 0),n===C0&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),jt.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var Yt=async(r,e,t)=>{t.codec==null&&(t.codec=Te);let n=await ce.digest(r),o=O.create(t.cidVersion,t.codec.code,n);return await e.put(o,r,t),o};function L0(r){return async function*(t,n){let o=0n;for await(let i of t.content)yield async()=>{let s,a={codec:Te,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=It,a.cidVersion=1):(s=new q({type:r.leafType,data:i}),i=re({Data:s.marshal(),Links:[]}));let c=await Yt(i,n,a);return o+=BigInt(i.byteLength),r.onProgress?.(new F("unixfs:importer:progress:file:write",{bytesWritten:o,cid:c,path:t.path})),{cid:c,unixfs:s,size:BigInt(i.length),block:i}}}}var vd=J(Ie(),1);var D0=async(r,e,t)=>{let n=new q({type:"directory",mtime:r.mtime,mode:r.mode}),o=re(_e({Data:n.marshal()})),i=await Yt(o,e,t),s=r.path;return{cid:i,path:s,unixfs:n,size:BigInt(o.length),originalPath:r.originalPath,block:o}};async function*b_(r,e,t){let n=-1,o;for await(let i of ds(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){o={...i,single:!0};continue}else n===1&&o!=null&&(yield{...o,block:void 0,single:void 0},o=void 0);yield{...i,block:void 0}}o!=null&&(yield o)}function P0(r){return r.single===!0}var x_=(r,e,t)=>async function(o){if(o.length===1&&P0(o[0])&&t.reduceSingleLeafToSelf){let l=o[0],f=l.block;return P0(l)&&(r.mtime!==void 0||r.mode!==void 0)&&(l.unixfs=new q({type:"file",mtime:r.mtime,mode:r.mode,data:l.block}),f={Data:l.unixfs.marshal(),Links:[]},l.block=re(_e(f)),l.cid=await Yt(l.block,e,{...t,cidVersion:t.cidVersion}),l.size=BigInt(l.block.length)),t.onProgress?.(new F("unixfs:importer:progress:file:layout",{cid:l.cid,path:l.originalPath})),{cid:l.cid,path:r.path,unixfs:l.unixfs,size:l.size,originalPath:l.originalPath}}let i=new q({type:"file",mtime:r.mtime,mode:r.mode}),s=o.filter(l=>l.cid.code===ge&&l.size>0||l.unixfs!=null&&l.unixfs.data==null&&l.unixfs.fileSize()>0n?!0:!!l.unixfs?.data?.length).map(l=>l.cid.code===ge?(i.addBlockSize(l.size),{Name:"",Tsize:Number(l.size),Hash:l.cid}):(l.unixfs==null||l.unixfs.data==null?i.addBlockSize(l.unixfs?.fileSize()??0n):i.addBlockSize(BigInt(l.unixfs.data.length)),{Name:"",Tsize:Number(l.size),Hash:l.cid})),a={Data:i.marshal(),Links:s},c=re(_e(a)),u=await Yt(c,e,t);return t.onProgress?.(new F("unixfs:importer:progress:file:layout",{cid:u,path:r.originalPath})),{cid:u,path:r.path,unixfs:i,size:BigInt(c.length+a.Links.reduce((l,f)=>l+(f.Tsize??0),0)),originalPath:r.originalPath,block:c}},O0=async(r,e,t)=>t.layout(b_(r,e,t),x_(r,e,t));function E_(r){return Symbol.iterator in r}function v_(r){return Symbol.asyncIterator in r}function S_(r){try{if(r instanceof Uint8Array)return async function*(){yield r}();if(E_(r))return async function*(){yield*r}();if(v_(r))return r}catch{throw(0,vd.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}throw(0,vd.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}function U0(r){return async function*(t,n){for await(let o of t){let i;if(o.path!=null&&(i=o.path,o.path=o.path.split("/").filter(s=>s!=null&&s!==".").join("/")),__(o)){let s={path:o.path,mtime:o.mtime,mode:o.mode,content:async function*(){let a=0n;for await(let c of r.chunker(r.chunkValidator(S_(o.content)))){let u=BigInt(c.byteLength);a+=u,r.onProgress?.(new F("unixfs:importer:progress:file:read",{bytesRead:a,chunkSize:u,path:o.path})),yield c}}(),originalPath:i};yield async()=>O0(s,n,r)}else if(o.path!=null){let s={path:o.path,mtime:o.mtime,mode:o.mode,originalPath:i};yield async()=>D0(s,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function __(r){return r.content!=null}var Sd=J(Ie(),1);var F0=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw(0,Sd.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT");if(typeof t=="string"||t instanceof String)yield U(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw(0,Sd.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}};var A_=174;function ps(r){let e=r?.maxChildrenPerNode??A_;return async function t(n,o){let i=[];for await(let s of $c(n,e))i.push(await o(s));return i.length>1?t(i,o):i[0]}}var ur=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},ms=O.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),ys=O.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var qn=class extends ur{_children;constructor(e,t){super(e,t),this._children=new Map}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(e,t)}async get(e){return Promise.resolve(this._children.get(e))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}async*eachChildSeries(){for(let[e,t]of this._children.entries())yield{key:e,child:t}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[e,t]of this._children.entries())t.size!=null&&t.cid!=null&&(this.nodeSize+=e.length+(this.options.cidVersion===1?ys.bytes.byteLength:ms.bytes.byteLength));return this.nodeSize}async*flush(e){let t=[];for(let[c,u]of this._children.entries()){let l=u;if(u instanceof ur)for await(let f of u.flush(e))l=f,yield f;l.size!=null&&l.cid!=null&&t.push({Name:c,Tsize:Number(l.size),Hash:l.cid})}let n=new q({type:"directory",mtime:this.mtime,mode:this.mode}),o={Data:n.marshal(),Links:t},i=re(_e(o)),s=await Yt(i,e,this.options),a=i.length+o.Links.reduce((c,u)=>c+(u.Tsize==null?0:u.Tsize),0);this.cid=s,this.size=a,yield{cid:s,unixfs:n,path:this.path,size:BigInt(a)}}};var Gc=J(M0(),1);function k_(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var A5=An({name:"murmur3-32",code:35,encode:r=>k_(Gc.default.x86.hash32(r))}),Gn=An({name:"murmur3-128",code:34,encode:r=>Jn.fromHex(Gc.default.x64.hash128(r))}),k5=An({name:"murmur3-x64-64",code:34,encode:r=>Jn.fromHex(Gc.default.x64.hash128(r)).subarray(0,8)});var K0=J(Wc(),1);var vt=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new K0.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(e,t)):o.push(e(i,s))),o),n))}async asyncTransform(e,t){return q0(this,e,t)}toJSON(){return this.serialize(N_,C_)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?U(e):e),n=await t.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:o}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let o=await n._findPlace(t.existingChild.hash);return o.bucket._putAt(o,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(T_);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function T_(r){return!!r}function N_(r,e){return r.key}function C_(r){return r}async function q0(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof vt)await q0(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var L_=[255,254,252,248,240,224,192,128],D_=[1,3,7,15,31,63,127,255],jc=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=P_(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function P_(r,e,t){let n=O_(e,t);return(r&n)>>>e}function O_(r,e){return L_[r]&D_[Math.min(e+r-1,7)]}function G0(r){function e(t){return t instanceof Yc?t:new Yc(t,r)}return e}var Yc=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?ue([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new jc(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Go(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:G0(r.hashFn)};return new vt(e)}async function U_(r){return(await Gn.encode(r)).slice(0,8).reverse()}var W0=BigInt(34),F_=8,_d=class extends ur{_bucket;constructor(e,t){super(e,t),this._bucket=Go({hashFn:U_,bits:t.shardFanoutBits??F_})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=X0(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of Y0(this._bucket,e,this,this.options))yield{...t,path:this.path}}},j0=_d;async function*Y0(r,e,t,n){let o=r._children,i=(r.tableSize()-1).toString(16).length,s=[],a=0n;for(let p=0;p<o.length;p++){let h=o.get(p);if(h==null)continue;let y=p.toString(16).toUpperCase().padStart(i,"0");if(h instanceof vt){let g;for await(let b of Y0(h,e,null,n))g=b;if(g==null)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:y,Tsize:Number(g.size),Hash:g.cid}),a+=g.size}else if(V_(h.value)){let g=h.value,b;for await(let v of g.flush(e))b=v,yield b;if(b==null)throw new Error("Did not flush dir");let x=y+h.key;s.push({Name:x,Tsize:Number(b.size),Hash:b.cid}),a+=b.size}else{let g=h.value;if(g.cid==null)continue;let b=y+h.key,x=g.size;s.push({Name:b,Tsize:Number(x),Hash:g.cid}),a+=BigInt(x??0)}}let c=Uint8Array.from(o.bitField().reverse()),u=new q({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:W0,mtime:t?.mtime,mode:t?.mode}),l={Data:u.marshal(),Links:s},f=re(_e(l)),m=await Yt(f,e,n),d=BigInt(f.byteLength)+a;yield{cid:m,unixfs:u,size:d}}function V_(r){return typeof r.flush=="function"}function X0(r,e,t){let n=r._children,o=(r.tableSize()-1).toString(16).length,i=[];for(let u=0;u<n.length;u++){let l=n.get(u);if(l==null)continue;let f=u.toString(16).toUpperCase().padStart(o,"0");if(l instanceof vt){let m=X0(l,null,t);i.push({Name:f,Tsize:Number(m),Hash:t.cidVersion===0?ms:ys})}else if(typeof l.value.flush=="function"){let d=l.value.nodeSize();i.push({Name:f+l.key,Tsize:Number(d),Hash:t.cidVersion===0?ms:ys})}else{let m=l.value;if(m.cid==null)continue;let d=f+l.key,p=m.size;i.push({Name:d,Tsize:Number(p),Hash:m.cid})}}let s=Uint8Array.from(n.bitField().reverse()),a=new q({type:"hamt-sharded-directory",data:s,fanout:BigInt(r.tableSize()),hashType:W0,mtime:e?.mtime,mode:e?.mode});return re(_e({Data:a.marshal(),Links:i})).length}async function Ad(r,e,t,n){let o=e;e instanceof qn&&e.estimateNodeSize()>t&&(o=await H_(e,n));let i=o.parent;if(i!=null){if(o!==e){if(r!=null&&(r.parent=o),o.parentKey==null)throw new Error("No parent key found");await i.put(o.parentKey,o)}return Ad(o,i,t,n)}return o}async function H_(r,e){let t=new j0({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for await(let{key:n,child:o}of r.eachChildSeries())await t.put(n,o);return t}var Z0=(r="")=>r.split(/(?<!\\)\//).filter(Boolean);async function M_(r,e,t){let n=Z0(r.path??""),o=n.length-1,i=e,s="";for(let a=0;a<n.length;a++){let c=n[a];s+=`${s!==""?"/":""}${c}`;let u=a===o;if(i.dirty=!0,i.cid=void 0,i.size=void 0,u)await i.put(c,r),e=await Ad(null,i,t.shardSplitThresholdBytes,t);else{let l=await i.get(c);(l==null||!(l instanceof ur))&&(l=new qn({root:!1,dir:!0,parent:i,parentKey:c,path:s,dirty:!0,flat:!0,mtime:l?.unixfs?.mtime,mode:l?.unixfs?.mode},t)),await i.put(c,l),i=l}}return e}async function*J0(r,e){if(!(r instanceof ur)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function Q0(r){return async function*(t,n){let o=new qn({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),i,s=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(i==null?(i=c,s=!0):i!==c&&(s=!1)),o=await M_(a,o,r),(a.unixfs==null||!a.unixfs.isDirectory())&&(yield a)}if(r.wrapWithDirectory||s&&o.childCount()>1)yield*J0(o,n);else for await(let a of o.eachChildSeries())a!=null&&(yield*J0(a.child,n))}}async function*wn(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let o=t.wrapWithDirectory??!1,i=t.shardSplitThresholdBytes??262144,s=t.shardFanoutBits??8,a=t.cidVersion??1,c=t.rawLeaves??!0,u=t.leafType??"file",l=t.fileImportConcurrency??50,f=t.blockWriteConcurrency??10,m=t.reduceSingleLeafToSelf??!0,d=t.chunker??hs(),p=t.chunkValidator??F0(),h=t.dagBuilder??U0({chunker:d,chunkValidator:p,wrapWithDirectory:o,layout:t.layout??ps(),bufferImporter:t.bufferImporter??L0({cidVersion:a,rawLeaves:c,leafType:u,onProgress:t.onProgress}),blockWriteConcurrency:f,reduceSingleLeafToSelf:m,cidVersion:a,onProgress:t.onProgress}),y=t.treeBuilder??Q0({wrapWithDirectory:o,shardSplitThresholdBytes:i,shardFanoutBits:s,cidVersion:a,onProgress:t.onProgress});for await(let g of y(ds(h(n,e),l),e))yield{cid:g.cid,path:g.path,unixfs:g.unixfs,size:g.size}}async function Xc(r,e,t={}){let n=await Hn(wn([r],e,t));if(n==null)throw(0,kd.default)(new Error("Nothing imported"),"ERR_INVALID_PARAMS");return n}async function ew(r,e,t={}){let n=await Hn(wn([r],e,t));if(n==null)throw(0,kd.default)(new Error("Nothing imported"),"ERR_INVALID_PARAMS");return n}async function tw(r,e,t={}){return Xc({content:r},e,t)}async function rw(r,e,t={}){return Xc({content:r},e,t)}var ws={cidVersion:1,rawLeaves:!0,layout:ps({maxChildrenPerNode:1024}),chunker:hs({chunkSize:1048576})};async function*nw(r,e,t={}){yield*wn(r,e,{...ws,...t})}async function ow(r,e,t={}){let{cid:n}=await tw(r,e,{...ws,...t});return n}async function iw(r,e,t={}){let{cid:n}=await rw(r,e,{...ws,...t});return n}async function sw(r,e,t={}){let{cid:n}=await Xc(r,e,{...ws,...t});return n}async function aw(r,e,t={}){let{cid:n}=await ew({...r,path:r.path??"-"},e,{...ws,...t});return n}var Jc=J(Ie(),1);function z_(r){return r[Symbol.asyncIterator]!=null}function $_(r){if(z_(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var bn=$_;var _w=J(Ie(),1);var cw=J(Ie(),1);function Wo(r,e,t,n,o,i,s){let a=r,c=o;for(;i.length>0;){let u=i[0];if(u in a){i.shift(),c=`${c}/${u}`;let l=O.asCID(a[u]);if(l!=null)return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:l,name:u,path:c,toResolve:i}};a=a[u]}else throw(0,cw.default)(new Error(`No property named ${u} found in node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var K_=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),u=zn(c);return Wo(u,c,r,e,t,n,i)},lw=K_;var q_=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),u=Tc(c);return Wo(u,c,r,e,t,n,i)},uw=q_;var fw=J(Ie(),1);function G_(r,e,t,n){let o=BigInt(r.length),i=BigInt(e+o);return t>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(r=r.subarray(0,Number(n-e))),t>=e&&t<i&&(r=r.subarray(Number(t-e))),r)}var Wn=G_;var bs=J(Ie(),1),W_=(r,e=0,t=r)=>{let n=BigInt(r),o=BigInt(e??0),i=BigInt(t);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw(0,bs.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(o>n)throw(0,bs.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(i<0n)throw(0,bs.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,bs.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:o,end:i}},jo=W_;var j_=r=>{async function*e(t={}){let{start:n,end:o}=jo(r.length,t.offset,t.length),i=Wn(r,0n,n,o);t.onProgress?.(new F("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},Y_=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,fw.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=Je(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:j_(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},dw=Y_;var X_=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),u=Hh(c);return Wo(u,c,r,e,t,n,i)},hw=X_;var pw=J(Ie(),1);var Z_=r=>{async function*e(t={}){let{start:n,end:o}=jo(r.length,t.offset,t.length),i=Wn(r,0n,n,o);t.onProgress?.(new F("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},J_=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,pw.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:Z_(c),depth:i,size:BigInt(c.length),node:c}}},mw=J_;var Es=J(Ie(),1);var xs=J(Ie(),1);var Q_=async function(r){return(await Gn.encode(r)).slice(0,8).reverse()},eA=async(r,e,t)=>{let n=(e.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);e._putObjectAt(i,new vt({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},yw=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),tA=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},gw=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw(0,xs.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let f;try{f=q.unmarshal(r.Data)}catch(d){throw(0,xs.default)(d,"ERR_NOT_UNIXFS")}if(f.type!=="hamt-sharded-directory")throw(0,xs.default)(new Error("not a HAMT"),"ERR_NOT_UNIXFS");if(f.fanout==null)throw(0,xs.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let m=Go({hashFn:Q_,bits:Math.log2(Number(f.fanout))});n={rootBucket:m,hamtDepth:1,lastBucket:m}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await eA(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=yw(s.pos,i),c=tA(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=yw(n.lastBucket._posAtParent,i));let u=r.Links.find(f=>{if(f.Name==null)return!1;let m=f.Name.substring(0,i),d=f.Name.substring(i);return!(m!==a||d!==""&&d!==e)});if(u==null)return;if(u.Name!=null&&u.Name.substring(i)===e)return u.Hash;n.hamtDepth++;let l=await t.get(u.Hash,o);return r=we(l),gw(r,e,t,n,o)},ww=gw;var rA=(r,e,t,n,o,i,s)=>{async function*a(c={}){let u=c.offset??0,l=c.length??e.Links.length,f=e.Links.slice(u,l);c.onProgress?.(new F("unixfs:exporter:walk:directory",{cid:r})),yield*at(f,m=>We(m,d=>async()=>{let p=d.Name??"",h=`${n}/${p}`;return(await o(d.Hash,p,h,[],i+1,s,c)).entry}),m=>Kn(m,{ordered:!0,concurrency:c.blockReadConcurrency}),m=>ht(m,d=>d!=null))}return a},bw=rA;var jn=J(Ie(),1);async function xw(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let u=Wn(e,n,o,i);t.push(u);return}if(e.Data==null)throw(0,jn.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=q.unmarshal(e.Data)}catch(u){throw(0,jn.default)(u,"ERR_NOT_UNIXFS")}if(a.data!=null){let u=a.data,l=Wn(u,n,o,i);t.push(l),n+=BigInt(l.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw(0,jn.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let u=0;u<e.Links.length;u++){let l=e.Links[u],f=n,m=f+a.blockSizes[u];if((o>=f&&o<m||i>=f&&i<=m||o<f&&i>m)&&c.push({link:l,blockStart:n}),n=m,n>i)break}await at(c,u=>We(u,l=>async()=>{let f=await r.get(l.link.Hash,s);return{...l,block:f}}),u=>Kn(u,{ordered:!0,concurrency:s.blockReadConcurrency}),async u=>{for await(let{link:l,block:f,blockStart:m}of u){let d;switch(l.Hash.code){case ye:d=we(f);break;case ge:d=f;break;default:t.end((0,jn.default)(new Error(`Unsupported codec: ${l.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new ut({concurrency:1});p.on("error",h=>{t.end(h)}),p.add(async()=>{s.onProgress?.(new F("unixfs:exporter:walk:file",{cid:l.Hash})),await xw(r,d,t,m,o,i,s)}),await p.onIdle()}}),n>=i&&t.end()}var nA=(r,e,t,n,o,i,s)=>{async function*a(c={}){let u=t.fileSize();if(u===void 0)throw new Error("File was a directory");let{start:l,end:f}=jo(u,c.offset,c.length);if(f===0n)return;let m=0n,d=f-l,p=Nt();c.onProgress?.(new F("unixfs:exporter:walk:file",{cid:r})),xw(s,e,p,0n,l,f,c).catch(h=>{p.end(h)});for await(let h of p)if(h!=null){if(m+=BigInt(h.byteLength),m>d)throw p.end(),(0,jn.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"),"ERR_OVER_READ");m===d&&p.end(),c.onProgress?.(new F("unixfs:exporter:progress:unixfs:file",{bytesRead:m,totalBytes:d,fileSize:u})),yield h}if(m<d)throw(0,jn.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return a},Bd=nA;var Zc=J(Ie(),1);var oA=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new F("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),Ew(e,n,o,i,s,c)}return a};async function*Ew(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw(0,Zc.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=q.unmarshal(r.Data)}catch(l){throw(0,Zc.default)(l,"ERR_NOT_UNIXFS")}if(a.fanout==null)throw(0,Zc.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let c=(a.fanout-1n).toString(16).length,u=at(s,l=>We(l,f=>async()=>{let m=f.Name!=null?f.Name.substring(c):null;if(m!=null&&m!==""){let d=await t(f.Hash,m,`${e}/${m}`,[],n+1,o,i);return{entries:d.entry==null?[]:[d.entry]}}else{let d=await o.get(f.Hash,i);return r=we(d),i.onProgress?.(new F("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:Ew(r,e,t,n,o,i)}}}),l=>Kn(l,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:l}of u)yield*l}var vw=oA;var iA=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,sA={raw:Bd,file:Bd,directory:bw,"hamt-sharded-directory":vw,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},aA=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),u=we(c),l,f;if(e==null&&(e=r.toString()),u.Data==null)throw(0,Es.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{l=q.unmarshal(u.Data)}catch(d){throw(0,Es.default)(d,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let d;if(l?.type==="hamt-sharded-directory"?d=await ww(u,n[0],s):d=iA(u,n[0]),d==null)throw(0,Es.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),h=`${t}/${p}`;f={cid:d,toResolve:n,name:p??"",path:h}}let m=sA[l.type](r,u,l,t,o,i,s);if(m==null)throw(0,Es.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return l.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:m,unixfs:l,depth:i,node:u,size:l.fileSize()},next:f}:{entry:{type:"file",name:e,path:t,cid:r,content:m,unixfs:l,depth:i,node:u,size:l.fileSize()},next:f}},Sw=aA;var cA={[ye]:Sw,[ge]:mw,[hn]:lw,[mn]:uw,[Ge.code]:dw,[Wr]:hw},Aw=async(r,e,t,n,o,i,s)=>{let a=cA[r.code];if(a==null)throw(0,_w.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return a(r,e,t,n,Aw,o,i,s)},kw=Aw;var lA=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),uA=r=>{if(r instanceof Uint8Array)return{cid:O.decode(r),toResolve:[]};let e=O.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=lA(r);return{cid:O.parse(t[0]),toResolve:t.slice(1)}}throw(0,Jc.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")};async function*vs(r,e,t={}){let{cid:n,toResolve:o}=uA(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await kw(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw(0,Jc.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");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 ze(r,e,t={}){let n=await bn(vs(r,e,t));if(n==null)throw(0,Jc.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}async function*Yo(r,e,t={}){let n=await ze(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,t))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))}}var Pw=J(Dw(),1),Ze=Pw.default;var Xt=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},fr=class extends Xt{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}},ot=class extends Xt{constructor(e="invalid PBNode"){super(e,"InvalidPBNodeError","ERR_INVALID_PBNODE")}},Fr=class extends Xt{constructor(e="unknown error"){super(e,"InvalidPBNodeError","ERR_UNKNOWN_ERROR")}},Ss=class extends Xt{constructor(e="path already exists"){super(e,"AlreadyExistsError","ERR_ALREADY_EXISTS")}},tl=class extends Xt{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}},Jo=class extends Xt{constructor(e="no content"){super(e,"NoContentError","ERR_NO_CONTENT")}},rl=class extends Xt{constructor(e="not a file"){super(e,"NotAFileError","ERR_NOT_A_FILE")}},xn=class extends Xt{constructor(e="not a directory"){super(e,"NotADirectoryError","ERR_NOT_A_DIRECTORY")}},St=class extends Xt{constructor(e="invalid parameters"){super(e,"InvalidParametersError","ERR_INVALID_PARAMETERS")}};var Cd=J(Wc(),1);function ol(r){function e(t){return t instanceof nl?t:new nl(t,r)}return e}var nl=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?ue([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Rd(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},yA=[255,254,252,248,240,224,192,128],gA=[1,3,7,15,31,63,127,255],Rd=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=wA(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function wA(r,e,t){let n=bA(e,t);return(r&n)>>>e}function bA(r,e){return yA[r]&gA[Math.min(e+r-1,7)]}var _s=BigInt(Gn.code),Yn=8;async function Qo(r){return(await Gn.encode(r)).subarray(0,8).reverse()}var Fw=J(Wc(),1);var Zt=async(r,e,t)=>{t.codec==null&&(t.codec=Te);let n=await ce.digest(r),o=O.create(t.cidVersion,t.codec.code,n);return await e.put(o,r,{...t,signal:t.signal}),o};var Td=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},il=class extends Td{_bucket;constructor(e,t){super(e,t),this._bucket=Go({hashFn:Qo,bits:8})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=Uw(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of Ow(this._bucket,e,this,this.options))yield{...t,path:this.path}}};async function*Ow(r,e,t,n){let o=r._children,i=[],s=0n;for(let d=0;d<o.length;d++){let p=o.get(d);if(p==null)continue;let h=d.toString(16).toUpperCase().padStart(2,"0");if(p instanceof vt){let y;for await(let g of Ow(p,e,null,n))y=g;if(y==null)throw new Error("Could not flush sharded directory, no subshard found");i.push({Name:h,Tsize:Number(y.size),Hash:y.cid}),s+=y.size}else if(xA(p.value)){let y=p.value,g;for await(let x of y.flush(e))g=x,yield g;if(g==null)throw new Error("Did not flush dir");let b=h+p.key;i.push({Name:b,Tsize:Number(g.size),Hash:g.cid}),s+=g.size}else{let y=p.value;if(y.cid==null)continue;let g=h+p.key,b=y.size;i.push({Name:g,Tsize:Number(b),Hash:y.cid}),s+=BigInt(b??0)}}let a=Uint8Array.from(o.bitField().reverse()),c=new q({type:"hamt-sharded-directory",data:a,fanout:BigInt(r.tableSize()),hashType:_s,mtime:t?.mtime,mode:t?.mode}),u={Data:c.marshal(),Links:i},l=re(_e(u)),f=await Zt(l,e,n),m=BigInt(l.byteLength)+s;yield{cid:f,unixfs:c,size:m}}function xA(r){return typeof r.flush=="function"}function Uw(r,e,t){let n=r._children,o=[];for(let c=0;c<n.length;c++){let u=n.get(c);if(u==null)continue;let l=c.toString(16).toUpperCase().padStart(2,"0");if(u instanceof vt){let f=Uw(u,null,t);o.push({Name:l,Tsize:Number(f),Hash:t.cidVersion===0?sl:al})}else if(typeof u.value.flush=="function"){let m=u.value.nodeSize();o.push({Name:l+u.key,Tsize:Number(m),Hash:t.cidVersion===0?sl:al})}else{let f=u.value;if(f.cid==null)continue;let m=l+u.key,d=f.size;o.push({Name:m,Tsize:Number(d),Hash:f.cid})}}let i=Uint8Array.from(n.bitField().reverse()),s=new q({type:"hamt-sharded-directory",data:i,fanout:BigInt(r.tableSize()),hashType:_s,mtime:e?.mtime,mode:e?.mode});return re(_e({Data:s.marshal(),Links:o})).length}var sl=O.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),al=O.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var Nd=Q("helia:unixfs:commands:utils:hamt-utils"),cl=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),Vw=async(r,e,t)=>{let n=new il({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let i=0;i<e.length;i++)await n._bucket.put(e[i].name,{size:e[i].size,cid:e[i].cid});let o=await bn(n.flush(r));if(o==null)throw new Error("Flushing shard yielded no result");return o},ll=async(r,e,t)=>{let n=q.unmarshal(r[0].node.Data??new Uint8Array(0)),o=BigInt(Math.pow(2,Yn));r.reverse();let i,s;for(let a=0;a<r.length;a++){let c=a===r.length-1,u=r[a],l=Uint8Array.from(u.children.bitField().reverse()),f=new q({type:"hamt-sharded-directory",data:l,fanout:o,hashType:_s});c&&(f.mtime=n.mtime,f.mode=n.mode),s={Data:f.marshal(),Links:u.node.Links};let m=re(_e(s));if(i=await Zt(m,e,t),!c){let d=r[a+1];if(d==null)throw new Error("Was not operating on shard root but also had no parent?");Nd("updating link in parent sub-shard with prefix %s",d.prefix),d.node.Links=d.node.Links.filter(p=>p.Name!==d.prefix),d.node.Links.push({Name:d.prefix,Hash:i,Tsize:u.node.Links.reduce((p,h)=>p+(h.Tsize??0),m.byteLength)})}}if(i==null||s==null)throw new Error("Noting persisted");return{cid:i,node:s}},ul=async(r,e,t,n)=>{let i=ol(Qo)(U(e)),s=[];for(;;){let a=await t.get(r,n),c=we(a),u=new Fw.default,l=await i.take(Yn),f=cl(l);s.push({prefix:f,children:u,node:c});let m;for(let p of c.Links){let h=p.Name??"";if(h.length<2)throw new Error("Invalid HAMT - link name was too short");let y=parseInt(h.substring(0,2),16);u.set(y,!0),h.startsWith(f)&&(m=p)}if(m==null){Nd("no link found with prefix %s for %s",f,e);break}let d=m.Name??"";if(d.length<2)throw new Error("Invalid HAMT - link name was too short");if(d.length===2){r=m.Hash,Nd("descend into sub-shard with prefix %s",d);continue}break}return{path:s,hash:i}};async function fl(r,e,t,n){if(r.Data==null)throw new Error("DagPB node had no data");let o=q.unmarshal(r.Data),i;if(o.type==="directory")i=EA(r);else if(o.type==="hamt-sharded-directory")i=await Hw(r,0,t,e,n);else throw new Error("Can only estimate the size of directories or shards");return i>t}function EA(r){let e=0;for(let t of r.Links)e+=(t.Name??"").length,e+=t.Hash.version===1?al.bytes.byteLength:sl.bytes.byteLength;return e}async function Hw(r,e,t,n,o){if(e>t)return t;if(r.Data==null||!q.unmarshal(r.Data).isDirectory())return e;for(let s of r.Links){let a=s.Name??"";if(a=a.substring(2),e+=a.length,e+=s.Hash.bytes.byteLength,s.Hash.code===ye){let c=await n.get(s.Hash,o),u=we(c);e+=await Hw(u,e,t,n,o)}}return e}var dr=Q("helia:unixfs:components:utils:add-link");async function ei(r,e,t,n){if(r.node.Data==null)throw new St("Invalid parent passed to addLink");if(q.unmarshal(r.node.Data).type==="hamt-sharded-directory")return dr("adding link to sharded directory"),_A(r,e,t,n);dr(`adding ${e.Name} (${e.Hash}) to regular directory`);let i=await SA(r,e,t,n);if(await fl(i.node,t,n.shardSplitThresholdBytes,n)){dr("converting directory to sharded directory");let s=await vA(i,t);i.cid=s.cid,i.node=we(await t.get(s.cid,n))}return i}var vA=async(r,e)=>{if(r.node.Data==null)throw new St("Invalid parent passed to convertToShardedDirectory");let t=q.unmarshal(r.node.Data),n=await Vw(e,r.node.Links.map(o=>({name:o.Name??"",size:BigInt(o.Tsize??0),cid:o.Hash})),{mode:t.mode,mtime:t.mtime,cidVersion:r.cid.version});return dr(`converted directory to sharded directory ${n.cid}`),n},SA=async(r,e,t,n)=>{let o=r.node.Links.filter(l=>{let f=l.Name===e.Name;if(f&&!n.allowOverwriting)throw new Ss;return!f});if(o.push(e),r.node.Data==null)throw new ot("Parent node with no data passed to addToDirectory");let i=q.unmarshal(r.node.Data),s;if(i.mtime!=null){let l=Date.now(),f=Math.floor(l/1e3);i.mtime={secs:BigInt(f),nsecs:(l-f*1e3)*1e3},s=i.marshal()}else s=r.node.Data;r.node=_e({Data:s,Links:o});let a=re(r.node),c=await ce.digest(a),u=O.create(r.cid.version,ye,c);return await t.put(u,a),{node:r.node,cid:u}},_A=async(r,e,t,n)=>{let{path:o,hash:i}=await ul(r.cid,e.Name,t,n),s=o[o.length-1];if(s==null)throw new Error("Invalid HAMT, could not generate path");let a=s.prefix,c=parseInt(a,16);dr("next prefix for %s is %s",e.Name,a);let u=`${a}${e.Name}`,l=s.node.Links.find(f=>(f.Name??"").startsWith(a));if(l!=null)if(dr("link %s was present in shard",u),l.Name===u){if(!n.allowOverwriting)throw new Ss;dr("overwriting %s in subshard",e.Name),s.node.Links=s.node.Links.filter(f=>f.Name!==u),s.node.Links.push({Name:u,Hash:e.Hash,Tsize:e.Tsize})}else{if(l.Name?.length===2)throw new Error("Existing link was subshard?!");{dr("prefix %s already exists, creating new subshard",a);let f=s.node.Links.findIndex(y=>y.Name?.startsWith(a)),m=s.node.Links.splice(f,1)[0],d=(m.Name??"").substring(2),h=ol(Qo)(U(d));for(let y=0;y<o.length;y++)await h.take(Yn);for(;;){let y=await h.take(Yn),g=cl(y);m.Name=`${g}${d}`;let b=await i.take(Yn),x=cl(b);if(g===x){let S=new Cd.default;S.set(b,!0),o.push({prefix:x,children:S,node:{Links:[]}});continue}let v=new Cd.default;v.set(b,!0),v.set(y,!0),o.push({prefix:a,children:v,node:{Links:[m,{Name:`${x}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else dr("link %s was not present in sub-shard",u),e.Name=u,s.node.Links.push(e),s.children.set(c,!0),dr("adding %s to existing sub-shard",u);return ll(o,t,n)};async function En(r,e,t={}){let n=await ze(r,e,t);if(n.type!=="directory")throw new xn(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function ti(r,e,t,n){let o=await ze(r,t,n);if(o.type!=="directory"&&o.type!=="file"&&o.type!=="raw")throw new fr(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:o.node instanceof Uint8Array?o.node.byteLength:AA(o.node),Hash:r}}function AA(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return re(r).byteLength+e}var kA=Q("helia:unixfs:components:utils:resolve");async function hr(r,e,t,n){if(e==null||e==="")return{cid:r};let o=`/ipfs/${r}${e==null?"":`/${e}`}`,i=await is(vs(o,t,n));if(i.length===0)throw new tl("Could not find path in directory");return kA("resolved %s to %c",e,r),{cid:i[i.length-1].cid,path:e,segments:i}}async function ri(r,e,t,n){if(e.segments==null||e.segments.length===0)return r;let o=e.segments.pop();if(o==null)throw new Error("Insufficient segments");o.cid=r,e.segments.reverse();for(let i of e.segments){let[s,a]=await Promise.all([En(i.cid,t,n),ti(o.cid,o.name,t,n)]);r=(await ei(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,i.cid=r,o=i}return r}var BA=Ze.bind({ignoreUndefined:!0}),IA={};async function*Mw(r,e,t={}){let n=BA(IA,t),o=await hr(r,n.path,e,n),i=await ze(o.cid,e,n);if(i.type!=="file"&&i.type!=="raw")throw new rl;if(i.content==null)throw new Jo;yield*i.content(n)}var RA=Ze.bind({ignoreUndefined:!0}),TA=Q("helia:unixfs:chmod"),NA={recursive:!1,shardSplitThresholdBytes:262144};async function zw(r,e,t,n={}){let o=RA(NA,n),i=await hr(r,o.path,t,n);if(TA("chmod %c %d",i.cid,e),o.recursive){let m=await at(async function*(){for await(let d of Yo(i.cid,t,n)){let p,h=[];if(d.type==="raw")p=new q({type:"file",data:d.node});else if(d.type==="file"||d.type==="directory")p=d.unixfs,h=d.node.Links;else throw new fr;p.mode=e;let y={Data:p.marshal(),Links:h};yield{path:d.path,content:y}}},d=>wn(d,t,{...o,dagBuilder:async function*(p,h){for await(let y of p)yield async function(){let g=y.content,b=re(g),x=await Zt(b,h,{...o,cidVersion:r.version});if(g.Data==null)throw new ot(`${x} had no data`);let v=q.unmarshal(g.Data);return{cid:x,size:BigInt(b.length),path:y.path,unixfs:v}}}}),async d=>bn(d));if(m==null)throw new Fr(`Could not chmod ${i.cid.toString()}`);return ri(m.cid,i,t,o)}let s=await t.get(i.cid,n),a,c=[];if(i.cid.code===ge)a=new q({type:"file",data:s});else{let m=we(s);if(m.Data==null)throw new ot(`${i.cid.toString()} had no data`);c=m.Links,a=q.unmarshal(m.Data)}a.mode=e;let u=re({Data:a.marshal(),Links:c}),l=await ce.digest(u),f=O.create(i.cid.version,ye,l);return await t.put(f,u),ri(f,i,t,o)}var CA=Ze.bind({ignoreUndefined:!0}),LA=Q("helia:unixfs:cp"),DA={force:!1,shardSplitThresholdBytes:262144};async function $w(r,e,t,n,o={}){let i=CA(DA,o);if(t.includes("/"))throw new St("Name must not have slashes");let[s,a]=await Promise.all([En(e,n,i),ti(r,t,n,i)]);return LA('Adding %c as "%s" to %c',r,t,e),(await ei(s,a,n,{allowOverwriting:i.force,cidVersion:e.version,...i})).cid}var PA=Ze.bind({ignoreUndefined:!0}),OA={};async function*Kw(r,e,t={}){let n=PA(OA,t),o=await hr(r,n.path,e,n),i=await ze(o.cid,e);if(i.type==="file"||i.type==="raw"){yield i;return}if(i.content==null)throw new Jo;if(i.type!=="directory")throw new xn;yield*i.content({offset:t.offset,length:t.length})}var UA=Ze.bind({ignoreUndefined:!0}),qw=Q("helia:unixfs:mkdir"),FA={cidVersion:1,force:!1,shardSplitThresholdBytes:262144};async function Gw(r,e,t,n={}){let o=UA(FA,n);if(e.includes("/"))throw new St("Path must not have slashes");if((await ze(r,t,n)).type!=="directory")throw new xn(`${r.toString()} was not a UnixFS directory`);qw("creating %s",e);let a={Data:new q({type:"directory",mode:o.mode,mtime:o.mtime}).marshal(),Links:[]},c=re(a),u=await ce.digest(c),l=O.create(o.cidVersion,ye,u);await t.put(l,c);let[f,m]=await Promise.all([En(r,t,o),ti(l,e,t,o)]);return qw("adding empty dir called %s to %c",e,r),(await ei(f,m,t,{...o,allowOverwriting:o.force})).cid}var dl=Q("helia:unixfs:utils:remove-link");async function Ww(r,e,t,n){if(r.node.Data==null)throw new ot("Parent node had no data");if(q.unmarshal(r.node.Data).type==="hamt-sharded-directory"){dl(`removing ${e} from sharded directory`);let i=await HA(r,e,t,n);return await fl(i.node,t,n.shardSplitThresholdBytes,n)?i:(dl("converting shard to flat directory %c",r.cid),MA(i,t,n))}return dl(`removing link ${e} regular directory`),VA(r,e,t,n)}var VA=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let o=re(r.node),i=await Zt(o,t,{...n,cidVersion:r.cid.version});return dl(`Updated regular directory ${i}`),{node:r.node,cid:i}},HA=async(r,e,t,n)=>{let{path:o}=await ul(r.cid,e,t,n),i=o[o.length-1];if(i==null)throw new Error("Invalid HAMT, could not generate path");let s=i.node.Links.filter(u=>(u.Name??"").substring(2)===e).map(u=>u.Name).pop();if(s==null)throw new Error("File not found");let a=s.substring(0,2),c=parseInt(a,16);if(i.node.Links=i.node.Links.filter(u=>u.Name!==s),i.children.unset(c),i.node.Links.length===1)for(;o.length!==1;){let u=o[o.length-1];if(u==null||u.node.Links.length>1)break;o.pop();let l=o[o.length-1];if(l==null)break;let f=u.node.Links[0];l.node.Links=l.node.Links.filter(m=>!(m.Name??"").startsWith(l.prefix)),l.node.Links.push({Hash:f.Hash,Name:`${l.prefix}${(f.Name??"").substring(2)}`,Tsize:f.Tsize})}return ll(o,t,n)},MA=async(r,e,t)=>{if(r.node.Data==null)throw new St("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},o=await ze(r.cid,e);if(o.type!=="directory")throw new Error("Unexpected node type");for await(let c of o.content()){let u=0;c.node instanceof Uint8Array?u=c.node.byteLength:u=re(c.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:u})}let i=q.unmarshal(r.node.Data);n.Data=new q({type:"directory",mode:i.mode,mtime:i.mtime}).marshal();let s=re(_e(n));return{cid:await Zt(s,e,{codec:Te,cidVersion:r.cid.version,signal:t.signal}),node:n}};var zA=Ze.bind({ignoreUndefined:!0}),$A=Q("helia:unixfs:rm"),KA={shardSplitThresholdBytes:262144};async function jw(r,e,t,n={}){let o=zA(KA,n);if(e.includes("/"))throw new St("Name must not have slashes");let i=await En(r,t,o);return $A("Removing %s from %c",e,r),(await Ww(i,e,t,{...o,cidVersion:r.version})).cid}var qA=Ze.bind({ignoreUndefined:!0}),GA=Q("helia:unixfs:stat"),WA={};async function Yw(r,e,t={}){let n=qA(WA,t),o=await hr(r,t.path,e,n);GA("stat %c",o.cid);let i=await ze(o.cid,e,n);if(i.type!=="file"&&i.type!=="directory"&&i.type!=="raw")throw new fr;let s=0n,a=0n,c=0n,u=0n,l=0,f,m,d=i.type,p;if(i.type==="raw"&&(s=BigInt(i.node.byteLength),a=BigInt(i.node.byteLength),c=BigInt(i.node.byteLength),u=BigInt(i.node.byteLength),l=1),i.type==="directory"&&(s=0n,a=BigInt(i.unixfs.marshal().byteLength),c=0n,u=a,l=1,f=i.unixfs.mode,m=i.unixfs.mtime,p=i.unixfs),i.type==="file"){let h=await Xw(o.cid,e,n);s=i.unixfs.fileSize(),a=BigInt((i.node.Data?.byteLength??0)+i.node.Links.reduce((y,g)=>y+(g.Tsize??0),0)),c=BigInt(h.localFileSize),u=BigInt(h.localDagSize),l=h.blocks,f=i.unixfs.mode,m=i.unixfs.mtime,p=i.unixfs}return{cid:o.cid,mode:f,mtime:m,fileSize:s,dagSize:a,localFileSize:c,localDagSize:u,blocks:l,type:d,unixfs:p}}async function Xw(r,e,t){let n={localFileSize:0,localDagSize:0,blocks:0};if(await e.has(r,t)){let o=await e.get(r,t);if(n.blocks++,n.localDagSize+=o.byteLength,r.code===ge)n.localFileSize+=o.byteLength;else if(r.code===ye){let i=we(o);if(i.Links.length>0)for(let s of i.Links){let a=await Xw(s.Hash,e,t);n.localFileSize+=a.localFileSize,n.localDagSize+=a.localDagSize,n.blocks+=a.blocks}else{if(i.Data==null)throw new ot(`PBNode ${r.toString()} had no data`);let s=q.unmarshal(i.Data);if(s.data==null)throw new ot(`UnixFS node ${r.toString()} had no data`);n.localFileSize+=s.data.byteLength??0}}else throw new Fr(`${r.toString()} was neither DAG_PB nor RAW`)}return n}var jA=Ze.bind({ignoreUndefined:!0}),YA=Q("helia:unixfs:touch"),XA={recursive:!1,shardSplitThresholdBytes:262144};async function Zw(r,e,t={}){let n=jA(XA,t),o=await hr(r,n.path,e,n),i=n.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(YA("touch %c %o",o.cid,i),n.recursive){let m=await at(async function*(){for await(let d of Yo(o.cid,e)){let p,h;if(d.type==="raw")p=new q({data:d.node}),h=[];else if(d.type==="file"||d.type==="directory")p=d.unixfs,h=d.node.Links;else throw new fr;p.mtime=i;let y={Data:p.marshal(),Links:h};yield{path:d.path,content:y}}},d=>wn(d,e,{...n,dagBuilder:async function*(p,h){for await(let y of p)yield async function(){let g=y.content,b=re(g),x=await Zt(b,h,{...n,cidVersion:r.version});if(g.Data==null)throw new ot(`${x} had no data`);let v=q.unmarshal(g.Data);return{cid:x,size:BigInt(b.length),path:y.path,unixfs:v}}}}),async d=>bn(d));if(m==null)throw new Fr(`Could not chmod ${o.cid.toString()}`);return ri(m.cid,o,e,n)}let s=await e.get(o.cid,t),a,c=[];if(o.cid.code===ge)a=new q({data:s});else{let m=we(s);if(c=m.Links,m.Data==null)throw new ot(`${o.cid.toString()} had no data`);a=q.unmarshal(m.Data)}a.mtime=i;let u=re({Data:a.marshal(),Links:c}),l=await ce.digest(u),f=O.create(o.cid.version,ye,l);return await e.put(f,u),ri(f,o,e,n)}var Ld=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*nw(e,this.components.blockstore,t)}async addBytes(e,t={}){return ow(e,this.components.blockstore,t)}async addByteStream(e,t={}){return iw(e,this.components.blockstore,t)}async addFile(e,t={}){return sw(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return aw(e,this.components.blockstore,t)}async*cat(e,t={}){yield*Mw(e,this.components.blockstore,t)}async chmod(e,t,n={}){return zw(e,t,this.components.blockstore,n)}async cp(e,t,n,o={}){return $w(e,t,n,this.components.blockstore,o)}async*ls(e,t={}){yield*Kw(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return Gw(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return jw(e,t,this.components.blockstore,n)}async stat(e,t={}){return Yw(e,this.components.blockstore,t)}async touch(e,t={}){return Zw(e,this.components.blockstore,t)}};function Jw(r){return new Ld(r)}function hl(r,e={}){let t={_cancelled:!1,async start(){this._cancelled=!1},async pull(n){try{let{value:o,done:i}=await r.next();if(this._cancelled)return;if(i===!0){n.close();return}n.enqueue(o)}catch(o){n.error(o)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(t,e)}function Qw(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function eb(r,e,t){if((r??0)>(e??1/0))throw new Error("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new Error("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(e??0)>(t??1/0))throw new Error("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Error("Invalid range: Range-start index cannot be negative.");if(r!=null&&e!=null)return{byteSize:e-r+1,start:r,end:e};if(r==null&&e!=null)return t==null?{end:e}:e===t?{byteSize:t,start:0,end:t-1}:{byteSize:e,start:t-e,end:t-1};if(r!=null&&e==null){if(t==null)return{start:r};let n=t-1;return{byteSize:t-r,start:r,end:n}}return{byteSize:t,start:0,end:t!=null?t-1:0}}function tb({ttl:r,protocol:e,response:t}){let n;e==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function rb({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new Error("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new Error("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&e==null)return t==null?`bytes */${n}`:`bytes ${r}-${t-1}/${t}`;if(r==null&&e!=null){if(t==null)return`bytes */${n}`;let o=t-1;return`bytes ${o-e+1}-${o}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function ZA(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 JA(r){let e=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(e?.groups==null)throw new Error("Invalid range request");let{start:t,end:n}=e.groups;return{start:t,end:n}}var As=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(e,t){if(this.headers=t,this.log=e.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=Qw(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=JA(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(e){this._body=e,this.setFileSize(this._fileSize??ZA(e)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let e=this._body;if(e==null)return this.log.trace("body is null"),e;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),e;let t=this.byteStart,n=this.byteEnd,o=this.byteSize;return t!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",t,n,o),e instanceof ReadableStream?e:this.getSlicedBody(e)):(this.log.error("returning unmodified body for valid range request"),e)}getSlicedBody(e){let t=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",t,n),e.slice(t,n)}setFileSize(e){this._fileSize=e!=null?Number(e):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:e,end:t,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",e,t,n),this.byteStart=e,this.byteEnd=t,this.byteSize=n}catch(e){this.log.error("error setting offset details: %o",e),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 Error("Invalid range request");return rb({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function nb(r){let e=rt(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(Qi(e))}function ob(r){let e=QA(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function QA(r){return r.replace(/[^\x00-\x7F]/g,"_")}function ib({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:o}){let i=t===!0?"W/":"",s=e==null?"":`.${e}`;return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}var ek={[hn]:["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"],[mn]:["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"],[Wr]:["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"],[ye]:["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"],[ge]:["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 sb(r,e){let t=ek[r.code];if(e!=null)return tk(e,t)}function tk(r,e){let t=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:rk(o[1])}}).sort((n,o)=>n.weight===o.weight?0:n.weight>o.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let o of e)if(n.includes(o)||n==="*/*"||n.startsWith("*/")&&o.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&o.split("/")[0]===n.split("/")[0])return o}function rk(r){if(r!=null&&(r=r.trim()),r==null||!r.startsWith("q="))return 1;let e=parseFloat(r.replace("q=",""));return isNaN(e)?0:e}var pl={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 ab(r){if(r!=null)return pl[r]}function Dd(r){let e=r.get("accept");return!!(e!=null&&Object.values(pl).includes(e))}function Pd(r){let e=r?.format;return!!(e!=null&&Object.keys(pl).includes(e))}function cb({query:r,headers:e}){return Dd(e)||Pd(r)}function lb({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),o=new Headers(e),i=o.get("accept")??void 0;if(i!=null&&n('incoming accept header "%s"',i),!cb({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=ab(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 ub(r,e,t,n){let o=t.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",e),new Error("No content found");return{stream:new ReadableStream({async start(u){n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),u.enqueue(s)},async pull(u){let{value:l,done:f}=await i.next();if(n?.signal?.aborted===!0){u.error(new Qt(n.signal.reason??"signal aborted by user")),u.close();return}if(f===!0){l!=null&&(n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),u.enqueue(l)),u.close();return}n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),u.enqueue(l)}}),firstChunk:s}}var qM=U("ustar\0","binary"),GM=U("ustar ","binary"),WM=U(" \0","binary");var mb=J(db(),1);function ok(r){return r[Symbol.asyncIterator]!=null}function ik(r){if(ok(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=ue([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return ue(e,t)}var hb=ik;var sk="0000000000000000000",ak="7777777777777777777",ck=48,lk=U("ustar\0","binary"),uk=U("00","binary"),fk=parseInt("7777",8),dk=257,hk=263,pk=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}},mk=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},vn=function(r,e){let t=r.toString(8);return t.length>e?U(ak.slice(0,e)+" "):U(sk.slice(0,e-t.length)+t+" ")},Od=function(r){let e=U(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function pb(r){let e="";r.name!=null&&(e+=Od(" path="+r.name+`
|
|
9
|
-
`)),r.linkname!=null&&(e+=
|
|
10
|
-
`));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=
|
|
11
|
-
`));return U(e)}function ml(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),U(t).byteLength!==t.length)return null;for(;U(t).byteLength>100;){let o=t.indexOf("/");if(o===-1)return null;n+=n!==""?"/"+t.slice(0,o):t.slice(0,o),t=t.slice(o+1)}return U(t).byteLength>100||U(n).byteLength>155||r.linkname!=null&&U(r.linkname).byteLength>100?null:(e.set(U(t),0),e.set(vn(r.mode&fk,6),100),e.set(vn(r.uid,6),108),e.set(vn(r.gid,6),116),e.set(vn(r.size,11),124),e.set(vn(r.mtime.getTime()/1e3|0,11),136),e[156]=ck+pk(r.type),r.linkname!=null&&e.set(U(r.linkname),157),e.set(lk,dk),e.set(uk,hk),r.uname!=null&&e.set(U(r.uname),265),r.gname!=null&&e.set(U(r.gname),297),e.set(vn(r.devmajor??0,6),329),e.set(vn(r.devminor??0,6),337),n!=null&&e.set(U(n),345),e.set(vn(mk(e),6),148),e)}var{S_IFMT:gk,S_IFBLK:wk,S_IFCHR:bk,S_IFDIR:xk,S_IFIFO:Ek,S_IFLNK:vk}=mb.default,Sk=parseInt("755",8),_k=parseInt("644",8),yb=new Uint8Array(1024);function Ak(r=0){switch(r&gk){case wk:return"block-device";case bk:return"character-device";case xk:return"directory";case Ek:return"fifo";case vk:return"symlink";default:return"file"}}function Fd(r){return r&=511,r!==0?yb.subarray(0,512-r):new Uint8Array(0)}function Ud(r){if(r.pax==null){let e=ml(r);if(e!=null)return e}return kk(r)}function kk(r){let e=pb(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new Vt(ml(t)??new Uint8Array(0),e,Fd(e.length),ml({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function yl(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??Ak(e.mode),mode:e.mode??(e.type==="directory"?Sk:_k),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=U(t)),t instanceof Uint8Array||tr(t)){n.size=t.length,yield Ud(n),yield tr(t)?t.subarray():t,yield Fd(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=W(await hb(t)),yield Ud(n);continue}if(yield Ud(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield tr(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield Fd(n.size)}yield yb}}var Bk=["file","raw","directory"];function Ik(r){let e,t;return(r.type==="file"||r.type==="directory")&&(e=r.unixfs.mode,t=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:e,mtime:t,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function gb(r){if(!Bk.includes(r.type))throw new N("Not a UnixFS node","ERR_NOT_UNIXFS");let e={header:Ik(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*wb(r,e,t){let n=await ze(r,e,t);if(n.type==="file"||n.type==="raw"){yield*at([gb(n)],yl());return}if(n.type==="directory"){yield*at(Yo(r,e,t),o=>We(o,i=>gb(i)),yl());return}throw new N("Not a UnixFS node","ERR_NOT_UNIXFS")}var bb=J(Of(),1),gl=class{lru;constructor(e){this.lru=(0,bb.default)(e)}get(e){let t=this.lru.get(e);if(t!=null){if(t.expire!=null&&t.expire<Date.now()){this.lru.remove(e);return}return t.value}}set(e,t,n){this.lru.set(e,{value:t,expire:Date.now()+n})}has(e){return this.get(e)!=null}remove(e){this.lru.remove(e)}clear(){this.lru.clear()}};var xb=new gl(1e3),Rk=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Tk=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Nk=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Ck=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function Lk(r){let e=r?.protocol;if(e==null)return!1;let t=r?.cidOrPeerIdOrDnsLink;if(t==null)return!1;let n=r?.path,o=r?.queryString;return["ipns","ipfs"].includes(e)&&typeof t=="string"&&(n==null||typeof n=="string")&&(o==null||typeof o=="string")}function Dk(r){for(let e of[Rk,Tk,Nk,Ck]){let t=r.match(e);if(Lk(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function Pk(r){if(r==null)return;let e=r.answer?.TTL,t=r.record?.ttl,n=t!=null?Number(t/BigInt(1e9)):void 0;return e??n}var Ok=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function Uk(r){return Ok.test(r)&&r.includes("-")&&!r.includes(".")}function Fk(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function Eb({urlString:r,ipns:e,logger:t},n){let o=t.forComponent("helia:verified-fetch:parse-url-string"),{protocol:i,cidOrPeerIdOrDnsLink:s,path:a,queryString:c}=Dk(r),u,l,f=[],m;if(i==="ipfs")try{u=O.parse(s)}catch(h){o.error(h),f.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(m=xb.get(s),m!=null)u=m.cid,l=m.path,o.trace("resolved %s to %c from cache",s,u);else{o.trace("Attempting to resolve PeerId for %s",s);let h=null;try{h=Qe(s),m=await e.resolve(h,n),u=m?.cid,l=m?.path,o.trace("resolved %s to %c",s,u)}catch(y){n?.signal?.throwIfAborted(),h==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",h,y),f.push(new TypeError(`Could not resolve PeerId "${s}", ${y.message}`)))}if(u==null){let y=s;Uk(s)&&(y=Fk(s),o.trace('decoded dnslink from "%s" to "%s"',s,y)),o.trace("Attempting to resolve DNSLink for %s",y);try{m=await e.resolveDNSLink(y,n),u=m?.cid,l=m?.path,o.trace("resolved %s to %c",y,u)}catch(g){n?.signal?.throwIfAborted(),o.error('could not resolve DnsLink for "%s"',s,g),f.push(g)}}}if(u==null)throw f.length===1?f[0]:new AggregateError(f,`Invalid resource. Cannot determine CID from URL "${r}"`);let d=Pk(m);m!=null&&(d=d??60*2,o.trace("caching %s resolved to %s with TTL: %s",s,u,d),xb.set(s,m,d*1e3));let p={};if(c!=null&&c.length>0){let h=c.split("&");for(let y of h){let[g,b]=y.split("=");p[g]=decodeURIComponent(b)}p.download!=null&&(p.download=p.download==="true"),p.filename!=null&&(p.filename=p.filename.toString())}return{protocol:i,cid:u,path:Vk(l,a??""),query:p,ttl:d}}function Vk(r,e){let t="";return r!=null&&(t+=r),e.length>0&&(t=`${t.length>0?`${t}/`:t}${e}`),t=t.replace(/\/(\/)+/g,"/"),t.startsWith("/")&&(t=t.substring(1)),t.split("/").map(decodeURIComponent).join("/")}async function vb(r,{ipns:e,logger:t},n){if(typeof r=="string")return Eb({urlString:r,ipns:e,logger:t},n);let o=O.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ttl:29030400};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function Vd(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function Hr(r,e){Vd(r,"type",e)}function Mr(r,e){Vd(r,"url",e)}function Sb(r){Vd(r,"redirected",!0)}function Xn(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&Sb(n),Hr(n,"basic"),Mr(n,r),n.headers.set("Accept-Ranges","bytes"),n}function bl(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return Hr(n,"basic"),Mr(n,r),n}function Hd(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Hr(n,"basic"),Mr(n,r),n}function ni(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return Hr(n,"basic"),Mr(n,r),n}function xl(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return Hr(n,"basic"),Mr(n,r),n}function El(r,e,t){e instanceof Error&&(e=e.message);let n=new Response(e,{...t??{},status:400,statusText:"Bad Request"});return Hr(n,"basic"),Mr(n,r),n}function _b(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return Hr(n,"basic"),Mr(n,r),n}function Md(r,e,{byteRangeContext:t,log:n},o){if(!t.isRangeRequest)return Xn(r,e,o);if(!t.isValidRangeRequest)return wl(r,e,o);let i;try{i=new Response(e,{...o??{},status:206,statusText:"Partial Content",headers:{...o?.headers??{},"content-range":t.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),wl(r,e,o)}return o?.redirected===!0&&Sb(i),Hr(i,"basic"),Mr(i,r),i.headers.set("Accept-Ranges","bytes"),i}function wl(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return Hr(n,"basic"),Mr(n,r),n}async function zd(r,e,t){let n=[],o;for await(let i of vs(e,r,t))n.push(i.cid),o=i;if(o==null)throw new N("No terminal element found","ERR_NO_TERMINAL_ELEMENT");return{ipfsRoots:n,terminalElement:o}}function Ab(r){return r.type==="object"}function Hk(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var Mk=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function zk({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(o=>o.split(";")[0]).map(o=>o.trim());for(let o of n){if(o==="*/*")return;if(Mk.includes(o??""))return o}}var vl=class{helia;ipns;unixfs;log;contentTypeParser;constructor({helia:e,ipns:t,unixfs:n},o){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??I0(e),this.unixfs=n??Jw(e),this.contentTypeParser=o?.contentTypeParser,this.log.trace("created VerifiedFetch instance")}async handleIPNSRecord({resource:e,cid:t,path:n,options:o}){if(n!==""||!e.startsWith("ipns://"))return El("Invalid IPNS name");let i;try{i=Qe(e.replace("ipns://",""))}catch{return this.log.error("could not parse peer id from IPNS url %s",e),El("Invalid IPNS name")}let s=ue([U("/ipns/"),i.toBytes()]),a=new ke("/dht/record/"+W(s,"base32"),!1),c=await this.helia.datastore.get(a,o),u=Or.deserialize(c),l=Xn(e,u.value);return l.headers.set("content-type","application/vnd.ipfs.ipns-record"),l}async handleCar({resource:e,cid:t,options:n}){let o=b0(this.helia),i=hl(o.stream(t,n)),s=Xn(e,i);return s.headers.set("content-type","application/vnd.ipld.car; version=1"),s}async handleTar({resource:e,cid:t,path:n,options:o}){if(t.code!==ye&&t.code!==ge)return ni("only UnixFS data can be returned in a TAR file");let i=hl(wb(`/ipfs/${t}/${n}`,this.helia.blockstore,o)),s=Xn(e,i);return s.headers.set("content-type","application/x-tar"),s}async handleJson({resource:e,cid:t,path:n,accept:o,options:i}){this.log.trace("fetching %c/%s",t,n);let s=await this.helia.blockstore.get(t,i),a;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let u=Tc(s);a=Zi(u)}catch(u){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",u),ni(e)}else a=s;let c=Xn(e,a);return c.headers.set("content-type",o??"application/json"),c}async handleDagCbor({resource:e,cid:t,path:n,accept:o,options:i}){this.log.trace("fetching %c/%s",t,n);let s,a;try{let f=await zd(this.helia.blockstore,`${t.toString()}/${n}`,i);a=f.ipfsRoots;let m=f.terminalElement;if(m==null)return xl(e);Ab(m)&&(s=m)}catch(f){return i?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT"].includes(f.code)?xl(e):(this.log.error("error walking path %s",n,f),bl(e,"Error walking path"))}let c=s?.node??await this.helia.blockstore.get(t,i),u;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")u=c;else if(o==="application/vnd.ipld.dag-json")try{let f=zn(c);u=Kg(f)}catch(f){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",f),ni(e)}else try{u=nb(c)}catch(f){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',f),ni(e);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",f),u=c}let l=Xn(e,u);return o==null&&(o=u instanceof Uint8Array?"application/octet-stream":"application/json"),l.headers.set("content-type",o),a!=null&&l.headers.set("X-Ipfs-Roots",a.map(f=>f.toV1().toString()).join(",")),l}async handleDagPb({cid:e,path:t,resource:n,options:o}){let i,s,a=!1,c=new As(this.helia.logger,o?.headers);try{let d=await zd(this.helia.blockstore,`${e.toString()}/${t}`,o);s=d.ipfsRoots,i=d.terminalElement}catch(d){return o?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT"].includes(d.code)?xl(n.toString()):(this.log.error("error walking path %s",t,d),bl(n.toString(),"Error walking path"))}let u=i?.cid??e;if(i?.type==="directory"){let d=i.cid;if(t===""?!n.toString().endsWith("/"):!t.endsWith("/")){if(o?.redirect==="error")throw this.log('could not redirect to %s/ as redirect option was set to "error"',n),new TypeError("Failed to fetch");if(o?.redirect==="manual")return this.log("returning 301 permanent redirect to %s/",n),_b(n,`${n}/`);n=`${n}/`,a=!0}let h="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",e,t);let y=await this.unixfs.stat(d,{path:h,signal:o?.signal,onProgress:o?.onProgress});this.log.trace("found root file at %c/%s with cid %c",d,h,y.cid),t=h,u=y.cid}catch(y){return o?.signal?.throwIfAborted(),this.log("error loading path %c/%s",d,h,y),Hd("Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented")}finally{o?.onProgress?.(new F("verified-fetch:request:end",{cid:d,path:h}))}}c.isRangeRequest&&c.isValidRangeRequest&&i.type==="file"&&(c.setFileSize(i.unixfs.fileSize()),this.log.trace("fileSize for rangeRequest %d",c.getFileSize()));let l=c.offset,f=c.length;this.log.trace("calling unixfs.cat for %c/%s with offset=%o & length=%o",u,t,l,f);let m=this.unixfs.cat(u,{signal:o?.signal,onProgress:o?.onProgress,offset:l,length:f});this.log("got async iterator for %c/%s",e,t);try{let{stream:d,firstChunk:p}=await ub(m,t??"",this.helia.logger,{onProgress:o?.onProgress,signal:o?.signal});c.setBody(d);let h=Md(n,c.getBody(),{byteRangeContext:c,log:this.log},{redirected:a});return await this.setContentType(p,t,h),s!=null&&h.headers.set("X-Ipfs-Roots",s.map(y=>y.toV1().toString()).join(",")),h}catch(d){return o?.signal?.throwIfAborted(),this.log.error("error streaming %c/%s",e,t,d),c.isRangeRequest&&d.code==="ERR_INVALID_PARAMS"?wl(n):bl(n.toString(),"Unable to stream content")}}async handleRaw({resource:e,cid:t,path:n,options:o,accept:i}){let s=new As(this.helia.logger,o?.headers),a=await this.helia.blockstore.get(t,o);s.setBody(a);let c=Md(e,s.getBody(),{byteRangeContext:s,log:this.log},{redirected:!1}),u=zk({headers:o?.headers,accept:i});return u!=null?c.headers.set("content-type",u):await this.setContentType(a,n,c),c}async setContentType(e,t,n){let o="application/octet-stream";if(this.contentTypeParser!=null)try{let i=t.split("/").pop()?.trim();i=i===""?void 0:i;let s=this.contentTypeParser(e,i);if($k(s)){let a=await s;a!=null&&(o=a)}else s!=null&&(o=s)}catch(i){this.log.error("error parsing content type",i)}this.log.trace('setting content type to "%s"',o),n.headers.set("content-type",o)}codecHandlers={[ye]:this.handleDagPb,[mn]:this.handleJson,[Wr]:this.handleJson,[hn]:this.handleDagCbor,[ge]:this.handleRaw,[Ge.code]:this.handleRaw};async fetch(e,t){this.log("fetch %s",e);let n=Hk(t);n?.onProgress?.(new F("verified-fetch:request:start",{resource:e}));let o,i,s,a,c;try{let h=await vb(e,{ipns:this.ipns,logger:this.helia.logger},n);o=h.cid,i=h.path,s=h.query,a=h.ttl,c=h.protocol}catch(h){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",e,h),El(e.toString(),h)}n?.onProgress?.(new F("verified-fetch:request:resolve",{cid:o,path:i}));let u=lb({query:s,headers:n?.headers,logger:this.helia.logger}),l=sb(o,u);if(this.log("output type %s",l),u!=null&&l==null)return ni(e.toString());let f,m,d={resource:e.toString(),cid:o,path:i,accept:l,options:n};if(l==="application/vnd.ipfs.ipns-record")m="ipns-record",f=await this.handleIPNSRecord(d);else if(l==="application/vnd.ipld.car")m="car",s.download=!0,s.filename=s.filename??`${o.toString()}.car`,f=await this.handleCar(d);else if(l==="application/vnd.ipld.raw")m="raw",s.download=!0,s.filename=s.filename??`${o.toString()}.bin`,f=await this.handleRaw(d);else if(l==="application/x-tar")m="tar",s.download=!0,s.filename=s.filename??`${o.toString()}.tar`,f=await this.handleTar(d);else{this.log.trace('finding handler for cid code "%s" and output type "%s"',o.code,l);let h=this.codecHandlers[o.code];if(h==null)return Hd(`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"',h.name),f=await h.call(this,d)}f.headers.set("etag",ib({cid:o,reqFormat:m,weak:!1})),tb({response:f,ttl:a,protocol:c}),f.headers.set("X-Ipfs-Path",e.toString());let p;return s.download===!0&&(p="attachment"),s.filename!=null&&(p==null&&(p="inline"),p=`${p}; ${ob(s.filename)}`),p!=null&&f.headers.set("Content-Disposition",p),n?.onProgress?.(new F("verified-fetch:request:end",{cid:o,path:i})),f}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function $k(r){return r?.then!=null}var ks,Sl=async function(e,t){return ks==null&&(ks=await $d()),ks(e,t)};Sl.start=async function(){await ks?.start()};Sl.stop=async function(){await ks?.stop()};async function $d(r,e){Kk(r)||(r=await d0({blockBrokers:[di({gateways:r?.gateways})],routers:(r?.routers??["https://delegated-ipfs.dev"]).map(o=>ji(o)),dns:qk(r?.dnsResolvers)}));let t=new vl({helia:r},e);async function n(o,i){return t.fetch(o,i)}return n.stop=t.stop.bind(t),n.start=t.start.bind(t),n}function Kk(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function qk(r){if(r!=null)return Array.isArray(r)?Yi({resolvers:{".":r}}):Yi({resolvers:r})}return Vb(Gk);})();
|
|
7
|
+
`)}`:`${t} :`}};tm=rn;H.Constructed=tm;rn.NAME="CONSTRUCTED";var ga=class extends je{fromBER(e,t,n){return t}toBER(e){return $t}};ga.override="EndOfContentValueBlock";var rm,wa=class extends Ve{constructor(e={}){super(e,ga),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};rm=wa;H.EndOfContent=rm;wa.NAME=vi;var nm,nn=class extends Ve{constructor(e={}){super(e,je),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};nm=nn;H.Null=nm;nn.NAME="NULL";var ba=class extends Br(je){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=ee.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=ee.BufferSourceConverter.toUint8Array(e);return kr(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Qu.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ba.NAME="BooleanValueBlock";var om,xa=class extends Ve{constructor(e={}){super(e,ba),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};om=xa;H.Boolean=om;xa.NAME="BOOLEAN";var Ea=class extends Br(ir){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=ir.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===vi){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==Zp)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?ir.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Ea.NAME="OctetStringValueBlock";var im,_r=class r extends Ve{constructor({idBlock:e={},lenBlock:t={},...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,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ea),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let s=Ya(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?rn.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${ee.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return ee.BufferSourceConverter.concat(e)}};im=_r;H.OctetString=im;_r.NAME=Zp;var va=class extends Br(ir){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=ir.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===vi){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Jp)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=a.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return o}let i=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,i,t,n))return-1;let s=i.subarray(t,t+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=Ya(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,t+n}toBER(e,t){if(this.isConstructed)return ir.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return $t;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}}};va.NAME="BitStringValueBlock";var sm,Io=class extends Ve{constructor({idBlock:e={},lenBlock:t={},...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,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},va),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return rn.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};sm=Io;H.BitString=sm;Io.NAME=Jp;var am;function Vv(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,u=0,l=c<s?s:c,f=0;for(let m=l;m>=0;m--,f++){switch(!0){case f<a.length:u=i[s-f]+a[c-f]+t[0];break;default:u=i[s-f]+t[0]}switch(t[0]=u/10,!0){case f>=i.length:i=ua(new Uint8Array([u%10]),i);break;default:i[s-f]=u%10}}return t[0]>0&&(i=ua(t,i)),i}function Xp(r){if(r>=xi.length)for(let e=xi.length;e<=r;e++){let t=new Uint8Array([0]),n=xi[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=i[0]/10,n[o]=i[0]%10}t[0]>0&&(n=ua(t,n)),xi.push(n)}return xi[r]}function Hv(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,u,l=0;for(let f=c;f>=0;f--,l++)switch(u=i[s-l]-a[c-l]-t,!0){case u<0:t=1,i[s-l]=u+10;break;default:t=0,i[s-l]=u}if(t>0)for(let f=s-c+1;f>=0;f--,l++)if(u=i[s-l]-t,u<0)t=1,i[s-l]=u+10;else{t=0,i[s-l]=u;break}return i.slice()}var Si=class extends Br(je){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Qu.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Wp(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let i=this.fromBER(e,t,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(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let u=0;u<8;u++){if((o&1)===1)switch(n){case e:t=Hv(Xp(n),t),s="-";break;default:t=Vv(t,Xp(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=Yp.charAt(t[c]));return a===!1&&(s+=Yp.charAt(0)),s}};am=Si;Si.NAME="IntegerValueBlock";Object.defineProperty(am.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var cm,Re=class r extends Ve{constructor(e={}){super(e,Si),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return fa(),BigInt(this.valueBlock.toString())}static fromBigInt(e){fa();let t=BigInt(e),n=new Ei,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(ee.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${ee.Convert.ToHex(a)}`)+t,l=ee.BufferSourceConverter.toUint8Array(ee.Convert.FromHex(u.toString(16)));l[0]|=128,n.write(l)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};cm=Re;H.Integer=cm;Re.NAME="INTEGER";var lm,Sa=class extends Re{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};lm=Sa;H.Enumerated=lm;Sa.NAME="ENUMERATED";var _i=class extends Br(je){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;let i=o.subarray(t,t+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=Pn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){fa();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let 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 t=tn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",$t;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let e="";if(this.isHexOnly)e=ee.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};_i.NAME="sidBlock";var _a=class extends je{constructor({value:e=Ro,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new _i;if(o=i.fromBER(e,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(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,$t;t.push(o)}return ef(t)}fromString(e){this.value=[];let t=0,n=0,o="",i=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=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 _i;if(o>Number.MAX_SAFE_INTEGER){fa();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 e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};_a.NAME="ObjectIdentifierValueBlock";var um,zt=class extends Ve{constructor(e={}){super(e,_a),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};um=zt;H.ObjectIdentifier=um;zt.NAME="OBJECT IDENTIFIER";var Ai=class extends Br(Sr){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=ee.BufferSourceConverter.toUint8Array(e);if(!kr(this,o,t,n))return-1;let i=o.subarray(t,t+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=Pn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let 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 t=tn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",$t;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ee.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ai.NAME="relativeSidBlock";var Aa=class extends je{constructor({value:e=Ro,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Ai;if(o=i.fromBER(e,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(e,t){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(e);if(i.byteLength===0)return this.error=this.value[o].error,$t;n.push(i)}return ef(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let i=new Ai;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Aa.NAME="RelativeObjectIdentifierValueBlock";var fm,ka=class extends Ve{constructor(e={}){super(e,Aa),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};fm=ka;H.RelativeObjectIdentifier=fm;ka.NAME="RelativeObjectIdentifier";var dm,De=class extends rn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};dm=De;H.Sequence=dm;De.NAME="SEQUENCE";var hm,Ba=class extends rn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};hm=Ba;H.Set=hm;Ba.NAME="SET";var Ia=class extends Br(je){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Ro}toJSON(){return{...super.toJSON(),value:this.value}}};Ia.NAME="StringValueBlock";var Ra=class extends Ia{};Ra.NAME="SimpleStringValueBlock";var tt=class extends pa{constructor({...e}={}){super(e,Ra)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,ee.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};tt.NAME="SIMPLE STRING";var Ta=class extends tt{fromBuffer(e){this.valueBlock.valueHexView=ee.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=ee.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=ee.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ee.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Ta.NAME="Utf8StringValueBlock";var pm,Ar=class extends Ta{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};pm=Ar;H.Utf8String=pm;Ar.NAME="UTF8String";var Na=class extends tt{fromBuffer(e){this.valueBlock.value=ee.Convert.ToUtf16String(e),this.valueBlock.valueHexView=ee.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ee.Convert.FromUtf16String(e))}};Na.NAME="BmpStringValueBlock";var mm,Ca=class extends Na{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};mm=Ca;H.BmpString=mm;Ca.NAME="BMPString";var La=class extends tt{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);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(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let i=tn(e.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=e}};La.NAME="UniversalStringValueBlock";var ym,Da=class extends La{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};ym=Da;H.UniversalString=ym;Da.NAME="UniversalString";var gm,Pa=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};gm=Pa;H.NumericString=gm;Pa.NAME="NumericString";var wm,Oa=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};wm=Oa;H.PrintableString=wm;Oa.NAME="PrintableString";var bm,Ua=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};bm=Ua;H.TeletexString=bm;Ua.NAME="TeletexString";var xm,Fa=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};xm=Fa;H.VideotexString=xm;Fa.NAME="VideotexString";var Em,Va=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Em=Va;H.IA5String=Em;Va.NAME="IA5String";var vm,Ha=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};vm=Ha;H.GraphicString=vm;Ha.NAME="GraphicString";var Sm,ki=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Sm=ki;H.VisibleString=Sm;ki.NAME="VisibleString";var _m,Ma=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};_m=Ma;H.GeneralString=_m;Ma.NAME="GeneralString";var Am,za=class extends tt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Am=za;H.CharacterString=Am;za.NAME="CharacterString";var km,Bi=class extends ki{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,ee.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let 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(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=ct(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=ct(this.month,2),t[2]=ct(this.day,2),t[3]=ct(this.hour,2),t[4]=ct(this.minute,2),t[5]=ct(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};km=Bi;H.UTCTime=km;Bi.NAME="UTCTime";var Bm,$a=class extends Bi{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",i=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,m=n.indexOf("+"),d="";if(m===-1&&(m=n.indexOf("-"),f=-1),m!==-1){if(d=n.substring(m+1),n=n.substring(0,m),d.length!==2&&d.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(d.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*p,d.length===4){if(p=parseInt(d.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=f*p}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let f=new Number(`0${n.substring(u)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");i=f.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,u!==-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,u!==-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,u!==-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,u!==-1){let f=1e3*i;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let l=s.exec(o);if(l===null)throw new Error("Wrong input string for conversion");for(let f=1;f<l.length;f++)switch(f){case 1:this.year=parseInt(l[f],10);break;case 2:this.month=parseInt(l[f],10);break;case 3:this.day=parseInt(l[f],10);break;case 4:this.hour=parseInt(l[f],10)+a;break;case 5:this.minute=parseInt(l[f],10)+c;break;case 6:this.second=parseInt(l[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(ct(this.year,4)),t.push(ct(this.month,2)),t.push(ct(this.day,2)),t.push(ct(this.hour,2)),t.push(ct(this.minute,2)),t.push(ct(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(ct(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Bm=$a;H.GeneralizedTime=Bm;$a.NAME="GeneralizedTime";var Im,Ka=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Im=Ka;H.DATE=Im;Ka.NAME="DATE";var Rm,qa=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Rm=qa;H.TimeOfDay=Rm;qa.NAME="TimeOfDay";var Tm,Ga=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Tm=Ga;H.DateTime=Tm;Ga.NAME="DateTime";var Nm,Wa=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Nm=Wa;H.Duration=Nm;Wa.NAME="Duration";var Cm,ja=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Cm=ja;H.TIME=Cm;ja.NAME="TIME";function zv(r){let{result:e}=To(r),t=e.valueBlock.value;return{n:W(sr(t[1].toBigInt()),"base64url"),e:W(sr(t[2].toBigInt()),"base64url"),d:W(sr(t[3].toBigInt()),"base64url"),p:W(sr(t[4].toBigInt()),"base64url"),q:W(sr(t[5].toBigInt()),"base64url"),dp:W(sr(t[6].toBigInt()),"base64url"),dq:W(sr(t[7].toBigInt()),"base64url"),qi:W(sr(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function $v(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 N("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new De({value:[new Re({value:0}),Re.fromBigInt(ar(U(r.n,"base64url"))),Re.fromBigInt(ar(U(r.e,"base64url"))),Re.fromBigInt(ar(U(r.d,"base64url"))),Re.fromBigInt(ar(U(r.p,"base64url"))),Re.fromBigInt(ar(U(r.q,"base64url"))),Re.fromBigInt(ar(U(r.dp,"base64url"))),Re.fromBigInt(ar(U(r.dq,"base64url"))),Re.fromBigInt(ar(U(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Kv(r){let{result:e}=To(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:W(sr(t[0].toBigInt()),"base64url"),e:W(sr(t[1].toBigInt()),"base64url")}}function qv(r){if(r.n==null||r.e==null)throw new N("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new De({value:[new De({value:[new zt({value:"1.2.840.113549.1.1.1"}),new nn]}),new Io({valueHex:new De({value:[Re.fromBigInt(ar(U(r.n,"base64url"))),Re.fromBigInt(ar(U(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function sr(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,i=0;for(;o<t;)n[o]=parseInt(e.slice(i,i+2),16),o+=1,i+=2;return n}function ar(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var Gv=16,rf=32,nf=1e4;async function Wv(r,e){let t=et.get(),o=new De({value:[new Re({value:0}),new De({value:[new zt({value:"1.2.840.113549.1.1.1"}),new nn]}),new _r({valueHex:r.marshal()})]}).toBER(),i=new Uint8Array(o,0,o.byteLength),s=Dn(Gv),a=await Zu(Eo,e,s,{c:nf,dkLen:rf}),c=Dn(16),u=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),l=await t.subtle.encrypt({name:"AES-CBC",iv:c},u,i),f=new De({value:[new _r({valueHex:s}),new Re({value:nf}),new Re({value:rf}),new De({value:[new zt({value:"1.2.840.113549.2.11"}),new nn]})]}),m=new De({value:[new zt({value:"1.2.840.113549.1.5.13"}),new De({value:[new De({value:[new zt({value:"1.2.840.113549.1.5.12"}),f]}),new De({value:[new zt({value:"2.16.840.1.101.3.4.1.42"}),new _r({valueHex:c})]})]})]}),p=new De({value:[m,new _r({valueHex:l})]}).toBER(),h=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...W(h,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
8
|
+
`)}async function jv(r,e){let t=et.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=U(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=To(o),{iv:s,salt:a,iterations:c,keySize:u,cipherText:l}=Yv(i),f=await Zu(Eo,e,a,{c,dkLen:u}),m=await t.subtle.importKey("raw",f,"AES-CBC",!1,["decrypt"]),d=Ii(await t.subtle.decrypt({name:"AES-CBC",iv:s},m,l)),{result:p}=To(d);n=Lm(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=U(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=To(o);n=Lm(i)}else throw new N("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return of(n)}function Yv(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new N("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new N("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let i=n.valueBlock.value[1],s=Ii(i.valueBlock.value[0].getValue()),a=nf,c=rf;if(i.valueBlock.value.length===3)a=Number(i.valueBlock.value[1].toBigInt()),c=Number(i.valueBlock.value[2].toBigInt());else if(i.valueBlock.value.length===2)throw new N("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let u=e.valueBlock.value[1].valueBlock.value[1],l=u.valueBlock.value[0].toString();if(l!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(l!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(l!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(l!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(l!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new N("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let f=Ii(u.valueBlock.value[1].getValue());return{cipherText:Ii(r.valueBlock.value[1].getValue()),salt:s,iterations:a,keySize:c,iv:f}}function Lm(r){return Ii(r.valueBlock.value[2].getValue())}function Ii(r){return new Uint8Array(r,0,r.byteLength)}async function Dm(r){let e=await et.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await Um(e);return{privateKey:t[0],publicKey:t[1]}}async function sf(r){let t=[await et.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Xv(r)],n=await Um({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Pm(r,e){let t=await et.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await et.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Om(r,e,t){let n=await et.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return et.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Um(r){if(r.privateKey==null||r.publicKey==null)throw new N("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([et.get().subtle.exportKey("jwk",r.privateKey),et.get().subtle.exportKey("jwk",r.publicKey)])}async function Xv(r){return et.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Xa(r){if(r.kty!=="RSA")throw new N("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new N("invalid key modulus","ERR_INVALID_KEY_MODULUS");return U(r.n,"base64url").length*8}var Ti=8192,Ri=class{_key;constructor(e){this._key=e}verify(e,t){return Om(this._key,t,e)}marshal(){return on.jwkToPkix(this._key)}get bytes(){return nr.encode({Type:me.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=ce.digest(this.bytes);return Ct(e)?e.then(({bytes:t})=>t):e.bytes}},No=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return Dn(16)}sign(e){return Pm(this._key,e)}get public(){if(this._publicKey==null)throw new N("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ri(this._publicKey)}marshal(){return on.jwkToPkcs1(this._key)}get bytes(){return or.encode({Type:me.RSA,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=ce.digest(this.bytes);return Ct(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return W(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return on.exportToPem(this,e);if(t==="libp2p-key")return Ao(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function of(r){let e=on.pkcs1ToJwk(r);if(Xa(e)>Ti)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await sf(e);return new No(t.privateKey,t.publicKey)}function Jv(r){let e=on.pkixToJwk(r);if(Xa(e)>Ti)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Ri(e)}async function Qv(r){if(Xa(r)>Ti)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await sf(r);return new No(e.privateKey,e.publicKey)}async function eS(r){if(r>Ti)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Dm(r);return new No(e.privateKey,e.publicKey)}var df={};xe(df,{Secp256k1PrivateKey:()=>Ci,Secp256k1PublicKey:()=>Ni,generateKeyPair:()=>hS,unmarshalSecp256k1PrivateKey:()=>fS,unmarshalSecp256k1PublicKey:()=>dS});var tS=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]),sn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),an=new Uint32Array(64),cf=class extends xo{constructor(){super(64,32,8,!1),this.A=sn[0]|0,this.B=sn[1]|0,this.C=sn[2]|0,this.D=sn[3]|0,this.E=sn[4]|0,this.F=sn[5]|0,this.G=sn[6]|0,this.H=sn[7]|0}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)an[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let m=an[f-15],d=an[f-2],p=Ht(m,7)^Ht(m,18)^m>>>3,h=Ht(d,17)^Ht(d,19)^d>>>10;an[f]=h+an[f-7]+p+an[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){let m=Ht(a,6)^Ht(a,11)^Ht(a,25),d=l+m+vp(a,c,u)+tS[f]+an[f]|0,h=(Ht(n,2)^Ht(n,13)^Ht(n,22))+Sp(n,o,i)|0;l=u,u=c,c=a,a=s+d|0,s=i,i=o,o=n,n=d+h|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,u=u+this.G|0,l=l+this.H|0,this.set(n,o,i,s,a,c,u,l)}roundClean(){an.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Fm=Xs(()=>new cf);function rS(r){let e=gi(r);rr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:nS,hexToBytes:oS}=Qs,On={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=On;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:nS(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=On,t=typeof r=="string"?oS(r):r;vo(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:i}=On._parseInt(t.subarray(2)),{d:s,l:a}=On._parseInt(i);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s}},hexFromSig(r){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,t=u=>{let l=u.toString(16);return l.length&1?`0${l}`:l},n=e(t(r.s)),o=e(t(r.r)),i=n.length/2,s=o.length/2,a=t(i),c=t(s);return`30${t(s+i+4)}02${c}${o}02${a}${n}`}},Ir=BigInt(0),Dt=BigInt(1),HN=BigInt(2),Vm=BigInt(3),MN=BigInt(4);function iS(r){let e=rS(r),{Fp:t}=e,n=e.toBytes||((p,h,y)=>{let g=h.toAffine();return br(Uint8Array.from([4]),t.toBytes(g.x),t.toBytes(g.y))}),o=e.fromBytes||(p=>{let h=p.subarray(1),y=t.fromBytes(h.subarray(0,t.BYTES)),g=t.fromBytes(h.subarray(t.BYTES,2*t.BYTES));return{x:y,y:g}});function i(p){let{a:h,b:y}=e,g=t.sqr(p),b=t.mul(g,p);return t.add(t.add(b,t.mul(p,h)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function s(p){return typeof p=="bigint"&&Ir<p&&p<e.n}function a(p){if(!s(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:h,nByteLength:y,wrapPrivateKey:g,n:b}=e;if(h&&typeof p!="bigint"){if(Jr(p)&&(p=gr(p)),typeof p!="string"||!h.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let x;try{x=typeof p=="bigint"?p:wr(Se("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return g&&(x=fe(x,b)),a(x),x}let u=new Map;function l(p){if(!(p instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(h,y,g){if(this.px=h,this.py=y,this.pz=g,h==null||!t.isValid(h))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(g==null||!t.isValid(g))throw new Error("z required")}static fromAffine(h){let{x:y,y:g}=h||{};if(!h||!t.isValid(y)||!t.isValid(g))throw new Error("invalid affine point");if(h instanceof f)throw new Error("projective point not allowed");let b=x=>t.eql(x,t.ZERO);return b(y)&&b(g)?f.ZERO:new f(y,g,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let y=t.invertBatch(h.map(g=>g.pz));return h.map((g,b)=>g.toAffine(y[b])).map(f.fromAffine)}static fromHex(h){let y=f.fromAffine(o(Se("pointHex",h)));return y.assertValidity(),y}static fromPrivateKey(h){return f.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:h,y}=this.toAffine();if(!t.isValid(h)||!t.isValid(y))throw new Error("bad point: x or y not FE");let g=t.sqr(y),b=i(h);if(!t.eql(g,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:h}=this.toAffine();if(t.isOdd)return!t.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:y,py:g,pz:b}=this,{px:x,py:v,pz:S}=h,I=t.eql(t.mul(y,S),t.mul(x,b)),_=t.eql(t.mul(g,S),t.mul(v,b));return I&&_}negate(){return new f(this.px,t.neg(this.py),this.pz)}double(){let{a:h,b:y}=e,g=t.mul(y,Vm),{px:b,py:x,pz:v}=this,S=t.ZERO,I=t.ZERO,_=t.ZERO,E=t.mul(b,b),P=t.mul(x,x),V=t.mul(v,v),L=t.mul(b,x);return L=t.add(L,L),_=t.mul(b,v),_=t.add(_,_),S=t.mul(h,_),I=t.mul(g,V),I=t.add(S,I),S=t.sub(P,I),I=t.add(P,I),I=t.mul(S,I),S=t.mul(L,S),_=t.mul(g,_),V=t.mul(h,V),L=t.sub(E,V),L=t.mul(h,L),L=t.add(L,_),_=t.add(E,E),E=t.add(_,E),E=t.add(E,V),E=t.mul(E,L),I=t.add(I,E),V=t.mul(x,v),V=t.add(V,V),E=t.mul(V,L),S=t.sub(S,E),_=t.mul(V,P),_=t.add(_,_),_=t.add(_,_),new f(S,I,_)}add(h){l(h);let{px:y,py:g,pz:b}=this,{px:x,py:v,pz:S}=h,I=t.ZERO,_=t.ZERO,E=t.ZERO,P=e.a,V=t.mul(e.b,Vm),L=t.mul(y,x),$=t.mul(g,v),C=t.mul(b,S),ne=t.add(y,g),B=t.add(x,v);ne=t.mul(ne,B),B=t.add(L,$),ne=t.sub(ne,B),B=t.add(y,b);let T=t.add(x,S);return B=t.mul(B,T),T=t.add(L,C),B=t.sub(B,T),T=t.add(g,b),I=t.add(v,S),T=t.mul(T,I),I=t.add($,C),T=t.sub(T,I),E=t.mul(P,B),I=t.mul(V,C),E=t.add(I,E),I=t.sub($,E),E=t.add($,E),_=t.mul(I,E),$=t.add(L,L),$=t.add($,L),C=t.mul(P,C),B=t.mul(V,B),$=t.add($,C),C=t.sub(L,C),C=t.mul(P,C),B=t.add(B,C),L=t.mul($,B),_=t.add(_,L),L=t.mul(T,B),I=t.mul(ne,I),I=t.sub(I,L),L=t.mul(ne,$),E=t.mul(T,E),E=t.add(E,L),new f(I,_,E)}subtract(h){return this.add(h.negate())}is0(){return this.equals(f.ZERO)}wNAF(h){return d.wNAFCached(this,u,h,y=>{let g=t.invertBatch(y.map(b=>b.pz));return y.map((b,x)=>b.toAffine(g[x])).map(f.fromAffine)})}multiplyUnsafe(h){let y=f.ZERO;if(h===Ir)return y;if(a(h),h===Dt)return this;let{endo:g}=e;if(!g)return d.unsafeLadder(this,h);let{k1neg:b,k1:x,k2neg:v,k2:S}=g.splitScalar(h),I=y,_=y,E=this;for(;x>Ir||S>Ir;)x&Dt&&(I=I.add(E)),S&Dt&&(_=_.add(E)),E=E.double(),x>>=Dt,S>>=Dt;return b&&(I=I.negate()),v&&(_=_.negate()),_=new f(t.mul(_.px,g.beta),_.py,_.pz),I.add(_)}multiply(h){a(h);let y=h,g,b,{endo:x}=e;if(x){let{k1neg:v,k1:S,k2neg:I,k2:_}=x.splitScalar(y),{p:E,f:P}=this.wNAF(S),{p:V,f:L}=this.wNAF(_);E=d.constTimeNegate(v,E),V=d.constTimeNegate(I,V),V=new f(t.mul(V.px,x.beta),V.py,V.pz),g=E.add(V),b=P.add(L)}else{let{p:v,f:S}=this.wNAF(y);g=v,b=S}return f.normalizeZ([g,b])[0]}multiplyAndAddUnsafe(h,y,g){let b=f.BASE,x=(S,I)=>I===Ir||I===Dt||!S.equals(b)?S.multiplyUnsafe(I):S.multiply(I),v=x(this,y).add(x(h,g));return v.is0()?void 0:v}toAffine(h){let{px:y,py:g,pz:b}=this,x=this.is0();h==null&&(h=x?t.ONE:t.inv(b));let v=t.mul(y,h),S=t.mul(g,h),I=t.mul(b,h);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:v,y:S}}isTorsionFree(){let{h,isTorsionFree:y}=e;if(h===Dt)return!0;if(y)return y(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:y}=e;return h===Dt?this:y?y(f,this):this.multiplyUnsafe(e.h)}toRawBytes(h=!0){return this.assertValidity(),n(f,this,h)}toHex(h=!0){return gr(this.toRawBytes(h))}}f.BASE=new f(e.Gx,e.Gy,t.ONE),f.ZERO=new f(t.ZERO,t.ONE,t.ZERO);let m=e.nBitLength,d=ra(f,e.endo?Math.ceil(m/2):m);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:s}}function sS(r){let e=gi(r);return rr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Hm(r){let e=sS(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(B){return Ir<B&&B<t.ORDER}function a(B){return fe(B,n)}function c(B){return ea(B,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:l,weierstrassEquation:f,isWithinCurveOrder:m}=iS({...e,toBytes(B,T,G){let R=T.toAffine(),A=t.toBytes(R.x),M=br;return G?M(Uint8Array.from([T.hasEvenY()?2:3]),A):M(Uint8Array.from([4]),A,t.toBytes(R.y))},fromBytes(B){let T=B.length,G=B[0],R=B.subarray(1);if(T===o&&(G===2||G===3)){let A=wr(R);if(!s(A))throw new Error("Point is not on curve");let M=f(A),K;try{K=t.sqrt(M)}catch(Z){let ae=Z instanceof Error?": "+Z.message:"";throw new Error("Point is not on curve"+ae)}let j=(K&Dt)===Dt;return(G&1)===1!==j&&(K=t.neg(K)),{x:A,y:K}}else if(T===i&&G===4){let A=t.fromBytes(R.subarray(0,t.BYTES)),M=t.fromBytes(R.subarray(t.BYTES,2*t.BYTES));return{x:A,y:M}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),d=B=>gr(en(B,e.nByteLength));function p(B){let T=n>>Dt;return B>T}function h(B){return p(B)?a(-B):B}let y=(B,T,G)=>wr(B.slice(T,G));class g{constructor(T,G,R){this.r=T,this.s=G,this.recovery=R,this.assertValidity()}static fromCompact(T){let G=e.nByteLength;return T=Se("compactSignature",T,G*2),new g(y(T,0,G),y(T,G,2*G))}static fromDER(T){let{r:G,s:R}=On.toSig(Se("DER",T));return new g(G,R)}assertValidity(){if(!m(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!m(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(T){return new g(this.r,this.s,T)}recoverPublicKey(T){let{r:G,s:R,recovery:A}=this,M=_(Se("msgHash",T));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let K=A===2||A===3?G+e.n:G;if(K>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let j=A&1?"03":"02",X=u.fromHex(j+d(K)),Z=c(K),ae=a(-M*Z),te=a(R*Z),oe=u.BASE.multiplyAndAddUnsafe(X,ae,te);if(!oe)throw new Error("point at infinify");return oe.assertValidity(),oe}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Tn(this.toDERHex())}toDERHex(){return On.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Tn(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let b={isValidPrivateKey(B){try{return l(B),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let B=$u(e.n);return Dp(e.randomBytes(B),e.n)},precompute(B=8,T=u.BASE){return T._setWindowSize(B),T.multiply(BigInt(3)),T}};function x(B,T=!0){return u.fromPrivateKey(B).toRawBytes(T)}function v(B){let T=Jr(B),G=typeof B=="string",R=(T||G)&&B.length;return T?R===o||R===i:G?R===2*o||R===2*i:B instanceof u}function S(B,T,G=!0){if(v(B))throw new Error("first arg must be private key");if(!v(T))throw new Error("second arg must be public key");return u.fromHex(T).multiply(l(B)).toRawBytes(G)}let I=e.bits2int||function(B){let T=wr(B),G=B.length*8-e.nBitLength;return G>0?T>>BigInt(G):T},_=e.bits2int_modN||function(B){return a(I(B))},E=yi(e.nBitLength);function P(B){if(typeof B!="bigint")throw new Error("bigint expected");if(!(Ir<=B&&B<E))throw new Error(`bigint expected < 2^${e.nBitLength}`);return en(B,e.nByteLength)}function V(B,T,G=L){if(["recovered","canonical"].some(be=>be in G))throw new Error("sign() legacy options not supported");let{hash:R,randomBytes:A}=e,{lowS:M,prehash:K,extraEntropy:j}=G;M==null&&(M=!0),B=Se("msgHash",B),K&&(B=Se("prehashed msgHash",R(B)));let X=_(B),Z=l(T),ae=[P(Z),P(X)];if(j!=null&&j!==!1){let be=j===!0?A(t.BYTES):j;ae.push(Se("extraEntropy",be))}let te=br(...ae),oe=X;function Be(be){let Oe=I(be);if(!m(Oe))return;let Ue=c(Oe),Ne=u.BASE.multiply(Oe).toAffine(),$e=a(Ne.x);if($e===Ir)return;let pr=a(Ue*a(oe+$e*Z));if(pr===Ir)return;let vn=(Ne.x===$e?0:2)|Number(Ne.y&Dt),oi=pr;return M&&p(pr)&&(oi=h(pr),vn^=1),new g($e,oi,vn)}return{seed:te,k2sig:Be}}let L={lowS:e.lowS,prehash:!1},$={lowS:e.lowS,prehash:!1};function C(B,T,G=L){let{seed:R,k2sig:A}=V(B,T,G),M=e;return Vu(M.hash.outputLen,M.nByteLength,M.hmac)(R,A)}u.BASE._setWindowSize(8);function ne(B,T,G,R=$){let A=B;if(T=Se("msgHash",T),G=Se("publicKey",G),"strict"in R)throw new Error("options.strict was renamed to lowS");let{lowS:M,prehash:K}=R,j,X;try{if(typeof A=="string"||Jr(A))try{j=g.fromDER(A)}catch(Ne){if(!(Ne instanceof On.Err))throw Ne;j=g.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:Ne,s:$e}=A;j=new g(Ne,$e)}else throw new Error("PARSE");X=u.fromHex(G)}catch(Ne){if(Ne.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(M&&j.hasHighS())return!1;K&&(T=e.hash(T));let{r:Z,s:ae}=j,te=_(T),oe=c(ae),Be=a(te*oe),be=a(Z*oe),Oe=u.BASE.multiplyAndAddUnsafe(X,Be,be)?.toAffine();return Oe?a(Oe.x)===Z:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:S,sign:C,verify:ne,ProjectivePoint:u,Signature:g,utils:b}}function aS(r){return{hash:r,hmac:(e,...t)=>bi(r,e,Ys(...t)),randomBytes:bo}}function Mm(r,e){let t=n=>Hm({...r,...aS(n)});return Object.freeze({...t(e),create:t})}var Km=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),zm=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),cS=BigInt(1),lf=BigInt(2),$m=(r,e)=>(r+e/lf)/e;function lS(r){let e=Km,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%e,l=u*u*r%e,f=pe(l,t,e)*l%e,m=pe(f,t,e)*l%e,d=pe(m,lf,e)*u%e,p=pe(d,o,e)*d%e,h=pe(p,i,e)*p%e,y=pe(h,a,e)*h%e,g=pe(y,c,e)*y%e,b=pe(g,a,e)*h%e,x=pe(b,t,e)*l%e,v=pe(x,s,e)*p%e,S=pe(v,n,e)*u%e,I=pe(S,lf,e);if(!uf.eql(uf.sqr(I),r))throw new Error("Cannot find square root");return I}var uf=ta(Km,void 0,void 0,{sqrt:lS}),Kt=Mm({a:BigInt(0),b:BigInt(7),Fp:uf,n:zm,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=zm,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-cS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=$m(i*r,e),c=$m(-n*r,e),u=fe(r-a*t-c*o,e),l=fe(-a*n-c*i,e),f=u>s,m=l>s;if(f&&(u=e-u),m&&(l=e-l),u>s||l>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:u,k2neg:m,k2:l}}}},Fm),XN=BigInt(0);var ZN=Kt.ProjectivePoint;function qm(){return Kt.utils.randomPrivateKey()}function Gm(r,e){let t=ce.digest(e instanceof Uint8Array?e:e.subarray());if(Ct(t))return t.then(({digest:n})=>Kt.sign(n,r).toDERRawBytes()).catch(n=>{throw new N(String(n),"ERR_INVALID_INPUT")});try{return Kt.sign(t.digest,r).toDERRawBytes()}catch(n){throw new N(String(n),"ERR_INVALID_INPUT")}}function Wm(r,e,t){let n=ce.digest(t instanceof Uint8Array?t:t.subarray());if(Ct(n))return n.then(({digest:o})=>Kt.verify(e,o,r)).catch(o=>{throw new N(String(o),"ERR_INVALID_INPUT")});try{return Kt.verify(e,n.digest,r)}catch(o){throw new N(String(o),"ERR_INVALID_INPUT")}}function jm(r){return Kt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Ym(r){try{Kt.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}function ff(r){try{Kt.ProjectivePoint.fromHex(r)}catch(e){throw new N(String(e),"ERR_INVALID_PUBLIC_KEY")}}function Xm(r){try{return Kt.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Ni=class{_key;constructor(e){ff(e),this._key=e}verify(e,t){return Wm(this._key,t,e)}marshal(){return jm(this._key)}get bytes(){return nr.encode({Type:me.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}async hash(){let e=ce.digest(this.bytes),t;return Ct(e)?{bytes:t}=await e:t=e.bytes,t}},Ci=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??Xm(e),Ym(this._key),ff(this._publicKey)}sign(e){return Gm(this._key,e)}get public(){return new Ni(this._publicKey)}marshal(){return this._key}get bytes(){return or.encode({Type:me.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ie(this.bytes,e.bytes)}hash(){let e=ce.digest(this.bytes);return Ct(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return W(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return Ao(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function fS(r){return new Ci(r)}function dS(r){return new Ni(r)}async function hS(){let r=qm();return new Ci(r)}var Un={rsa:af,ed25519:Xu,secp256k1:df};function Zm(r){let e=Object.keys(Un).join(" / ");return new N(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function hf(r){let e=nr.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case me.RSA:return Un.rsa.unmarshalRsaPublicKey(t);case me.Ed25519:return Un.ed25519.unmarshalEd25519PublicKey(t);case me.Secp256k1:return Un.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw Zm(e.Type??"unknown")}}async function Jm(r){let e=or.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case me.RSA:return Un.rsa.unmarshalRsaPrivateKey(t);case me.Ed25519:return Un.ed25519.unmarshalEd25519PrivateKey(t);case me.Secp256k1:return Un.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw Zm(e.Type??"RSA")}}var If=J(Ie(),1);var Rr="/",Qm=new TextEncoder().encode(Rr),Za=Qm[0],ke=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=U(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Za)throw new Error("Invalid key")}toString(e="utf8"){return W(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Rr))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Qm),this._buf[0]!==Za){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Za,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Za;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Rr).slice(1)}type(){return pS(this.baseNamespace())}name(){return mS(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Rr)||(e+=Rr),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Rr):new r(e.slice(0,-1).join(Rr))}child(e){return this.toString()===Rr?e:e.toString()===Rr?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...yS(e.map(t=>t.namespaces()))])}};function pS(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function mS(r){let e=r.split(":");return e[e.length-1]}function yS(r){return[].concat(...r)}var mg=J(Ja(),1);var ey="ERR_IPNS_EXPIRED_RECORD",Li="ERR_UNRECOGNIZED_VALIDITY",ty="ERR_SIGNATURE_CREATION",Tr="ERR_SIGNATURE_VERIFICATION";var mf="ERR_UNDEFINED_PARAMETER",ry="ERR_INVALID_RECORD_DATA",ny="ERR_INVALID_VALUE",oy="ERR_INVALID_EMBEDDED_KEY",iy="ERR_MISSING_PRIVATE_KEY",sy="ERR_RECORD_TOO_LARGE";var He;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),function(o){o.codec=()=>Rn(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=Tt((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)=>{let s={},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.value=o.bytes();break;case 2:s.signatureV1=o.bytes();break;case 3:s.validityType=r.ValidityType.codec().decode(o);break;case 4:s.validity=o.bytes();break;case 5:s.sequence=o.uint64();break;case 6:s.ttl=o.uint64();break;case 7:s.pubKey=o.bytes();break;case 8:s.signatureV2=o.bytes();break;case 9:s.data=o.bytes();break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>Rt(o,r.codec()),r.decode=o=>Bt(o,r.codec())})(He||(He={}));var gS=["string","number","bigint","symbol"],wS=["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 ay(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(gS.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(bS(r))return"Buffer";let t=xS(r);return t||"Object"}function bS(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function xS(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(wS.includes(e))return e}var w=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};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 k=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Co=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ES=new TextDecoder,vS=new TextEncoder;function Qa(r){return Co&&globalThis.Buffer.isBuffer(r)}function Di(r){return r instanceof Uint8Array?Qa(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var fy=Co?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):ly(r,e,t):(r,e,t)=>t-e>64?ES.decode(r.subarray(e,t)):ly(r,e,t),ec=Co?r=>r.length>64?globalThis.Buffer.from(r):cy(r):r=>r.length>64?vS.encode(r):cy(r),cr=r=>Uint8Array.from(r),Lo=Co?(r,e,t)=>Qa(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),dy=Co?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Di(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},hy=Co?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function py(r,e){if(Qa(r)&&Qa(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function cy(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function ly(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,c,u,l;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(l=(o&31)<<6|a&63,l>127&&(i=l));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(l=(o&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(i=l));break;case 4:a=r[e+1],c=r[e+2],u=r[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(o&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(i=l))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return gf(n)}var uy=4096;function gf(r){let e=r.length;if(e<=uy)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=uy));return t}var SS=256,Pi=class{constructor(e=SS){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=hy(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=Lo(n,0,this.cursor)}else t=dy(this.chunks,this.cursor);return e&&this.reset(),t}};var z="CBOR decode error:",Nr="CBOR encode error:",Oi=[];Oi[23]=1;Oi[24]=2;Oi[25]=3;Oi[26]=5;Oi[27]=9;function Cr(r,e,t){if(r.length-e<t)throw new Error(`${z} not enough data for type`)}var Pe=[24,256,65536,4294967296,BigInt("18446744073709551616")];function wt(r,e,t){Cr(r,e,1);let n=r[e];if(t.strict===!0&&n<Pe[0])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return n}function bt(r,e,t){Cr(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Pe[1])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return n}function xt(r,e,t){Cr(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Pe[2])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return n}function Et(r,e,t){Cr(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<Pe[3])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${z} integers outside of the safe integer range are not supported`)}function my(r,e,t,n){return new k(w.uint,wt(r,e+1,n),2)}function yy(r,e,t,n){return new k(w.uint,bt(r,e+1,n),3)}function gy(r,e,t,n){return new k(w.uint,xt(r,e+1,n),5)}function wy(r,e,t,n){return new k(w.uint,Et(r,e+1,n),9)}function Pt(r,e){return Me(r,0,e.value)}function Me(r,e,t){if(t<Pe[0]){let n=Number(t);r.push([e|n])}else if(t<Pe[1]){let n=Number(t);r.push([e|24,n])}else if(t<Pe[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Pe[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<Pe[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${z} encountered BigInt larger than allowable range`)}}Pt.encodedSize=function(e){return Me.encodedSize(e.value)};Me.encodedSize=function(e){return e<Pe[0]?1:e<Pe[1]?2:e<Pe[2]?3:e<Pe[3]?5:9};Pt.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function by(r,e,t,n){return new k(w.negint,-1-wt(r,e+1,n),2)}function xy(r,e,t,n){return new k(w.negint,-1-bt(r,e+1,n),3)}function Ey(r,e,t,n){return new k(w.negint,-1-xt(r,e+1,n),5)}var wf=BigInt(-1),vy=BigInt(1);function Sy(r,e,t,n){let o=Et(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new k(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${z} integers outside of the safe integer range are not supported`);return new k(w.negint,wf-BigInt(o),9)}function tc(r,e){let t=e.value,n=typeof t=="bigint"?t*wf-vy:t*-1-1;Me(r,e.type.majorEncoded,n)}tc.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*wf-vy:t*-1-1;return n<Pe[0]?1:n<Pe[1]?2:n<Pe[2]?3:n<Pe[3]?5:9};tc.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Ui(r,e,t,n){Cr(r,e,t+n);let o=Lo(r,e+t,e+t+n);return new k(w.bytes,o,t+n)}function _y(r,e,t,n){return Ui(r,e,1,t)}function Ay(r,e,t,n){return Ui(r,e,2,wt(r,e+1,n))}function ky(r,e,t,n){return Ui(r,e,3,bt(r,e+1,n))}function By(r,e,t,n){return Ui(r,e,5,xt(r,e+1,n))}function Iy(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer bytes lengths not supported`);return Ui(r,e,9,o)}function rc(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===w.string?ec(r.value):r.value),r.encodedBytes}function Do(r,e){let t=rc(e);Me(r,e.type.majorEncoded,t.length),r.push(t)}Do.encodedSize=function(e){let t=rc(e);return Me.encodedSize(t.length)+t.length};Do.compareTokens=function(e,t){return AS(rc(e),rc(t))};function AS(r,e){return r.length<e.length?-1:r.length>e.length?1:py(r,e)}function Fi(r,e,t,n,o){let i=t+n;Cr(r,e,i);let s=new k(w.string,fy(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Lo(r,e+t,e+i)),s}function Ry(r,e,t,n){return Fi(r,e,1,t,n)}function Ty(r,e,t,n){return Fi(r,e,2,wt(r,e+1,n),n)}function Ny(r,e,t,n){return Fi(r,e,3,bt(r,e+1,n),n)}function Cy(r,e,t,n){return Fi(r,e,5,xt(r,e+1,n),n)}function Ly(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer string lengths not supported`);return Fi(r,e,9,o,n)}var Dy=Do;function Po(r,e,t,n){return new k(w.array,n,t)}function Py(r,e,t,n){return Po(r,e,1,t)}function Oy(r,e,t,n){return Po(r,e,2,wt(r,e+1,n))}function Uy(r,e,t,n){return Po(r,e,3,bt(r,e+1,n))}function Fy(r,e,t,n){return Po(r,e,5,xt(r,e+1,n))}function Vy(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer array lengths not supported`);return Po(r,e,9,o)}function Hy(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return Po(r,e,1,1/0)}function nc(r,e){Me(r,w.array.majorEncoded,e.value)}nc.compareTokens=Pt.compareTokens;nc.encodedSize=function(e){return Me.encodedSize(e.value)};function Oo(r,e,t,n){return new k(w.map,n,t)}function My(r,e,t,n){return Oo(r,e,1,t)}function zy(r,e,t,n){return Oo(r,e,2,wt(r,e+1,n))}function $y(r,e,t,n){return Oo(r,e,3,bt(r,e+1,n))}function Ky(r,e,t,n){return Oo(r,e,5,xt(r,e+1,n))}function qy(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer map lengths not supported`);return Oo(r,e,9,o)}function Gy(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return Oo(r,e,1,1/0)}function oc(r,e){Me(r,w.map.majorEncoded,e.value)}oc.compareTokens=Pt.compareTokens;oc.encodedSize=function(e){return Me.encodedSize(e.value)};function Wy(r,e,t,n){return new k(w.tag,t,1)}function jy(r,e,t,n){return new k(w.tag,wt(r,e+1,n),2)}function Yy(r,e,t,n){return new k(w.tag,bt(r,e+1,n),3)}function Xy(r,e,t,n){return new k(w.tag,xt(r,e+1,n),5)}function Zy(r,e,t,n){return new k(w.tag,Et(r,e+1,n),9)}function ic(r,e){Me(r,w.tag.majorEncoded,e.value)}ic.compareTokens=Pt.compareTokens;ic.encodedSize=function(e){return Me.encodedSize(e.value)};var NS=20,CS=21,LS=22,DS=23;function Jy(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${z} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new k(w.null,null,1):new k(w.undefined,void 0,1)}function Qy(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return new k(w.break,void 0,1)}function bf(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${z} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${z} Infinity values are not supported`)}return new k(w.float,r,e)}function eg(r,e,t,n){return bf(xf(r,e+1),3,n)}function tg(r,e,t,n){return bf(Ef(r,e+1),5,n)}function rg(r,e,t,n){return bf(sg(r,e+1),9,n)}function sc(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|NS]);else if(n===!0)r.push([w.float.majorEncoded|CS]);else if(n===null)r.push([w.float.majorEncoded|LS]);else if(n===void 0)r.push([w.float.majorEncoded|DS]);else{let o,i=!1;(!t||t.float64!==!0)&&(og(n),o=xf(qt,1),n===o||Number.isNaN(n)?(qt[0]=249,r.push(qt.slice(0,3)),i=!0):(ig(n),o=Ef(qt,1),n===o&&(qt[0]=250,r.push(qt.slice(0,5)),i=!0))),i||(PS(n),o=sg(qt,1),qt[0]=251,r.push(qt.slice(0,9)))}}sc.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){og(n);let o=xf(qt,1);if(n===o||Number.isNaN(n))return 3;if(ig(n),o=Ef(qt,1),n===o)return 5}return 9};var ng=new ArrayBuffer(9),Ot=new DataView(ng,1),qt=new Uint8Array(ng,0);function og(r){if(r===1/0)Ot.setUint16(0,31744,!1);else if(r===-1/0)Ot.setUint16(0,64512,!1);else if(Number.isNaN(r))Ot.setUint16(0,32256,!1);else{Ot.setFloat32(0,r);let e=Ot.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Ot.setUint16(0,31744,!1);else if(t===0)Ot.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Ot.setUint16(0,0):o<-14?Ot.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Ot.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function xf(r,e){if(r.length-e<2)throw new Error(`${z} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function ig(r){Ot.setFloat32(0,r,!1)}function Ef(r,e){if(r.length-e<4)throw new Error(`${z} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function PS(r){Ot.setFloat64(0,r,!1)}function sg(r,e){if(r.length-e<8)throw new Error(`${z} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}sc.compareTokens=Pt.compareTokens;function se(r,e,t){throw new Error(`${z} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function ac(r){return()=>{throw new Error(`${z} ${r}`)}}var D=[];for(let r=0;r<=23;r++)D[r]=se;D[24]=my;D[25]=yy;D[26]=gy;D[27]=wy;D[28]=se;D[29]=se;D[30]=se;D[31]=se;for(let r=32;r<=55;r++)D[r]=se;D[56]=by;D[57]=xy;D[58]=Ey;D[59]=Sy;D[60]=se;D[61]=se;D[62]=se;D[63]=se;for(let r=64;r<=87;r++)D[r]=_y;D[88]=Ay;D[89]=ky;D[90]=By;D[91]=Iy;D[92]=se;D[93]=se;D[94]=se;D[95]=ac("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)D[r]=Ry;D[120]=Ty;D[121]=Ny;D[122]=Cy;D[123]=Ly;D[124]=se;D[125]=se;D[126]=se;D[127]=ac("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)D[r]=Py;D[152]=Oy;D[153]=Uy;D[154]=Fy;D[155]=Vy;D[156]=se;D[157]=se;D[158]=se;D[159]=Hy;for(let r=160;r<=183;r++)D[r]=My;D[184]=zy;D[185]=$y;D[186]=Ky;D[187]=qy;D[188]=se;D[189]=se;D[190]=se;D[191]=Gy;for(let r=192;r<=215;r++)D[r]=Wy;D[216]=jy;D[217]=Yy;D[218]=Xy;D[219]=Zy;D[220]=se;D[221]=se;D[222]=se;D[223]=se;for(let r=224;r<=243;r++)D[r]=ac("simple values are not supported");D[244]=se;D[245]=se;D[246]=se;D[247]=Jy;D[248]=ac("simple values are not supported");D[249]=eg;D[250]=tg;D[251]=rg;D[252]=se;D[253]=se;D[254]=se;D[255]=Qy;var Gt=[];for(let r=0;r<24;r++)Gt[r]=new k(w.uint,r,1);for(let r=-1;r>=-24;r--)Gt[31-r]=new k(w.negint,r,1);Gt[64]=new k(w.bytes,new Uint8Array(0),1);Gt[96]=new k(w.string,"",1);Gt[128]=new k(w.array,0,1);Gt[160]=new k(w.map,0,1);Gt[244]=new k(w.false,!1,1);Gt[245]=new k(w.true,!0,1);Gt[246]=new k(w.null,null,1);function vf(r){switch(r.type){case w.false:return cr([244]);case w.true:return cr([245]);case w.null:return cr([246]);case w.bytes:return r.value.length?void 0:cr([64]);case w.string:return r.value===""?cr([96]):void 0;case w.array:return r.value===0?cr([128]):void 0;case w.map:return r.value===0?cr([160]):void 0;case w.uint:return r.value<24?cr([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return cr([31-Number(r.value)])}}var US={float64:!1,mapSorter:VS,quickEncodeToken:vf};function _f(){let r=[];return r[w.uint.major]=Pt,r[w.negint.major]=tc,r[w.bytes.major]=Do,r[w.string.major]=Dy,r[w.array.major]=nc,r[w.map.major]=oc,r[w.tag.major]=ic,r[w.float.major]=sc,r}var ag=_f(),Sf=new Pi,cc=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Nr} object contains circular references`);return new r(t,e)}},cn={null:new k(w.null,null),undefined:new k(w.undefined,void 0),true:new k(w.true,!0),false:new k(w.false,!1),emptyArray:new k(w.array,0),emptyMap:new k(w.map,0)},ln={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new k(w.float,r):r>=0?new k(w.uint,r):new k(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new k(w.uint,r):new k(w.negint,r)},Uint8Array(r,e,t,n){return new k(w.bytes,r)},string(r,e,t,n){return new k(w.string,r)},boolean(r,e,t,n){return r?cn.true:cn.false},null(r,e,t,n){return cn.null},undefined(r,e,t,n){return cn.undefined},ArrayBuffer(r,e,t,n){return new k(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new k(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[cn.emptyArray,new k(w.break)]:cn.emptyArray;n=cc.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Vi(s,t,n);return t.addBreakTokens?[new k(w.array,r.length),o,new k(w.break)]:[new k(w.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[cn.emptyMap,new k(w.break)]:cn.emptyMap;n=cc.createCheck(n,r);let a=[],c=0;for(let u of i)a[c++]=[Vi(u,t,n),Vi(o?r.get(u):r[u],t,n)];return FS(a,t),t.addBreakTokens?[new k(w.map,s),a,new k(w.break)]:[new k(w.map,s),a]}};ln.Map=ln.Object;ln.Buffer=ln.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ln[`${r}Array`]=ln.DataView;function Vi(r,e={},t){let n=ay(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||ln[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=ln[n];if(!i)throw new Error(`${Nr} unsupported type: ${n}`);return i(r,n,e,t)}function FS(r,e){e.mapSorter&&r.sort(e.mapSorter)}function VS(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=ag[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function cg(r,e,t,n){if(Array.isArray(e))for(let o of e)cg(r,o,t,n);else t[e.type.major](r,e,n)}function Af(r,e,t){let n=Vi(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new Pi(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Di(a.chunks[0])}}return Sf.reset(),cg(Sf,n,e,t),Sf.toBytes(!0)}function un(r,e){return e=Object.assign({},US,e),Af(r,ag,e)}var HS={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},lc=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Gt[e];if(t===void 0){let n=D[e];if(!n)throw new Error(`${z} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},Hi=Symbol.for("DONE"),uc=Symbol.for("BREAK");function MS(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Uo(e,t);if(i===uc){if(r.value===1/0)break;throw new Error(`${z} got unexpected break to lengthed array`)}if(i===Hi)throw new Error(`${z} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function zS(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=Uo(e,t);if(a===uc){if(r.value===1/0)break;throw new Error(`${z} got unexpected break to lengthed map`)}if(a===Hi)throw new Error(`${z} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${z} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${z} found repeat map key "${a}"`);let c=Uo(e,t);if(c===Hi)throw new Error(`${z} 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 Uo(r,e){if(r.done())return Hi;let t=r.next();if(t.type===w.break)return uc;if(t.type.terminal)return t.value;if(t.type===w.array)return MS(t,r,e);if(t.type===w.map)return zS(t,r,e);if(t.type===w.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Uo(r,e);return e.tags[t.value](n)}throw new Error(`${z} tag not supported (${t.value})`)}throw new Error("unsupported")}function kf(r,e){if(!(r instanceof Uint8Array))throw new Error(`${z} data to decode must be a Uint8Array`);e=Object.assign({},HS,e);let t=e.tokenizer||new lc(r,e),n=Uo(t,e);if(n===Hi)throw new Error(`${z} did not find any content to decode`);if(n===uc)throw new Error(`${z} got unexpected break`);return[n,r.subarray(t.pos())]}function rt(r,e){let[t,n]=kf(r,e);if(n.length>0)throw new Error(`${z} too many terminals, data makes no sense`);return t}var lt=J(Ie(),1);var lg=Q("ipns:utils"),ug=U("/ipns/"),$S=114,fg=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw lg.error(n),(0,lt.default)(n,mf)}let t;if(e.pubKey!=null){try{t=hf(e.pubKey)}catch(o){throw lg.error(o),o}if(!(await tp(e.pubKey)).equals(r))throw(0,lt.default)(new Error("Embedded public key did not match PeerID"),oy)}else r.publicKey!=null&&(t=hf(r.publicKey));if(t!=null)return t;throw(0,lt.default)(new Error("no public key is available"),mf)},dg=(r,e,t)=>{let n=U(e);return ue([r,t,n])},dc=r=>{let e=U("ipns-signature:");return ue([e,r])},Lr=r=>"signatureV1"in r?He.encode({value:U(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:U(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):He.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data});function Ye(r){let e=He.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw(0,lt.default)(new Error("missing data or signatureV2"),Tr);let t=pg(e.data),n=Bf(t.Value),o=W(t.Validity);if(e.value!=null&&e.signatureV1!=null)return KS(e),{value:n,validityType:He.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:He.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}var Fo=r=>ue([ug,r.toBytes()]),Vo=r=>pi(r.slice(ug.length)),hg=(r,e,t,n,o)=>{let i;if(e===He.ValidityType.EOL)i=0;else throw(0,lt.default)(new Error("Unknown validity type"),Li);return un({Value:r,Validity:t,ValidityType:i,Sequence:n,TTL:o})},pg=r=>{let e=rt(r);if(e.ValidityType===0)e.ValidityType=He.ValidityType.EOL;else throw(0,lt.default)(new Error("Unknown validity type"),Li);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e},Bf=r=>{if(r!=null){if(dh(r))return`/ipns/${r.toCID().toString(Gr)}`;if(r instanceof Uint8Array){let n=W(r);n.startsWith("/")&&(r=n)}let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e;let t=O.asCID(r);if(t!=null)return t.code===$S?`/ipns/${t.toString(Gr)}`:`/ipfs/${t.toV1().toString()}`;try{return r instanceof Uint8Array?`/ipfs/${O.decode(r).toV1().toString()}`:`/ipfs/${O.parse(e).toV1().toString()}`}catch{}}throw(0,lt.default)(new Error("Value must be a valid content path starting with /"),ny)},KS=r=>{if(r.data==null)throw(0,lt.default)(new Error("Record data is missing"),ry);let e=pg(r.data);if(!ie(e.Value,r.value??new Uint8Array(0)))throw(0,lt.default)(new Error('Field "value" did not match between protobuf and CBOR'),Tr);if(!ie(e.Validity,r.validity??new Uint8Array(0)))throw(0,lt.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Tr);if(e.ValidityType!==r.validityType)throw(0,lt.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Tr);if(e.Sequence!==r.sequence)throw(0,lt.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Tr);if(e.TTL!==r.ttl)throw(0,lt.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Tr)};var qS=Q("ipns"),GS=Ge.code,yg=60*60*1e9,WS="/ipns/",O6=WS.length,gg={v1Compatible:!0,ttlNs:yg};async function wg(r,e,t,n,o=gg){let i=new mg.default(Date.now()+Number(n)),s=He.ValidityType.EOL,a=BigInt(o.ttlNs!=null?o.ttlNs:yg);return jS(r,e,t,s,i.toString(),a,o)}var jS=async(r,e,t,n,o,i,s=gg)=>{t=BigInt(t);let a=U(o),c=Bf(e),u=U(c);if(r.privateKey==null)throw(0,If.default)(new Error("Missing private key"),iy);let l=await Jm(r.privateKey),f=hg(u,n,a,t,i),m=dc(f),d=await l.sign(m),p;if(r.publicKey!=null){let h=Je(r.toBytes());(h.code!==GS||!ie(r.publicKey,h.digest))&&(p=r.publicKey)}if(s.v1Compatible===!0){let h=await YS(l,u,n,a),y={value:c,signatureV1:h,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:d,data:f};return p!=null&&(y.pubKey=p),y}else{let h={value:c,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:d,data:f};return p!=null&&(h.pubKey=p),h}};var YS=async(r,e,t,n)=>{try{let o=dg(e,t,n);return await r.sign(o)}catch(o){throw qS.error("record signature creation failed",o),(0,If.default)(new Error("record signature creation failed"),ty)}};var Mi=J(Ie(),1),bg=J(Ja(),1);var hc=Q("ipns:validator"),XS=1024*10,ZS=async(r,e)=>{let t=Ye(e),n;try{let o=dc(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw hc.error("record signature verification failed"),(0,Mi.default)(new Error("record signature verification failed"),Tr);if(t.validityType===He.ValidityType.EOL){if(bg.default.fromString(t.validity).toDate().getTime()<Date.now())throw hc.error("record has expired"),(0,Mi.default)(new Error("record has expired"),ey)}else if(t.validityType!=null)throw hc.error("unrecognized validity type"),(0,Mi.default)(new Error("unrecognized validity type"),Li);hc("ipns record for %s is valid",t.value)};async function zi(r,e){if(e.byteLength>XS)throw(0,Mi.default)(new Error("record too large"),sy);let t=Vo(r),n=Ye(e),o=await fg(t,n);await ZS(o,e)}async function*$i(r){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=t.decode(o,{stream:!0});let i=n.split(e);n=i.pop()??"";for(let s=0;s<i.length;s++)yield JSON.parse(i[s])}n+=t.decode(),n!==""&&(yield JSON.parse(n))}var Tf=J(Eg(),1);var qi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Nf=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},vg=r=>globalThis.DOMException===void 0?new Nf(r):new DOMException(r),Sg=r=>{let e=r.reason===void 0?vg("This operation was aborted."):r.reason;return e instanceof Error?e:vg(e)};function Gi(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,c=new Promise((u,l)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:m}=e;m.aborted&&l(Sg(m)),m.addEventListener("abort",()=>{l(Sg(m))})}if(t===Number.POSITIVE_INFINITY){r.then(u,l);return}let f=new qi;s=i.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){l(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?l(o):(f.message=o??`Promise timed out after ${t} milliseconds`,l(f))},t),(async()=>{try{u(await r)}catch(m){l(m)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function Cf(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var Wi=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Cf(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var ut=class extends Tf.default{#e;#t;#r=0;#s;#c;#p=0;#o;#l;#n;#m;#i=0;#u;#a;#y;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Wi,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#s=e.intervalCap,this.#c=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=e.throwOnTimeout===!0,this.#a=e.autoStart===!1}get#b(){return this.#t||this.#r<this.#s}get#x(){return this.#i<this.#u}#E(){this.#i--,this.#f(),this.emit("next")}#v(){this.#w(),this.#g(),this.#l=void 0}get#S(){let e=Date.now();if(this.#o===void 0){let t=this.#p-e;if(t<0)this.#r=this.#e?this.#i:0;else return this.#l===void 0&&(this.#l=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#i===0&&this.emit("idle"),!1;if(!this.#a){let e=!this.#S;if(this.#b&&this.#x){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#g(),!0):!1}}return!1}#g(){this.#t||this.#o!==void 0||(this.#o=setInterval(()=>{this.#w()},this.#c),this.#p=Date.now()+this.#c)}#w(){this.#r===0&&this.#i===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#r=this.#e?this.#i:0,this.#d()}#d(){for(;this.#f(););}get concurrency(){return this.#u}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#u=e,this.#d()}async#_(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#y,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#i++,this.#r++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=Gi(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#_(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof qi&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#E()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#a?(this.#a=!1,this.#d(),this):this}pause(){this.#a=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#h("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#h("next",()=>this.#n.size<e)}async onIdle(){this.#i===0&&this.#n.size===0||await this.#h("idle")}async#h(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#i}get isPaused(){return this.#a}};function e2(r){return r[Symbol.asyncIterator]!=null}function t2(r){if(e2(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Vn=t2;var Lf=U("/ipns/");function _g(r){return ie(r.subarray(0,Lf.byteLength),Lf)}var Ag=r=>pi(r.slice(Lf.length)),mc=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*We(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!_g(e))return;let o=Ag(e),i=Ye(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!_g(e))throw new N("Not found","ERR_NOT_FOUND");let n=Ag(e);try{let o=await this.client.getIPNS(n,t);return Lr(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}},yc=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await Vn(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new N("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){}};var ft=Q("delegated-routing-v1-http-api-client"),kg={concurrentRequests:4,timeout:3e4},gc=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,to(1/0,this.shutDownController.signal),this.httpQueue=new ut({concurrency:t.concurrentRequests??kg.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??kg.timeout,this.contentRouting=new mc(this),this.peerRouting=new yc(this)}get[ci](){return this.contentRouting}get[li](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(e,t={}){ft("getProviders starts: %c",e);let n=Sn([this.shutDownController.signal,t.signal,AbortSignal.timeout(this.timeout)]),o=ve(),i=ve();this.httpQueue.add(async()=>(o.resolve(),i.promise));try{await o.promise;let s=`${this.clientUrl}routing/v1/providers/${e.toString()}`,c=await fetch(s,{headers:{Accept:"application/x-ndjson"},signal:n});if(c.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(c.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(c.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(c.headers.get("Content-Type")==="application/json"){let l=await c.json();for(let f of l.Providers){let m=this.#e(f);m!=null&&(yield m)}}else for await(let l of $i(Gs(c.body))){let f=this.#e(l);f!=null&&(yield f)}}catch(s){ft.error("getProviders errored:",s)}finally{n.clear(),i.resolve(),ft("getProviders finished: %c",e)}}async*getPeers(e,t={}){ft("getPeers starts: %c",e);let n=Sn([this.shutDownController.signal,t.signal,AbortSignal.timeout(this.timeout)]),o=ve(),i=ve();this.httpQueue.add(async()=>(o.resolve(),i.promise));try{await o.promise;let s=`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`,c=await fetch(s,{headers:{Accept:"application/x-ndjson"},signal:n});if(c.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(c.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(c.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(c.headers.get("Content-Type")==="application/json"){let l=await c.json();for(let f of l.Peers){let m=this.#e(f);m!=null&&(yield m)}}else for await(let l of $i(Gs(c.body))){let f=this.#e(l);f!=null&&(yield f)}}catch(s){ft.error("getPeers errored:",s)}finally{n.clear(),i.resolve(),ft("getPeers finished: %c",e)}}async getIPNS(e,t={}){ft("getIPNS starts: %c",e);let n=Sn([this.shutDownController.signal,t.signal,AbortSignal.timeout(this.timeout)]),o=ve(),i=ve();this.httpQueue.add(async()=>(o.resolve(),i.promise));let s=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await o.promise;let c=await fetch(s,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:n});if(ft("getIPNS GET %s %d",s,c.status),c.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(c.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(c.body==null)throw new N("GET ipns response had no body","ERR_BAD_RESPONSE");let u=await c.arrayBuffer(),l=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await zi(Fo(e),l),Ye(l)}catch(a){throw ft.error("getIPNS GET %s error:",s,a),a}finally{n.clear(),i.resolve(),ft("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){ft("putIPNS starts: %c",e);let o=Sn([this.shutDownController.signal,n.signal,AbortSignal.timeout(this.timeout)]),i=ve(),s=ve();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await i.promise;let c=Lr(t),l=await fetch(a,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:c,signal:o});if(ft("putIPNS PUT %s %d",a,l.status),l.status!==200)throw new N("PUT ipns response had status other than 200","ERR_BAD_RESPONSE")}catch(c){throw ft.error("putIPNS PUT %s error:",a,c.stack),c}finally{o.clear(),s.resolve(),ft("putIPNS finished: %c",e)}}#e(e){let t=[],n=e.Addrs?.map(mi)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Qe(e.ID),Addrs:n,Protocols:t}}};function Bg(r,e={}){return new gc(new URL(r),e)}var Ig=U("/ipns/");function Rg(r){return ie(r.subarray(0,Ig.byteLength),Ig)}var Df=class{client;constructor(e){this.client=Bg(e)}async provide(e,t){}async*findProviders(e,t){yield*We(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols}))}async put(e,t,n){if(!Rg(e))return;let o=Vo(e),i=Ye(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!Rg(e))throw new N("Not found","ERR_NOT_FOUND");let n=Vo(e);try{let o=await this.client.getIPNS(n,t);return Lr(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}async findPeer(e,t){let n=await Vn(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new N("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t){}};function ji(r){return new Df(new URL(r))}function wc(r){let e=[dt.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Pf=60;function bc(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:dt[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:dt[e.type],TTL:e.TTL??e.ttl??Pf,data:e.data instanceof Uint8Array?W(e.data):e.data}))}}var r2=4;function Of(r,e={}){let t=new ut({concurrency:e.queryConcurrency??r2});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),wc(o.types).forEach(a=>{i.append("type",dt[a])}),o.onProgress?.(new F("dns:query",{detail:n}));let s=await t.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=bc(await a.json());return o.onProgress?.(new F("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Tg(){return[Of("https://cloudflare-dns.com/dns-query"),Of("https://dns.google/resolve")]}var Cg=J(Uf(),1);var Ff=class{lru;constructor(e){this.lru=(0,Cg.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return bc({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:dt[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Pf)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Lg(r){return new Ff(r)}var n2=1e3,xc=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Lg(e.cacheSize??n2),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Tg())}async query(e,t={}){let n=wc(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new F("dns:cache",{detail:o})),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let u=await c(e,{...t,types:n});for(let l of u.Answer)this.cache.add(e,l);return u}catch(u){a.push(u),t.onProgress?.(new F("dns:error",{detail:u}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var dt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(dt||(dt={}));function Yi(r={}){return new xc(r)}var Vf=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Ec(r,e,t,n){let o=new Vf(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{let a=u=>{try{if(n?.filter?.(u)===!1)return}catch(l){r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(l);return}r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(u)},c=()=>{r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(o)};r.addEventListener(e,a),t?.addEventListener("abort",c)})}var vc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Dg(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new vc(t?.errorMessage,t?.errorCode));let n,o=new vc(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Sc=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=ve(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(new Qt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function o2(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var _c=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=o2(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,to(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&this.controller.abort(new Qt)}async join(e={}){let t=new Sc(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Dg(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.signal?.removeEventListener("abort",this.onAbort)})}};function i2(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var Xi=class extends Rs{concurrency;queue;pending;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){if(this.queue[this.size-1]?.priority>=e.priority){this.queue.push(e);return}let t=i2(this.queue,e,(n,o)=>o.priority-n.priority);this.queue.splice(t,0,e)}async add(e,t){t?.signal?.throwIfAborted();let n=new _c(e,t,t?.priority),o=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),i)).catch(i=>{throw this.safeDispatchEvent("error",{detail:i}),i});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Qt)}),this.clear()}async onEmpty(e){this.size!==0&&await Ec(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Ec(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Ec(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Nt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new N("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var Fg="/pin/",Pg="/pinned-block/",Hf=Gr,Og=1;function Ug(r){return r.version===0&&(r=r.toV1()),new ke(`${Fg}${r.toString(Hf)}`)}var Ac=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers=n}async*add(e,t={}){let n=Ug(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new Xi({concurrency:Og});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(u=>ie(u,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,un(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=this.dagWalkers[e.code];if(o==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let i=await this.blockstore.get(e,n);yield e;for await(let s of o.walk(i))yield*await t.add(async()=>this.#e(s,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new ke(`${Pg}${Hf.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=rt(await this.datastore.get(o,n))}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,un(i),n),n.onProgress?.(new F("helia:pin:add",e))}}async*rm(e,t={}){let n=Ug(e),o=await this.datastore.get(n,t),i=rt(o);await this.datastore.delete(n,t);let s=new Xi({concurrency:Og});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(u=>ie(u,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Fg+(e.cid!=null?`${e.cid.toString(Gr)}`:"")},e)){let o=O.parse(t.toString().substring(5),Gr),i=rt(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new ke(`${Pg}${Hf.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};function Mf(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var Ho=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Mf(this.set.entries(),e=>{let t=Qe(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Qe(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Mf(this.set.values(),e=>Qe(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var kc=class{log;routers;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[]}async start(){await $r(...this.routers)}async stop(){await Kr(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new N("No content routers available","ERR_NO_ROUTERS_AVAILABLE");let n=new Ho;for await(let o of mr(...Mo(this.routers,"findProviders").map(i=>i.findProviders(e,t))))o!=null&&(n.has(o.id)||(n.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new N("No content routers available","ERR_NO_ROUTERS_AVAILABLE");await Promise.all(Mo(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(Mo(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(Mo(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new N("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");let n=this,o=mr(...Mo(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new N("Could not find peer in routing","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new N("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");let n=new Ho;for await(let o of mr(...Mo(this.routers,"getClosestPeers").map(i=>i.getClosestPeers(e,t))))o!=null&&(n.has(o.id)||(n.add(o.id),yield o))}};function Mo(r,e){return r.filter(t=>t[e]!=null)}var fn={},zo=r=>{r.addEventListener("message",e=>{zo.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{zo.dispatchEvent("message",r,e)})};zo.addEventListener=(r,e)=>{fn[r]==null&&(fn[r]=[]),fn[r].push(e)};zo.removeEventListener=(r,e)=>{fn[r]!=null&&(fn[r]=fn[r].filter(t=>t===e))};zo.dispatchEvent=function(r,e,t){fn[r]!=null&&fn[r].forEach(n=>n(e,t))};var zf=zo;var $f="lock:worker:request-read",Kf="lock:worker:release-read",qf="lock:master:grant-read",Gf="lock:worker:request-write",Wf="lock:worker:release-write",jf="lock:master:grant-write";var Vg=(r=21)=>Math.random().toString().substring(2);var Hg=(r,e,t,n,o)=>(i,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let u=l=>{if(l==null||l.data==null)return;let f={type:l.data.type,name:l.data.name,identifier:l.data.identifier};f.type===n&&f.identifier===a.identifier&&(i.removeEventListener("message",u),c())};i.addEventListener("message",u)})}}}))},Mg=(r,e,t,n)=>async()=>{let o=Vg();return globalThis.postMessage({type:e,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===t&&c.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},s2={singleProcess:!1},zg=r=>{if(r=Object.assign({},s2,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return zf.addEventListener("message",Hg(t,"requestReadLock",$f,Kf,qf)),zf.addEventListener("message",Hg(t,"requestWriteLock",Gf,Wf,jf)),t}return{isWorker:!0,readLock:t=>Mg(t,$f,qf,Kf),writeLock:t=>Mg(t,Gf,jf,Wf)}};var Hn={},dn;async function Yf(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Gi((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var a2=(r,e)=>{if(dn.isWorker===!0)return{readLock:dn.readLock(r,e),writeLock:dn.writeLock(r,e)};let t=new ut({concurrency:1}),n;return{async readLock(){if(n!=null)return Yf(n,e);n=new ut({concurrency:e.concurrency,autoStart:!1});let o=n,i=Yf(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,Yf(t,e)}}},c2={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Xf(r){let e=Object.assign({},c2,r);return dn==null&&(dn=zg(e),dn.isWorker!==!0&&(dn.addEventListener("requestReadLock",t=>{Hn[t.data.name]!=null&&Hn[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),dn.addEventListener("requestWriteLock",async t=>{Hn[t.data.name]!=null&&Hn[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Hn[e.name]==null&&(Hn[e.name]=a2(e.name,e)),Hn[e.name]}var Bc=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Xf({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await $r(this.child),this.started=!0}async stop(){await Kr(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),t)}finally{n()}}async has(e,t={}){let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}};var $g=42;function l2(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function u2(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=O.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new k(w.tag,$g),new k(w.bytes,t)]}function f2(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function d2(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 Zf={float64:!0,typeEncoders:{Object:u2,undefined:f2,number:d2}},a4={...Zf,typeEncoders:{...Zf.typeEncoders}};function h2(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return O.decode(r.subarray(1))}var Ic={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Ic.tags[$g]=h2;var c4={...Ic,tags:Ic.tags.slice()};var hn=113,Zi=r=>un(r,Zf),Mn=r=>rt(l2(r),Ic);var Jf=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===w.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===w.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[w.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[w.negint.major](e,t){this[w.uint.major](e,t)}[w.bytes.major](e,t){throw new Error(`${Nr} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=ec(JSON.stringify(t.value));e.push(n.length>32?Di(n):n)}[w.array.major](e,t){this.prefix(e),this.inRecursive.push({type:w.array,elements:0}),e.push([91])}[w.map.major](e,t){this.prefix(e),this.inRecursive.push({type:w.map,elements:0}),e.push([123])}[w.tag.major](e,t){}[w.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===w.array)e.push([93]);else if(s.type===w.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Nr} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.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)),e.push(o)}};function p2(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Nr} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==w.string||n.type!==w.string)throw new Error(`${Nr} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Nr} unexpected duplicate map keys, this is not supported`)}var m2={addBreakTokens:!0,mapSorter:p2};function Qi(r,e){return e=Object.assign({},m2,e),Af(r,new Jf,e)}var pn=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,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 e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${z} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${z} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new k(w.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${z} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${z} 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(e,this._pos)),s=parseFloat(i);return n?new k(w.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new k(s>=0?w.uint:w.negint,s,this._pos-e):new k(s>=0?w.uint:w.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${z} 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 k(w.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${z} 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(`${z} 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(`${z} unexpected unicode sequence at position ${this._pos}`);let c,u,l,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],u=this.data[this._pos+2],(c&192)===128&&(u&192)===128&&(f=(i&15)<<12|(c&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],u=this.data[this._pos+2],l=this.data[this._pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(f=(i&15)<<18|(c&63)<<12|(u&63)<<6|l&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.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(`${z} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${z} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new k(w.string,gf(t),this._pos-e);default:if(i<32)throw new Error(`${z} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${z} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new k(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new k(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new k(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new k(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new k(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(`${z} 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 k(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${z} 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 k(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 k(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${z} 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 k(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${z} 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"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${z} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function es(r,e){return e=Object.assign({tokenizer:new pn(r,e)},e),rt(r,e)}function y2(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 e=O.asCID(r);if(!e)return null;let t=e.toString();return[new k(w.map,1/0,1),new k(w.string,"/",1),new k(w.string,t,t.length),new k(w.break,void 0,1)]}function Rc(r){let e=er.encode(r).slice(1);return[new k(w.map,1/0,1),new k(w.string,"/",1),new k(w.map,1/0,1),new k(w.string,"bytes",5),new k(w.string,e,e.length),new k(w.break,void 0,1),new k(w.break,void 0,1)]}function Wt(r){return Rc(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function w2(r){return Rc(new Uint8Array(r))}function b2(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function x2(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 E2={typeEncoders:{Object:g2,Buffer:Rc,Uint8Array:Rc,Int8Array:Wt,Uint16Array:Wt,Int16Array:Wt,Uint32Array:Wt,Int32Array:Wt,Float32Array:Wt,Float64Array:Wt,Uint8ClampedArray:Wt,BigInt64Array:Wt,BigUint64Array:Wt,DataView:Wt,ArrayBuffer:w2,undefined:b2,number:x2}},Qf=class extends pn{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===w.map){let t=this._next();if(t.type===w.string&&t.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 k(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=er.decode(`m${i.value}`);return new k(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},ed={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};ed.tags[42]=O.parse;var mn=297,qg=r=>Qi(r,E2),Tc=r=>{let e=y2(r),t=Object.assign(ed,{tokenizer:new Qf(e,ed)});return es(e,t)};var A4=new TextDecoder;var k4=new TextEncoder;var Te={};xe(Te,{code:()=>ye,createLink:()=>t0,createNode:()=>e0,decode:()=>we,encode:()=>re,name:()=>C2,prepare:()=>_e,validate:()=>nd});var v2=new TextDecoder;function td(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Cc(r,e){let t;[t,e]=td(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function Gg(r,e){let t;return[t,e]=td(r,e),[t&7,t>>3,e]}function S2(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=Gg(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Cc(r,n)}else if(i===2){if(e.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(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=Cc(r,n),e.Name=v2.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=td(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Wg(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=Gg(r,t),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,t]=Cc(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,t]=Cc(r,t),n.push(S2(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var Yg=new TextEncoder,jg=2**32,_2=2**31;function A2(r,e){let t=e.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");t=ts(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Yg.encode(r.Name);t-=n.length,e.set(n,t),t=ts(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=ts(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Xg(r){let e=B2(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=ts(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=A2(r.Links[o],t.subarray(0,n));n-=i,n=ts(t,n,i)-1,t[n]=18}return t}function k2(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+$o(t)}if(typeof r.Name=="string"){let t=Yg.encode(r.Name).length;e+=1+t+$o(t)}return typeof r.Tsize=="number"&&(e+=1+$o(r.Tsize)),e}function B2(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+$o(t)}if(r.Links)for(let t of r.Links){let n=k2(t);e+=1+n+$o(n)}return e}function ts(r,e,t){e-=$o(t);let n=e;for(;t>=_2;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function $o(r){return r%2===0&&r++,Math.floor((I2(r)+6)/7)}function I2(r){let e=0;return r>=jg&&(r=Math.floor(r/jg),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+R2[r]}var R2=[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 T2=["Data","Links"],N2=["Hash","Name","Tsize"],rd=new TextEncoder;function Jg(r,e){if(r===e)return 0;let t=r.Name?rd.encode(r.Name):[],n=e.Name?rd.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function Zg(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Qg(r){if(typeof r.asCID=="object"){let t=O.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=O.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=O.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=O.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function _e(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 e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=rd.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(Qg),e.Links.sort(Jg);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function nd(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Zg(r,T2))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 e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Zg(t,N2))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&Jg(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function e0(r,e=[]){return _e({Data:r,Links:e})}function t0(r,e,t){return Qg({Hash:t,Name:r,Tsize:e})}function r0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var C2="dag-pb",ye=112;function re(r){nd(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),Xg(e)}function we(r){let e=r0(r),t=Wg(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=O.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}var L2={codec:ye,*walk(r){yield*we(r).Links.map(t=>t.Hash)}},D2={codec:ge,*walk(){}},n0=42,P2={codec:hn,*walk(r){let e=[],t=[];t[n0]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let o=O.decode(n.subarray(1));return e.push(o),o},rt(r,{tags:t}),yield*e}},od=class extends pn{tokenBuffer;constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===w.map){let t=this._next();if(t.type===w.string&&t.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 k(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=er.decode(`m${i.value}`);return new k(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},O2={codec:mn,*walk(r){let e=[],t=[];t[n0]=n=>{let o=O.parse(n);return e.push(o),o},es(r,{tags:t,tokenizer:new od(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}},U2={codec:Wr,*walk(){}};function o0(r=[]){let e={};return[L2,D2,P2,O2,U2,...r].forEach(t=>{e[t.codec]=t}),e}var id=new ke("/version"),i0=1;async function s0(r){if(!await r.has(id)){await r.put(id,U(`${i0}`));return}let e=await r.get(id),t=W(e);if(parseInt(t,10)!==i0)throw new Error("Unknown datastore version, a datastore migration may be required")}function a0(r=[]){let e={};return[ce,Ml,Ge,...r].forEach(t=>{e[t.code]=t}),e}var lr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var qo={};xe(qo,{abortedError:()=>z2,closeFailedError:()=>V2,deleteFailedError:()=>ad,getFailedError:()=>H2,hasFailedError:()=>M2,notFoundError:()=>Ko,openFailedError:()=>F2,putFailedError:()=>sd});var Dr=J(Ie(),1);function F2(r){return r=r??new Error("Open failed"),(0,Dr.default)(r,"ERR_OPEN_FAILED")}function V2(r){return r=r??new Error("Close failed"),(0,Dr.default)(r,"ERR_CLOSE_FAILED")}function sd(r){return r=r??new Error("Put failed"),(0,Dr.default)(r,"ERR_PUT_FAILED")}function H2(r){return r=r??new Error("Get failed"),(0,Dr.default)(r,"ERR_GET_FAILED")}function ad(r){return r=r??new Error("Delete failed"),(0,Dr.default)(r,"ERR_DELETE_FAILED")}function M2(r){return r=r??new Error("Has failed"),(0,Dr.default)(r,"ERR_HAS_FAILED")}function Ko(r){return r=r??new Error("Not Found"),(0,Dr.default)(r,"ERR_NOT_FOUND")}function z2(r){return r=r??new Error("Aborted"),(0,Dr.default)(r,"ERR_ABORTED")}var rs=class extends lr{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(Fe.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(Fe.encode(e.multihash.bytes));if(t==null)throw Ko();return t}has(e){return this.data.has(Fe.encode(e.multihash.bytes))}async delete(e){this.data.delete(Fe.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:O.createV1(ge,Je(Fe.decode(e))),block:t}}};function $2(r){return r[Symbol.asyncIterator]!=null}function K2(r,e){if($2(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=Yn(r),{value:n,done:o}=t.next();if(o===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){await i&&(yield n);for await(let a of t)await e(a)&&(yield a)}();let s=e;return function*(){i===!0&&(yield n);for(let a of t)s(a)&&(yield a)}()}var ht=K2;var q2=Q("blockstore:core:tiered"),ns=class extends lr{stores;constructor(e){super(),this.stores=e.slice()}async put(e,t,n){try{return await Promise.all(this.stores.map(async o=>{await o.put(e,t,n)})),e}catch(o){throw sd(o)}}async get(e,t){for(let n of this.stores)try{let o=await n.get(e,t);if(o!=null)return o}catch(o){q2.error(o)}throw Ko()}async has(e,t){for(let n of this.stores)if(await n.has(e,t))return!0;return!1}async delete(e,t){try{await Promise.all(this.stores.map(async n=>{await n.delete(e,t)}))}catch(n){throw ad(n)}}async*putMany(e,t={}){let n,o=this.stores.map(i=>{let s=Nt({objectMode:!0});return Ft(i.putMany(s,t)).catch(a=>{n=a}),s});try{for await(let i of e){if(n!=null)throw n;o.forEach(s=>s.push(i)),yield i.cid}}finally{o.forEach(i=>i.end())}}async*deleteMany(e,t={}){let n,o=this.stores.map(i=>{let s=Nt({objectMode:!0});return Ft(i.deleteMany(s,t)).catch(a=>{n=a}),s});try{for await(let i of e){if(n!=null)throw n;o.forEach(s=>s.push(i)),yield i}}finally{o.forEach(i=>i.end())}}async*getAll(e){let t=new Set;yield*ht(mr(...this.stores.map(n=>n.getAll(e))),n=>{let o=n.cid.toString();return t.has(o)?!1:(t.add(o),!0)})}};var c0={...qo};var Lc=0,Dc=class extends lr{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Lc||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Lc)return e.multihash.digest;if(this.child==null)throw c0.notFoundError();return this.child.get(e)}has(e){return e.multihash.code===Lc?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Lc&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function G2(r){return typeof r.retrieve=="function"}function W2(r){return typeof r.announce=="function"}var Pc=class{child;blockRetrievers;blockAnnouncers;hashers;started;log;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.child=new ns([new Dc,e.blockstore]),this.blockRetrievers=(e.blockBrokers??[]).filter(G2),this.blockAnnouncers=(e.blockBrokers??[]).filter(W2),this.hashers=e.hashers??{},this.started=!1}isStarted(){return this.started}async start(){await $r(this.child,...new Set([...this.blockRetrievers,...this.blockAnnouncers])),this.started=!0}async stop(){await Kr(this.child,...new Set([...this.blockRetrievers,...this.blockAnnouncers])),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){return await this.child.has(e)?(n.onProgress?.(new F("blocks:put:duplicate",e)),e):(n.onProgress?.(new F("blocks:put:providers:notify",e)),this.blockAnnouncers.forEach(o=>{o.announce(e,t,n)}),n.onProgress?.(new F("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=ht(e,async({cid:i})=>{let s=await this.child.has(i);return s&&t.onProgress?.(new F("blocks:put-many:duplicate",i)),!s}),o=kl(n,({cid:i,block:s})=>{t.onProgress?.(new F("blocks:put-many:providers:notify",i)),this.blockAnnouncers.forEach(a=>{a.announce(i,s,t)})});t.onProgress?.(new F("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e)){t.onProgress?.(new F("blocks:get:providers:get",e));let n=await l0(e,this.blockRetrievers,this.hashers[e.multihash.code],{...t,log:this.log});return t.onProgress?.(new F("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),t.onProgress?.(new F("blocks:get:providers:notify",e)),this.blockAnnouncers.forEach(o=>{o.announce(e,n,t)}),n}return t.onProgress?.(new F("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new F("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(kl(e,async n=>{if(t.offline!==!0&&!await this.child.has(n)){t.onProgress?.(new F("blocks:get-many:providers:get",n));let o=await l0(n,this.blockRetrievers,this.hashers[n.multihash.code],{...t,log:this.log});t.onProgress?.(new F("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new F("blocks:get-many:providers:notify",n)),this.blockAnnouncers.forEach(i=>{i.announce(n,o,t)})}}))}async delete(e,t={}){t.onProgress?.(new F("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new F("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new F("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},j2=(r,e)=>{if(e==null)throw new N(`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`,"ERR_UNKNOWN_HASH_ALG");return async t=>{let n=await e.digest(t);if(!ie(n.digest,r.multihash.digest))throw new N("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function l0(r,e,t,n){let o=j2(r,t),i=new AbortController,s=Sn([i.signal,n.signal]);try{return await Promise.any(e.map(async a=>{try{let c=!1,u=await a.retrieve(r,{...n,signal:s,validateFn:async l=>{await o(l),c=!0}});return c||await o(u),u}catch(c){throw n.log.error("could not retrieve verified block for %c",r,c),c}}))}finally{s.clear()}}var Oc=class{blockstore;datastore;pins;logger;routing;dagWalkers;hashers;dns;log;constructor(e){this.logger=e.logger??Eh(),this.log=this.logger.forComponent("helia"),this.hashers=a0(e.hashers),this.dagWalkers=o0(e.dagWalkers),this.dns=e.dns??Yi();let t={blockstore:e.blockstore,datastore:e.datastore,hashers:this.hashers,dagWalkers:this.dagWalkers,logger:this.logger,blockBrokers:[],dns:this.dns,...e.components??{}};t.blockBrokers=e.blockBrokers.map(o=>o(t));let n=new Pc(t);this.pins=new Ac(e.datastore,n,this.dagWalkers),this.blockstore=new Bc(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,this.routing=new kc(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[ci]!=null&&i.push(o[ci]),o[li]!=null&&i.push(o[li]),i})})}async start(){await s0(this.datastore),await $r(this.blockstore,this.datastore,this.routing)}async stop(){await Kr(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Ft(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new F("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new F("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};var u0=J(Ie(),1);function Uc(r){return r=r??new Error("Not Found"),(0,u0.default)(r,"ERR_NOT_FOUND")}var f0="SHARDING";function X2(r){return r[Symbol.asyncIterator]!=null}function Z2(r){if(X2(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var is=Z2;function J2(r){return r[Symbol.asyncIterator]!=null}function Q2(r,e){return J2(r)?async function*(){yield*(await is(r)).sort(e)}():function*(){yield*is(r).sort(e)}()}var Fc=Q2;var Pr=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Ft(this.putMany(e,n)),e=[],await Ft(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=ht(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>ht(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>Fc(o,i),n)),e.offset!=null){let o=0,i=e.offset;n=ht(n,()=>o++>=i)}return e.limit!=null&&(n=Vs(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=ht(n,i=>i.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>ht(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>Fc(o,i),n)),e.offset!=null){let o=e.offset,i=0;n=ht(n,()=>i++>=o)}return e.limit!=null&&(n=Vs(n,e.limit)),n}};var ss=class extends Pr{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw Uc();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new ke(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new ke(e)}};var aP=new ke(f0);var bP=Q("datastore:core:tiered");async function h0(r={}){let e=r.datastore??new ss,t=r.blockstore??new rs,n=new Oc({...r,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[di()],routers:r.routers??[ji("https://delegated-ipfs.dev")]});return r.start!==!1&&await n.start(),n}var cd=J(Cs(),1);var ld=40;function ud(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=cd.default.decode(r);return e.seek(cd.default.decode.bytes),t}function fd(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var yn={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},as={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":yn.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(yn.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=as["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=as["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:yn.Int,CarV1HeaderOrV2Pragma:r=>{if(yn.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=as["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=as.Int(r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},cs={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":yn.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(yn.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=cs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=cs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:yn.Int,CarV1HeaderOrV2Pragma:r=>{if(yn.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=cs["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=cs.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},dd={toTyped:as.CarV1HeaderOrV2Pragma,toRepresentation:cs.CarV1HeaderOrV2Pragma};var nO=_f();var i_=J(Cs(),1);var cO=[new k(w.map,2),new k(w.string,"version"),new k(w.uint,1),new k(w.string,"roots")],lO=new k(w.tag,42);async function hd(r,e){let t=ud(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=Mn(n);if(dd.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);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=fd(await r.exactly(ld,!0));r.seek(i.dataOffset-r.pos);let s=await hd(r,1);return Object.assign(s,i)}function ls(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let o=r.subarray(e,e+t);return n&&(e+=t),o},seek(t){e+=t},get pos(){return e}}}var pd=J(Cs(),1),y0=1;function md(r){let e=Zi({version:y0,roots:r}),t=pd.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function g0(r){return{async setRoots(e){let t=md(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(pd.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return y0}}}function Vc(){}function w0(){let r=[],e=null,t=Vc,n=!1,o=null,i=Vc,s=()=>(e||(e=new Promise(u=>{t=()=>{e=null,t=Vc,u()}})),e),a={write(u){r.push(u);let l=s();return i(),l},async end(){n=!0;let u=s();i(),await u}},c={async next(){let u=r.shift();return u?(r.length===0&&t(),{done:!1,value:u}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(l=>{i=()=>(o=null,i=Vc,l(c.next()))})),o)}};return{writer:a,iterator:c}}var us=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=O.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.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(e){e=l_(e);let{encoder:t,iterator:n}=b0(),o=new r(e,t),i=new Hc(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=b0();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new Hc(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=ls(e);await hd(n);let o=md(t);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 e.set(o,0),e}},Hc=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function b0(){let r=w0(),{writer:e,iterator:t}=r;return{encoder:g0(e),iterator:t}}function l_(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=O.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=O.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var u_=1,yd=class{components;constructor(e,t){this.components=e}async import(e,t){await Ft(this.components.blockstore.putMany(We(e.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),t))}async export(e,t,n){let o=ve(),i=Array.isArray(e)?e:[e],s=new ut({concurrency:u_});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#e(a,s,async(c,u)=>{await t.put({cid:c,bytes:u})},n)}).catch(()=>{});try{await o.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:o}=us.create(e);this.export(e,n,t).catch(()=>{});for await(let i of o)yield i}async#e(e,t,n,o){let i=this.components.dagWalkers[e.code];if(i==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.components.blockstore.get(e,o);await n(e,s);for await(let a of i.walk(s))t.add(async()=>{await this.#e(a,t,n,o)})}};function x0(r,e={}){return new yd(r,e)}var gd=J(Ja(),1);function E0(r,e){let t=e.map((n,o)=>({record:Ye(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===He.ValidityType.EOL&&o.record.validityType===He.ValidityType.EOL){let a=gd.default.fromString(n.record.validity).toDate(),c=gd.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var f_=32;async function v0(r,e,t,n,o={}){if(e===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=(await t.query(r,{...o,types:[dt.TXT]})).Answer.sort((u,l)=>u.data.localeCompare(l.data));n("found %d TXT records for %s",s.length,r);for(let u of s)try{let l=u.data;if(l.startsWith('"')&&l.endsWith('"')&&(l=l.substring(1,l.length-1)),!l.startsWith("dnslink="))continue;n("%s TXT %s",u.name,l),l=l.replace("dnslink=","");let[,f,m,...d]=l.split("/");if(f==="ipfs")try{return{value:`/ipfs/${O.parse(m)}${d.length>0?`/${d.join("/")}`:""}`,answer:u}}catch{}else if(f==="ipns"){try{return{value:`/ipns/${Qe(m)}${d.length>0?`/${d.join("/")}`:""}`,answer:u}}catch{}return await Mc(m,e-1,t,n,o)}else{if(f==="dnslink")return await Mc(m,e-1,t,n,o);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(l){n.error("could not parse DNS link record for domain %s, %s",r,u.data,l)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=(await t.query(r,{...o,types:[dt.CNAME]})).Answer.sort((u,l)=>u.data.localeCompare(l.data));n("found %d CNAME records for %s",c.length,r);for(let u of c)try{return await Mc(u.data,e-1,t,n,o)}catch(l){n.error("domain %s cname %s had no DNSLink records",r,u.data,l)}throw new N(`No DNSLink records found for domain: ${r}`,"ERR_DNSLINK_NOT_FOUND")}async function Mc(r,e,t,n,o={}){if(e===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await v0(r,e,t,n,o)}catch(i){if(i.code!=="ENOTFOUND"&&i.code!=="ERR_DNSLINK_NOT_FOUND"&&i.code!=="ENODATA")throw i;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,await v0(r,e,t,n,o)}}async function S0(r,e,t,n={}){return Mc(r,n.maxRecursiveDepth??f_,e,t,n)}var wd=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(o){n.onProgress?.(new F("ipns:routing:helia:error",o))}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){t.onProgress?.(new F("ipns:routing:helia:error",n))}throw new Error("Not found")}};function _0(r){return new wd(r)}var fs;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.key!=null&&t.key.byteLength>0&&(n.uint32(10),n.bytes(t.key)),t.value!=null&&t.value.byteLength>0&&(n.uint32(18),n.bytes(t.value)),t.timeReceived!=null&&t.timeReceived!==""&&(n.uint32(42),n.string(t.timeReceived)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={key:kt(0),value:kt(0),timeReceived:""},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.key=t.bytes();break}case 2:{i.value=t.bytes();break}case 5:{i.timeReceived=t.string();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Rt(t,r.codec()),r.decode=(t,n)=>Bt(t,r.codec(),n)})(fs||(fs={}));function A0(r){let e=r.getUTCFullYear(),t=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`${e}-${t}-${n}T${o}:${i}:${s}.${c}Z`}function k0(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),o=parseInt(t[2],10)-1,i=parseInt(t[3],10),s=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),u=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,u))}var Or=class r{key;value;timeReceived;constructor(e,t,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return fs.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:A0(this.timeReceived)}}static deserialize(e){let t=fs.decode(e);return new r(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=k0(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new r(e.key,e.value,t)}};var zc=globalThis.CustomEvent??Event;async function*zn(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,i=[],s=ve(),a=ve(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(i.length===t&&(s=ve(),await s.promise),l)break;let h={done:!1};i.push(h),p().then(y=>{h.done=!0,h.ok=!0,h.value=y,o.dispatchEvent(new zc("task-complete"))},y=>{h.done=!0,h.err=y,o.dispatchEvent(new zc("task-complete"))})}c=!0,o.dispatchEvent(new zc("task-complete"))}catch(p){u=p,o.dispatchEvent(new zc("task-complete"))}});function f(){return n?i[0]?.done:!!i.find(p=>p.done)}function*m(){for(;i.length>0&&i[0].done;){let p=i[0];if(i.shift(),p.ok)yield p.value;else throw l=!0,s.resolve(),p.err;s.resolve()}}function*d(){for(;f();)for(let p=0;p<i.length;p++)if(i[p].done){let h=i[p];if(i.splice(p,1),p--,h.ok)yield h.value;else throw l=!0,s.resolve(),h.err;s.resolve()}}for(;;){if(f()||(a=ve(),await a.promise),u!=null)throw u;if(n?yield*m():yield*d(),c&&i.length===0)break}}var B0;(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"})(B0||(B0={}));function $c(r){return new ke("/dht/record/"+W(r,"base32"),!1)}function I0(r){return{async put(e,t,n={}){try{let o=$c(e);try{let s=await r.get(o),a=Or.deserialize(s);if(ie(a.value,t))return}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}let i=new Or(e,t,new Date);n.onProgress?.(new F("ipns:routing:datastore:put")),await r.put(o,i.serialize(),n)}catch(o){throw n.onProgress?.(new F("ipns:routing:datastore:error",o)),o}},async get(e,t={}){try{let n=$c(e);t.onProgress?.(new F("ipns:routing:datastore:get"));let o=await r.get(n,t),i=Or.deserialize(o);return{record:i.value,created:i.timeReceived}}catch(n){throw t.onProgress?.(new F("ipns:routing:datastore:error",n)),n}},async has(e,t={}){let n=$c(e);return r.has(n,t)},async delete(e,t){let n=$c(e);return r.delete(n,t)}}}var Ur=Q("helia:ipns"),h_=60*1e3,Ed=60*h_,p_=24*Ed,bd=23*Ed,m_=BigInt(Ed)*1000000n,xd=class{routers;localStore;timeout;dns;log;constructor(e,t=[]){this.routers=[_0(e.routing),...t],this.localStore=I0(e.datastore),this.dns=e.dns,this.log=e.logger.forComponent("helia:ipns")}async publish(e,t,n={}){try{let o=1n,i=Fo(e);if(await this.localStore.has(i,n)){let{record:c}=await this.localStore.get(i,n);o=Ye(c).sequence+1n}let s=await wg(e,t,o,n.lifetime??p_,n),a=Lr(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 F("ipns:publish:error",o)),o}}async resolve(e,t={}){let n=Fo(e),o=await this.#t(n,t);return{...await this.#e(o.value,t),record:o}}async resolveDNSLink(e,t={}){let n=await S0(e,this.dns,this.log,t);return{...await this.#e(n.value,t),answer:n.answer}}republish(e={}){if(this.timeout!=null)throw new Error("Republish is already running");e.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function t(){let n=Date.now();e.onProgress?.(new F("ipns:republish:start"));let i=Date.now()-n,s=bd-i;s<0&&(s=e.interval??bd),setTimeout(()=>{t().catch(a=>{Ur.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{t().catch(n=>{Ur.error("error republishing",n)})},e.interval??bd)}async#e(e,t={}){let n=e.split("/");try{let o=n[1];if(o==="ipns"){let{cid:i}=await this.resolve(Qe(n[2]),t),s=n.slice(3).join("/");return{cid:i,path:s}}else if(o==="ipfs"){let i=O.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",e),new Error("Invalid value")}async#t(e,t={}){let n=[];if(await this.localStore.has(e,t))if(Ur("record is present in the cache"),t.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await zi(e,a),this.log("record was valid");let u=Ye(a),l=Number((u.ttl??m_)/1000000n);if(c.getTime()+l>Date.now())return this.log("record TTL was valid"),u;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),u;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(e,t)}else Ur("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new N("Record was not present in the cache or has expired","ERR_NOT_FOUND");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(e,{...t,validate:!1})}catch(u){Ur.error("error finding IPNS record",u);return}try{await zi(e,c),n.push(c)}catch(u){i++,Ur.error("error finding IPNS record",u)}})),n.length===0)throw i>0?new N(`${i>1?`${i} records`:"Record"} found for routing key ${i>1?"were":"was"} invalid`,"ERR_RECORDS_FAILED_VALIDATION"):new N("Could not find record for routing key","ERR_NOT_FOUND");let s=n[E0(e,n)];return await this.localStore.put(e,s,t),Ye(s)}};function R0(r,{routers:e=[]}={}){return new xd(r,e)}var Bd=J(Ie(),1);function y_(r){return r[Symbol.asyncIterator]!=null}function g_(r,e=1){return e=Number(e),y_(r)?async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}():function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}()}var Kc=g_;async function*ds(r,e=1){for await(let t of Kc(r,e)){let n=t.map(async o=>o().then(i=>({ok:!0,value:i}),i=>({ok:!1,err:i})));for(let o=0;o<n.length;o++){let i=await n[o];if(i.ok)yield i.value;else throw i.err}}}var w_=262144,hs=(r={})=>{let e=r.chunkSize??w_;return async function*(n){let o=new Vt,i=0,s=!1;for await(let a of n)for(o.append(a),i+=a.length;i>=e;)if(yield o.slice(0,e),s=!0,e===o.length)o=new Vt,i=0;else{let c=new Vt;c.append(o.sublist(e)),o=c,i-=e}(!s||i>0)&&(yield o.subarray(0,i))}};var vd=J(Ie(),1);var jt;(function(r){let e;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(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"})(t||(t={})),function(o){o.codec=()=>Rn(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=Tt((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),qc.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=qc.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>Rt(o,r.codec()),r.decode=o=>Bt(o,r.codec())})(jt||(jt={}));var qc;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>Rt(t,r.codec()),r.decode=t=>Bt(t,r.codec())})(qc||(qc={}));var T0;(function(r){let e;r.codec=()=>(e==null&&(e=Tt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.MimeType=t.string();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>Rt(t,r.codec()),r.decode=t=>Bt(t,r.codec())})(T0||(T0={}));var N0={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},b_=["directory","hamt-sharded-directory"],C0=parseInt("0644",8),L0=parseInt("0755",8),q=class r{static unmarshal(e){let t=jt.decode(e),n=new r({type:N0[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(N0).includes(t))throw(0,vd.default)(new Error("Type: "+t+" is not valid"),"ERR_INVALID_TYPE");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?L0:C0:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return b_.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=jt.DataType.Raw;break;case"directory":e=jt.DataType.Directory;break;case"file":e=jt.DataType.File;break;case"metadata":e=jt.DataType.Metadata;break;case"symlink":e=jt.DataType.Symlink;break;case"hamt-sharded-directory":e=jt.DataType.HAMTShard;break;default:throw(0,vd.default)(new Error(`Type: ${e} is not valid`),"ERR_INVALID_TYPE")}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===C0&&!this.isDirectory()&&(n=void 0),n===L0&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),jt.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var Yt=async(r,e,t)=>{t.codec==null&&(t.codec=Te);let n=await ce.digest(r),o=O.create(t.cidVersion,t.codec.code,n);return await e.put(o,r,t),o};function D0(r){return async function*(t,n){let o=0n;for await(let i of t.content)yield async()=>{let s,a={codec:Te,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=It,a.cidVersion=1):(s=new q({type:r.leafType,data:i}),i=re({Data:s.marshal(),Links:[]}));let c=await Yt(i,n,a);return o+=BigInt(i.byteLength),r.onProgress?.(new F("unixfs:importer:progress:file:write",{bytesWritten:o,cid:c,path:t.path})),{cid:c,unixfs:s,size:BigInt(i.length),block:i}}}}var Sd=J(Ie(),1);var P0=async(r,e,t)=>{let n=new q({type:"directory",mtime:r.mtime,mode:r.mode}),o=re(_e({Data:n.marshal()})),i=await Yt(o,e,t),s=r.path;return{cid:i,path:s,unixfs:n,size:BigInt(o.length),originalPath:r.originalPath,block:o}};async function*x_(r,e,t){let n=-1,o;for await(let i of ds(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){o={...i,single:!0};continue}else n===1&&o!=null&&(yield{...o,block:void 0,single:void 0},o=void 0);yield{...i,block:void 0}}o!=null&&(yield o)}function O0(r){return r.single===!0}var E_=(r,e,t)=>async function(o){if(o.length===1&&O0(o[0])&&t.reduceSingleLeafToSelf){let l=o[0],f=l.block;return O0(l)&&(r.mtime!==void 0||r.mode!==void 0)&&(l.unixfs=new q({type:"file",mtime:r.mtime,mode:r.mode,data:l.block}),f={Data:l.unixfs.marshal(),Links:[]},l.block=re(_e(f)),l.cid=await Yt(l.block,e,{...t,cidVersion:t.cidVersion}),l.size=BigInt(l.block.length)),t.onProgress?.(new F("unixfs:importer:progress:file:layout",{cid:l.cid,path:l.originalPath})),{cid:l.cid,path:r.path,unixfs:l.unixfs,size:l.size,originalPath:l.originalPath}}let i=new q({type:"file",mtime:r.mtime,mode:r.mode}),s=o.filter(l=>l.cid.code===ge&&l.size>0||l.unixfs!=null&&l.unixfs.data==null&&l.unixfs.fileSize()>0n?!0:!!l.unixfs?.data?.length).map(l=>l.cid.code===ge?(i.addBlockSize(l.size),{Name:"",Tsize:Number(l.size),Hash:l.cid}):(l.unixfs==null||l.unixfs.data==null?i.addBlockSize(l.unixfs?.fileSize()??0n):i.addBlockSize(BigInt(l.unixfs.data.length)),{Name:"",Tsize:Number(l.size),Hash:l.cid})),a={Data:i.marshal(),Links:s},c=re(_e(a)),u=await Yt(c,e,t);return t.onProgress?.(new F("unixfs:importer:progress:file:layout",{cid:u,path:r.originalPath})),{cid:u,path:r.path,unixfs:i,size:BigInt(c.length+a.Links.reduce((l,f)=>l+(f.Tsize??0),0)),originalPath:r.originalPath,block:c}},U0=async(r,e,t)=>t.layout(x_(r,e,t),E_(r,e,t));function v_(r){return Symbol.iterator in r}function S_(r){return Symbol.asyncIterator in r}function __(r){try{if(r instanceof Uint8Array)return async function*(){yield r}();if(v_(r))return async function*(){yield*r}();if(S_(r))return r}catch{throw(0,Sd.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}throw(0,Sd.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}function F0(r){return async function*(t,n){for await(let o of t){let i;if(o.path!=null&&(i=o.path,o.path=o.path.split("/").filter(s=>s!=null&&s!==".").join("/")),A_(o)){let s={path:o.path,mtime:o.mtime,mode:o.mode,content:async function*(){let a=0n;for await(let c of r.chunker(r.chunkValidator(__(o.content)))){let u=BigInt(c.byteLength);a+=u,r.onProgress?.(new F("unixfs:importer:progress:file:read",{bytesRead:a,chunkSize:u,path:o.path})),yield c}}(),originalPath:i};yield async()=>U0(s,n,r)}else if(o.path!=null){let s={path:o.path,mtime:o.mtime,mode:o.mode,originalPath:i};yield async()=>P0(s,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function A_(r){return r.content!=null}var _d=J(Ie(),1);var V0=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw(0,_d.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT");if(typeof t=="string"||t instanceof String)yield U(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw(0,_d.default)(new Error("Content was invalid"),"ERR_INVALID_CONTENT")}};var k_=174;function ps(r){let e=r?.maxChildrenPerNode??k_;return async function t(n,o){let i=[];for await(let s of Kc(n,e))i.push(await o(s));return i.length>1?t(i,o):i[0]}}var ur=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},ms=O.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),ys=O.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var $n=class extends ur{_children;constructor(e,t){super(e,t),this._children=new Map}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(e,t)}async get(e){return Promise.resolve(this._children.get(e))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}async*eachChildSeries(){for(let[e,t]of this._children.entries())yield{key:e,child:t}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[e,t]of this._children.entries())t.size!=null&&t.cid!=null&&(this.nodeSize+=e.length+(this.options.cidVersion===1?ys.bytes.byteLength:ms.bytes.byteLength));return this.nodeSize}async*flush(e){let t=[];for(let[c,u]of this._children.entries()){let l=u;if(u instanceof ur)for await(let f of u.flush(e))l=f,yield f;l.size!=null&&l.cid!=null&&t.push({Name:c,Tsize:Number(l.size),Hash:l.cid})}let n=new q({type:"directory",mtime:this.mtime,mode:this.mode}),o={Data:n.marshal(),Links:t},i=re(_e(o)),s=await Yt(i,e,this.options),a=i.length+o.Links.reduce((c,u)=>c+(u.Tsize==null?0:u.Tsize),0);this.cid=s,this.size=a,yield{cid:s,unixfs:n,path:this.path,size:BigInt(a)}}};var Wc=J(z0(),1);function B_(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var k5=_n({name:"murmur3-32",code:35,encode:r=>B_(Wc.default.x86.hash32(r))}),Kn=_n({name:"murmur3-128",code:34,encode:r=>Xn.fromHex(Wc.default.x64.hash128(r))}),B5=_n({name:"murmur3-x64-64",code:34,encode:r=>Xn.fromHex(Wc.default.x64.hash128(r)).subarray(0,8)});var q0=J(jc(),1);var vt=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new q0.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(e,t)):o.push(e(i,s))),o),n))}async asyncTransform(e,t){return G0(this,e,t)}toJSON(){return this.serialize(C_,L_)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?U(e):e),n=await t.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:o}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let o=await n._findPlace(t.existingChild.hash);return o.bucket._putAt(o,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(N_);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function N_(r){return!!r}function C_(r,e){return r.key}function L_(r){return r}async function G0(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof vt)await G0(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var D_=[255,254,252,248,240,224,192,128],P_=[1,3,7,15,31,63,127,255],Yc=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=O_(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function O_(r,e,t){let n=U_(e,t);return(r&n)>>>e}function U_(r,e){return D_[r]&P_[Math.min(e+r-1,7)]}function W0(r){function e(t){return t instanceof Xc?t:new Xc(t,r)}return e}var Xc=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?ue([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Yc(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Go(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:W0(r.hashFn)};return new vt(e)}async function F_(r){return(await Kn.encode(r)).slice(0,8).reverse()}var j0=BigInt(34),V_=8,Ad=class extends ur{_bucket;constructor(e,t){super(e,t),this._bucket=Go({hashFn:F_,bits:t.shardFanoutBits??V_})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=Z0(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of X0(this._bucket,e,this,this.options))yield{...t,path:this.path}}},Y0=Ad;async function*X0(r,e,t,n){let o=r._children,i=(r.tableSize()-1).toString(16).length,s=[],a=0n;for(let p=0;p<o.length;p++){let h=o.get(p);if(h==null)continue;let y=p.toString(16).toUpperCase().padStart(i,"0");if(h instanceof vt){let g;for await(let b of X0(h,e,null,n))g=b;if(g==null)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:y,Tsize:Number(g.size),Hash:g.cid}),a+=g.size}else if(H_(h.value)){let g=h.value,b;for await(let v of g.flush(e))b=v,yield b;if(b==null)throw new Error("Did not flush dir");let x=y+h.key;s.push({Name:x,Tsize:Number(b.size),Hash:b.cid}),a+=b.size}else{let g=h.value;if(g.cid==null)continue;let b=y+h.key,x=g.size;s.push({Name:b,Tsize:Number(x),Hash:g.cid}),a+=BigInt(x??0)}}let c=Uint8Array.from(o.bitField().reverse()),u=new q({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:j0,mtime:t?.mtime,mode:t?.mode}),l={Data:u.marshal(),Links:s},f=re(_e(l)),m=await Yt(f,e,n),d=BigInt(f.byteLength)+a;yield{cid:m,unixfs:u,size:d}}function H_(r){return typeof r.flush=="function"}function Z0(r,e,t){let n=r._children,o=(r.tableSize()-1).toString(16).length,i=[];for(let u=0;u<n.length;u++){let l=n.get(u);if(l==null)continue;let f=u.toString(16).toUpperCase().padStart(o,"0");if(l instanceof vt){let m=Z0(l,null,t);i.push({Name:f,Tsize:Number(m),Hash:t.cidVersion===0?ms:ys})}else if(typeof l.value.flush=="function"){let d=l.value.nodeSize();i.push({Name:f+l.key,Tsize:Number(d),Hash:t.cidVersion===0?ms:ys})}else{let m=l.value;if(m.cid==null)continue;let d=f+l.key,p=m.size;i.push({Name:d,Tsize:Number(p),Hash:m.cid})}}let s=Uint8Array.from(n.bitField().reverse()),a=new q({type:"hamt-sharded-directory",data:s,fanout:BigInt(r.tableSize()),hashType:j0,mtime:e?.mtime,mode:e?.mode});return re(_e({Data:a.marshal(),Links:i})).length}async function kd(r,e,t,n){let o=e;e instanceof $n&&e.estimateNodeSize()>t&&(o=await M_(e,n));let i=o.parent;if(i!=null){if(o!==e){if(r!=null&&(r.parent=o),o.parentKey==null)throw new Error("No parent key found");await i.put(o.parentKey,o)}return kd(o,i,t,n)}return o}async function M_(r,e){let t=new Y0({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for await(let{key:n,child:o}of r.eachChildSeries())await t.put(n,o);return t}var J0=(r="")=>r.split(/(?<!\\)\//).filter(Boolean);async function z_(r,e,t){let n=J0(r.path??""),o=n.length-1,i=e,s="";for(let a=0;a<n.length;a++){let c=n[a];s+=`${s!==""?"/":""}${c}`;let u=a===o;if(i.dirty=!0,i.cid=void 0,i.size=void 0,u)await i.put(c,r),e=await kd(null,i,t.shardSplitThresholdBytes,t);else{let l=await i.get(c);(l==null||!(l instanceof ur))&&(l=new $n({root:!1,dir:!0,parent:i,parentKey:c,path:s,dirty:!0,flat:!0,mtime:l?.unixfs?.mtime,mode:l?.unixfs?.mode},t)),await i.put(c,l),i=l}}return e}async function*Q0(r,e){if(!(r instanceof ur)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function ew(r){return async function*(t,n){let o=new $n({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),i,s=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(i==null?(i=c,s=!0):i!==c&&(s=!1)),o=await z_(a,o,r),(a.unixfs==null||!a.unixfs.isDirectory())&&(yield a)}if(r.wrapWithDirectory||s&&o.childCount()>1)yield*Q0(o,n);else for await(let a of o.eachChildSeries())a!=null&&(yield*Q0(a.child,n))}}async function*gn(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let o=t.wrapWithDirectory??!1,i=t.shardSplitThresholdBytes??262144,s=t.shardFanoutBits??8,a=t.cidVersion??1,c=t.rawLeaves??!0,u=t.leafType??"file",l=t.fileImportConcurrency??50,f=t.blockWriteConcurrency??10,m=t.reduceSingleLeafToSelf??!0,d=t.chunker??hs(),p=t.chunkValidator??V0(),h=t.dagBuilder??F0({chunker:d,chunkValidator:p,wrapWithDirectory:o,layout:t.layout??ps(),bufferImporter:t.bufferImporter??D0({cidVersion:a,rawLeaves:c,leafType:u,onProgress:t.onProgress}),blockWriteConcurrency:f,reduceSingleLeafToSelf:m,cidVersion:a,onProgress:t.onProgress}),y=t.treeBuilder??ew({wrapWithDirectory:o,shardSplitThresholdBytes:i,shardFanoutBits:s,cidVersion:a,onProgress:t.onProgress});for await(let g of y(ds(h(n,e),l),e))yield{cid:g.cid,path:g.path,unixfs:g.unixfs,size:g.size}}async function Zc(r,e,t={}){let n=await Vn(gn([r],e,t));if(n==null)throw(0,Bd.default)(new Error("Nothing imported"),"ERR_INVALID_PARAMS");return n}async function tw(r,e,t={}){let n=await Vn(gn([r],e,t));if(n==null)throw(0,Bd.default)(new Error("Nothing imported"),"ERR_INVALID_PARAMS");return n}async function rw(r,e,t={}){return Zc({content:r},e,t)}async function nw(r,e,t={}){return Zc({content:r},e,t)}var ws={cidVersion:1,rawLeaves:!0,layout:ps({maxChildrenPerNode:1024}),chunker:hs({chunkSize:1048576})};async function*ow(r,e,t={}){yield*gn(r,e,{...ws,...t})}async function iw(r,e,t={}){let{cid:n}=await rw(r,e,{...ws,...t});return n}async function sw(r,e,t={}){let{cid:n}=await nw(r,e,{...ws,...t});return n}async function aw(r,e,t={}){let{cid:n}=await Zc(r,e,{...ws,...t});return n}async function cw(r,e,t={}){let{cid:n}=await tw({...r,path:r.path??"-"},e,{...ws,...t});return n}var Qc=J(Ie(),1);function $_(r){return r[Symbol.asyncIterator]!=null}function K_(r){if($_(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var wn=K_;var Aw=J(Ie(),1);var lw=J(Ie(),1);function Wo(r,e,t,n,o,i,s){let a=r,c=o;for(;i.length>0;){let u=i[0];if(u in a){i.shift(),c=`${c}/${u}`;let l=O.asCID(a[u]);if(l!=null)return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:l,name:u,path:c,toResolve:i}};a=a[u]}else throw(0,lw.default)(new Error(`No property named ${u} found in node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var q_=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),u=Mn(c);return Wo(u,c,r,e,t,n,i)},uw=q_;var G_=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),u=Tc(c);return Wo(u,c,r,e,t,n,i)},fw=G_;var dw=J(Ie(),1);function W_(r,e,t,n){let o=BigInt(r.length),i=BigInt(e+o);return t>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(r=r.subarray(0,Number(n-e))),t>=e&&t<i&&(r=r.subarray(Number(t-e))),r)}var qn=W_;var bs=J(Ie(),1),j_=(r,e=0,t=r)=>{let n=BigInt(r),o=BigInt(e??0),i=BigInt(t);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw(0,bs.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(o>n)throw(0,bs.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(i<0n)throw(0,bs.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,bs.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:o,end:i}},jo=j_;var Y_=r=>{async function*e(t={}){let{start:n,end:o}=jo(r.length,t.offset,t.length),i=qn(r,0n,n,o);t.onProgress?.(new F("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},X_=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,dw.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=Je(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:Y_(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},hw=X_;var Z_=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),u=Mh(c);return Wo(u,c,r,e,t,n,i)},pw=Z_;var mw=J(Ie(),1);var J_=r=>{async function*e(t={}){let{start:n,end:o}=jo(r.length,t.offset,t.length),i=qn(r,0n,n,o);t.onProgress?.(new F("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},Q_=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,mw.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:J_(c),depth:i,size:BigInt(c.length),node:c}}},yw=Q_;var Es=J(Ie(),1);var xs=J(Ie(),1);var eA=async function(r){return(await Kn.encode(r)).slice(0,8).reverse()},tA=async(r,e,t)=>{let n=(e.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);e._putObjectAt(i,new vt({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},gw=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),rA=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},ww=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw(0,xs.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let f;try{f=q.unmarshal(r.Data)}catch(d){throw(0,xs.default)(d,"ERR_NOT_UNIXFS")}if(f.type!=="hamt-sharded-directory")throw(0,xs.default)(new Error("not a HAMT"),"ERR_NOT_UNIXFS");if(f.fanout==null)throw(0,xs.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let m=Go({hashFn:eA,bits:Math.log2(Number(f.fanout))});n={rootBucket:m,hamtDepth:1,lastBucket:m}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await tA(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=gw(s.pos,i),c=rA(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=gw(n.lastBucket._posAtParent,i));let u=r.Links.find(f=>{if(f.Name==null)return!1;let m=f.Name.substring(0,i),d=f.Name.substring(i);return!(m!==a||d!==""&&d!==e)});if(u==null)return;if(u.Name!=null&&u.Name.substring(i)===e)return u.Hash;n.hamtDepth++;let l=await t.get(u.Hash,o);return r=we(l),ww(r,e,t,n,o)},bw=ww;var nA=(r,e,t,n,o,i,s)=>{async function*a(c={}){let u=c.offset??0,l=c.length??e.Links.length,f=e.Links.slice(u,l);c.onProgress?.(new F("unixfs:exporter:walk:directory",{cid:r})),yield*at(f,m=>We(m,d=>async()=>{let p=d.Name??"",h=`${n}/${p}`;return(await o(d.Hash,p,h,[],i+1,s,c)).entry}),m=>zn(m,{ordered:!0,concurrency:c.blockReadConcurrency}),m=>ht(m,d=>d!=null))}return a},xw=nA;var Gn=J(Ie(),1);async function Ew(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let u=qn(e,n,o,i);t.push(u);return}if(e.Data==null)throw(0,Gn.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=q.unmarshal(e.Data)}catch(u){throw(0,Gn.default)(u,"ERR_NOT_UNIXFS")}if(a.data!=null){let u=a.data,l=qn(u,n,o,i);t.push(l),n+=BigInt(l.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw(0,Gn.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let u=0;u<e.Links.length;u++){let l=e.Links[u],f=n,m=f+a.blockSizes[u];if((o>=f&&o<m||i>=f&&i<=m||o<f&&i>m)&&c.push({link:l,blockStart:n}),n=m,n>i)break}await at(c,u=>We(u,l=>async()=>{let f=await r.get(l.link.Hash,s);return{...l,block:f}}),u=>zn(u,{ordered:!0,concurrency:s.blockReadConcurrency}),async u=>{for await(let{link:l,block:f,blockStart:m}of u){let d;switch(l.Hash.code){case ye:d=we(f);break;case ge:d=f;break;default:t.end((0,Gn.default)(new Error(`Unsupported codec: ${l.Hash.code}`),"ERR_NOT_UNIXFS"));return}let p=new ut({concurrency:1});p.on("error",h=>{t.end(h)}),p.add(async()=>{s.onProgress?.(new F("unixfs:exporter:walk:file",{cid:l.Hash})),await Ew(r,d,t,m,o,i,s)}),await p.onIdle()}}),n>=i&&t.end()}var oA=(r,e,t,n,o,i,s)=>{async function*a(c={}){let u=t.fileSize();if(u===void 0)throw new Error("File was a directory");let{start:l,end:f}=jo(u,c.offset,c.length);if(f===0n)return;let m=0n,d=f-l,p=Nt();c.onProgress?.(new F("unixfs:exporter:walk:file",{cid:r})),Ew(s,e,p,0n,l,f,c).catch(h=>{p.end(h)});for await(let h of p)if(h!=null){if(m+=BigInt(h.byteLength),m>d)throw p.end(),(0,Gn.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"),"ERR_OVER_READ");m===d&&p.end(),c.onProgress?.(new F("unixfs:exporter:progress:unixfs:file",{bytesRead:m,totalBytes:d,fileSize:u})),yield h}if(m<d)throw(0,Gn.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return a},Id=oA;var Jc=J(Ie(),1);var iA=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new F("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),vw(e,n,o,i,s,c)}return a};async function*vw(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw(0,Jc.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=q.unmarshal(r.Data)}catch(l){throw(0,Jc.default)(l,"ERR_NOT_UNIXFS")}if(a.fanout==null)throw(0,Jc.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let c=(a.fanout-1n).toString(16).length,u=at(s,l=>We(l,f=>async()=>{let m=f.Name!=null?f.Name.substring(c):null;if(m!=null&&m!==""){let d=await t(f.Hash,m,`${e}/${m}`,[],n+1,o,i);return{entries:d.entry==null?[]:[d.entry]}}else{let d=await o.get(f.Hash,i);return r=we(d),i.onProgress?.(new F("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:vw(r,e,t,n,o,i)}}}),l=>zn(l,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:l}of u)yield*l}var Sw=iA;var sA=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,aA={raw:Id,file:Id,directory:xw,"hamt-sharded-directory":Sw,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},cA=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),u=we(c),l,f;if(e==null&&(e=r.toString()),u.Data==null)throw(0,Es.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{l=q.unmarshal(u.Data)}catch(d){throw(0,Es.default)(d,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let d;if(l?.type==="hamt-sharded-directory"?d=await bw(u,n[0],s):d=sA(u,n[0]),d==null)throw(0,Es.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let p=n.shift(),h=`${t}/${p}`;f={cid:d,toResolve:n,name:p??"",path:h}}let m=aA[l.type](r,u,l,t,o,i,s);if(m==null)throw(0,Es.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return l.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:m,unixfs:l,depth:i,node:u,size:l.fileSize()},next:f}:{entry:{type:"file",name:e,path:t,cid:r,content:m,unixfs:l,depth:i,node:u,size:l.fileSize()},next:f}},_w=cA;var lA={[ye]:_w,[ge]:yw,[hn]:uw,[mn]:fw,[Ge.code]:hw,[Wr]:pw},kw=async(r,e,t,n,o,i,s)=>{let a=lA[r.code];if(a==null)throw(0,Aw.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return a(r,e,t,n,kw,o,i,s)},Bw=kw;var uA=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),fA=r=>{if(r instanceof Uint8Array)return{cid:O.decode(r),toResolve:[]};let e=O.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=uA(r);return{cid:O.parse(t[0]),toResolve:t.slice(1)}}throw(0,Qc.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")};async function*vs(r,e,t={}){let{cid:n,toResolve:o}=fA(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await Bw(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw(0,Qc.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");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 ze(r,e,t={}){let n=await wn(vs(r,e,t));if(n==null)throw(0,Qc.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}async function*Yo(r,e,t={}){let n=await ze(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,t))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))}}var Ow=J(Pw(),1),Ze=Ow.default;var Xt=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},fr=class extends Xt{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}},ot=class extends Xt{constructor(e="invalid PBNode"){super(e,"InvalidPBNodeError","ERR_INVALID_PBNODE")}},Fr=class extends Xt{constructor(e="unknown error"){super(e,"InvalidPBNodeError","ERR_UNKNOWN_ERROR")}},Ss=class extends Xt{constructor(e="path already exists"){super(e,"AlreadyExistsError","ERR_ALREADY_EXISTS")}},rl=class extends Xt{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}},Jo=class extends Xt{constructor(e="no content"){super(e,"NoContentError","ERR_NO_CONTENT")}},nl=class extends Xt{constructor(e="not a file"){super(e,"NotAFileError","ERR_NOT_A_FILE")}},bn=class extends Xt{constructor(e="not a directory"){super(e,"NotADirectoryError","ERR_NOT_A_DIRECTORY")}},St=class extends Xt{constructor(e="invalid parameters"){super(e,"InvalidParametersError","ERR_INVALID_PARAMETERS")}};var Ld=J(jc(),1);function il(r){function e(t){return t instanceof ol?t:new ol(t,r)}return e}var ol=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?ue([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Td(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},gA=[255,254,252,248,240,224,192,128],wA=[1,3,7,15,31,63,127,255],Td=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=bA(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function bA(r,e,t){let n=xA(e,t);return(r&n)>>>e}function xA(r,e){return gA[r]&wA[Math.min(e+r-1,7)]}var _s=BigInt(Kn.code),Wn=8;async function Qo(r){return(await Kn.encode(r)).subarray(0,8).reverse()}var Vw=J(jc(),1);var Zt=async(r,e,t)=>{t.codec==null&&(t.codec=Te);let n=await ce.digest(r),o=O.create(t.cidVersion,t.codec.code,n);return await e.put(o,r,{...t,signal:t.signal}),o};var Nd=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},sl=class extends Nd{_bucket;constructor(e,t){super(e,t),this._bucket=Go({hashFn:Qo,bits:8})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=Fw(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of Uw(this._bucket,e,this,this.options))yield{...t,path:this.path}}};async function*Uw(r,e,t,n){let o=r._children,i=[],s=0n;for(let d=0;d<o.length;d++){let p=o.get(d);if(p==null)continue;let h=d.toString(16).toUpperCase().padStart(2,"0");if(p instanceof vt){let y;for await(let g of Uw(p,e,null,n))y=g;if(y==null)throw new Error("Could not flush sharded directory, no subshard found");i.push({Name:h,Tsize:Number(y.size),Hash:y.cid}),s+=y.size}else if(EA(p.value)){let y=p.value,g;for await(let x of y.flush(e))g=x,yield g;if(g==null)throw new Error("Did not flush dir");let b=h+p.key;i.push({Name:b,Tsize:Number(g.size),Hash:g.cid}),s+=g.size}else{let y=p.value;if(y.cid==null)continue;let g=h+p.key,b=y.size;i.push({Name:g,Tsize:Number(b),Hash:y.cid}),s+=BigInt(b??0)}}let a=Uint8Array.from(o.bitField().reverse()),c=new q({type:"hamt-sharded-directory",data:a,fanout:BigInt(r.tableSize()),hashType:_s,mtime:t?.mtime,mode:t?.mode}),u={Data:c.marshal(),Links:i},l=re(_e(u)),f=await Zt(l,e,n),m=BigInt(l.byteLength)+s;yield{cid:f,unixfs:c,size:m}}function EA(r){return typeof r.flush=="function"}function Fw(r,e,t){let n=r._children,o=[];for(let c=0;c<n.length;c++){let u=n.get(c);if(u==null)continue;let l=c.toString(16).toUpperCase().padStart(2,"0");if(u instanceof vt){let f=Fw(u,null,t);o.push({Name:l,Tsize:Number(f),Hash:t.cidVersion===0?al:cl})}else if(typeof u.value.flush=="function"){let m=u.value.nodeSize();o.push({Name:l+u.key,Tsize:Number(m),Hash:t.cidVersion===0?al:cl})}else{let f=u.value;if(f.cid==null)continue;let m=l+u.key,d=f.size;o.push({Name:m,Tsize:Number(d),Hash:f.cid})}}let i=Uint8Array.from(n.bitField().reverse()),s=new q({type:"hamt-sharded-directory",data:i,fanout:BigInt(r.tableSize()),hashType:_s,mtime:e?.mtime,mode:e?.mode});return re(_e({Data:s.marshal(),Links:o})).length}var al=O.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),cl=O.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var Cd=Q("helia:unixfs:commands:utils:hamt-utils"),ll=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),Hw=async(r,e,t)=>{let n=new sl({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let i=0;i<e.length;i++)await n._bucket.put(e[i].name,{size:e[i].size,cid:e[i].cid});let o=await wn(n.flush(r));if(o==null)throw new Error("Flushing shard yielded no result");return o},ul=async(r,e,t)=>{let n=q.unmarshal(r[0].node.Data??new Uint8Array(0)),o=BigInt(Math.pow(2,Wn));r.reverse();let i,s;for(let a=0;a<r.length;a++){let c=a===r.length-1,u=r[a],l=Uint8Array.from(u.children.bitField().reverse()),f=new q({type:"hamt-sharded-directory",data:l,fanout:o,hashType:_s});c&&(f.mtime=n.mtime,f.mode=n.mode),s={Data:f.marshal(),Links:u.node.Links};let m=re(_e(s));if(i=await Zt(m,e,t),!c){let d=r[a+1];if(d==null)throw new Error("Was not operating on shard root but also had no parent?");Cd("updating link in parent sub-shard with prefix %s",d.prefix),d.node.Links=d.node.Links.filter(p=>p.Name!==d.prefix),d.node.Links.push({Name:d.prefix,Hash:i,Tsize:u.node.Links.reduce((p,h)=>p+(h.Tsize??0),m.byteLength)})}}if(i==null||s==null)throw new Error("Noting persisted");return{cid:i,node:s}},fl=async(r,e,t,n)=>{let i=il(Qo)(U(e)),s=[];for(;;){let a=await t.get(r,n),c=we(a),u=new Vw.default,l=await i.take(Wn),f=ll(l);s.push({prefix:f,children:u,node:c});let m;for(let p of c.Links){let h=p.Name??"";if(h.length<2)throw new Error("Invalid HAMT - link name was too short");let y=parseInt(h.substring(0,2),16);u.set(y,!0),h.startsWith(f)&&(m=p)}if(m==null){Cd("no link found with prefix %s for %s",f,e);break}let d=m.Name??"";if(d.length<2)throw new Error("Invalid HAMT - link name was too short");if(d.length===2){r=m.Hash,Cd("descend into sub-shard with prefix %s",d);continue}break}return{path:s,hash:i}};async function dl(r,e,t,n){if(r.Data==null)throw new Error("DagPB node had no data");let o=q.unmarshal(r.Data),i;if(o.type==="directory")i=vA(r);else if(o.type==="hamt-sharded-directory")i=await Mw(r,0,t,e,n);else throw new Error("Can only estimate the size of directories or shards");return i>t}function vA(r){let e=0;for(let t of r.Links)e+=(t.Name??"").length,e+=t.Hash.version===1?cl.bytes.byteLength:al.bytes.byteLength;return e}async function Mw(r,e,t,n,o){if(e>t)return t;if(r.Data==null||!q.unmarshal(r.Data).isDirectory())return e;for(let s of r.Links){let a=s.Name??"";if(a=a.substring(2),e+=a.length,e+=s.Hash.bytes.byteLength,s.Hash.code===ye){let c=await n.get(s.Hash,o),u=we(c);e+=await Mw(u,e,t,n,o)}}return e}var dr=Q("helia:unixfs:components:utils:add-link");async function ei(r,e,t,n){if(r.node.Data==null)throw new St("Invalid parent passed to addLink");if(q.unmarshal(r.node.Data).type==="hamt-sharded-directory")return dr("adding link to sharded directory"),AA(r,e,t,n);dr(`adding ${e.Name} (${e.Hash}) to regular directory`);let i=await _A(r,e,t,n);if(await dl(i.node,t,n.shardSplitThresholdBytes,n)){dr("converting directory to sharded directory");let s=await SA(i,t);i.cid=s.cid,i.node=we(await t.get(s.cid,n))}return i}var SA=async(r,e)=>{if(r.node.Data==null)throw new St("Invalid parent passed to convertToShardedDirectory");let t=q.unmarshal(r.node.Data),n=await Hw(e,r.node.Links.map(o=>({name:o.Name??"",size:BigInt(o.Tsize??0),cid:o.Hash})),{mode:t.mode,mtime:t.mtime,cidVersion:r.cid.version});return dr(`converted directory to sharded directory ${n.cid}`),n},_A=async(r,e,t,n)=>{let o=r.node.Links.filter(l=>{let f=l.Name===e.Name;if(f&&!n.allowOverwriting)throw new Ss;return!f});if(o.push(e),r.node.Data==null)throw new ot("Parent node with no data passed to addToDirectory");let i=q.unmarshal(r.node.Data),s;if(i.mtime!=null){let l=Date.now(),f=Math.floor(l/1e3);i.mtime={secs:BigInt(f),nsecs:(l-f*1e3)*1e3},s=i.marshal()}else s=r.node.Data;r.node=_e({Data:s,Links:o});let a=re(r.node),c=await ce.digest(a),u=O.create(r.cid.version,ye,c);return await t.put(u,a),{node:r.node,cid:u}},AA=async(r,e,t,n)=>{let{path:o,hash:i}=await fl(r.cid,e.Name,t,n),s=o[o.length-1];if(s==null)throw new Error("Invalid HAMT, could not generate path");let a=s.prefix,c=parseInt(a,16);dr("next prefix for %s is %s",e.Name,a);let u=`${a}${e.Name}`,l=s.node.Links.find(f=>(f.Name??"").startsWith(a));if(l!=null)if(dr("link %s was present in shard",u),l.Name===u){if(!n.allowOverwriting)throw new Ss;dr("overwriting %s in subshard",e.Name),s.node.Links=s.node.Links.filter(f=>f.Name!==u),s.node.Links.push({Name:u,Hash:e.Hash,Tsize:e.Tsize})}else{if(l.Name?.length===2)throw new Error("Existing link was subshard?!");{dr("prefix %s already exists, creating new subshard",a);let f=s.node.Links.findIndex(y=>y.Name?.startsWith(a)),m=s.node.Links.splice(f,1)[0],d=(m.Name??"").substring(2),h=il(Qo)(U(d));for(let y=0;y<o.length;y++)await h.take(Wn);for(;;){let y=await h.take(Wn),g=ll(y);m.Name=`${g}${d}`;let b=await i.take(Wn),x=ll(b);if(g===x){let S=new Ld.default;S.set(b,!0),o.push({prefix:x,children:S,node:{Links:[]}});continue}let v=new Ld.default;v.set(b,!0),v.set(y,!0),o.push({prefix:a,children:v,node:{Links:[m,{Name:`${x}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else dr("link %s was not present in sub-shard",u),e.Name=u,s.node.Links.push(e),s.children.set(c,!0),dr("adding %s to existing sub-shard",u);return ul(o,t,n)};async function xn(r,e,t={}){let n=await ze(r,e,t);if(n.type!=="directory")throw new bn(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function ti(r,e,t,n){let o=await ze(r,t,n);if(o.type!=="directory"&&o.type!=="file"&&o.type!=="raw")throw new fr(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:o.node instanceof Uint8Array?o.node.byteLength:kA(o.node),Hash:r}}function kA(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return re(r).byteLength+e}var BA=Q("helia:unixfs:components:utils:resolve");async function hr(r,e,t,n){if(e==null||e==="")return{cid:r};let o=`/ipfs/${r}${e==null?"":`/${e}`}`,i=await is(vs(o,t,n));if(i.length===0)throw new rl("Could not find path in directory");return BA("resolved %s to %c",e,r),{cid:i[i.length-1].cid,path:e,segments:i}}async function ri(r,e,t,n){if(e.segments==null||e.segments.length===0)return r;let o=e.segments.pop();if(o==null)throw new Error("Insufficient segments");o.cid=r,e.segments.reverse();for(let i of e.segments){let[s,a]=await Promise.all([xn(i.cid,t,n),ti(o.cid,o.name,t,n)]);r=(await ei(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,i.cid=r,o=i}return r}var IA=Ze.bind({ignoreUndefined:!0}),RA={};async function*zw(r,e,t={}){let n=IA(RA,t),o=await hr(r,n.path,e,n),i=await ze(o.cid,e,n);if(i.type!=="file"&&i.type!=="raw")throw new nl;if(i.content==null)throw new Jo;yield*i.content(n)}var TA=Ze.bind({ignoreUndefined:!0}),NA=Q("helia:unixfs:chmod"),CA={recursive:!1,shardSplitThresholdBytes:262144};async function $w(r,e,t,n={}){let o=TA(CA,n),i=await hr(r,o.path,t,n);if(NA("chmod %c %d",i.cid,e),o.recursive){let m=await at(async function*(){for await(let d of Yo(i.cid,t,n)){let p,h=[];if(d.type==="raw")p=new q({type:"file",data:d.node});else if(d.type==="file"||d.type==="directory")p=d.unixfs,h=d.node.Links;else throw new fr;p.mode=e;let y={Data:p.marshal(),Links:h};yield{path:d.path,content:y}}},d=>gn(d,t,{...o,dagBuilder:async function*(p,h){for await(let y of p)yield async function(){let g=y.content,b=re(g),x=await Zt(b,h,{...o,cidVersion:r.version});if(g.Data==null)throw new ot(`${x} had no data`);let v=q.unmarshal(g.Data);return{cid:x,size:BigInt(b.length),path:y.path,unixfs:v}}}}),async d=>wn(d));if(m==null)throw new Fr(`Could not chmod ${i.cid.toString()}`);return ri(m.cid,i,t,o)}let s=await t.get(i.cid,n),a,c=[];if(i.cid.code===ge)a=new q({type:"file",data:s});else{let m=we(s);if(m.Data==null)throw new ot(`${i.cid.toString()} had no data`);c=m.Links,a=q.unmarshal(m.Data)}a.mode=e;let u=re({Data:a.marshal(),Links:c}),l=await ce.digest(u),f=O.create(i.cid.version,ye,l);return await t.put(f,u),ri(f,i,t,o)}var LA=Ze.bind({ignoreUndefined:!0}),DA=Q("helia:unixfs:cp"),PA={force:!1,shardSplitThresholdBytes:262144};async function Kw(r,e,t,n,o={}){let i=LA(PA,o);if(t.includes("/"))throw new St("Name must not have slashes");let[s,a]=await Promise.all([xn(e,n,i),ti(r,t,n,i)]);return DA('Adding %c as "%s" to %c',r,t,e),(await ei(s,a,n,{allowOverwriting:i.force,cidVersion:e.version,...i})).cid}var OA=Ze.bind({ignoreUndefined:!0}),UA={};async function*qw(r,e,t={}){let n=OA(UA,t),o=await hr(r,n.path,e,n),i=await ze(o.cid,e);if(i.type==="file"||i.type==="raw"){yield i;return}if(i.content==null)throw new Jo;if(i.type!=="directory")throw new bn;yield*i.content({offset:t.offset,length:t.length})}var FA=Ze.bind({ignoreUndefined:!0}),Gw=Q("helia:unixfs:mkdir"),VA={cidVersion:1,force:!1,shardSplitThresholdBytes:262144};async function Ww(r,e,t,n={}){let o=FA(VA,n);if(e.includes("/"))throw new St("Path must not have slashes");if((await ze(r,t,n)).type!=="directory")throw new bn(`${r.toString()} was not a UnixFS directory`);Gw("creating %s",e);let a={Data:new q({type:"directory",mode:o.mode,mtime:o.mtime}).marshal(),Links:[]},c=re(a),u=await ce.digest(c),l=O.create(o.cidVersion,ye,u);await t.put(l,c);let[f,m]=await Promise.all([xn(r,t,o),ti(l,e,t,o)]);return Gw("adding empty dir called %s to %c",e,r),(await ei(f,m,t,{...o,allowOverwriting:o.force})).cid}var hl=Q("helia:unixfs:utils:remove-link");async function jw(r,e,t,n){if(r.node.Data==null)throw new ot("Parent node had no data");if(q.unmarshal(r.node.Data).type==="hamt-sharded-directory"){hl(`removing ${e} from sharded directory`);let i=await MA(r,e,t,n);return await dl(i.node,t,n.shardSplitThresholdBytes,n)?i:(hl("converting shard to flat directory %c",r.cid),zA(i,t,n))}return hl(`removing link ${e} regular directory`),HA(r,e,t,n)}var HA=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let o=re(r.node),i=await Zt(o,t,{...n,cidVersion:r.cid.version});return hl(`Updated regular directory ${i}`),{node:r.node,cid:i}},MA=async(r,e,t,n)=>{let{path:o}=await fl(r.cid,e,t,n),i=o[o.length-1];if(i==null)throw new Error("Invalid HAMT, could not generate path");let s=i.node.Links.filter(u=>(u.Name??"").substring(2)===e).map(u=>u.Name).pop();if(s==null)throw new Error("File not found");let a=s.substring(0,2),c=parseInt(a,16);if(i.node.Links=i.node.Links.filter(u=>u.Name!==s),i.children.unset(c),i.node.Links.length===1)for(;o.length!==1;){let u=o[o.length-1];if(u==null||u.node.Links.length>1)break;o.pop();let l=o[o.length-1];if(l==null)break;let f=u.node.Links[0];l.node.Links=l.node.Links.filter(m=>!(m.Name??"").startsWith(l.prefix)),l.node.Links.push({Hash:f.Hash,Name:`${l.prefix}${(f.Name??"").substring(2)}`,Tsize:f.Tsize})}return ul(o,t,n)},zA=async(r,e,t)=>{if(r.node.Data==null)throw new St("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},o=await ze(r.cid,e);if(o.type!=="directory")throw new Error("Unexpected node type");for await(let c of o.content()){let u=0;c.node instanceof Uint8Array?u=c.node.byteLength:u=re(c.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:u})}let i=q.unmarshal(r.node.Data);n.Data=new q({type:"directory",mode:i.mode,mtime:i.mtime}).marshal();let s=re(_e(n));return{cid:await Zt(s,e,{codec:Te,cidVersion:r.cid.version,signal:t.signal}),node:n}};var $A=Ze.bind({ignoreUndefined:!0}),KA=Q("helia:unixfs:rm"),qA={shardSplitThresholdBytes:262144};async function Yw(r,e,t,n={}){let o=$A(qA,n);if(e.includes("/"))throw new St("Name must not have slashes");let i=await xn(r,t,o);return KA("Removing %s from %c",e,r),(await jw(i,e,t,{...o,cidVersion:r.version})).cid}var GA=Ze.bind({ignoreUndefined:!0}),WA=Q("helia:unixfs:stat"),jA={};async function Xw(r,e,t={}){let n=GA(jA,t),o=await hr(r,t.path,e,n);WA("stat %c",o.cid);let i=await ze(o.cid,e,n);if(i.type!=="file"&&i.type!=="directory"&&i.type!=="raw")throw new fr;let s=0n,a=0n,c=0n,u=0n,l=0,f,m,d=i.type,p;if(i.type==="raw"&&(s=BigInt(i.node.byteLength),a=BigInt(i.node.byteLength),c=BigInt(i.node.byteLength),u=BigInt(i.node.byteLength),l=1),i.type==="directory"&&(s=0n,a=BigInt(i.unixfs.marshal().byteLength),c=0n,u=a,l=1,f=i.unixfs.mode,m=i.unixfs.mtime,p=i.unixfs),i.type==="file"){let h=await Zw(o.cid,e,n);s=i.unixfs.fileSize(),a=BigInt((i.node.Data?.byteLength??0)+i.node.Links.reduce((y,g)=>y+(g.Tsize??0),0)),c=BigInt(h.localFileSize),u=BigInt(h.localDagSize),l=h.blocks,f=i.unixfs.mode,m=i.unixfs.mtime,p=i.unixfs}return{cid:o.cid,mode:f,mtime:m,fileSize:s,dagSize:a,localFileSize:c,localDagSize:u,blocks:l,type:d,unixfs:p}}async function Zw(r,e,t){let n={localFileSize:0,localDagSize:0,blocks:0};if(await e.has(r,t)){let o=await e.get(r,t);if(n.blocks++,n.localDagSize+=o.byteLength,r.code===ge)n.localFileSize+=o.byteLength;else if(r.code===ye){let i=we(o);if(i.Links.length>0)for(let s of i.Links){let a=await Zw(s.Hash,e,t);n.localFileSize+=a.localFileSize,n.localDagSize+=a.localDagSize,n.blocks+=a.blocks}else{if(i.Data==null)throw new ot(`PBNode ${r.toString()} had no data`);let s=q.unmarshal(i.Data);if(s.data==null)throw new ot(`UnixFS node ${r.toString()} had no data`);n.localFileSize+=s.data.byteLength??0}}else throw new Fr(`${r.toString()} was neither DAG_PB nor RAW`)}return n}var YA=Ze.bind({ignoreUndefined:!0}),XA=Q("helia:unixfs:touch"),ZA={recursive:!1,shardSplitThresholdBytes:262144};async function Jw(r,e,t={}){let n=YA(ZA,t),o=await hr(r,n.path,e,n),i=n.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(XA("touch %c %o",o.cid,i),n.recursive){let m=await at(async function*(){for await(let d of Yo(o.cid,e)){let p,h;if(d.type==="raw")p=new q({data:d.node}),h=[];else if(d.type==="file"||d.type==="directory")p=d.unixfs,h=d.node.Links;else throw new fr;p.mtime=i;let y={Data:p.marshal(),Links:h};yield{path:d.path,content:y}}},d=>gn(d,e,{...n,dagBuilder:async function*(p,h){for await(let y of p)yield async function(){let g=y.content,b=re(g),x=await Zt(b,h,{...n,cidVersion:r.version});if(g.Data==null)throw new ot(`${x} had no data`);let v=q.unmarshal(g.Data);return{cid:x,size:BigInt(b.length),path:y.path,unixfs:v}}}}),async d=>wn(d));if(m==null)throw new Fr(`Could not chmod ${o.cid.toString()}`);return ri(m.cid,o,e,n)}let s=await e.get(o.cid,t),a,c=[];if(o.cid.code===ge)a=new q({data:s});else{let m=we(s);if(c=m.Links,m.Data==null)throw new ot(`${o.cid.toString()} had no data`);a=q.unmarshal(m.Data)}a.mtime=i;let u=re({Data:a.marshal(),Links:c}),l=await ce.digest(u),f=O.create(o.cid.version,ye,l);return await e.put(f,u),ri(f,o,e,n)}var Dd=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*ow(e,this.components.blockstore,t)}async addBytes(e,t={}){return iw(e,this.components.blockstore,t)}async addByteStream(e,t={}){return sw(e,this.components.blockstore,t)}async addFile(e,t={}){return aw(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return cw(e,this.components.blockstore,t)}async*cat(e,t={}){yield*zw(e,this.components.blockstore,t)}async chmod(e,t,n={}){return $w(e,t,this.components.blockstore,n)}async cp(e,t,n,o={}){return Kw(e,t,n,this.components.blockstore,o)}async*ls(e,t={}){yield*qw(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return Ww(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return Yw(e,t,this.components.blockstore,n)}async stat(e,t={}){return Xw(e,this.components.blockstore,t)}async touch(e,t={}){return Jw(e,this.components.blockstore,t)}};function Qw(r){return new Dd(r)}function pl(r,e={}){let t={_cancelled:!1,async start(){this._cancelled=!1},async pull(n){try{let{value:o,done:i}=await r.next();if(this._cancelled)return;if(i===!0){n.close();return}n.enqueue(o)}catch(o){n.error(o)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(t,e)}function eb(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function tb(r,e,t){if((r??0)>(e??1/0))throw new Error("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new Error("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(e??0)>(t??1/0))throw new Error("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Error("Invalid range: Range-start index cannot be negative.");if(r!=null&&e!=null)return{byteSize:e-r+1,start:r,end:e};if(r==null&&e!=null)return t==null?{end:e}:e===t?{byteSize:t,start:0,end:t-1}:{byteSize:e,start:t-e,end:t-1};if(r!=null&&e==null){if(t==null)return{start:r};let n=t-1;return{byteSize:t-r,start:r,end:n}}return{byteSize:t,start:0,end:t!=null?t-1:0}}function rb({ttl:r,protocol:e,response:t}){let n;e==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function nb({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new Error("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new Error("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&e==null)return t==null?`bytes */${n}`:`bytes ${r}-${t-1}/${t}`;if(r==null&&e!=null){if(t==null)return`bytes */${n}`;let o=t-1;return`bytes ${o-e+1}-${o}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function JA(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 QA(r){let e=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(e?.groups==null)throw new Error("Invalid range request");let{start:t,end:n}=e.groups;return{start:t,end:n}}var As=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(e,t){if(this.headers=t,this.log=e.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=eb(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=QA(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(e){this._body=e,this.setFileSize(this._fileSize??JA(e)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let e=this._body;if(e==null)return this.log.trace("body is null"),e;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),e;let t=this.byteStart,n=this.byteEnd,o=this.byteSize;return t!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",t,n,o),e instanceof ReadableStream?e:this.getSlicedBody(e)):(this.log.error("returning unmodified body for valid range request"),e)}getSlicedBody(e){let t=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",t,n),e.slice(t,n)}setFileSize(e){this._fileSize=e!=null?Number(e):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:e,end:t,byteSize:n}=tb(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",e,t,n),this.byteStart=e,this.byteEnd=t,this.byteSize=n}catch(e){this.log.error("error setting offset details: %o",e),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 Error("Invalid range request");return nb({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function ob(r){let e=rt(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(Qi(e))}function ib(r){let e=ek(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function ek(r){return r.replace(/[^\x00-\x7F]/g,"_")}function sb({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:o}){let i=t===!0?"W/":"",s=e==null?"":`.${e}`;return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}var tk={[hn]:["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"],[mn]:["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"],[Wr]:["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"],[ye]:["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"],[ge]:["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,e){let t=tk[r.code];if(e!=null)return rk(e,t)}function rk(r,e){let t=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:nk(o[1])}}).sort((n,o)=>n.weight===o.weight?0:n.weight>o.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let o of e)if(n.includes(o)||n==="*/*"||n.startsWith("*/")&&o.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&o.split("/")[0]===n.split("/")[0])return o}function nk(r){if(r!=null&&(r=r.trim()),r==null||!r.startsWith("q="))return 1;let e=parseFloat(r.replace("q=",""));return isNaN(e)?0:e}var ml={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 ml[r]}function Pd(r){let e=r.get("accept");return!!(e!=null&&Object.values(ml).includes(e))}function Od(r){let e=r?.format;return!!(e!=null&&Object.keys(ml).includes(e))}function lb({query:r,headers:e}){return Pd(e)||Od(r)}function ub({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),o=new Headers(e),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!Pd(o)&&Od(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,e,t,n){let o=t.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",e),new Error("No content found");return{stream:new ReadableStream({async start(u){n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),u.enqueue(s)},async pull(u){let{value:l,done:f}=await i.next();if(n?.signal?.aborted===!0){u.error(new Qt(n.signal.reason??"signal aborted by user")),u.close();return}if(f===!0){l!=null&&(n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),u.enqueue(l)),u.close();return}n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),u.enqueue(l)}}),firstChunk:s}}var GM=U("ustar\0","binary"),WM=U("ustar ","binary"),jM=U(" \0","binary");var yb=J(hb(),1);function ik(r){return r[Symbol.asyncIterator]!=null}function sk(r){if(ik(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=ue([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return ue(e,t)}var pb=sk;var ak="0000000000000000000",ck="7777777777777777777",lk=48,uk=U("ustar\0","binary"),fk=U("00","binary"),dk=parseInt("7777",8),hk=257,pk=263,mk=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}},yk=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},En=function(r,e){let t=r.toString(8);return t.length>e?U(ck.slice(0,e)+" "):U(ak.slice(0,e-t.length)+t+" ")},Ud=function(r){let e=U(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function mb(r){let e="";r.name!=null&&(e+=Ud(" path="+r.name+`
|
|
9
|
+
`)),r.linkname!=null&&(e+=Ud(" linkpath="+r.linkname+`
|
|
10
|
+
`));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=Ud(" "+n+"="+t[n]+`
|
|
11
|
+
`));return U(e)}function yl(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),U(t).byteLength!==t.length)return null;for(;U(t).byteLength>100;){let o=t.indexOf("/");if(o===-1)return null;n+=n!==""?"/"+t.slice(0,o):t.slice(0,o),t=t.slice(o+1)}return U(t).byteLength>100||U(n).byteLength>155||r.linkname!=null&&U(r.linkname).byteLength>100?null:(e.set(U(t),0),e.set(En(r.mode&dk,6),100),e.set(En(r.uid,6),108),e.set(En(r.gid,6),116),e.set(En(r.size,11),124),e.set(En(r.mtime.getTime()/1e3|0,11),136),e[156]=lk+mk(r.type),r.linkname!=null&&e.set(U(r.linkname),157),e.set(uk,hk),e.set(fk,pk),r.uname!=null&&e.set(U(r.uname),265),r.gname!=null&&e.set(U(r.gname),297),e.set(En(r.devmajor??0,6),329),e.set(En(r.devminor??0,6),337),n!=null&&e.set(U(n),345),e.set(En(yk(e),6),148),e)}var{S_IFMT:wk,S_IFBLK:bk,S_IFCHR:xk,S_IFDIR:Ek,S_IFIFO:vk,S_IFLNK:Sk}=yb.default,_k=parseInt("755",8),Ak=parseInt("644",8),gb=new Uint8Array(1024);function kk(r=0){switch(r&wk){case bk:return"block-device";case xk:return"character-device";case Ek:return"directory";case vk:return"fifo";case Sk:return"symlink";default:return"file"}}function Vd(r){return r&=511,r!==0?gb.subarray(0,512-r):new Uint8Array(0)}function Fd(r){if(r.pax==null){let e=yl(r);if(e!=null)return e}return Bk(r)}function Bk(r){let e=mb(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new Vt(yl(t)??new Uint8Array(0),e,Vd(e.length),yl({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function gl(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??kk(e.mode),mode:e.mode??(e.type==="directory"?_k:Ak),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=U(t)),t instanceof Uint8Array||tr(t)){n.size=t.length,yield Fd(n),yield tr(t)?t.subarray():t,yield Vd(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=W(await pb(t)),yield Fd(n);continue}if(yield Fd(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield tr(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield Vd(n.size)}yield gb}}var Ik=["file","raw","directory"];function Rk(r){let e,t;return(r.type==="file"||r.type==="directory")&&(e=r.unixfs.mode,t=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:e,mtime:t,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function wb(r){if(!Ik.includes(r.type))throw new N("Not a UnixFS node","ERR_NOT_UNIXFS");let e={header:Rk(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*bb(r,e,t){let n=await ze(r,e,t);if(n.type==="file"||n.type==="raw"){yield*at([wb(n)],gl());return}if(n.type==="directory"){yield*at(Yo(r,e,t),o=>We(o,i=>wb(i)),gl());return}throw new N("Not a UnixFS node","ERR_NOT_UNIXFS")}var xb=J(Uf(),1),wl=class{lru;constructor(e){this.lru=(0,xb.default)(e)}get(e){let t=this.lru.get(e);if(t!=null){if(t.expire!=null&&t.expire<Date.now()){this.lru.remove(e);return}return t.value}}set(e,t,n){this.lru.set(e,{value:t,expire:Date.now()+n})}has(e){return this.get(e)!=null}remove(e){this.lru.remove(e)}clear(){this.lru.clear()}};var Eb=new wl(1e3),Tk=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Nk=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Ck=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Lk=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function Dk(r){let e=r?.protocol;if(e==null)return!1;let t=r?.cidOrPeerIdOrDnsLink;if(t==null)return!1;let n=r?.path,o=r?.queryString;return["ipns","ipfs"].includes(e)&&typeof t=="string"&&(n==null||typeof n=="string")&&(o==null||typeof o=="string")}function Pk(r){for(let e of[Tk,Nk,Ck,Lk]){let t=r.match(e);if(Dk(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function Ok(r){if(r==null)return;let e=r.answer?.TTL,t=r.record?.ttl,n=t!=null?Number(t/BigInt(1e9)):void 0;return e??n}var Uk=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function Fk(r){return Uk.test(r)&&r.includes("-")&&!r.includes(".")}function Vk(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function vb({urlString:r,ipns:e,logger:t},n){let o=t.forComponent("helia:verified-fetch:parse-url-string"),{protocol:i,cidOrPeerIdOrDnsLink:s,path:a,queryString:c}=Pk(r),u,l,f=[],m;if(i==="ipfs")try{u=O.parse(s)}catch(h){o.error(h),f.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(m=Eb.get(s),m!=null)u=m.cid,l=m.path,o.trace("resolved %s to %c from cache",s,u);else{o.trace("Attempting to resolve PeerId for %s",s);let h=null;try{h=Qe(s),m=await e.resolve(h,n),u=m?.cid,l=m?.path,o.trace("resolved %s to %c",s,u)}catch(y){n?.signal?.throwIfAborted(),h==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",h,y),f.push(new TypeError(`Could not resolve PeerId "${s}", ${y.message}`)))}if(u==null){let y=s;Fk(s)&&(y=Vk(s),o.trace('decoded dnslink from "%s" to "%s"',s,y)),o.trace("Attempting to resolve DNSLink for %s",y);try{m=await e.resolveDNSLink(y,n),u=m?.cid,l=m?.path,o.trace("resolved %s to %c",y,u)}catch(g){n?.signal?.throwIfAborted(),o.error('could not resolve DnsLink for "%s"',s,g),f.push(g)}}}if(u==null)throw f.length===1?f[0]:new AggregateError(f,`Invalid resource. Cannot determine CID from URL "${r}"`);let d=Ok(m);m!=null&&(d=d??60*2,o.trace("caching %s resolved to %s with TTL: %s",s,u,d),Eb.set(s,m,d*1e3));let p={};if(c!=null&&c.length>0){let h=c.split("&");for(let y of h){let[g,b]=y.split("=");p[g]=decodeURIComponent(b)}p.download!=null&&(p.download=p.download==="true"),p.filename!=null&&(p.filename=p.filename.toString())}return{protocol:i,cid:u,path:Hk(l,a??""),query:p,ttl:d}}function Hk(r,e){let t="";return r!=null&&(t+=r),e.length>0&&(t=`${t.length>0?`${t}/`:t}${e}`),t=t.replace(/\/(\/)+/g,"/"),t.startsWith("/")&&(t=t.substring(1)),t.split("/").map(decodeURIComponent).join("/")}async function Sb(r,{ipns:e,logger:t},n){if(typeof r=="string")return vb({urlString:r,ipns:e,logger:t},n);let o=O.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ttl:29030400};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function Hd(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function Hr(r,e){Hd(r,"type",e)}function Mr(r,e){Hd(r,"url",e)}function _b(r){Hd(r,"redirected",!0)}function jn(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&_b(n),Hr(n,"basic"),Mr(n,r),n.headers.set("Accept-Ranges","bytes"),n}function xl(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return Hr(n,"basic"),Mr(n,r),n}function Md(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Hr(n,"basic"),Mr(n,r),n}function ni(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return Hr(n,"basic"),Mr(n,r),n}function El(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return Hr(n,"basic"),Mr(n,r),n}function vl(r,e,t){e instanceof Error&&(e=e.message);let n=new Response(e,{...t??{},status:400,statusText:"Bad Request"});return Hr(n,"basic"),Mr(n,r),n}function Ab(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return Hr(n,"basic"),Mr(n,r),n}function zd(r,e,{byteRangeContext:t,log:n},o){if(!t.isRangeRequest)return jn(r,e,o);if(!t.isValidRangeRequest)return bl(r,e,o);let i;try{i=new Response(e,{...o??{},status:206,statusText:"Partial Content",headers:{...o?.headers??{},"content-range":t.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),bl(r,e,o)}return o?.redirected===!0&&_b(i),Hr(i,"basic"),Mr(i,r),i.headers.set("Accept-Ranges","bytes"),i}function bl(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return Hr(n,"basic"),Mr(n,r),n}async function $d(r,e,t){let n=[],o;for await(let i of vs(e,r,t))n.push(i.cid),o=i;if(o==null)throw new N("No terminal element found","ERR_NO_TERMINAL_ELEMENT");return{ipfsRoots:n,terminalElement:o}}function kb(r){return r.type==="object"}function Mk(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var zk=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function $k({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(o=>o.split(";")[0]).map(o=>o.trim());for(let o of n){if(o==="*/*")return;if(zk.includes(o??""))return o}}var Sl=class{helia;ipns;unixfs;log;contentTypeParser;constructor({helia:e,ipns:t,unixfs:n},o){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??R0(e),this.unixfs=n??Qw(e),this.contentTypeParser=o?.contentTypeParser,this.log.trace("created VerifiedFetch instance")}async handleIPNSRecord({resource:e,cid:t,path:n,options:o}){if(n!==""||!e.startsWith("ipns://"))return vl(e,"Invalid IPNS name");let i;try{i=Qe(e.replace("ipns://",""))}catch(f){return this.log.error("could not parse peer id from IPNS url %s",e),vl(e,f)}let s=ue([U("/ipns/"),i.toBytes()]),a=new ke("/dht/record/"+W(s,"base32"),!1),c=await this.helia.datastore.get(a,o),u=Or.deserialize(c),l=jn(e,u.value);return l.headers.set("content-type","application/vnd.ipfs.ipns-record"),l}async handleCar({resource:e,cid:t,options:n}){let o=x0(this.helia),i=pl(o.stream(t,n)),s=jn(e,i);return s.headers.set("content-type","application/vnd.ipld.car; version=1"),s}async handleTar({resource:e,cid:t,path:n,options:o}){if(t.code!==ye&&t.code!==ge)return ni("only UnixFS data can be returned in a TAR file");let i=pl(bb(`/ipfs/${t}/${n}`,this.helia.blockstore,o)),s=jn(e,i);return s.headers.set("content-type","application/x-tar"),s}async handleJson({resource:e,cid:t,path:n,accept:o,options:i}){this.log.trace("fetching %c/%s",t,n);let s=await this.helia.blockstore.get(t,i),a;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let u=Tc(s);a=Zi(u)}catch(u){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",u),ni(e)}else a=s;let c=jn(e,a);return c.headers.set("content-type",o??"application/json"),c}async handleDagCbor({resource:e,cid:t,path:n,accept:o,options:i}){this.log.trace("fetching %c/%s",t,n);let s,a;try{let f=await $d(this.helia.blockstore,`${t.toString()}/${n}`,i);a=f.ipfsRoots;let m=f.terminalElement;if(m==null)return El(e);kb(m)&&(s=m)}catch(f){return i?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT"].includes(f.code)?El(e):(this.log.error("error walking path %s",n,f),xl(e,"Error walking path"))}let c=s?.node??await this.helia.blockstore.get(t,i),u;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")u=c;else if(o==="application/vnd.ipld.dag-json")try{let f=Mn(c);u=qg(f)}catch(f){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",f),ni(e)}else try{u=ob(c)}catch(f){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',f),ni(e);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",f),u=c}let l=jn(e,u);return o==null&&(o=u instanceof Uint8Array?"application/octet-stream":"application/json"),l.headers.set("content-type",o),a!=null&&l.headers.set("X-Ipfs-Roots",a.map(f=>f.toV1().toString()).join(",")),l}async handleDagPb({cid:e,path:t,resource:n,options:o}){let i,s,a=!1,c=new As(this.helia.logger,o?.headers);try{let d=await $d(this.helia.blockstore,`${e.toString()}/${t}`,o);s=d.ipfsRoots,i=d.terminalElement}catch(d){return o?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT"].includes(d.code)?El(n.toString()):(this.log.error("error walking path %s",t,d),xl(n.toString(),"Error walking path"))}let u=i?.cid??e;if(i?.type==="directory"){let d=i.cid;if(t===""?!n.toString().endsWith("/"):!t.endsWith("/")){if(o?.redirect==="error")throw this.log('could not redirect to %s/ as redirect option was set to "error"',n),new TypeError("Failed to fetch");if(o?.redirect==="manual")return this.log("returning 301 permanent redirect to %s/",n),Ab(n,`${n}/`);n=`${n}/`,a=!0}let h="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",e,t);let y=await this.unixfs.stat(d,{path:h,signal:o?.signal,onProgress:o?.onProgress});this.log.trace("found root file at %c/%s with cid %c",d,h,y.cid),t=h,u=y.cid}catch(y){return o?.signal?.throwIfAborted(),this.log("error loading path %c/%s",d,h,y),Md("Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented")}finally{o?.onProgress?.(new F("verified-fetch:request:end",{cid:d,path:h}))}}c.isRangeRequest&&c.isValidRangeRequest&&i.type==="file"&&(c.setFileSize(i.unixfs.fileSize()),this.log.trace("fileSize for rangeRequest %d",c.getFileSize()));let l=c.offset,f=c.length;this.log.trace("calling unixfs.cat for %c/%s with offset=%o & length=%o",u,t,l,f);let m=this.unixfs.cat(u,{signal:o?.signal,onProgress:o?.onProgress,offset:l,length:f});this.log("got async iterator for %c/%s",e,t);try{let{stream:d,firstChunk:p}=await fb(m,t??"",this.helia.logger,{onProgress:o?.onProgress,signal:o?.signal});c.setBody(d);let h=zd(n,c.getBody(),{byteRangeContext:c,log:this.log},{redirected:a});return await this.setContentType(p,t,h),s!=null&&h.headers.set("X-Ipfs-Roots",s.map(y=>y.toV1().toString()).join(",")),h}catch(d){return o?.signal?.throwIfAborted(),this.log.error("error streaming %c/%s",e,t,d),c.isRangeRequest&&d.code==="ERR_INVALID_PARAMS"?bl(n):xl(n.toString(),"Unable to stream content")}}async handleRaw({resource:e,cid:t,path:n,options:o,accept:i}){let s=new As(this.helia.logger,o?.headers),a=await this.helia.blockstore.get(t,o);s.setBody(a);let c=zd(e,s.getBody(),{byteRangeContext:s,log:this.log},{redirected:!1});return await this.setContentType(a,n,c,$k({headers:o?.headers,accept:i})),c}async setContentType(e,t,n,o="application/octet-stream"){let i;if(this.contentTypeParser!=null)try{let s=t.split("/").pop()?.trim();s=s===""?void 0:s;let a=this.contentTypeParser(e,s);if(Kk(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={[ye]:this.handleDagPb,[mn]:this.handleJson,[Wr]:this.handleJson,[hn]:this.handleDagCbor,[ge]:this.handleRaw,[Ge.code]:this.handleRaw};async fetch(e,t){this.log("fetch %s",e);let n=Mk(t);n?.onProgress?.(new F("verified-fetch:request:start",{resource:e}));let o,i,s,a,c;try{let h=await Sb(e,{ipns:this.ipns,logger:this.helia.logger},n);o=h.cid,i=h.path,s=h.query,a=h.ttl,c=h.protocol}catch(h){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",e,h),vl(e.toString(),h)}n?.onProgress?.(new F("verified-fetch:request:resolve",{cid:o,path:i}));let u=ub({query:s,headers:n?.headers,logger:this.helia.logger}),l=ab(o,u);if(this.log("output type %s",l),u!=null&&l==null)return ni(e.toString());let f,m,d={resource:e.toString(),cid:o,path:i,accept:l,options:n};if(l==="application/vnd.ipfs.ipns-record")m="ipns-record",f=await this.handleIPNSRecord(d);else if(l==="application/vnd.ipld.car")m="car",s.download=!0,s.filename=s.filename??`${o.toString()}.car`,f=await this.handleCar(d);else if(l==="application/vnd.ipld.raw")m="raw",s.download=!0,s.filename=s.filename??`${o.toString()}.bin`,f=await this.handleRaw(d);else if(l==="application/x-tar")m="tar",s.download=!0,s.filename=s.filename??`${o.toString()}.tar`,f=await this.handleTar(d);else{this.log.trace('finding handler for cid code "%s" and output type "%s"',o.code,l);let h=this.codecHandlers[o.code];if(h==null)return Md(`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"',h.name),f=await h.call(this,d)}f.headers.set("etag",sb({cid:o,reqFormat:m,weak:!1})),rb({response:f,ttl:a,protocol:c}),f.headers.set("X-Ipfs-Path",e.toString());let p;return s.download===!0&&(p="attachment"),s.filename!=null&&(p==null&&(p="inline"),p=`${p}; ${ib(s.filename)}`),p!=null&&f.headers.set("Content-Disposition",p),n?.onProgress?.(new F("verified-fetch:request:end",{cid:o,path:i})),f}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function Kk(r){return r?.then!=null}var ks,_l=async function(e,t){return ks==null&&(ks=await Kd()),ks(e,t)};_l.start=async function(){await ks?.start()};_l.stop=async function(){await ks?.stop()};async function Kd(r,e){qk(r)||(r=await h0({blockBrokers:[di({gateways:r?.gateways})],routers:(r?.routers??["https://delegated-ipfs.dev"]).map(o=>ji(o)),dns:Gk(r?.dnsResolvers)}));let t=new Sl({helia:r},e);async function n(o,i){return t.fetch(o,i)}return n.stop=t.stop.bind(t),n.start=t.start.bind(t),n}function qk(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function Gk(r){if(r!=null)return Array.isArray(r)?Yi({resolvers:{".":r}}):Yi({resolvers:r})}return Hb(Wk);})();
|
|
12
12
|
/*! Bundled license information:
|
|
13
13
|
|
|
14
14
|
pvtsutils/build/index.js:
|