@helia/verified-fetch 1.3.13 → 1.4.0
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/README.md +11 -6
- package/dist/index.min.js +18 -7
- package/dist/src/index.d.ts +86 -6
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +20 -9
- package/dist/src/index.js.map +1 -1
- package/dist/src/utils/parse-url-string.d.ts +7 -0
- package/dist/src/utils/parse-url-string.d.ts.map +1 -1
- package/dist/src/utils/parse-url-string.js +1 -1
- package/dist/src/utils/parse-url-string.js.map +1 -1
- package/dist/src/utils/resource-to-cache-key.d.ts +15 -0
- package/dist/src/utils/resource-to-cache-key.d.ts.map +1 -0
- package/dist/src/utils/resource-to-cache-key.js +27 -0
- package/dist/src/utils/resource-to-cache-key.js.map +1 -0
- package/dist/src/verified-fetch.d.ts +4 -10
- package/dist/src/verified-fetch.d.ts.map +1 -1
- package/dist/src/verified-fetch.js +44 -14
- package/dist/src/verified-fetch.js.map +1 -1
- package/package.json +14 -14
- package/src/index.ts +101 -9
- package/src/utils/parse-url-string.ts +1 -1
- package/src/utils/resource-to-cache-key.ts +30 -0
- package/src/verified-fetch.ts +66 -26
package/dist/index.min.js
CHANGED
|
@@ -1,14 +1,25 @@
|
|
|
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 mw=Object.create;var Zi=Object.defineProperty;var gw=Object.getOwnPropertyDescriptor;var yw=Object.getOwnPropertyNames;var ww=Object.getPrototypeOf,bw=Object.prototype.hasOwnProperty;var Ce=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Se=(r,e)=>{for(var t in e)Zi(r,t,{get:e[t],enumerable:!0})},fh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yw(e))!bw.call(r,o)&&o!==t&&Zi(r,o,{get:()=>e[o],enumerable:!(n=gw(e,o))||n.enumerable});return r};var re=(r,e,t)=>(t=r!=null?mw(ww(r)):{},fh(e||!r||!r.__esModule?Zi(t,"default",{value:r,enumerable:!0}):t,r)),xw=r=>fh(Zi({},"__esModule",{value:!0}),r);var gh=Ce((c_,mh)=>{var Fn=1e3,Vn=Fn*60,Mn=Vn*60,dn=Mn*24,_w=dn*7,kw=dn*365.25;mh.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Iw(r);if(t==="number"&&isFinite(r))return e.long?Bw(r):Rw(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Iw(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*kw;case"weeks":case"week":case"w":return t*_w;case"days":case"day":case"d":return t*dn;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Mn;case"minutes":case"minute":case"mins":case"min":case"m":return t*Vn;case"seconds":case"second":case"secs":case"sec":case"s":return t*Fn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Rw(r){var e=Math.abs(r);return e>=dn?Math.round(r/dn)+"d":e>=Mn?Math.round(r/Mn)+"h":e>=Vn?Math.round(r/Vn)+"m":e>=Fn?Math.round(r/Fn)+"s":r+"ms"}function Bw(r){var e=Math.abs(r);return e>=dn?os(r,e,dn,"day"):e>=Mn?os(r,e,Mn,"hour"):e>=Vn?os(r,e,Vn,"minute"):e>=Fn?os(r,e,Fn,"second"):r+" ms"}function os(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var wh=Ce((l_,yh)=>{function Tw(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=gh(),t.destroy=l,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let u=0;for(let p=0;p<f.length;p++)u=(u<<5)-u+f.charCodeAt(p),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(f){let u,p=null,h,m;function d(...y){if(!d.enabled)return;let w=d,x=Number(new Date),b=x-(u||x);w.diff=b,w.prev=u,w.curr=x,u=x,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let A=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(R,v)=>{if(R==="%%")return"%";A++;let E=t.formatters[v];if(typeof E=="function"){let P=y[A];R=E.call(w,P),y.splice(A,1),A--}return R}),t.formatArgs.call(w,y),(w.log||t.log).apply(w,y)}return d.namespace=f,d.useColors=t.useColors(),d.color=t.selectColor(f),d.extend=n,d.destroy=t.destroy,Object.defineProperty(d,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(f)),m),set:y=>{p=y}}),typeof t.init=="function"&&t.init(d),d}function n(f,u){let p=t(this.namespace+(typeof u>"u"?":":u)+f);return p.log=this.log,p}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let u,p=(typeof f=="string"?f:"").split(/[\s,]+/),h=p.length;for(u=0;u<h;u++)p[u]&&(f=p[u].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.slice(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function i(){let f=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),f}function s(f){if(f[f.length-1]==="*")return!0;let u,p;for(u=0,p=t.skips.length;u<p;u++)if(t.skips[u].test(f))return!1;for(u=0,p=t.names.length;u<p;u++)if(t.names[u].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack||f.message:f}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}yh.exports=Tw});var bh=Ce((lt,is)=>{lt.formatArgs=Cw;lt.save=Lw;lt.load=Dw;lt.useColors=Nw;lt.storage=Pw();lt.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`."))}})();lt.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 Nw(){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 Cw(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+is.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)}lt.log=console.debug||console.log||(()=>{});function Lw(r){try{r?lt.storage.setItem("debug",r):lt.storage.removeItem("debug")}catch{}}function Dw(){let r;try{r=lt.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Pw(){try{return localStorage}catch{}}is.exports=wh()(lt);var{formatters:Ow}=is.exports;Ow.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Le=Ce((S_,Ah)=>{"use strict";function Sh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function qw(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 Sh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),Sh(new o,t)}}Ah.exports=qw});var id=Ce((pI,Ol)=>{"use strict";var p1=Object.prototype.hasOwnProperty,Xe="~";function Wo(){}Object.create&&(Wo.prototype=Object.create(null),new Wo().__proto__||(Xe=!1));function m1(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function od(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new m1(t,n||r,o),s=Xe?Xe+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 ds(r,e){--r._eventsCount===0?r._events=new Wo:delete r._events[e]}function qe(){this._events=new Wo,this._eventsCount=0}qe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)p1.call(t,n)&&e.push(Xe?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};qe.prototype.listeners=function(e){var t=Xe?Xe+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};qe.prototype.listenerCount=function(e){var t=Xe?Xe+e:e,n=this._events[t];return n?n.fn?1:n.length:0};qe.prototype.emit=function(e,t,n,o,i,s){var a=Xe?Xe+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,f,u;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,i),!0;case 6:return c.fn.call(c.context,t,n,o,i,s),!0}for(u=1,f=new Array(l-1);u<l;u++)f[u-1]=arguments[u];c.fn.apply(c.context,f)}else{var p=c.length,h;for(u=0;u<p;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,o);break;default:if(!f)for(h=1,f=new Array(l-1);h<l;h++)f[h-1]=arguments[h];c[u].fn.apply(c[u].context,f)}}return!0};qe.prototype.on=function(e,t,n){return od(this,e,t,n,!1)};qe.prototype.once=function(e,t,n){return od(this,e,t,n,!0)};qe.prototype.removeListener=function(e,t,n,o){var i=Xe?Xe+e:e;if(!this._events[i])return this;if(!t)return ds(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&ds(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:ds(this,i)}return this};qe.prototype.removeAllListeners=function(e){var t;return e?(t=Xe?Xe+e:e,this._events[t]&&ds(this,t)):(this._events=new Wo,this._eventsCount=0),this};qe.prototype.off=qe.prototype.removeListener;qe.prototype.addListener=qe.prototype.on;qe.prefixed=Xe;qe.EventEmitter=qe;typeof Ol<"u"&&(Ol.exports=qe)});var $l=Ce((UI,ld)=>{ld.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 hm=Ce(Eo=>{"use strict";var ME="[object ArrayBuffer]",Er=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===ME}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}},Fu="string",HE=/^[0-9a-f]+$/i,$E=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,KE=/^[a-zA-Z0-9-_]+$/,oa=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=Er.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},Bt=class{static toString(e,t=!1){let n=Er.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}},ia=class r{static isHex(e){return typeof e===Fu&&HE.test(e)}static isBase64(e){return typeof e===Fu&&$E.test(e)}static isBase64Url(e){return typeof e===Fu&&KE.test(e)}static ToString(e,t="utf8"){let n=Er.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 Bt.toString(n,!0);case"utf16":case"utf16be":return Bt.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 Bt.fromString(e,!0);case"utf16":case"utf16be":return Bt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Er.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 oa.fromString(e);case"utf16":case"utf16be":return Bt.fromString(e);case"utf16le":case"usc2":return Bt.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 oa.toString(e);case"utf16":case"utf16be":return Bt.toString(e);case"utf16le":case"usc2":return Bt.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=Er.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Er.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 Bt.toString(e,t)}static FromUtf16String(e,t=!1){return Bt.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,"")||""}};ia.DEFAULT_UTF8_ENCODING="utf8";function qE(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 zE(...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 GE(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}Eo.BufferSourceConverter=Er;Eo.Convert=ia;Eo.assign=qE;Eo.combine=zE;Eo.isEqual=GE});var bg=Ce((Ri,Wa)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function o(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function i(h,m){return h<<m|h>>>32-m}function s(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]+m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]+m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]+m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]+m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]*m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]*m[3],d[1]+=d[2]>>>16,d[2]&=65535,d[2]+=h[3]*m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]*m[3],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[2]*m[2],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[3]*m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function f(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function u(h,m){return[h[0]^m[0],h[1]^m[1]]}function p(h){return h=u(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=u(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=u(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%4,y=h.length-d,w=m,x=0,b=3432918353,A=461845907,S=0;S<y;S=S+4)x=h[S]|h[S+1]<<8|h[S+2]<<16|h[S+3]<<24,x=o(x,b),x=i(x,15),x=o(x,A),w^=x,w=i(w,13),w=o(w,5)+3864292196;switch(x=0,d){case 3:x^=h[S+2]<<16;case 2:x^=h[S+1]<<8;case 1:x^=h[S],x=o(x,b),x=i(x,15),x=o(x,A),w^=x}return w^=h.length,w=s(w),w>>>0},t.x86.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,w=m,x=m,b=m,A=m,S=0,R=0,v=0,E=0,P=597399067,U=2869860233,L=951274213,$=2716044179,C=0;C<y;C=C+16)S=h[C]|h[C+1]<<8|h[C+2]<<16|h[C+3]<<24,R=h[C+4]|h[C+5]<<8|h[C+6]<<16|h[C+7]<<24,v=h[C+8]|h[C+9]<<8|h[C+10]<<16|h[C+11]<<24,E=h[C+12]|h[C+13]<<8|h[C+14]<<16|h[C+15]<<24,S=o(S,P),S=i(S,15),S=o(S,U),w^=S,w=i(w,19),w+=x,w=o(w,5)+1444728091,R=o(R,U),R=i(R,16),R=o(R,L),x^=R,x=i(x,17),x+=b,x=o(x,5)+197830471,v=o(v,L),v=i(v,17),v=o(v,$),b^=v,b=i(b,15),b+=A,b=o(b,5)+2530024501,E=o(E,$),E=i(E,18),E=o(E,P),A^=E,A=i(A,13),A+=w,A=o(A,5)+850148119;switch(S=0,R=0,v=0,E=0,d){case 15:E^=h[C+14]<<16;case 14:E^=h[C+13]<<8;case 13:E^=h[C+12],E=o(E,$),E=i(E,18),E=o(E,P),A^=E;case 12:v^=h[C+11]<<24;case 11:v^=h[C+10]<<16;case 10:v^=h[C+9]<<8;case 9:v^=h[C+8],v=o(v,L),v=i(v,17),v=o(v,$),b^=v;case 8:R^=h[C+7]<<24;case 7:R^=h[C+6]<<16;case 6:R^=h[C+5]<<8;case 5:R^=h[C+4],R=o(R,U),R=i(R,16),R=o(R,L),x^=R;case 4:S^=h[C+3]<<24;case 3:S^=h[C+2]<<16;case 2:S^=h[C+1]<<8;case 1:S^=h[C],S=o(S,P),S=i(S,15),S=o(S,U),w^=S}return w^=h.length,x^=h.length,b^=h.length,A^=h.length,w+=x,w+=b,w+=A,x+=w,b+=w,A+=w,w=s(w),x=s(x),b=s(b),A=s(A),w+=x,w+=b,w+=A,x+=w,b+=w,A+=w,("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(A>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,w=[0,m],x=[0,m],b=[0,0],A=[0,0],S=[2277735313,289559509],R=[1291169091,658871167],v=0;v<y;v=v+16)b=[h[v+4]|h[v+5]<<8|h[v+6]<<16|h[v+7]<<24,h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24],A=[h[v+12]|h[v+13]<<8|h[v+14]<<16|h[v+15]<<24,h[v+8]|h[v+9]<<8|h[v+10]<<16|h[v+11]<<24],b=c(b,S),b=l(b,31),b=c(b,R),w=u(w,b),w=l(w,27),w=a(w,x),w=a(c(w,[0,5]),[0,1390208809]),A=c(A,R),A=l(A,33),A=c(A,S),x=u(x,A),x=l(x,31),x=a(x,w),x=a(c(x,[0,5]),[0,944331445]);switch(b=[0,0],A=[0,0],d){case 15:A=u(A,f([0,h[v+14]],48));case 14:A=u(A,f([0,h[v+13]],40));case 13:A=u(A,f([0,h[v+12]],32));case 12:A=u(A,f([0,h[v+11]],24));case 11:A=u(A,f([0,h[v+10]],16));case 10:A=u(A,f([0,h[v+9]],8));case 9:A=u(A,[0,h[v+8]]),A=c(A,R),A=l(A,33),A=c(A,S),x=u(x,A);case 8:b=u(b,f([0,h[v+7]],56));case 7:b=u(b,f([0,h[v+6]],48));case 6:b=u(b,f([0,h[v+5]],40));case 5:b=u(b,f([0,h[v+4]],32));case 4:b=u(b,f([0,h[v+3]],24));case 3:b=u(b,f([0,h[v+2]],16));case 2:b=u(b,f([0,h[v+1]],8));case 1:b=u(b,[0,h[v]]),b=c(b,S),b=l(b,31),b=c(b,R),w=u(w,b)}return w=u(w,[0,h.length]),x=u(x,[0,h.length]),w=a(w,x),x=a(x,w),w=p(w),x=p(x),w=a(w,x),x=a(x,w),("00000000"+(w[0]>>>0).toString(16)).slice(-8)+("00000000"+(w[1]>>>0).toString(16)).slice(-8)+("00000000"+(x[0]>>>0).toString(16)).slice(-8)+("00000000"+(x[1]>>>0).toString(16)).slice(-8)},typeof Ri<"u"?(typeof Wa<"u"&&Wa.exports&&(Ri=Wa.exports=t),Ri.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)})(Ri)});var Qu=Ce((d6,xg)=>{xg.exports=bg()});var vg=Ce(Ti=>{(function(){var r,e,t,n,o,i,s,a;a=function(c){var l,f,u,p;return l=(c&255<<24)>>>24,f=(c&255<<16)>>>16,u=(c&65280)>>>8,p=c&255,[l,f,u,p].join(".")},s=function(c){var l,f,u,p,h,m;for(l=[],u=p=0;p<=3&&c.length!==0;u=++p){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=e(c),h=m[0],f=m[1],c=c.substring(f),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),i=t("a"),o=t("A"),e=function(c){var l,f,u,p,h;for(p=0,l=10,f="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,f="7")),h=u;u<c.length;){if("0"<=c[u]&&c[u]<=f)p=p*l+(t(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")p=p*l+(10+t(c[u])-i)>>>0;else if("A"<=c[u]&&c[u]<="F")p=p*l+(10+t(c[u])-o)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");u++}if(u===h)throw new Error("empty octet");return[p,u]},r=function(){function c(l,f){var u,p,h,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(f||(m=l.split("/",2),l=m[0],f=m[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=s(f)}catch(d){throw u=d,new Error("Invalid mask: "+f)}for(p=h=32;h>=0;p=--h)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(l)&this.maskLong)>>>0}catch(d){throw u=d,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(s(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var f,u,p;for(p=s(this.first),u=s(this.last),f=0;p<=u;)l(a(p),p,f),f++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Ti.ip2long=s,Ti.long2ip=a,Ti.Netmask=r}).call(Ti)});var cc=Ce((r4,Ef)=>{var t4=function(){typeof Ef<"u"&&(Ef.exports=d);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(E){var P=E-E%1;return P==0&&(E<0||E===0&&1/E!=1/0)?-0:P},f=d.prototype,u=(d.fromDate=function(E){return new d(+E)},d.fromInt64BE=A(0,1,2,3,0,4),d.fromInt64LE=A(3,2,1,0,4,0),d.fromString=function(L){var P,U=new d,L=(L+="").replace(/^\s*[+\-]?\d+/,function(C){var C=+C,ee=1970+(C-1970)%400;return U.year=C-ee,ee}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function($,C,ee){return C<0&&(ee*=-1),P=6e4*(60*+C+ +ee),""}).replace(/\.\d+$/,function($){return U.nano=+($+c).substr(1,9),""}).split(/\D+/);if(1<L.length?L[1]--:L[1]=0,U.time=P=Date.UTC.apply(Date,L)-(P||0),isNaN(P))throw new TypeError("Invalid Date");return y(U)},d.fromTimeT=function(E){return x(E,0)},f.year=0,f.time=0,f.nano=0,f.addNano=function(E){return this.nano+=+E||0,this},f.getNano=function(){var E=y(this);return(E.time%1e3*a+ +E.nano+1e9)%1e9},f.getTimeT=function(){var P=y(this),E=Math.floor(P.time/1e3),P=P.year;return P&&(E+=P*t*r/e),E},f.getYear=function(){return this.toDate().getUTCFullYear()+this.year},f.toDate=function(){return w(y(this).time)},f.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},f.toString=function(E){var P=this,U=P.toDate(),L={H:function(){return R(U.getUTCHours())},L:function(){return v(U.getUTCMilliseconds(),3)},M:function(){return R(U.getUTCMinutes())},N:function(){return v(P.getNano(),9)},S:function(){return R(U.getUTCSeconds())},Y:function(){var $=P.getYear();return 999999<$?"+"+$:9999<$?"+"+v($,6):0<=$?v($,4):-999999<=$?"-"+v(-$,6):$},a:function(){return h[U.getUTCDay()]},b:function(){return p[U.getUTCMonth()]},d:function(){return R(U.getUTCDate())},e:function(){return function($){return(9<$?"":" ")+(0|$)}(U.getUTCDate())},m:function(){return R(U.getUTCMonth()+1)}};return function $(C){return C.replace(/%./g,function(ee){var T=ee[1],I=m[T],T=L[T];return I?$(I):T?T():ee})}(E||u)},f.writeInt64BE=b(0,1,2,3,0,4),f.writeInt64LE=b(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),p=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m={"%":"%",F:"%Y-%m-%d",n:`
|
|
3
|
-
`,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return d;function d(E,P,U){var L=this;if(!(L instanceof d))return new d(E,P,U);L.time=+E||0,L.nano=+P||0,L.year=+U||0,y(L)}function y(E){var P,U,L,$=E.year,C=E.time,ee=E.nano,I=((ee<0||a<=ee)&&(ee-=(U=Math.floor(ee/a))*a,C+=U,U=1),$%e);return(C<-i||i<C||I)&&((P=l(C/o))&&($+=P*e,C-=P*o),(L=w(C)).setUTCFullYear(I+L.getUTCFullYear()),L=(C=+L)+(P=l(($-=I)/e))*o,P&&-i<=L&&L<=i&&($-=P*e,C=L),U=1),U&&(E.year=$,E.time=C,E.nano=ee),E}function w(E){var P=new Date(0);return P.setTime(E),P}function x($,L){$=+$||0;var U=l((L=(L|0)*s)/n)+l($/n),L=L%n+$%n,$=l(L/n);return $&&(U+=$,L-=$*n),new d(1e3*L,0,U*e)}function b(E,P,U,L,$,C){return function(I,T){var B=y(this);I=I||new Array(8),S(I,T|=0);var _=Math.floor(B.time/1e3),B=B.year*(t*r/e),z=l(B/s)+l(_/s),B=B%s+_%s,_=Math.floor(B/s);return _&&(z+=_,B-=_*s),ee(I,T+$,z),ee(I,T+C,B),I};function ee(I,T,z){I[T+E]=z>>24&255,I[T+P]=z>>16&255,I[T+U]=z>>8&255,I[T+L]=255&z}}function A(E,P,U,L,$,C){return function(I,T){S(I,T|=0);var z=ee(I,T+$);return x(ee(I,T+C),z)};function ee(I,T){return 16777216*I[T+E]+(I[T+P]<<16|I[T+U]<<8|I[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 R(E){return(9<E?"":"0")+(0|E)}function v(E,P){return(c+(0|E)).substr(-P)}}()});var C0=Ce((kD,N0)=>{N0.exports=Rf;var T0=128,I2=127,R2=~I2,B2=Math.pow(2,31);function Rf(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Rf.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=B2;)e[t++]=r&255|T0,r/=128;for(;r&R2;)e[t++]=r&255|T0,r>>>=7;return e[t]=r|0,Rf.bytes=t-n+1,e}});var P0=Ce((ID,D0)=>{D0.exports=Bf;var T2=128,L0=127;function Bf(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw Bf.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&L0)<<o:(s&L0)*Math.pow(2,o),o+=7}while(s>=T2);return Bf.bytes=i-n,t}});var U0=Ce((RD,O0)=>{var N2=Math.pow(2,7),C2=Math.pow(2,14),L2=Math.pow(2,21),D2=Math.pow(2,28),P2=Math.pow(2,35),O2=Math.pow(2,42),U2=Math.pow(2,49),F2=Math.pow(2,56),V2=Math.pow(2,63);O0.exports=function(r){return r<N2?1:r<C2?2:r<L2?3:r<D2?4:r<P2?5:r<O2?6:r<U2?7:r<F2?8:r<V2?9:10}});var yc=Ce((BD,F0)=>{F0.exports={encode:C0(),decode:P0(),encodingLength:U0()}});var yy=Ce((GO,gy)=>{"use strict";gy.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(dS,0),c=~(4294967295<<i+1),l=my(o&c);return a+l-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(pS),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),l=~(255<<c),f=i&l;o|=f<<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(mS)}};function dS(r,e){return r+my(e)}function my(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function pS(r,e){return r[0]-e[0]}function mS(r){return r[1]}});var Wy=Ce((MU,Gy)=>{"use strict";Gy.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 TA={};Se(TA,{createVerifiedFetch:()=>rh,verifiedFetch:()=>Vc});var Uo=Symbol.for("@libp2p/content-routing");var Hc=Symbol.for("@libp2p/peer-id");function hh(r){return r!=null&&!!r[Hc]}var Fo=Symbol.for("@libp2p/peer-routing");var Kt=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 me=(r,...e)=>{try{[...e]}catch{}};var On=class extends EventTarget{#e=new Map;constructor(){super(),me(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 Ew(e,t))}},$c=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Ew=globalThis.CustomEvent??$c;function dh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Pr(...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 Or(...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()}))}function We(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 fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ji=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}},Un=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ji(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 Ji(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 Kc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function qt(r={}){return vw(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 vw(r,e){e=e??{};let t=e.onEnd,n=new Un,o,i,s,a=fe(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,w)=>{i=x=>{i=null,n.push(x);try{y(r(n))}catch(b){w(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fe()})}},l=y=>i!=null?i(y):(n.push(y),o),f=y=>(n=new Un,i!=null?i({error:y}):(n.push({error:y}),o)),u=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 l({done:!1,value:y})},p=y=>s?o:(s=!0,y!=null?f(y):l({done:!0})),h=()=>(n=new Un,p(),{done:!0}),m=y=>(p(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:u,end:p,get readableLength(){return n.size},onEmpty:async y=>{let w=y?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,b;w!=null&&(x=new Promise((A,S)=>{b=()=>{S(new Kc)},w.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&w!=null&&w?.removeEventListener("abort",b)}}},t==null)return o;let d=o;return o={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(y){return d.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return d.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return d.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return d.readableLength},onEmpty:y=>d.onEmpty(y)},o}var qc=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 Qi(r,e,t,n){let o=new qc(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{let a=l=>{try{if(n?.filter?.(l)===!1)return}catch(f){r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(f);return}r.removeEventListener(e,a),t?.removeEventListener("abort",c),i(l)},c=()=>{r.removeEventListener(e,a),t?.removeEventListener("abort",c),s(o)};r.addEventListener(e,a),t?.addEventListener("abort",c)})}var es=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 ph(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new es(t?.errorMessage,t?.errorCode));let n,o=new es(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 ts=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=fe(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Kt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Sw(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var rs=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=Sw(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,me(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 Kt),this.cleanup())}async join(e={}){let t=new ts(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 ph(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Aw(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 ar=class extends On{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=Aw(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 rs(e,t,t?.priority),o=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:i}),this.safeDispatchEvent("failure",{detail:{job:n,error: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 Kt)}),this.clear()}async onEmpty(e){this.size!==0&&await Qi(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Qi(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Qi(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=qt({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 ns=class extends ar{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function Uw(r){return r[Symbol.asyncIterator]!=null}function Fw(r){if(Uw(r))return(async()=>{for await(let e of r);})();for(let e of r);}var cr=Fw;function tt(r=0){return new Uint8Array(r)}function rt(r=0){return new Uint8Array(r)}var Vw=Math.pow(2,7),Mw=Math.pow(2,14),Hw=Math.pow(2,21),zc=Math.pow(2,28),Gc=Math.pow(2,35),Wc=Math.pow(2,42),jc=Math.pow(2,49),ae=128,Me=127;function nt(r){if(r<Vw)return 1;if(r<Mw)return 2;if(r<Hw)return 3;if(r<zc)return 4;if(r<Gc)return 5;if(r<Wc)return 6;if(r<jc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Yc(r,e,t=0){switch(nt(r)){case 8:e[t++]=r&255|ae,r/=128;case 7:e[t++]=r&255|ae,r/=128;case 6:e[t++]=r&255|ae,r/=128;case 5:e[t++]=r&255|ae,r/=128;case 4:e[t++]=r&255|ae,r>>>=7;case 3:e[t++]=r&255|ae,r>>>=7;case 2:e[t++]=r&255|ae,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function $w(r,e,t=0){switch(nt(r)){case 8:e.set(t++,r&255|ae),r/=128;case 7:e.set(t++,r&255|ae),r/=128;case 6:e.set(t++,r&255|ae),r/=128;case 5:e.set(t++,r&255|ae),r/=128;case 4:e.set(t++,r&255|ae),r>>>=7;case 3:e.set(t++,r&255|ae),r>>>=7;case 2:e.set(t++,r&255|ae),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Xc(r,e){let t=r[e],n=0;if(n+=t&Me,t<ae||(t=r[e+1],n+=(t&Me)<<7,t<ae)||(t=r[e+2],n+=(t&Me)<<14,t<ae)||(t=r[e+3],n+=(t&Me)<<21,t<ae)||(t=r[e+4],n+=(t&Me)*zc,t<ae)||(t=r[e+5],n+=(t&Me)*Gc,t<ae)||(t=r[e+6],n+=(t&Me)*Wc,t<ae)||(t=r[e+7],n+=(t&Me)*jc,t<ae))return n;throw new RangeError("Could not decode varint")}function Kw(r,e){let t=r.get(e),n=0;if(n+=t&Me,t<ae||(t=r.get(e+1),n+=(t&Me)<<7,t<ae)||(t=r.get(e+2),n+=(t&Me)<<14,t<ae)||(t=r.get(e+3),n+=(t&Me)<<21,t<ae)||(t=r.get(e+4),n+=(t&Me)*zc,t<ae)||(t=r.get(e+5),n+=(t&Me)*Gc,t<ae)||(t=r.get(e+6),n+=(t&Me)*Wc,t<ae)||(t=r.get(e+7),n+=(t&Me)*jc,t<ae))return n;throw new RangeError("Could not decode varint")}function Hn(r,e,t=0){return e==null&&(e=rt(nt(r))),e instanceof Uint8Array?Yc(r,e,t):$w(r,e,t)}function pn(r,e=0){return r instanceof Uint8Array?Xc(r,e):Kw(r,e)}function ue(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=rt(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function ne(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}var vh=Symbol.for("@achingbrain/uint8arraylist");function Eh(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 zt(r){return!!r?.[vh]}var lr=class r{bufs;length;[vh]=!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(zt(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(zt(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=Eh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Eh(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(zt(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 l=e>=a&&e<c,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(s);break}let u=e-a;n.push(s.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(f){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(!zt(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 u=0;u<i;u++)s[u]=-1;for(let u=0;u<o;u++)s[n[u]]=u;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let u=t;u<=c;u+=f){f=0;for(let p=l;p>=0;p--){let h=this.get(u+p);if(n[p]!==h){f=Math.max(1,p-a[h]);break}}if(f===0)return u}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=rt(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=tt(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=tt(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=tt(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=rt(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=tt(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=tt(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=tt(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=tt(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=tt(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(!ne(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 zw(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 $n=zw;function Gw(r){return r[Symbol.asyncIterator]!=null}function Ww(r,e){if(Gw(r))return async function*(){for await(let a of r)yield e(a)}();let t=$n(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 He=Ww;function jw(r){return r[Symbol.asyncIterator]!=null}function Yw(...r){let e=[];for(let t of r)jw(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=qt({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 Ur=Yw;function Gt(r,...e){if(r==null)throw new Error("Empty pipeline");if(Zc(r)){let n=r;r=()=>n.source}else if(kh(r)||_h(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Zc(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++)Zc(t[n])&&(t[n]=Zw(t[n]));return Xw(...t)}var Xw=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},_h=r=>r?.[Symbol.asyncIterator]!=null,kh=r=>r?.[Symbol.iterator]!=null,Zc=r=>r==null?!1:r.sink!=null&&r.source!=null,Zw=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=qt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(_h(i))o=async function*(){yield*i,n.end()};else if(kh(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Ur(n,o())}return r.source};function Jw(r){return r[Symbol.asyncIterator]!=null}function Qw(r,e){return Jw(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 ss=Qw;var sl={};Se(sl,{base64:()=>Et,base64pad:()=>cb,base64url:()=>il,base64urlpad:()=>lb});var Kn={};Se(Kn,{coerce:()=>Wt,empty:()=>Ih,equals:()=>Jc,fromHex:()=>tb,fromString:()=>Qc,isBinary:()=>rb,toHex:()=>eb,toString:()=>el});var Ih=new Uint8Array(0);function eb(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function tb(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):Ih}function Jc(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 Wt(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 rb(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function Qc(r){return new TextEncoder().encode(r)}function el(r){return new TextDecoder().decode(r)}function nb(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function u(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var d=0,y=0,w=0,x=m.length;w!==x&&m[w]===0;)w++,d++;for(var b=(x-w)*f+1>>>0,A=new Uint8Array(b);w!==x;){for(var S=m[w],R=0,v=b-1;(S!==0||R<y)&&v!==-1;v--,R++)S+=256*A[v]>>>0,A[v]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=R,w++}for(var E=b-y;E!==b&&A[E]===0;)E++;for(var P=c.repeat(d);E<b;++E)P+=r.charAt(A[E]);return P}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var d=0;if(m[d]!==" "){for(var y=0,w=0;m[d]===c;)y++,d++;for(var x=(m.length-d)*l+1>>>0,b=new Uint8Array(x);m[d];){var A=t[m.charCodeAt(d)];if(A===255)return;for(var S=0,R=x-1;(A!==0||S<w)&&R!==-1;R--,S++)A+=a*b[R]>>>0,b[R]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=S,d++}if(m[d]!==" "){for(var v=x-w;v!==x&&b[v]===0;)v++;for(var E=new Uint8Array(y+(x-v)),P=y;v!==x;)E[P++]=b[v++];return E}}}function h(m){var d=p(m);if(d)return d;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:h}}var ob=nb,ib=ob,Rh=ib;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")}},rl=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 Bh(this,e)}},nl=class{decoders;constructor(e){this.decoders=e}or(e){return Bh(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 Bh(r,e){return new nl({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var ol=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 rl(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 ol(r,e,t,n)}function Fr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Rh(t,r);return qn({prefix:e,name:r,encode:n,decode:i=>Wt(o(i))})}function sb(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),a=0,c=0,l=0;for(let f=0;f<i;++f){let u=o[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function ab(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 we({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return qn({prefix:e,name:r,encode(o){return ab(o,n,t)},decode(o){return sb(o,n,t,r)}})}var Et=we({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cb=we({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),il=we({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lb=we({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var al={};Se(al,{base32:()=>De,base32hex:()=>hb,base32hexpad:()=>pb,base32hexpadupper:()=>mb,base32hexupper:()=>db,base32pad:()=>ub,base32padupper:()=>fb,base32upper:()=>Th,base32z:()=>gb});var De=we({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Th=we({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ub=we({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fb=we({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hb=we({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),db=we({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pb=we({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mb=we({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gb=we({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var cl={};Se(cl,{base58btc:()=>ge,base58flickr:()=>yb});var ge=Fr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),yb=Fr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var wb=Lh,Nh=128,bb=127,xb=~bb,Eb=Math.pow(2,31);function Lh(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Eb;)e[t++]=r&255|Nh,r/=128;for(;r&xb;)e[t++]=r&255|Nh,r>>>=7;return e[t]=r|0,Lh.bytes=t-n+1,e}var vb=ll,Sb=128,Ch=127;function ll(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw ll.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&Ch)<<o:(s&Ch)*Math.pow(2,o),o+=7}while(s>=Sb);return ll.bytes=i-n,t}var Ab=Math.pow(2,7),_b=Math.pow(2,14),kb=Math.pow(2,21),Ib=Math.pow(2,28),Rb=Math.pow(2,35),Bb=Math.pow(2,42),Tb=Math.pow(2,49),Nb=Math.pow(2,56),Cb=Math.pow(2,63),Lb=function(r){return r<Ab?1:r<_b?2:r<kb?3:r<Ib?4:r<Rb?5:r<Bb?6:r<Tb?7:r<Nb?8:r<Cb?9:10},Db={encode:wb,decode:vb,encodingLength:Lb},Pb=Db,Vo=Pb;function Mo(r,e=0){return[Vo.decode(r,e),Vo.decode.bytes]}function zn(r,e,t=0){return Vo.encode(r,e,t),e}function Gn(r){return Vo.encodingLength(r)}function jt(r,e){let t=e.byteLength,n=Gn(r),o=n+Gn(t),i=new Uint8Array(o+t);return zn(r,i,0),zn(t,i,n),i.set(e,o),new Wn(r,t,e,i)}function je(r){let e=Wt(r),[t,n]=Mo(e),[o,i]=Mo(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Wn(t,o,s,e)}function Dh(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Jc(r.bytes,t.bytes)}}var Wn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Ph(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Ub(t,ul(r),e??ge.encoder);default:return Fb(t,ul(r),e??De.encoder)}}var Oh=new WeakMap;function ul(r){let e=Oh.get(r);if(e==null){let t=new Map;return Oh.set(r,t),t}return e}var q=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!==Ho)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Vb)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&&Dh(e.multihash,n.multihash)}toString(e){return Ph(this,e)}toJSON(){return{"/":Ph(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[Mb]===!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!==Ho)throw new Error(`Version 0 CID must use dag-pb (code: ${Ho}) 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,Ho,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=Wt(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 Wn(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[u,p]=Mo(e.subarray(t));return t+=p,u},o=n(),i=Ho;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=Ob(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 Ob(r,e){switch(r[0]){case"Q":{let t=e??ge;return[ge.prefix,t.decode(`${ge.prefix}${r}`)]}case ge.prefix:{let t=e??ge;return[ge.prefix,t.decode(r)]}case De.prefix:{let t=e??De;return[De.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 Ub(r,e,t){let{prefix:n}=t;if(n!==ge.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 Fb(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 Ho=112,Vb=18;function Uh(r,e,t){let n=Gn(r),o=n+Gn(e),i=new Uint8Array(o+t.byteLength);return zn(r,i,0),zn(e,i,n),i.set(t,o),i}var Mb=Symbol.for("@ipld/js-cid/CID");var M=class extends Event{constructor(e,t){super(e),this.detail=t}};var fl={};Se(fl,{base10:()=>Hb});var Hb=Fr({prefix:"9",name:"base10",alphabet:"0123456789"});var hl={};Se(hl,{base16:()=>$b,base16upper:()=>Kb});var $b=we({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Kb=we({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var dl={};Se(dl,{base2:()=>qb});var qb=we({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var pl={};Se(pl,{base256emoji:()=>Yb});var Fh=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}"),zb=Fh.reduce((r,e,t)=>(r[t]=e,r),[]),Gb=Fh.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Wb(r){return r.reduce((e,t)=>(e+=zb[t],e),"")}function jb(r){let e=[];for(let t of r){let n=Gb[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Yb=qn({prefix:"\u{1F680}",name:"base256emoji",encode:Wb,decode:jb});var ml={};Se(ml,{base36:()=>Vr,base36upper:()=>Xb});var Vr=Fr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Xb=Fr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gl={};Se(gl,{base8:()=>Zb});var Zb=we({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var yl={};Se(yl,{identity:()=>Jb});var Jb=qn({prefix:"\0",name:"identity",encode:r=>el(r),decode:r=>Qc(r)});var nk=new TextEncoder,Qb=new TextDecoder;var Mr=512;function Vh(r){return JSON.parse(Qb.decode(r))}var ut=85;var wl={};Se(wl,{identity:()=>$e});var Mh=0,e1="identity",Hh=Wt;function t1(r){return jt(Mh,Hh(r))}var $e={code:Mh,name:e1,encode:Hh,digest:t1};var El={};Se(El,{sha256:()=>ke,sha512:()=>xl});function mn({name:r,code:e,encode:t}){return new bl(r,e,t)}var bl=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 Kh(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ke=mn({name:"sha2-256",code:18,encode:Kh("SHA-256")}),xl=mn({name:"sha2-512",code:19,encode:Kh("SHA-512")});var Hr={...yl,...dl,...gl,...fl,...hl,...al,...ml,...cl,...sl,...pl},gk={...El,...wl};function zh(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var qh=zh("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),vl=zh("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=rt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),r1={utf8:qh,"utf-8":qh,hex:Hr.base16,latin1:vl,ascii:vl,binary:vl,...Hr},ls=r1;function G(r,e="utf8"){let t=ls[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Sl=new Float32Array([-0]),$r=new Uint8Array(Sl.buffer);function Gh(r,e,t){Sl[0]=r,e[t]=$r[0],e[t+1]=$r[1],e[t+2]=$r[2],e[t+3]=$r[3]}function Wh(r,e){return $r[0]=r[e],$r[1]=r[e+1],$r[2]=r[e+2],$r[3]=r[e+3],Sl[0]}var Al=new Float64Array([-0]),Ke=new Uint8Array(Al.buffer);function jh(r,e,t){Al[0]=r,e[t]=Ke[0],e[t+1]=Ke[1],e[t+2]=Ke[2],e[t+3]=Ke[3],e[t+4]=Ke[4],e[t+5]=Ke[5],e[t+6]=Ke[6],e[t+7]=Ke[7]}function Yh(r,e){return Ke[0]=r[e],Ke[1]=r[e+1],Ke[2]=r[e+2],Ke[3]=r[e+3],Ke[4]=r[e+4],Ke[5]=r[e+5],Ke[6]=r[e+6],Ke[7]=r[e+7],Al[0]}var n1=BigInt(Number.MAX_SAFE_INTEGER),o1=BigInt(Number.MIN_SAFE_INTEGER),ft=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 gn;if(e<n1&&e>o1)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>Xh&&(o=0n,++n>Xh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gn;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):gn}},gn=new ft(0,0);gn.toBigInt=function(){return 0n};gn.zzEncode=gn.zzDecode=function(){return this};gn.length=function(){return 1};var Xh=4294967296n;function Zh(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 Jh(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 _l(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 Nt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function us(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var kl=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,Nt(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 Nt(this,4);return us(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Nt(this,4);return us(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Nt(this,4);let e=Wh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Nt(this,4);let e=Yh(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 Nt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Jh(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Nt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Nt(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 ft(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 Nt(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 Nt(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 Nt(this,8);let e=us(this.buf,this.pos+=4),t=us(this.buf,this.pos+=4);return new ft(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=Xc(this.buf,this.pos);return this.pos+=nt(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 Il(r){return new kl(r instanceof Uint8Array?r:r.subarray())}function St(r,e,t){let n=Il(r);return e.decode(n,void 0,t)}function O(r,e="utf8"){let t=ls[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Rl(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return rt(s);o+s>e&&(n=rt(e),o=0);let a=n.subarray(o,o+=s);return o&7&&(o=(o|7)+1),a}}var yn=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Bl(){}var Nl=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},i1=Rl();function s1(r){return globalThis.Buffer!=null?rt(r):i1(r)}var qo=class{len;head;tail;states;constructor(){this.len=0,this.head=new yn(Bl,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yn(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Cl((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(fs,10,ft.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ft.fromBigInt(e);return this._push(fs,t.length(),t)}uint64Number(e){return this._push(Yc,nt(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=ft.fromBigInt(e).zzEncode();return this._push(fs,t.length(),t)}sint64Number(e){let t=ft.fromNumber(e).zzEncode();return this._push(fs,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Tl,1,e?1:0)}fixed32(e){return this._push(Ko,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ft.fromBigInt(e);return this._push(Ko,4,t.lo)._push(Ko,4,t.hi)}fixed64Number(e){let t=ft.fromNumber(e);return this._push(Ko,4,t.lo)._push(Ko,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(Gh,4,e)}double(e){return this._push(jh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Tl,1,0):this.uint32(t)._push(c1,t,e)}string(e){let t=Zh(e);return t!==0?this.uint32(t)._push(_l,t,e):this._push(Tl,1,0)}fork(){return this.states=new Nl(this),this.head=this.tail=new yn(Bl,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 yn(Bl,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=s1(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Tl(r,e,t){e[t]=r&255}function a1(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Cl=class extends yn{next;constructor(e,t){super(a1,e,t),this.next=void 0}};function fs(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 Ko(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 c1(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(qo.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(l1,e,r),this},qo.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(u1,e,r),this});function l1(r,e,t){e.set(r,t)}function u1(r,e,t){r.length<40?_l(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(O(r),t)}function Ll(){return new qo}function At(r,e){let t=Ll();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var jn;(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"})(jn||(jn={}));function hs(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function wn(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 hs("enum",jn.VARINT,t,n)}function _t(r,e){return hs("message",jn.LENGTH_DELIMITED,r,e)}var f1=Symbol.for("nodejs.util.inspect.custom"),ed=Object.values(Hr).map(r=>r.decoder).reduce((r,e)=>r.or(e),Hr.identity.decoder),td=114,Dl=36,Pl=37,zo=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()})`}[Hc]=!0;toString(){return this.string==null&&(this.string=ge.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return q.createV1(td,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ne(this.multihash.bytes,e);if(typeof e=="string")return Ct(e).equals(this);if(e?.multihash?.bytes!=null)return ne(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[f1](){return`PeerId(${this.toString()})`}},Yn=class extends zo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Xn=class extends zo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Zn=class extends zo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function Ct(r,e){if(e=e??ed,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=je(ge.decode(`z${r}`));return r.startsWith("12D")?new Xn({multihash:t}):r.startsWith("16U")?new Zn({multihash:t}):new Yn({multihash:t})}return Go(ed.decode(r))}function Go(r){try{let e=je(r);if(e.code===$e.code){if(e.digest.length===Dl)return new Xn({multihash:e});if(e.digest.length===Pl)return new Zn({multihash:e})}if(e.code===ke.code)return new Yn({multihash:e})}catch{return h1(q.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function h1(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==td)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===ke.code)return new Yn({multihash:r.multihash});if(e.code===$e.code){if(e.digest.length===Dl)return new Xn({multihash:r.multihash});if(e.digest.length===Pl)return new Zn({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function rd(r,e){return r.length===Dl?new Xn({multihash:jt($e.code,r),privateKey:e}):r.length===Pl?new Zn({multihash:jt($e.code,r),privateKey:e}):new Yn({multihash:await ke.digest(r),publicKey:r,privateKey:e})}var ht=re(bh(),1);ht.default.formatters.b=r=>r==null?"undefined":ge.baseEncode(r);ht.default.formatters.t=r=>r==null?"undefined":De.baseEncode(r);ht.default.formatters.m=r=>r==null?"undefined":Et.baseEncode(r);ht.default.formatters.p=r=>r==null?"undefined":r.toString();ht.default.formatters.c=r=>r==null?"undefined":r.toString();ht.default.formatters.k=r=>r==null?"undefined":r.toString();ht.default.formatters.a=r=>r==null?"undefined":r.toString();function d1(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 nd(){return{forComponent(r){return Ye(r)}}}function Ye(r){let e=d1(`${r}:trace`);return ht.default.enabled(`${r}:trace`)&&ht.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,ht.default)(`${r}:trace`)),Object.assign((0,ht.default)(r),{error:(0,ht.default)(`${r}:error`),trace:e})}var Ul=re(id(),1);var jo=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Fl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},sd=r=>globalThis.DOMException===void 0?new Fl(r):new DOMException(r),ad=r=>{let e=r.reason===void 0?sd("This operation was aborted."):r.reason;return e instanceof Error?e:sd(e)};function Yo(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,c=new Promise((l,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&f(ad(p)),p.addEventListener("abort",()=>{f(ad(p))})}if(t===Number.POSITIVE_INFINITY){r.then(l,f);return}let u=new jo;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?f(o):(u.message=o??`Promise timed out after ${t} milliseconds`,f(u))},t),(async()=>{try{l(await r)}catch(p){f(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function Vl(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 Xo=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=Vl(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 ot=class extends Ul.default{#e;#t;#r=0;#s;#c;#p=0;#o;#l;#n;#m;#i=0;#u;#a;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Xo,...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.#g=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.#y(),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.#y(),!0):!1}}return!1}#y(){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.#h()}#h(){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.#h()}async#A(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.#g,...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=Yo(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#A(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof jo&&!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.#h(),this):this}pause(){this.#a=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#d("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#d("next",()=>this.#n.size<e)}async onIdle(){this.#i===0&&this.#n.size===0||await this.#d("idle")}async#d(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 ps(r){let e=[it.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Ml=60;function ms(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:it[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:it[e.type],TTL:e.TTL??e.ttl??Ml,data:e.data instanceof Uint8Array?G(e.data):e.data}))}}var g1=4;function Hl(r,e={}){let t=new ot({concurrency:e.queryConcurrency??g1});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),ps(o.types).forEach(a=>{i.append("type",it[a])}),o.onProgress?.(new M("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=ms(await a.json());return o.onProgress?.(new M("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function cd(){return[Hl("https://cloudflare-dns.com/dns-query"),Hl("https://dns.google/resolve")]}var ud=re($l(),1);var Kl=class{lru;constructor(e){this.lru=(0,ud.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 ms({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:it[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??Ml)*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 fd(r){return new Kl(r)}var y1=1e3,gs=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=fd(e.cacheSize??y1),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["."]=cd())}async query(e,t={}){let n=ps(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new M("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 l=await c(e,{...t,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new M("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var it;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(it||(it={}));function Zo(r={}){return new gs(r)}var w1=["string","number","bigint","symbol"],b1=["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 hd(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(w1.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(x1(r))return"Buffer";let t=E1(r);return t||"Object"}function x1(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function E1(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(b1.includes(e))return e}var g=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}};g.uint=new g(0,"uint",!0);g.negint=new g(1,"negint",!0);g.bytes=new g(2,"bytes",!0);g.string=new g(3,"string",!0);g.array=new g(4,"array",!1);g.map=new g(5,"map",!1);g.tag=new g(6,"tag",!1);g.float=new g(7,"float",!0);g.false=new g(7,"false",!0);g.true=new g(7,"true",!0);g.null=new g(7,"null",!0);g.undefined=new g(7,"undefined",!0);g.break=new g(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 Jn=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",v1=new TextDecoder,S1=new TextEncoder;function ys(r){return Jn&&globalThis.Buffer.isBuffer(r)}function Jo(r){return r instanceof Uint8Array?ys(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var gd=Jn?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):pd(r,e,t):(r,e,t)=>t-e>64?v1.decode(r.subarray(e,t)):pd(r,e,t),ws=Jn?r=>r.length>64?globalThis.Buffer.from(r):dd(r):r=>r.length>64?S1.encode(r):dd(r),Yt=r=>Uint8Array.from(r),Qn=Jn?(r,e,t)=>ys(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),yd=Jn?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Jo(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},wd=Jn?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function bd(r,e){if(ys(r)&&ys(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 dd(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 pd(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,l,f;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(f=(o&31)<<6|a&63,f>127&&(i=f));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(f=(o&15)<<12|(a&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(f=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,f>65535&&f<1114112&&(i=f))}}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 ql(n)}var md=4096;function ql(r){let e=r.length;if(e<=md)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=md));return t}var A1=256,Qo=class{constructor(e=A1){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=wd(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=Qn(n,0,this.cursor)}else t=yd(this.chunks,this.cursor);return e&&this.reset(),t}};var H="CBOR decode error:",ur="CBOR encode error:",ei=[];ei[23]=1;ei[24]=2;ei[25]=3;ei[26]=5;ei[27]=9;function fr(r,e,t){if(r.length-e<t)throw new Error(`${H} not enough data for type`)}var Re=[24,256,65536,4294967296,BigInt("18446744073709551616")];function dt(r,e,t){fr(r,e,1);let n=r[e];if(t.strict===!0&&n<Re[0])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function pt(r,e,t){fr(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Re[1])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function mt(r,e,t){fr(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Re[2])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function gt(r,e,t){fr(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<Re[3])throw new Error(`${H} 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(`${H} integers outside of the safe integer range are not supported`)}function xd(r,e,t,n){return new k(g.uint,dt(r,e+1,n),2)}function Ed(r,e,t,n){return new k(g.uint,pt(r,e+1,n),3)}function vd(r,e,t,n){return new k(g.uint,mt(r,e+1,n),5)}function Sd(r,e,t,n){return new k(g.uint,gt(r,e+1,n),9)}function kt(r,e){return Pe(r,0,e.value)}function Pe(r,e,t){if(t<Re[0]){let n=Number(t);r.push([e|n])}else if(t<Re[1]){let n=Number(t);r.push([e|24,n])}else if(t<Re[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Re[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<Re[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(`${H} encountered BigInt larger than allowable range`)}}kt.encodedSize=function(e){return Pe.encodedSize(e.value)};Pe.encodedSize=function(e){return e<Re[0]?1:e<Re[1]?2:e<Re[2]?3:e<Re[3]?5:9};kt.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Ad(r,e,t,n){return new k(g.negint,-1-dt(r,e+1,n),2)}function _d(r,e,t,n){return new k(g.negint,-1-pt(r,e+1,n),3)}function kd(r,e,t,n){return new k(g.negint,-1-mt(r,e+1,n),5)}var zl=BigInt(-1),Id=BigInt(1);function Rd(r,e,t,n){let o=gt(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new k(g.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${H} integers outside of the safe integer range are not supported`);return new k(g.negint,zl-BigInt(o),9)}function bs(r,e){let t=e.value,n=typeof t=="bigint"?t*zl-Id:t*-1-1;Pe(r,e.type.majorEncoded,n)}bs.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*zl-Id:t*-1-1;return n<Re[0]?1:n<Re[1]?2:n<Re[2]?3:n<Re[3]?5:9};bs.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function ti(r,e,t,n){fr(r,e,t+n);let o=Qn(r,e+t,e+t+n);return new k(g.bytes,o,t+n)}function Bd(r,e,t,n){return ti(r,e,1,t)}function Td(r,e,t,n){return ti(r,e,2,dt(r,e+1,n))}function Nd(r,e,t,n){return ti(r,e,3,pt(r,e+1,n))}function Cd(r,e,t,n){return ti(r,e,5,mt(r,e+1,n))}function Ld(r,e,t,n){let o=gt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer bytes lengths not supported`);return ti(r,e,9,o)}function xs(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===g.string?ws(r.value):r.value),r.encodedBytes}function eo(r,e){let t=xs(e);Pe(r,e.type.majorEncoded,t.length),r.push(t)}eo.encodedSize=function(e){let t=xs(e);return Pe.encodedSize(t.length)+t.length};eo.compareTokens=function(e,t){return k1(xs(e),xs(t))};function k1(r,e){return r.length<e.length?-1:r.length>e.length?1:bd(r,e)}function ri(r,e,t,n,o){let i=t+n;fr(r,e,i);let s=new k(g.string,gd(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Qn(r,e+t,e+i)),s}function Dd(r,e,t,n){return ri(r,e,1,t,n)}function Pd(r,e,t,n){return ri(r,e,2,dt(r,e+1,n),n)}function Od(r,e,t,n){return ri(r,e,3,pt(r,e+1,n),n)}function Ud(r,e,t,n){return ri(r,e,5,mt(r,e+1,n),n)}function Fd(r,e,t,n){let o=gt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer string lengths not supported`);return ri(r,e,9,o,n)}var Vd=eo;function to(r,e,t,n){return new k(g.array,n,t)}function Md(r,e,t,n){return to(r,e,1,t)}function Hd(r,e,t,n){return to(r,e,2,dt(r,e+1,n))}function $d(r,e,t,n){return to(r,e,3,pt(r,e+1,n))}function Kd(r,e,t,n){return to(r,e,5,mt(r,e+1,n))}function qd(r,e,t,n){let o=gt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer array lengths not supported`);return to(r,e,9,o)}function zd(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return to(r,e,1,1/0)}function Es(r,e){Pe(r,g.array.majorEncoded,e.value)}Es.compareTokens=kt.compareTokens;Es.encodedSize=function(e){return Pe.encodedSize(e.value)};function ro(r,e,t,n){return new k(g.map,n,t)}function Gd(r,e,t,n){return ro(r,e,1,t)}function Wd(r,e,t,n){return ro(r,e,2,dt(r,e+1,n))}function jd(r,e,t,n){return ro(r,e,3,pt(r,e+1,n))}function Yd(r,e,t,n){return ro(r,e,5,mt(r,e+1,n))}function Xd(r,e,t,n){let o=gt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer map lengths not supported`);return ro(r,e,9,o)}function Zd(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return ro(r,e,1,1/0)}function vs(r,e){Pe(r,g.map.majorEncoded,e.value)}vs.compareTokens=kt.compareTokens;vs.encodedSize=function(e){return Pe.encodedSize(e.value)};function Jd(r,e,t,n){return new k(g.tag,t,1)}function Qd(r,e,t,n){return new k(g.tag,dt(r,e+1,n),2)}function ep(r,e,t,n){return new k(g.tag,pt(r,e+1,n),3)}function tp(r,e,t,n){return new k(g.tag,mt(r,e+1,n),5)}function rp(r,e,t,n){return new k(g.tag,gt(r,e+1,n),9)}function Ss(r,e){Pe(r,g.tag.majorEncoded,e.value)}Ss.compareTokens=kt.compareTokens;Ss.encodedSize=function(e){return Pe.encodedSize(e.value)};var C1=20,L1=21,D1=22,P1=23;function np(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${H} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new k(g.null,null,1):new k(g.undefined,void 0,1)}function op(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return new k(g.break,void 0,1)}function Gl(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${H} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${H} Infinity values are not supported`)}return new k(g.float,r,e)}function ip(r,e,t,n){return Gl(Wl(r,e+1),3,n)}function sp(r,e,t,n){return Gl(jl(r,e+1),5,n)}function ap(r,e,t,n){return Gl(fp(r,e+1),9,n)}function As(r,e,t){let n=e.value;if(n===!1)r.push([g.float.majorEncoded|C1]);else if(n===!0)r.push([g.float.majorEncoded|L1]);else if(n===null)r.push([g.float.majorEncoded|D1]);else if(n===void 0)r.push([g.float.majorEncoded|P1]);else{let o,i=!1;(!t||t.float64!==!0)&&(lp(n),o=Wl(Lt,1),n===o||Number.isNaN(n)?(Lt[0]=249,r.push(Lt.slice(0,3)),i=!0):(up(n),o=jl(Lt,1),n===o&&(Lt[0]=250,r.push(Lt.slice(0,5)),i=!0))),i||(O1(n),o=fp(Lt,1),Lt[0]=251,r.push(Lt.slice(0,9)))}}As.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){lp(n);let o=Wl(Lt,1);if(n===o||Number.isNaN(n))return 3;if(up(n),o=jl(Lt,1),n===o)return 5}return 9};var cp=new ArrayBuffer(9),It=new DataView(cp,1),Lt=new Uint8Array(cp,0);function lp(r){if(r===1/0)It.setUint16(0,31744,!1);else if(r===-1/0)It.setUint16(0,64512,!1);else if(Number.isNaN(r))It.setUint16(0,32256,!1);else{It.setFloat32(0,r);let e=It.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)It.setUint16(0,31744,!1);else if(t===0)It.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?It.setUint16(0,0):o<-14?It.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):It.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Wl(r,e){if(r.length-e<2)throw new Error(`${H} 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 up(r){It.setFloat32(0,r,!1)}function jl(r,e){if(r.length-e<4)throw new Error(`${H} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function O1(r){It.setFloat64(0,r,!1)}function fp(r,e){if(r.length-e<8)throw new Error(`${H} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}As.compareTokens=kt.compareTokens;function oe(r,e,t){throw new Error(`${H} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function _s(r){return()=>{throw new Error(`${H} ${r}`)}}var D=[];for(let r=0;r<=23;r++)D[r]=oe;D[24]=xd;D[25]=Ed;D[26]=vd;D[27]=Sd;D[28]=oe;D[29]=oe;D[30]=oe;D[31]=oe;for(let r=32;r<=55;r++)D[r]=oe;D[56]=Ad;D[57]=_d;D[58]=kd;D[59]=Rd;D[60]=oe;D[61]=oe;D[62]=oe;D[63]=oe;for(let r=64;r<=87;r++)D[r]=Bd;D[88]=Td;D[89]=Nd;D[90]=Cd;D[91]=Ld;D[92]=oe;D[93]=oe;D[94]=oe;D[95]=_s("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)D[r]=Dd;D[120]=Pd;D[121]=Od;D[122]=Ud;D[123]=Fd;D[124]=oe;D[125]=oe;D[126]=oe;D[127]=_s("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)D[r]=Md;D[152]=Hd;D[153]=$d;D[154]=Kd;D[155]=qd;D[156]=oe;D[157]=oe;D[158]=oe;D[159]=zd;for(let r=160;r<=183;r++)D[r]=Gd;D[184]=Wd;D[185]=jd;D[186]=Yd;D[187]=Xd;D[188]=oe;D[189]=oe;D[190]=oe;D[191]=Zd;for(let r=192;r<=215;r++)D[r]=Jd;D[216]=Qd;D[217]=ep;D[218]=tp;D[219]=rp;D[220]=oe;D[221]=oe;D[222]=oe;D[223]=oe;for(let r=224;r<=243;r++)D[r]=_s("simple values are not supported");D[244]=oe;D[245]=oe;D[246]=oe;D[247]=np;D[248]=_s("simple values are not supported");D[249]=ip;D[250]=sp;D[251]=ap;D[252]=oe;D[253]=oe;D[254]=oe;D[255]=op;var Dt=[];for(let r=0;r<24;r++)Dt[r]=new k(g.uint,r,1);for(let r=-1;r>=-24;r--)Dt[31-r]=new k(g.negint,r,1);Dt[64]=new k(g.bytes,new Uint8Array(0),1);Dt[96]=new k(g.string,"",1);Dt[128]=new k(g.array,0,1);Dt[160]=new k(g.map,0,1);Dt[244]=new k(g.false,!1,1);Dt[245]=new k(g.true,!0,1);Dt[246]=new k(g.null,null,1);function Yl(r){switch(r.type){case g.false:return Yt([244]);case g.true:return Yt([245]);case g.null:return Yt([246]);case g.bytes:return r.value.length?void 0:Yt([64]);case g.string:return r.value===""?Yt([96]):void 0;case g.array:return r.value===0?Yt([128]):void 0;case g.map:return r.value===0?Yt([160]):void 0;case g.uint:return r.value<24?Yt([Number(r.value)]):void 0;case g.negint:if(r.value>=-24)return Yt([31-Number(r.value)])}}var F1={float64:!1,mapSorter:M1,quickEncodeToken:Yl};function Zl(){let r=[];return r[g.uint.major]=kt,r[g.negint.major]=bs,r[g.bytes.major]=eo,r[g.string.major]=Vd,r[g.array.major]=Es,r[g.map.major]=vs,r[g.tag.major]=Ss,r[g.float.major]=As,r}var hp=Zl(),Xl=new Qo,ks=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(`${ur} object contains circular references`);return new r(t,e)}},Kr={null:new k(g.null,null),undefined:new k(g.undefined,void 0),true:new k(g.true,!0),false:new k(g.false,!1),emptyArray:new k(g.array,0),emptyMap:new k(g.map,0)},qr={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new k(g.float,r):r>=0?new k(g.uint,r):new k(g.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new k(g.uint,r):new k(g.negint,r)},Uint8Array(r,e,t,n){return new k(g.bytes,r)},string(r,e,t,n){return new k(g.string,r)},boolean(r,e,t,n){return r?Kr.true:Kr.false},null(r,e,t,n){return Kr.null},undefined(r,e,t,n){return Kr.undefined},ArrayBuffer(r,e,t,n){return new k(g.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new k(g.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Kr.emptyArray,new k(g.break)]:Kr.emptyArray;n=ks.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=ni(s,t,n);return t.addBreakTokens?[new k(g.array,r.length),o,new k(g.break)]:[new k(g.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?[Kr.emptyMap,new k(g.break)]:Kr.emptyMap;n=ks.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[ni(l,t,n),ni(o?r.get(l):r[l],t,n)];return V1(a,t),t.addBreakTokens?[new k(g.map,s),a,new k(g.break)]:[new k(g.map,s),a]}};qr.Map=qr.Object;qr.Buffer=qr.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))qr[`${r}Array`]=qr.DataView;function ni(r,e={},t){let n=hd(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||qr[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=qr[n];if(!i)throw new Error(`${ur} unsupported type: ${n}`);return i(r,n,e,t)}function V1(r,e){e.mapSorter&&r.sort(e.mapSorter)}function M1(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=hp[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function dp(r,e,t,n){if(Array.isArray(e))for(let o of e)dp(r,o,t,n);else t[e.type.major](r,e,n)}function Jl(r,e,t){let n=ni(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 Qo(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Jo(a.chunks[0])}}return Xl.reset(),dp(Xl,n,e,t),Xl.toBytes(!0)}function zr(r,e){return e=Object.assign({},F1,e),Jl(r,hp,e)}var H1={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Is=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=Dt[e];if(t===void 0){let n=D[e];if(!n)throw new Error(`${H} 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}},oi=Symbol.for("DONE"),Rs=Symbol.for("BREAK");function $1(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=no(e,t);if(i===Rs){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed array`)}if(i===oi)throw new Error(`${H} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function K1(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=no(e,t);if(a===Rs){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed map`)}if(a===oi)throw new Error(`${H} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${H} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${H} found repeat map key "${a}"`);let c=no(e,t);if(c===oi)throw new Error(`${H} 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 no(r,e){if(r.done())return oi;let t=r.next();if(t.type===g.break)return Rs;if(t.type.terminal)return t.value;if(t.type===g.array)return $1(t,r,e);if(t.type===g.map)return K1(t,r,e);if(t.type===g.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=no(r,e);return e.tags[t.value](n)}throw new Error(`${H} tag not supported (${t.value})`)}throw new Error("unsupported")}function Ql(r,e){if(!(r instanceof Uint8Array))throw new Error(`${H} data to decode must be a Uint8Array`);e=Object.assign({},H1,e);let t=e.tokenizer||new Is(r,e),n=no(t,e);if(n===oi)throw new Error(`${H} did not find any content to decode`);if(n===Rs)throw new Error(`${H} got unexpected break`);return[n,r.subarray(t.pos())]}function Ze(r,e){let[t,n]=Ql(r,e);if(n.length>0)throw new Error(`${H} too many terminals, data makes no sense`);return t}var hr="/",pp=new TextEncoder().encode(hr),Ts=pp[0],xe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=O(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]!==Ts)throw new Error("Invalid key")}toString(e="utf8"){return G(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(hr))}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=pp),this._buf[0]!==Ts){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ts,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ts;)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(hr).slice(1)}type(){return q1(this.baseNamespace())}name(){return z1(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(hr)||(e+=hr),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(hr):new r(e.slice(0,-1).join(hr))}child(e){return this.toString()===hr?e:e.toString()===hr?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(),...G1(e.map(t=>t.namespaces()))])}};function q1(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function z1(r){let e=r.split(":");return e[e.length-1]}function G1(r){return[].concat(...r)}var wp="/pin/",mp="/pinned-block/",eu=Vr,gp=1;function yp(r){return r.version===0&&(r=r.toV1()),new xe(`${wp}${r.toString(eu)}`)}var Ns=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers=n}async*add(e,t={}){let n=yp(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 ar({concurrency:gp});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>ne(l,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,zr(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 xe(`${mp}${eu.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=Ze(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,zr(i),n),n.onProgress?.(new M("helia:pin:add",e))}}async*rm(e,t={}){let n=yp(e),o=await this.datastore.get(n,t),i=Ze(o);await this.datastore.delete(n,t);let s=new ar({concurrency:gp});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(l=>ne(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:wp+(e.cid!=null?`${e.cid.toString(Vr)}`:"")},e)){let o=q.parse(t.toString().substring(5),Vr),i=Ze(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new xe(`${mp}${eu.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var W1=5,Cs=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??W1}async start(){await Pr(...this.routers)}async stop(){await Or(...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 ns({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Ur(n.toGenerator(),...oo(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs=o.multiaddrs.map(i=>i.getPeerId()!=null?i:i.encapsulate(`/p2p/${o.id}`)),o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer",o.id,i)})}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(oo(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(oo(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(oo(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=Ur(...oo(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");for await(let n of Ur(...oo(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function oo(r,e){return r.filter(t=>t[e]!=null)}var Gr={},io=r=>{r.addEventListener("message",e=>{io.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{io.dispatchEvent("message",r,e)})};io.addEventListener=(r,e)=>{Gr[r]==null&&(Gr[r]=[]),Gr[r].push(e)};io.removeEventListener=(r,e)=>{Gr[r]!=null&&(Gr[r]=Gr[r].filter(t=>t===e))};io.dispatchEvent=function(r,e,t){Gr[r]!=null&&Gr[r].forEach(n=>n(e,t))};var tu=io;var ru="lock:worker:request-read",nu="lock:worker:release-read",ou="lock:master:grant-read",iu="lock:worker:request-write",su="lock:worker:release-write",au="lock:master:grant-write";var bp=(r=21)=>Math.random().toString().substring(2);var xp=(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 l=f=>{if(f==null||f.data==null)return;let u={type:f.data.type,name:f.data.name,identifier:f.data.identifier};u.type===n&&u.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},Ep=(r,e,t,n)=>async()=>{let o=bp();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)})},j1={singleProcess:!1},vp=r=>{if(r=Object.assign({},j1,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return tu.addEventListener("message",xp(t,"requestReadLock",ru,nu,ou)),tu.addEventListener("message",xp(t,"requestWriteLock",iu,su,au)),t}return{isWorker:!0,readLock:t=>Ep(t,ru,ou,nu),writeLock:t=>Ep(t,iu,au,su)}};var xn={},Wr;async function cu(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Yo((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Y1=(r,e)=>{if(Wr.isWorker===!0)return{readLock:Wr.readLock(r,e),writeLock:Wr.writeLock(r,e)};let t=new ot({concurrency:1}),n;return{async readLock(){if(n!=null)return cu(n,e);n=new ot({concurrency:e.concurrency,autoStart:!1});let o=n,i=cu(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,cu(t,e)}}},X1={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function lu(r){let e=Object.assign({},X1,r);return Wr==null&&(Wr=vp(e),Wr.isWorker!==!0&&(Wr.addEventListener("requestReadLock",t=>{xn[t.data.name]!=null&&xn[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),Wr.addEventListener("requestWriteLock",async t=>{xn[t.data.name]!=null&&xn[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),xn[e.name]==null&&(xn[e.name]=Y1(e.name,e)),xn[e.name]}var Ls=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=lu({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Pr(this.child),this.started=!0}async stop(){await Or(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();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={}){t?.signal?.throwIfAborted();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={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Sp=42;function Z1(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function J1(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=q.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new k(g.tag,Sp),new k(g.bytes,t)]}function Q1(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function ex(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 uu={float64:!0,typeEncoders:{Object:J1,undefined:Q1,number:ex}},vB={...uu,typeEncoders:{...uu.typeEncoders}};function tx(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return q.decode(r.subarray(1))}var Ds={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Ds.tags[Sp]=tx;var SB={...Ds,tags:Ds.tags.slice()};var jr=113,ii=r=>zr(r,uu),En=r=>Ze(Z1(r),Ds);var fu=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===g.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===g.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[g.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)}[g.negint.major](e,t){this[g.uint.major](e,t)}[g.bytes.major](e,t){throw new Error(`${ur} unsupported type: Uint8Array`)}[g.string.major](e,t){this.prefix(e);let n=ws(JSON.stringify(t.value));e.push(n.length>32?Jo(n):n)}[g.array.major](e,t){this.prefix(e),this.inRecursive.push({type:g.array,elements:0}),e.push([91])}[g.map.major](e,t){this.prefix(e),this.inRecursive.push({type:g.map,elements:0}),e.push([123])}[g.tag.major](e,t){}[g.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===g.array)e.push([93]);else if(s.type===g.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(`${ur} 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 rx(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${ur} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==g.string||n.type!==g.string)throw new Error(`${ur} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${ur} unexpected duplicate map keys, this is not supported`)}var nx={addBreakTokens:!0,mapSorter:rx};function ai(r,e){return e=Object.assign({},nx,e),Jl(r,new fu,e)}var Yr=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(`${H} 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(`${H} 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(g.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(`${H} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${H} 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(g.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new k(s>=0?g.uint:g.negint,s,this._pos-e):new k(s>=0?g.uint:g.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${H} 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(g.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${H} 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(`${H} 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(`${H} unexpected unicode sequence at position ${this._pos}`);let c,l,f,u;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(i&31)<<6|c&63,u>127&&(s=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(i&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],f=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(f&192)===128&&(u=(i&15)<<18|(c&63)<<12|(l&63)<<6|f&63,u>65535&&u<1114112&&(s=u))}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(`${H} 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(`${H} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new k(g.string,ql(t),this._pos-e);default:if(i<32)throw new Error(`${H} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${H} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new k(g.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new k(g.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new k(g.null,null,4);case 102:return this.expect([102,97,108,115,101]),new k(g.false,!1,5);case 116:return this.expect([116,114,117,101]),new k(g.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(`${H} 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(g.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} 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(g.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(g.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} 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(g.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${H} 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(`${H} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function ci(r,e){return e=Object.assign({tokenizer:new Yr(r,e)},e),Ze(r,e)}function ox(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function ix(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=q.asCID(r);if(!e)return null;let t=e.toString();return[new k(g.map,1/0,1),new k(g.string,"/",1),new k(g.string,t,t.length),new k(g.break,void 0,1)]}function Ps(r){let e=Et.encode(r).slice(1);return[new k(g.map,1/0,1),new k(g.string,"/",1),new k(g.map,1/0,1),new k(g.string,"bytes",5),new k(g.string,e,e.length),new k(g.break,void 0,1),new k(g.break,void 0,1)]}function Pt(r){return Ps(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function sx(r){return Ps(new Uint8Array(r))}function ax(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function cx(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 lx={typeEncoders:{Object:ix,Buffer:Ps,Uint8Array:Ps,Int8Array:Pt,Uint16Array:Pt,Int16Array:Pt,Uint32Array:Pt,Int32Array:Pt,Float32Array:Pt,Float64Array:Pt,Uint8ClampedArray:Pt,BigInt64Array:Pt,BigUint64Array:Pt,DataView:Pt,ArrayBuffer:sx,undefined:ax,number:cx}},hu=class extends Yr{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===g.map){let t=this._next();if(t.type===g.string&&t.value==="/"){let n=this._next();if(n.type===g.string){if(this._next().type!==g.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new k(g.tag,42,0)}if(n.type===g.map){let o=this._next();if(o.type===g.string&&o.value==="bytes"){let i=this._next();if(i.type===g.string){for(let a=0;a<2;a++)if(this._next().type!==g.break)throw new Error("Invalid encoded Bytes form");let s=Et.decode(`m${i.value}`);return new k(g.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},du={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};du.tags[42]=q.parse;var Xr=297,_p=r=>ai(r,lx),Os=r=>{let e=ox(r),t=Object.assign(du,{tokenizer:new hu(e,du)});return ci(e,t)};var MB=new TextDecoder;var HB=new TextEncoder;var ux=new TextDecoder;function pu(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 Fs(r,e){let t;[t,e]=pu(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 kp(r,e){let t;return[t,e]=pu(r,e),[t&7,t>>3,e]}function fx(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=kp(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]=Fs(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]=Fs(r,n),e.Name=ux.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]=pu(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 Ip(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=kp(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]=Fs(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Fs(r,t),n.push(fx(l))}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 KB=new TextEncoder,qB=2**32,zB=2**31;var jB=new TextEncoder;function Rp(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var Ot=112;function Xt(r){let e=Rp(r),t=Ip(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=q.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 hx={codec:Ot,*walk(r){yield*Xt(r).Links.map(t=>t.Hash)}},dx={codec:ut,*walk(){}},Bp=42,px={codec:jr,*walk(r){let e=[],t=[];t[Bp]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let o=q.decode(n.subarray(1));return e.push(o),o},Ze(r,{tags:t}),yield*e}},gu=class extends Yr{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===g.map){let t=this._next();if(t.type===g.string&&t.value==="/"){let n=this._next();if(n.type===g.string){if(this._next().type!==g.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new k(g.tag,42,0)}if(n.type===g.map){let o=this._next();if(o.type===g.string&&o.value==="bytes"){let i=this._next();if(i.type===g.string){for(let a=0;a<2;a++)if(this._next().type!==g.break)throw new Error("Invalid encoded Bytes form");let s=Et.decode(`m${i.value}`);return new k(g.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},mx={codec:Xr,*walk(r){let e=[],t=[];t[Bp]=n=>{let o=q.parse(n);return e.push(o),o},ci(r,{tags:t,tokenizer:new gu(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}},gx={codec:Mr,*walk(){}};function Tp(r=[]){let e={};return[hx,dx,px,mx,gx,...r].forEach(t=>{e[t.codec]=t}),e}var yu=new xe("/version"),Np=1;async function Cp(r){if(!await r.has(yu)){await r.put(yu,O(`${Np}`));return}let e=await r.get(yu),t=G(e);if(parseInt(t,10)!==Np)throw new Error("Unknown datastore version, a datastore migration may be required")}function Lp(r=[]){let e={};return[ke,xl,$e,...r].forEach(t=>{e[t.code]=t}),e}var dr=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 so={};Se(so,{abortedError:()=>Ex,closeFailedError:()=>wx,deleteFailedError:()=>Pp,getFailedError:()=>bx,hasFailedError:()=>xx,notFoundError:()=>li,openFailedError:()=>yx,putFailedError:()=>Dp});var pr=re(Le(),1);function yx(r){return r=r??new Error("Open failed"),(0,pr.default)(r,"ERR_OPEN_FAILED")}function wx(r){return r=r??new Error("Close failed"),(0,pr.default)(r,"ERR_CLOSE_FAILED")}function Dp(r){return r=r??new Error("Put failed"),(0,pr.default)(r,"ERR_PUT_FAILED")}function bx(r){return r=r??new Error("Get failed"),(0,pr.default)(r,"ERR_GET_FAILED")}function Pp(r){return r=r??new Error("Delete failed"),(0,pr.default)(r,"ERR_DELETE_FAILED")}function xx(r){return r=r??new Error("Has failed"),(0,pr.default)(r,"ERR_HAS_FAILED")}function li(r){return r=r??new Error("Not Found"),(0,pr.default)(r,"ERR_NOT_FOUND")}function Ex(r){return r=r??new Error("Aborted"),(0,pr.default)(r,"ERR_ABORTED")}var ui=class extends dr{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(De.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(De.encode(e.multihash.bytes));if(t==null)throw li();return t}has(e){return this.data.has(De.encode(e.multihash.bytes))}async delete(e){this.data.delete(De.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:q.createV1(ut,je(De.decode(e))),block:t}}};function vx(r){return r[Symbol.asyncIterator]!=null}function Sx(r,e){if(vx(r))return async function*(){for await(let a of r)await e(a)&&(yield a)}();let t=$n(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 yt=Sx;var N8=Ye("blockstore:core:tiered");var Op={...so};var Vs=0,Ms=class extends dr{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Vs||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Vs)return e.multihash.digest;if(this.child==null)throw Op.notFoundError();return this.child.get(e)}has(e){return e.multihash.code===Vs?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Vs&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function Ax(r){return r[Symbol.asyncIterator]!=null}function Up(r){return r?.then!=null}function _x(r,e){if(Ax(r))return async function*(){for await(let a of r){let c=e(a);Up(c)&&await c,yield a}}();let t=$n(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);Up(c)&&await c,yield a}}();let s=e;return function*(){yield n;for(let a of t)s(a),yield a}()}var wu=_x;var Hs=class{child;hashers;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Ms(e.blockstore),this.hashers=e.hashers??{}}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new M("blocks:put:duplicate",e)),e):(n.onProgress?.(new M("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new M("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=yt(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new M("blocks:put-many:duplicate",i)),!s}),o=wu(n,async({cid:i,block:s})=>{t.onProgress?.(new M("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,t)))});t.onProgress?.(new M("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)){t.onProgress?.(new M("blocks:get:providers:get",e));let n=await Fp(e,this.components.blockBrokers,this.hashers[e.multihash.code],{...t,log:this.log});return t.onProgress?.(new M("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),t.onProgress?.(new M("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n,t))),n}return t.onProgress?.(new M("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new M("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(wu(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){t.onProgress?.(new M("blocks:get-many:providers:get",n));let o=await Fp(n,this.components.blockBrokers,this.hashers[n.multihash.code],{...t,log:this.log});t.onProgress?.(new M("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new M("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(n,o,t)))}}))}async delete(e,t={}){t.onProgress?.(new M("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new M("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 M("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},$s=class extends Hs{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await Pr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Or(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new bu({blockstore:this.child,blockBrokers:n,hashers:this.hashers,logger:this.logger},{root:e})}},bu=class extends Hs{closeController;constructor(e,t){super(e),this.closeController=new AbortController,me(1/0,this.closeController.signal),this.log=e.logger.forComponent(`helia:session-storage${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=We([this.closeController.signal,n.signal]);me(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=We([this.closeController.signal,t.signal]);me(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=We([this.closeController.signal,t.signal]);me(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=We([this.closeController.signal,t.signal]);me(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=We([this.closeController.signal,t.signal]);me(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=We([this.closeController.signal,t.signal]);me(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=We([this.closeController.signal,t.signal]);me(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=We([this.closeController.signal,e.signal]);me(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function kx(r){return typeof r.retrieve=="function"}var Ix=(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(!ne(n.digest,r.multihash.digest))throw new N("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function Fp(r,e,t,n){let o=Ix(r,t),i=new AbortController,s=We([i.signal,n.signal]);me(1/0,i.signal,s);let a=[];for(let c of e)kx(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,f=await c.retrieve(r,{...n,signal:s,validateFn:async u=>{await o(u),l=!0}});return l||await o(f),f}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var Je={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 Ou={};Se(Ou,{Ed25519PrivateKey:()=>_n,Ed25519PublicKey:()=>di,generateKeyPair:()=>UE,generateKeyPairFromSeed:()=>fm,unmarshalEd25519PrivateKey:()=>PE,unmarshalEd25519PublicKey:()=>OE});function Rt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function ao(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Rx(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function co(r,...e){if(!Rx(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 Ks(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ao(r.outputLen),ao(r.blockLen)}function lo(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 Vp(r,e){co(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var qs=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var fo=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Ut=(r,e)=>r<<32-e|r>>>e;var aT=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Bx=async()=>{};async function Mp(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 Bx(),n+=i)}}function xu(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Zr(r){return typeof r=="string"&&(r=xu(r)),co(r),r}function zs(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];co(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 uo=class{clone(){return this._cloneInto()}},Tx={}.toString;function Hp(r,e){if(e!==void 0&&Tx.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Gs(r){let e=n=>r().update(Zr(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function ho(r=32){if(qs&&typeof qs.getRandomValues=="function")return qs.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Nx(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,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,a,n)}var $p=(r,e,t)=>r&e^~r&t,Kp=(r,e,t)=>r&e^r&t^e&t,po=class extends uo{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=fo(this.buffer)}update(e){lo(this);let{view:t,buffer:n,blockLen:o}=this;e=Zr(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=fo(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){lo(this),Vp(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 u=s;u<o;u++)t[u]=0;Nx(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=fo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],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 Ws=BigInt(4294967295),Eu=BigInt(32);function qp(r,e=!1){return e?{h:Number(r&Ws),l:Number(r>>Eu&Ws)}:{h:Number(r>>Eu&Ws)|0,l:Number(r&Ws)|0}}function Cx(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}=qp(r[o],e);[t[o],n[o]]=[i,s]}return[t,n]}var Lx=(r,e)=>BigInt(r>>>0)<<Eu|BigInt(e>>>0),Dx=(r,e,t)=>r>>>t,Px=(r,e,t)=>r<<32-t|e>>>t,Ox=(r,e,t)=>r>>>t|e<<32-t,Ux=(r,e,t)=>r<<32-t|e>>>t,Fx=(r,e,t)=>r<<64-t|e>>>t-32,Vx=(r,e,t)=>r>>>t-32|e<<64-t,Mx=(r,e)=>e,Hx=(r,e)=>r,$x=(r,e,t)=>r<<t|e>>>32-t,Kx=(r,e,t)=>e<<t|r>>>32-t,qx=(r,e,t)=>e<<t-32|r>>>64-t,zx=(r,e,t)=>r<<t-32|e>>>64-t;function Gx(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Wx=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),jx=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Yx=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Xx=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Zx=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Jx=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var Qx={fromBig:qp,split:Cx,toBig:Lx,shrSH:Dx,shrSL:Px,rotrSH:Ox,rotrSL:Ux,rotrBH:Fx,rotrBL:Vx,rotr32H:Mx,rotr32L:Hx,rotlSH:$x,rotlSL:Kx,rotlBH:qx,rotlBL:zx,add:Gx,add3L:Wx,add3H:jx,add4L:Yx,add4H:Xx,add5H:Jx,add5L:Zx},j=Qx;var[eE,tE]=j.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Jr=new Uint32Array(80),Qr=new Uint32Array(80),vu=class extends po{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:l,El:f,Fh:u,Fl:p,Gh:h,Gl:m,Hh:d,Hl:y}=this;return[e,t,n,o,i,s,a,c,l,f,u,p,h,m,d,y]}set(e,t,n,o,i,s,a,c,l,f,u,p,h,m,d,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=l|0,this.El=f|0,this.Fh=u|0,this.Fl=p|0,this.Gh=h|0,this.Gl=m|0,this.Hh=d|0,this.Hl=y|0}process(e,t){for(let b=0;b<16;b++,t+=4)Jr[b]=e.getUint32(t),Qr[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let A=Jr[b-15]|0,S=Qr[b-15]|0,R=j.rotrSH(A,S,1)^j.rotrSH(A,S,8)^j.shrSH(A,S,7),v=j.rotrSL(A,S,1)^j.rotrSL(A,S,8)^j.shrSL(A,S,7),E=Jr[b-2]|0,P=Qr[b-2]|0,U=j.rotrSH(E,P,19)^j.rotrBH(E,P,61)^j.shrSH(E,P,6),L=j.rotrSL(E,P,19)^j.rotrBL(E,P,61)^j.shrSL(E,P,6),$=j.add4L(v,L,Qr[b-7],Qr[b-16]),C=j.add4H($,R,U,Jr[b-7],Jr[b-16]);Jr[b]=C|0,Qr[b]=$|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:p,Fh:h,Fl:m,Gh:d,Gl:y,Hh:w,Hl:x}=this;for(let b=0;b<80;b++){let A=j.rotrSH(u,p,14)^j.rotrSH(u,p,18)^j.rotrBH(u,p,41),S=j.rotrSL(u,p,14)^j.rotrSL(u,p,18)^j.rotrBL(u,p,41),R=u&h^~u&d,v=p&m^~p&y,E=j.add5L(x,S,v,tE[b],Qr[b]),P=j.add5H(E,w,A,R,eE[b],Jr[b]),U=E|0,L=j.rotrSH(n,o,28)^j.rotrBH(n,o,34)^j.rotrBH(n,o,39),$=j.rotrSL(n,o,28)^j.rotrBL(n,o,34)^j.rotrBL(n,o,39),C=n&i^n&a^i&a,ee=o&s^o&c^s&c;w=d|0,x=y|0,d=h|0,y=m|0,h=u|0,m=p|0,{h:u,l:p}=j.add(l|0,f|0,P|0,U|0),l=a|0,f=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let I=j.add3L(U,$,ee);n=j.add3H(I,P,L,C),o=I|0}({h:n,l:o}=j.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=j.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=j.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=j.add(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:p}=j.add(this.Eh|0,this.El|0,u|0,p|0),{h,l:m}=j.add(this.Fh|0,this.Fl|0,h|0,m|0),{h:d,l:y}=j.add(this.Gh|0,this.Gl|0,d|0,y|0),{h:w,l:x}=j.add(this.Hh|0,this.Hl|0,w|0,x|0),this.set(n,o,i,s,a,c,l,f,u,p,h,m,d,y,w,x)}roundClean(){Jr.fill(0),Qr.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 mo=Gs(()=>new vu);var Ys={};Se(Ys,{abytes:()=>go,bitGet:()=>cE,bitLen:()=>aE,bitMask:()=>fi,bitSet:()=>lE,bytesToHex:()=>gr,bytesToNumberBE:()=>yr,bytesToNumberLE:()=>tn,concatBytes:()=>wr,createHmacDrbg:()=>_u,ensureBytes:()=>be,equalBytes:()=>iE,hexToBytes:()=>vn,hexToNumber:()=>Au,isBytes:()=>en,numberToBytesBE:()=>rn,numberToBytesLE:()=>Sn,numberToHexUnpadded:()=>jp,numberToVarBytesBE:()=>oE,utf8ToBytes:()=>sE,validateObject:()=>Zt});var Wp=BigInt(0),js=BigInt(1),rE=BigInt(2);function en(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function go(r){if(!en(r))throw new Error("Uint8Array expected")}var nE=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function gr(r){go(r);let e="";for(let t=0;t<r.length;t++)e+=nE[r[t]];return e}function jp(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Au(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var mr={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function zp(r){if(r>=mr._0&&r<=mr._9)return r-mr._0;if(r>=mr._A&&r<=mr._F)return r-(mr._A-10);if(r>=mr._a&&r<=mr._f)return r-(mr._a-10)}function vn(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=zp(r.charCodeAt(i)),a=zp(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 yr(r){return Au(gr(r))}function tn(r){return go(r),Au(gr(Uint8Array.from(r).reverse()))}function rn(r,e){return vn(r.toString(16).padStart(e*2,"0"))}function Sn(r,e){return rn(r,e).reverse()}function oE(r){return vn(jp(r))}function be(r,e,t){let n;if(typeof e=="string")try{n=vn(e)}catch(i){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${i}`)}else if(en(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 wr(...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}function iE(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 sE(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function aE(r){let e;for(e=0;r>Wp;r>>=js,e+=1);return e}function cE(r,e){return r>>BigInt(e)&js}function lE(r,e,t){return r|(t?js:Wp)<<BigInt(e)}var fi=r=>(rE<<BigInt(r-1))-js,Su=r=>new Uint8Array(r),Gp=r=>Uint8Array.from(r);function _u(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=Su(r),o=Su(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...u)=>t(o,n,...u),c=(u=Su())=>{o=a(Gp([0]),u),n=a(),u.length!==0&&(o=a(Gp([1]),u),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let u=0,p=[];for(;u<e;){n=a();let h=n.slice();p.push(h),u+=n.length}return wr(...p)};return(u,p)=>{s(),c(u);let h;for(;!(h=p(l()));)c();return s(),h}}var uE={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"||en(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 Zt(r,e,t={}){let n=(o,i,s)=>{let a=uE[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 Ie=BigInt(0),he=BigInt(1),An=BigInt(2),fE=BigInt(3),ku=BigInt(4),Yp=BigInt(5),Xp=BigInt(8),hE=BigInt(9),dE=BigInt(16);function ce(r,e){let t=r%e;return t>=Ie?t:e+t}function pE(r,e,t){if(t<=Ie||e<Ie)throw new Error("Expected power/modulo > 0");if(t===he)return Ie;let n=he;for(;e>Ie;)e&he&&(n=n*r%t),r=r*r%t,e>>=he;return n}function de(r,e,t){let n=r;for(;e-- >Ie;)n*=n,n%=t;return n}function Xs(r,e){if(r===Ie||e<=Ie)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=ce(r,e),n=e,o=Ie,i=he,s=he,a=Ie;for(;t!==Ie;){let l=n/t,f=n%t,u=o-s*l,p=i-a*l;n=t,t=f,o=s,i=a,s=u,a=p}if(n!==he)throw new Error("invert: does not exist");return ce(o,e)}function mE(r){let e=(r-he)/An,t,n,o;for(t=r-he,n=0;t%An===Ie;t/=An,n++);for(o=An;o<r&&pE(o,e,r)!==r-he;o++);if(n===1){let s=(r+he)/ku;return function(c,l){let f=c.pow(l,s);if(!c.eql(c.sqr(f),l))throw new Error("Cannot find square root");return f}}let i=(t+he)/An;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,f=a.pow(a.mul(a.ONE,o),t),u=a.pow(c,i),p=a.pow(c,t);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let h=1;for(let d=a.sqr(p);h<l&&!a.eql(d,a.ONE);h++)d=a.sqr(d);let m=a.pow(f,he<<BigInt(l-h-1));f=a.sqr(m),u=a.mul(u,m),p=a.mul(p,f),l=h}return u}}function gE(r){if(r%ku===fE){let e=(r+he)/ku;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%Xp===Yp){let e=(r-Yp)/Xp;return function(n,o){let i=n.mul(o,An),s=n.pow(i,e),a=n.mul(o,s),c=n.mul(n.mul(a,An),s),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%dE,mE(r)}var Zp=(r,e)=>(ce(r,e)&he)===he,yE=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Iu(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=yE.reduce((n,o)=>(n[o]="function",n),e);return Zt(r,t)}function wE(r,e,t){if(t<Ie)throw new Error("Expected power > 0");if(t===Ie)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>Ie;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function bE(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 Ru(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Zs(r,e,t=!1,n={}){if(r<=Ie)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:i}=Ru(r,e);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=gE(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:i,MASK:fi(o),ZERO:Ie,ONE:he,create:c=>ce(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Ie<=c&&c<r},is0:c=>c===Ie,isOdd:c=>(c&he)===he,neg:c=>ce(-c,r),eql:(c,l)=>c===l,sqr:c=>ce(c*c,r),add:(c,l)=>ce(c+l,r),sub:(c,l)=>ce(c-l,r),mul:(c,l)=>ce(c*l,r),pow:(c,l)=>wE(a,c,l),div:(c,l)=>ce(c*Xs(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Xs(c,r),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>bE(a,c),cmov:(c,l,f)=>f?l:c,toBytes:c=>t?Sn(c,i):rn(c,i),fromBytes:c=>{if(c.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);return t?tn(c):yr(c)}});return Object.freeze(a)}function Jp(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 Qp(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 Bu(r){let e=Qp(r);return e+Math.ceil(e/2)}function em(r,e,t=!1){let n=r.length,o=Qp(e),i=Bu(e);if(n<16||n<i||n>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);let s=t?yr(r):tn(r),a=ce(s,e-he)+he;return t?Sn(a,o):rn(a,o)}var EE=BigInt(0),Tu=BigInt(1);function Js(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>EE;)i&Tu&&(s=s.add(a)),a=a.double(),i>>=Tu;return s},precomputeWindow(o,i){let{windows:s,windowSize:a}=n(i),c=[],l=o,f=l;for(let u=0;u<s;u++){f=l,c.push(f);for(let p=1;p<a;p++)f=f.add(l),c.push(f);l=f.double()}return c},wNAF(o,i,s){let{windows:a,windowSize:c}=n(o),l=r.ZERO,f=r.BASE,u=BigInt(2**o-1),p=2**o,h=BigInt(o);for(let m=0;m<a;m++){let d=m*c,y=Number(s&u);s>>=h,y>c&&(y-=p,s+=Tu);let w=d,x=d+Math.abs(y)-1,b=m%2!==0,A=y<0;y===0?f=f.add(t(b,i[w])):l=l.add(t(A,i[x]))}return{p:l,f}},wNAFCached(o,i,s,a){let c=o._WINDOW_SIZE||1,l=i.get(o);return l||(l=this.precomputeWindow(o,c),c!==1&&i.set(o,a(l))),this.wNAF(c,l,s)}}}function hi(r){return Iu(r.Fp),Zt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ru(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Ft=BigInt(0),wt=BigInt(1),Qs=BigInt(2),vE=BigInt(8),SE={zip215:!0};function AE(r){let e=hi(r);return Zt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function ea(r){let e=AE(r),{Fp:t,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=e,l=Qs<<BigInt(a*8)-wt,f=t.create,u=e.uvRatio||((B,_)=>{try{return{isValid:!0,value:t.sqrt(B*t.inv(_))}}catch{return{isValid:!1,value:Ft}}}),p=e.adjustScalarBytes||(B=>B),h=e.domain||((B,_,V)=>{if(_.length||V)throw new Error("Contexts/pre-hash are not supported");return B}),m=B=>typeof B=="bigint"&&Ft<B,d=(B,_)=>m(B)&&m(_)&&B<_,y=B=>B===Ft||d(B,l);function w(B,_){if(d(B,_))return B;throw new Error(`Expected valid scalar < ${_}, got ${typeof B} ${B}`)}function x(B){return B===Ft?B:w(B,n)}let b=new Map;function A(B){if(!(B instanceof S))throw new Error("ExtendedPoint expected")}class S{constructor(_,V,K,W){if(this.ex=_,this.ey=V,this.ez=K,this.et=W,!y(_))throw new Error("x required");if(!y(V))throw new Error("y required");if(!y(K))throw new Error("z required");if(!y(W))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(_){if(_ instanceof S)throw new Error("extended point not allowed");let{x:V,y:K}=_||{};if(!y(V)||!y(K))throw new Error("invalid affine point");return new S(V,K,wt,f(V*K))}static normalizeZ(_){let V=t.invertBatch(_.map(K=>K.ez));return _.map((K,W)=>K.toAffine(V[W])).map(S.fromAffine)}_setWindowSize(_){this._WINDOW_SIZE=_,b.delete(this)}assertValidity(){let{a:_,d:V}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:K,ey:W,ez:X,et:Z}=this,ie=f(K*K),Q=f(W*W),te=f(X*X),ve=f(te*te),ye=f(ie*_),Te=f(te*f(ye+Q)),Ne=f(ve+f(V*f(ie*Q)));if(Te!==Ne)throw new Error("bad point: equation left != right (1)");let _e=f(K*W),Ve=f(X*Z);if(_e!==Ve)throw new Error("bad point: equation left != right (2)")}equals(_){A(_);let{ex:V,ey:K,ez:W}=this,{ex:X,ey:Z,ez:ie}=_,Q=f(V*ie),te=f(X*W),ve=f(K*ie),ye=f(Z*W);return Q===te&&ve===ye}is0(){return this.equals(S.ZERO)}negate(){return new S(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:_}=e,{ex:V,ey:K,ez:W}=this,X=f(V*V),Z=f(K*K),ie=f(Qs*f(W*W)),Q=f(_*X),te=V+K,ve=f(f(te*te)-X-Z),ye=Q+Z,Te=ye-ie,Ne=Q-Z,_e=f(ve*Te),Ve=f(ye*Ne),sr=f(ve*Ne),hn=f(Te*ye);return new S(_e,Ve,hn,sr)}add(_){A(_);let{a:V,d:K}=e,{ex:W,ey:X,ez:Z,et:ie}=this,{ex:Q,ey:te,ez:ve,et:ye}=_;if(V===BigInt(-1)){let oh=f((X-W)*(te+Q)),ih=f((X+W)*(te-Q)),Mc=f(ih-oh);if(Mc===Ft)return this.double();let sh=f(Z*Qs*ye),ah=f(ie*Qs*ve),ch=ah+sh,lh=ih+oh,uh=ah-sh,fw=f(ch*Mc),hw=f(lh*uh),dw=f(ch*uh),pw=f(Mc*lh);return new S(fw,hw,pw,dw)}let Te=f(W*Q),Ne=f(X*te),_e=f(ie*K*ye),Ve=f(Z*ve),sr=f((W+X)*(Q+te)-Te-Ne),hn=Ve-_e,Oo=Ve+_e,nh=f(Ne-V*Te),aw=f(sr*hn),cw=f(Oo*nh),lw=f(sr*nh),uw=f(hn*Oo);return new S(aw,cw,uw,lw)}subtract(_){return this.add(_.negate())}wNAF(_){return E.wNAFCached(this,b,_,S.normalizeZ)}multiply(_){let{p:V,f:K}=this.wNAF(w(_,n));return S.normalizeZ([V,K])[0]}multiplyUnsafe(_){let V=x(_);return V===Ft?v:this.equals(v)||V===wt?this:this.equals(R)?this.wNAF(V).p:E.unsafeLadder(this,V)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return E.unsafeLadder(this,n).is0()}toAffine(_){let{ex:V,ey:K,ez:W}=this,X=this.is0();_==null&&(_=X?vE:t.inv(W));let Z=f(V*_),ie=f(K*_),Q=f(W*_);if(X)return{x:Ft,y:wt};if(Q!==wt)throw new Error("invZ was invalid");return{x:Z,y:ie}}clearCofactor(){let{h:_}=e;return _===wt?this:this.multiplyUnsafe(_)}static fromHex(_,V=!1){let{d:K,a:W}=e,X=t.BYTES;_=be("pointHex",_,X);let Z=_.slice(),ie=_[X-1];Z[X-1]=ie&-129;let Q=tn(Z);Q===Ft||(V?w(Q,l):w(Q,t.ORDER));let te=f(Q*Q),ve=f(te-wt),ye=f(K*te-W),{isValid:Te,value:Ne}=u(ve,ye);if(!Te)throw new Error("Point.fromHex: invalid y coordinate");let _e=(Ne&wt)===wt,Ve=(ie&128)!==0;if(!V&&Ne===Ft&&Ve)throw new Error("Point.fromHex: x=0 and x_0=1");return Ve!==_e&&(Ne=f(-Ne)),S.fromAffine({x:Ne,y:Q})}static fromPrivateKey(_){return L(_).point}toRawBytes(){let{x:_,y:V}=this.toAffine(),K=Sn(V,t.BYTES);return K[K.length-1]|=_&wt?128:0,K}toHex(){return gr(this.toRawBytes())}}S.BASE=new S(e.Gx,e.Gy,wt,f(e.Gx*e.Gy)),S.ZERO=new S(Ft,wt,wt,Ft);let{BASE:R,ZERO:v}=S,E=Js(S,a*8);function P(B){return ce(B,n)}function U(B){return P(tn(B))}function L(B){let _=a;B=be("private key",B,_);let V=be("hashed private key",i(B),2*_),K=p(V.slice(0,_)),W=V.slice(_,2*_),X=U(K),Z=R.multiply(X),ie=Z.toRawBytes();return{head:K,prefix:W,scalar:X,point:Z,pointBytes:ie}}function $(B){return L(B).pointBytes}function C(B=new Uint8Array,..._){let V=wr(..._);return U(i(h(V,be("context",B),!!o)))}function ee(B,_,V={}){B=be("message",B),o&&(B=o(B));let{prefix:K,scalar:W,pointBytes:X}=L(_),Z=C(V.context,K,B),ie=R.multiply(Z).toRawBytes(),Q=C(V.context,ie,X,B),te=P(Z+Q*W);x(te);let ve=wr(ie,Sn(te,t.BYTES));return be("result",ve,a*2)}let I=SE;function T(B,_,V,K=I){let{context:W,zip215:X}=K,Z=t.BYTES;B=be("signature",B,2*Z),_=be("message",_),o&&(_=o(_));let ie=tn(B.slice(Z,2*Z)),Q,te,ve;try{Q=S.fromHex(V,X),te=S.fromHex(B.slice(0,Z),X),ve=R.multiplyUnsafe(ie)}catch{return!1}if(!X&&Q.isSmallOrder())return!1;let ye=C(W,te.toRawBytes(),Q.toRawBytes(),_);return te.add(Q.multiplyUnsafe(ye)).subtract(ve).clearCofactor().equals(S.ZERO)}return R._setWindowSize(8),{CURVE:e,getPublicKey:$,sign:ee,verify:T,ExtendedPoint:S,utils:{getExtendedPublicKey:L,randomPrivateKey:()=>s(t.BYTES),precompute(B=8,_=S.BASE){return _._setWindowSize(B),_.multiply(BigInt(3)),_}}}}var Cu=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),tm=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),BT=BigInt(0),_E=BigInt(1),Nu=BigInt(2),kE=BigInt(5),rm=BigInt(10),IE=BigInt(20),RE=BigInt(40),nm=BigInt(80);function BE(r){let e=Cu,n=r*r%e*r%e,o=de(n,Nu,e)*n%e,i=de(o,_E,e)*r%e,s=de(i,kE,e)*i%e,a=de(s,rm,e)*s%e,c=de(a,IE,e)*a%e,l=de(c,RE,e)*c%e,f=de(l,nm,e)*l%e,u=de(f,nm,e)*l%e,p=de(u,rm,e)*s%e;return{pow_p_5_8:de(p,Nu,e)*r%e,b2:n}}function TE(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function NE(r,e){let t=Cu,n=ce(e*e*e,t),o=ce(n*n*e,t),i=BE(r*o).pow_p_5_8,s=ce(r*n*i,t),a=ce(e*s*s,t),c=s,l=ce(s*tm,t),f=a===r,u=a===ce(-r,t),p=a===ce(-r*tm,t);return f&&(s=c),(u||p)&&(s=l),Zp(s,t)&&(s=ce(-s,t)),{isValid:f||u,value:s}}var br=Zs(Cu,void 0,!0),Lu={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:br,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:mo,randomBytes:ho,adjustScalarBytes:TE,uvRatio:NE},yo=ea(Lu);function om(r,e,t){if(e.length>255)throw new Error("Context is too big");return zs(xu("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var TT=ea({...Lu,domain:om}),NT=ea({...Lu,domain:om,prehash:mo});var CE=(br.ORDER+BigInt(3))/BigInt(8),CT=br.pow(Nu,CE),LT=br.sqrt(br.neg(br.ONE)),DT=(br.ORDER-BigInt(5))/BigInt(8),PT=BigInt(486662);var OT=Jp(br,br.neg(BigInt(486664)));var UT=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),FT=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),VT=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),MT=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var HT=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var wo=32,xr=64,ta=32;function im(){let r=yo.utils.randomPrivateKey(),e=yo.getPublicKey(r);return{privateKey:lm(r,e),publicKey:e}}function sm(r){if(r.length!==ta)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=yo.getPublicKey(e);return{privateKey:lm(e,t),publicKey:t}}function am(r,e){let t=r.subarray(0,ta);return yo.sign(e instanceof Uint8Array?e:e.subarray(),t)}function cm(r,e,t){return yo.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function lm(r,e){let t=new Uint8Array(xr);for(let n=0;n<ta;n++)t[n]=r[n],t[ta+n]=e[n];return t}var Du={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function um(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=Je.get();t*=8;async function c(u,p){let h=a.getRandomValues(new Uint8Array(i)),m=a.getRandomValues(new Uint8Array(n)),d={name:e,iv:m};typeof p=="string"&&(p=O(p));let y;if(p.length===0){y=await a.subtle.importKey("jwk",Du,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(x,b,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Du,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(x,b,{name:e,length:t},!0,["encrypt"])}let w=await a.subtle.encrypt(d,y,u);return ue([h,d.iv,new Uint8Array(w)])}async function l(u,p){let h=u.subarray(0,i),m=u.subarray(i,i+n),d=u.subarray(i+n),y={name:e,iv:m};typeof p=="string"&&(p=O(p));let w;if(p.length===0)try{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},A=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}catch{w=await a.subtle.importKey("jwk",Du,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},A=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(b,A,{name:e,length:t},!0,["decrypt"])}let x=await a.subtle.decrypt(y,w,d);return new Uint8Array(x)}return{encrypt:c,decrypt:l}}async function bo(r,e){let n=await um().encrypt(r,e);return Et.encode(n)}var pe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(pe||(pe={}));var Pu;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(Pu||(Pu={}));(function(r){r.codec=()=>wn(Pu)})(pe||(pe={}));var Jt;(function(r){let e;r.codec=()=>(e==null&&(e=_t((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),pe.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=pe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>At(t,r.codec()),r.decode=t=>St(t,r.codec())})(Jt||(Jt={}));var Qt;(function(r){let e;r.codec=()=>(e==null&&(e=_t((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),pe.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=pe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>At(t,r.codec()),r.decode=t=>St(t,r.codec())})(Qt||(Qt={}));var di=class{_key;constructor(e){this._key=xo(e,wo)}verify(e,t){return cm(this._key,t,e)}marshal(){return this._key}get bytes(){return Jt.encode({Type:pe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=ke.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}},_n=class{_key;_publicKey;constructor(e,t){this._key=xo(e,xr),this._publicKey=xo(t,wo)}sign(e){return am(this._key,e)}get public(){return new di(this._publicKey)}marshal(){return this._key}get bytes(){return Qt.encode({Type:pe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=ke.digest(this.bytes),t;return Rt(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=$e.digest(this.public.bytes);return ge.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 PE(r){if(r.length>xr){r=xo(r,xr+wo);let n=r.subarray(0,xr),o=r.subarray(xr,r.length);return new _n(n,o)}r=xo(r,xr);let e=r.subarray(0,xr),t=r.subarray(wo);return new _n(e,t)}function OE(r){return r=xo(r,wo),new di(r)}async function UE(){let{privateKey:r,publicKey:e}=im();return new _n(r,e)}async function fm(r){let{privateKey:e,publicKey:t}=sm(r);return new _n(e,t)}function xo(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 Gu={};Se(Gu,{MAX_RSA_KEY_SIZE:()=>_i,RsaPrivateKey:()=>_o,RsaPublicKey:()=>Ai,fromJwk:()=>uv,generateKeyPair:()=>fv,unmarshalRsaPrivateKey:()=>qu,unmarshalRsaPublicKey:()=>lv});function er(r){if(isNaN(r)||r<=0)throw new N("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return ho(r)}var an={};Se(an,{exportToPem:()=>ov,importFromPem:()=>iv,jwkToPkcs1:()=>ev,jwkToPkix:()=>rv,pkcs1ToJwk:()=>QE,pkixToJwk:()=>tv});var na=class extends uo{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ks(e);let n=Zr(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 lo(this),this.iHash.update(e),this}digestInto(e){lo(this),co(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()}},pi=(r,e,t)=>new na(r,e).update(t).digest();pi.create=(r,e)=>new na(r,e);function FE(r,e,t,n){Ks(r);let o=Hp({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(ao(i),ao(s),ao(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Zr(e),l=Zr(t),f=new Uint8Array(s),u=pi.create(r,c),p=u._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:f,PRF:u,PRFSalt:p}}function VE(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function Uu(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=FE(r,e,t,n),f,u=new Uint8Array(4),p=fo(u),h=new Uint8Array(c.outputLen);for(let m=1,d=0;d<i;m++,d+=c.outputLen){let y=a.subarray(d,d+c.outputLen);p.setInt32(0,m,!1),(f=l._cloneInto(f)).update(u).digestInto(h),y.set(h.subarray(0,y.length)),await Mp(o-1,s,()=>{c._cloneInto(f).update(h).digestInto(h);for(let w=0;w<y.length;w++)y[w]^=h[w]})}return VE(c,l,a,f,h)}var J=re(hm());function kn(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 nn(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 l=new Uint8Array(c);for(let f=a-1;f>=0;f--){let u=Math.pow(2,f*e);l[i-f-1]=Math.floor(o/u),o-=l[i-f-1]*u}return c}s*=Math.pow(2,e)}return new ArrayBuffer(0)}function sa(...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 Vu(){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=kn(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,kn(i,8)-n}function dm(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=nn(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=nn(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 pm(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 st(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 aa(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Mu(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 _r(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 gi=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Mu(this.items)}},mi=[new Uint8Array([1])],mm="0123456789";var So="",Mt=new ArrayBuffer(0),Hu=new Uint8Array(0),yi="EndOfContent",ym="OCTET STRING",wm="BIT STRING";function kr(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?J.BufferSourceConverter.toUint8Array(i.valueHex):Hu}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(!_r(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",Mt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:J.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var vr=class{constructor({blockLength:e=0,error:t=So,warnings:n=[],valueBeforeDecode:o=Hu}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=J.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:J.Convert.ToHex(this.valueBeforeDecodeView)}}};vr.NAME="baseBlock";var ze=class extends vr{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'")}};ze.NAME="valueBlock";var ca=class extends kr(vr){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?J.BufferSourceConverter.toUint8Array(e.valueHex):Hu,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",Mt}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=nn(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=J.BufferSourceConverter.toUint8Array(e);if(!_r(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,l=this.valueHexView=new Uint8Array(255),f=255;for(;i[c]&128;){if(l[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let p=new Uint8Array(f);for(let h=0;h<l.length;h++)p[h]=l[h];l=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,l[c-1]=i[c]&127;let u=new Uint8Array(c);for(let p=0;p<c;p++)u[p]=l[p];l=this.valueHexView=new Uint8Array(c),l.set(u),this.blockLength<=9?this.tagNumber=kn(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ca.NAME="identificationBlock";var la=class extends vr{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=J.BufferSourceConverter.toUint8Array(e);if(!_r(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=kn(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=nn(this.length,8);if(o.byteLength>127)return this.error="Too big length",Mt;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}}};la.NAME="lengthBlock";var F={},Oe=class extends vr{constructor({name:e=So,optional:t=!1,primitiveSchema:n,...o}={},i){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new ca(o),this.lenBlock=new la(o),this.valueBlock=i?new i(o):new ze(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 gi;t||bm(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?Mt: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():J.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${J.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 pm(t,n)}};Oe.NAME="BaseBlock";function bm(r){if(r instanceof F.Constructed)for(let e of r.valueBlock.value)bm(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ua=class extends Oe{constructor({value:e=So,...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}'`}};ua.NAME="BaseStringBlock";var fa=class extends kr(ze){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};fa.NAME="PrimitiveValueBlock";var xm,ha=class extends Oe{constructor(e={}){super(e,fa),this.idBlock.isConstructed=!1}};xm=ha;F.Primitive=xm;ha.NAME="PRIMITIVE";function jE(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 za(r,e=0,t=r.length){let n=e,o=new Oe({},ze),i=new vr;if(!_r(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=Oe;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=F.EndOfContent;break;case 1:c=F.Boolean;break;case 2:c=F.Integer;break;case 3:c=F.BitString;break;case 4:c=F.OctetString;break;case 5:c=F.Null;break;case 6:c=F.ObjectIdentifier;break;case 10:c=F.Enumerated;break;case 12:c=F.Utf8String;break;case 13:c=F.RelativeObjectIdentifier;break;case 14:c=F.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=F.Sequence;break;case 17:c=F.Set;break;case 18:c=F.NumericString;break;case 19:c=F.PrintableString;break;case 20:c=F.TeletexString;break;case 21:c=F.VideotexString;break;case 22:c=F.IA5String;break;case 23:c=F.UTCTime;break;case 24:c=F.GeneralizedTime;break;case 25:c=F.GraphicString;break;case 26:c=F.VisibleString;break;case 27:c=F.GeneralString;break;case 28:c=F.UniversalString;break;case 29:c=F.CharacterString;break;case 30:c=F.BmpString;break;case 31:c=F.DATE;break;case 32:c=F.TimeOfDay;break;case 33:c=F.DateTime;break;case 34:c=F.Duration;break;default:{let l=o.idBlock.isConstructed?new F.Constructed:new F.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?F.Constructed:F.Primitive}return o=jE(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 Ao(r){if(!r.byteLength){let e=new Oe({},ze);return e.error="Input buffer has zero length",{offset:-1,result:e}}return za(J.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function YE(r,e){return r?1:e}var tr=class extends ze{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=J.BufferSourceConverter.toUint8Array(e);if(!_r(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(;YE(this.isIndefiniteForm,n)>0;){let s=za(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===yi)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===yi?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){let n=t||new gi;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Mt:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};tr.NAME="ConstructedValueBlock";var Em,on=class extends Oe{constructor(e={}){super(e,tr),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 Jw=Object.create;var os=Object.defineProperty;var Qw=Object.getOwnPropertyDescriptor;var eb=Object.getOwnPropertyNames;var tb=Object.getPrototypeOf,rb=Object.prototype.hasOwnProperty;var Oe=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Se=(r,e)=>{for(var t in e)os(r,t,{get:e[t],enumerable:!0})},Ph=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of eb(e))!rb.call(r,o)&&o!==t&&os(r,o,{get:()=>e[o],enumerable:!(n=Qw(e,o))||n.enumerable});return r};var re=(r,e,t)=>(t=r!=null?Jw(tb(r)):{},Ph(e||!r||!r.__esModule?os(t,"default",{value:r,enumerable:!0}):t,r)),nb=r=>Ph(os({},"__esModule",{value:!0}),r);var De=Oe((xI,Kh)=>{"use strict";function zh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function mb(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 zh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),zh(new o,t)}}Kh.exports=mb});var Xd=Oe(fo=>{"use strict";var X1="[object ArrayBuffer]",wr=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===X1}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}},du="string",Z1=/^[0-9a-f]+$/i,J1=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Q1=/^[a-zA-Z0-9-_]+$/,Ls=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=wr.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},kt=class{static toString(e,t=!1){let n=wr.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}},Os=class r{static isHex(e){return typeof e===du&&Z1.test(e)}static isBase64(e){return typeof e===du&&J1.test(e)}static isBase64Url(e){return typeof e===du&&Q1.test(e)}static ToString(e,t="utf8"){let n=wr.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 kt.toString(n,!0);case"utf16":case"utf16be":return kt.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 kt.fromString(e,!0);case"utf16":case"utf16be":return kt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=wr.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 Ls.fromString(e);case"utf16":case"utf16be":return kt.fromString(e);case"utf16le":case"usc2":return kt.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 Ls.toString(e);case"utf16":case"utf16be":return kt.toString(e);case"utf16le":case"usc2":return kt.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=wr.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=wr.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 kt.toString(e,t)}static FromUtf16String(e,t=!1){return kt.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,"")||""}};Os.DEFAULT_UTF8_ENCODING="utf8";function eE(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 tE(...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 rE(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}fo.BufferSourceConverter=wr;fo.Convert=Os;fo.assign=eE;fo.combine=tE;fo.isEqual=rE});var nm=Oe((gi,va)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function o(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function i(h,m){return h<<m|h>>>32-m}function s(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]+m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]+m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]+m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]+m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]*m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]*m[3],d[1]+=d[2]>>>16,d[2]&=65535,d[2]+=h[3]*m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]*m[3],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[2]*m[2],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[3]*m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function u(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function f(h,m){return[h[0]^m[0],h[1]^m[1]]}function p(h){return h=f(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=f(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=f(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%4,y=h.length-d,g=m,b=0,x=3432918353,E=461845907,v=0;v<y;v=v+4)b=h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24,b=o(b,x),b=i(b,15),b=o(b,E),g^=b,g=i(g,13),g=o(g,5)+3864292196;switch(b=0,d){case 3:b^=h[v+2]<<16;case 2:b^=h[v+1]<<8;case 1:b^=h[v],b=o(b,x),b=i(b,15),b=o(b,E),g^=b}return g^=h.length,g=s(g),g>>>0},t.x86.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,g=m,b=m,x=m,E=m,v=0,_=0,S=0,A=0,L=597399067,U=2869860233,O=951274213,$=2716044179,C=0;C<y;C=C+16)v=h[C]|h[C+1]<<8|h[C+2]<<16|h[C+3]<<24,_=h[C+4]|h[C+5]<<8|h[C+6]<<16|h[C+7]<<24,S=h[C+8]|h[C+9]<<8|h[C+10]<<16|h[C+11]<<24,A=h[C+12]|h[C+13]<<8|h[C+14]<<16|h[C+15]<<24,v=o(v,L),v=i(v,15),v=o(v,U),g^=v,g=i(g,19),g+=b,g=o(g,5)+1444728091,_=o(_,U),_=i(_,16),_=o(_,O),b^=_,b=i(b,17),b+=x,b=o(b,5)+197830471,S=o(S,O),S=i(S,17),S=o(S,$),x^=S,x=i(x,15),x+=E,x=o(x,5)+2530024501,A=o(A,$),A=i(A,18),A=o(A,L),E^=A,E=i(E,13),E+=g,E=o(E,5)+850148119;switch(v=0,_=0,S=0,A=0,d){case 15:A^=h[C+14]<<16;case 14:A^=h[C+13]<<8;case 13:A^=h[C+12],A=o(A,$),A=i(A,18),A=o(A,L),E^=A;case 12:S^=h[C+11]<<24;case 11:S^=h[C+10]<<16;case 10:S^=h[C+9]<<8;case 9:S^=h[C+8],S=o(S,O),S=i(S,17),S=o(S,$),x^=S;case 8:_^=h[C+7]<<24;case 7:_^=h[C+6]<<16;case 6:_^=h[C+5]<<8;case 5:_^=h[C+4],_=o(_,U),_=i(_,16),_=o(_,O),b^=_;case 4:v^=h[C+3]<<24;case 3:v^=h[C+2]<<16;case 2:v^=h[C+1]<<8;case 1:v^=h[C],v=o(v,L),v=i(v,15),v=o(v,U),g^=v}return g^=h.length,b^=h.length,x^=h.length,E^=h.length,g+=b,g+=x,g+=E,b+=g,x+=g,E+=g,g=s(g),b=s(b),x=s(x),E=s(E),g+=b,g+=x,g+=E,b+=g,x+=g,E+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,g=[0,m],b=[0,m],x=[0,0],E=[0,0],v=[2277735313,289559509],_=[1291169091,658871167],S=0;S<y;S=S+16)x=[h[S+4]|h[S+5]<<8|h[S+6]<<16|h[S+7]<<24,h[S]|h[S+1]<<8|h[S+2]<<16|h[S+3]<<24],E=[h[S+12]|h[S+13]<<8|h[S+14]<<16|h[S+15]<<24,h[S+8]|h[S+9]<<8|h[S+10]<<16|h[S+11]<<24],x=c(x,v),x=l(x,31),x=c(x,_),g=f(g,x),g=l(g,27),g=a(g,b),g=a(c(g,[0,5]),[0,1390208809]),E=c(E,_),E=l(E,33),E=c(E,v),b=f(b,E),b=l(b,31),b=a(b,g),b=a(c(b,[0,5]),[0,944331445]);switch(x=[0,0],E=[0,0],d){case 15:E=f(E,u([0,h[S+14]],48));case 14:E=f(E,u([0,h[S+13]],40));case 13:E=f(E,u([0,h[S+12]],32));case 12:E=f(E,u([0,h[S+11]],24));case 11:E=f(E,u([0,h[S+10]],16));case 10:E=f(E,u([0,h[S+9]],8));case 9:E=f(E,[0,h[S+8]]),E=c(E,_),E=l(E,33),E=c(E,v),b=f(b,E);case 8:x=f(x,u([0,h[S+7]],56));case 7:x=f(x,u([0,h[S+6]],48));case 6:x=f(x,u([0,h[S+5]],40));case 5:x=f(x,u([0,h[S+4]],32));case 4:x=f(x,u([0,h[S+3]],24));case 3:x=f(x,u([0,h[S+2]],16));case 2:x=f(x,u([0,h[S+1]],8));case 1:x=f(x,[0,h[S]]),x=c(x,v),x=l(x,31),x=c(x,_),g=f(g,x)}return g=f(g,[0,h.length]),b=f(b,[0,h.length]),g=a(g,b),b=a(b,g),g=p(g),b=p(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 gi<"u"?(typeof va<"u"&&va.exports&&(gi=va.exports=t),gi.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)})(gi)});var ku=Oe((E8,om)=>{om.exports=nm()});var sm=Oe((v8,im)=>{var yo=1e3,wo=yo*60,bo=wo*60,Tn=bo*24,DE=Tn*7,PE=Tn*365.25;im.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return UE(r);if(t==="number"&&isFinite(r))return e.long?ME(r):FE(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function UE(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*PE;case"weeks":case"week":case"w":return t*DE;case"days":case"day":case"d":return t*Tn;case"hours":case"hour":case"hrs":case"hr":case"h":return t*bo;case"minutes":case"minute":case"mins":case"min":case"m":return t*wo;case"seconds":case"second":case"secs":case"sec":case"s":return t*yo;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function FE(r){var e=Math.abs(r);return e>=Tn?Math.round(r/Tn)+"d":e>=bo?Math.round(r/bo)+"h":e>=wo?Math.round(r/wo)+"m":e>=yo?Math.round(r/yo)+"s":r+"ms"}function ME(r){var e=Math.abs(r);return e>=Tn?Sa(r,e,Tn,"day"):e>=bo?Sa(r,e,bo,"hour"):e>=wo?Sa(r,e,wo,"minute"):e>=yo?Sa(r,e,yo,"second"):r+" ms"}function Sa(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var cm=Oe((S8,am)=>{function VE(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=sm(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let p=0;p<u.length;p++)f=(f<<5)-f+u.charCodeAt(p),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,p=null,h,m;function d(...y){if(!d.enabled)return;let g=d,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 E=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(_,S)=>{if(_==="%%")return"%";E++;let A=t.formatters[S];if(typeof A=="function"){let L=y[E];_=A.call(g,L),y.splice(E,1),E--}return _}),t.formatArgs.call(g,y),(g.log||t.log).apply(g,y)}return d.namespace=u,d.useColors=t.useColors(),d.color=t.selectColor(u),d.extend=n,d.destroy=t.destroy,Object.defineProperty(d,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(u)),m),set:y=>{p=y}}),typeof t.init=="function"&&t.init(d),d}function n(u,f){let p=t(this.namespace+(typeof f>"u"?":":f)+u);return p.log=this.log,p}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,p=(typeof u=="string"?u:"").split(/[\s,]+/),h=p.length;for(f=0;f<h;f++)p[f]&&(u=p[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.slice(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let f,p;for(f=0,p=t.skips.length;f<p;f++)if(t.skips[f].test(u))return!1;for(f=0,p=t.names.length;f<p;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}am.exports=VE});var lm=Oe((pt,Aa)=>{pt.formatArgs=$E;pt.save=zE;pt.load=KE;pt.useColors=HE;pt.storage=qE();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 HE(){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 $E(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Aa.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 zE(r){try{r?pt.storage.setItem("debug",r):pt.storage.removeItem("debug")}catch{}}function KE(){let r;try{r=pt.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function qE(){try{return localStorage}catch{}}Aa.exports=cm()(pt);var{formatters:GE}=Aa.exports;GE.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var hm=Oe((k8,Bu)=>{"use strict";var jE=Object.prototype.hasOwnProperty,et="~";function yi(){}Object.create&&(yi.prototype=Object.create(null),new yi().__proto__||(et=!1));function YE(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function fm(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new YE(t,n||r,o),s=et?et+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 _a(r,e){--r._eventsCount===0?r._events=new yi:delete r._events[e]}function We(){this._events=new yi,this._eventsCount=0}We.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)jE.call(t,n)&&e.push(et?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};We.prototype.listeners=function(e){var t=et?et+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};We.prototype.listenerCount=function(e){var t=et?et+e:e,n=this._events[t];return n?n.fn?1:n.length:0};We.prototype.emit=function(e,t,n,o,i,s){var a=et?et+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,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,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var p=c.length,h;for(f=0;f<p;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};We.prototype.on=function(e,t,n){return fm(this,e,t,n,!1)};We.prototype.once=function(e,t,n){return fm(this,e,t,n,!0)};We.prototype.removeListener=function(e,t,n,o){var i=et?et+e:e;if(!this._events[i])return this;if(!t)return _a(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&_a(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:_a(this,i)}return this};We.prototype.removeAllListeners=function(e){var t;return e?(t=et?et+e:e,this._events[t]&&_a(this,t)):(this._events=new yi,this._eventsCount=0),this};We.prototype.off=We.prototype.removeListener;We.prototype.addListener=We.prototype.on;We.prefixed=et;We.EventEmitter=We;typeof Bu<"u"&&(Bu.exports=We)});var Du=Oe((Z8,gm)=>{gm.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 Wg=Oe(Pi=>{(function(){var r,e,t,n,o,i,s,a;a=function(c){var l,u,f,p;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,p=c&255,[l,u,f,p].join(".")},s=function(c){var l,u,f,p,h,m;for(l=[],f=p=0;p<=3&&c.length!==0;f=++p){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=e(c),h=m[0],u=m[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),i=t("a"),o=t("A"),e=function(c){var l,u,f,p,h;for(p=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)p=p*l+(t(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")p=p*l+(10+t(c[f])-i)>>>0;else if("A"<=c[f]&&c[f]<="F")p=p*l+(10+t(c[f])-o)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[p,f]},r=function(){function c(l,u){var f,p,h,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(m=l.split("/",2),l=m[0],u=m[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=s(u)}catch(d){throw f=d,new Error("Invalid mask: "+u)}for(p=h=32;h>=0;p=--h)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(l)&this.maskLong)>>>0}catch(d){throw f=d,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(s(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,p;for(p=s(this.first),f=s(this.last),u=0;p<=f;)l(a(p),p,u),u++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Pi.ip2long=s,Pi.long2ip=a,Pi.Netmask=r}).call(Pi)});var bc=Oe((oL,Lf)=>{var nL=function(){typeof Lf<"u"&&(Lf.exports=d);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(A){var L=A-A%1;return L==0&&(A<0||A===0&&1/A!=1/0)?-0:L},u=d.prototype,f=(d.fromDate=function(A){return new d(+A)},d.fromInt64BE=E(0,1,2,3,0,4),d.fromInt64LE=E(3,2,1,0,4,0),d.fromString=function(O){var L,U=new d,O=(O+="").replace(/^\s*[+\-]?\d+/,function(C){var C=+C,ee=1970+(C-1970)%400;return U.year=C-ee,ee}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function($,C,ee){return C<0&&(ee*=-1),L=6e4*(60*+C+ +ee),""}).replace(/\.\d+$/,function($){return U.nano=+($+c).substr(1,9),""}).split(/\D+/);if(1<O.length?O[1]--:O[1]=0,U.time=L=Date.UTC.apply(Date,O)-(L||0),isNaN(L))throw new TypeError("Invalid Date");return y(U)},d.fromTimeT=function(A){return b(A,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(A){return this.nano+=+A||0,this},u.getNano=function(){var A=y(this);return(A.time%1e3*a+ +A.nano+1e9)%1e9},u.getTimeT=function(){var L=y(this),A=Math.floor(L.time/1e3),L=L.year;return L&&(A+=L*t*r/e),A},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return g(y(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(A){var L=this,U=L.toDate(),O={H:function(){return _(U.getUTCHours())},L:function(){return S(U.getUTCMilliseconds(),3)},M:function(){return _(U.getUTCMinutes())},N:function(){return S(L.getNano(),9)},S:function(){return _(U.getUTCSeconds())},Y:function(){var $=L.getYear();return 999999<$?"+"+$:9999<$?"+"+S($,6):0<=$?S($,4):-999999<=$?"-"+S(-$,6):$},a:function(){return h[U.getUTCDay()]},b:function(){return p[U.getUTCMonth()]},d:function(){return _(U.getUTCDate())},e:function(){return function($){return(9<$?"":" ")+(0|$)}(U.getUTCDate())},m:function(){return _(U.getUTCMonth()+1)}};return function $(C){return C.replace(/%./g,function(ee){var T=ee[1],k=m[T],T=O[T];return k?$(k):T?T():ee})}(A||f)},u.writeInt64BE=x(0,1,2,3,0,4),u.writeInt64LE=x(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),p=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m={"%":"%",F:"%Y-%m-%d",n:`
|
|
3
|
+
`,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return d;function d(A,L,U){var O=this;if(!(O instanceof d))return new d(A,L,U);O.time=+A||0,O.nano=+L||0,O.year=+U||0,y(O)}function y(A){var L,U,O,$=A.year,C=A.time,ee=A.nano,k=((ee<0||a<=ee)&&(ee-=(U=Math.floor(ee/a))*a,C+=U,U=1),$%e);return(C<-i||i<C||k)&&((L=l(C/o))&&($+=L*e,C-=L*o),(O=g(C)).setUTCFullYear(k+O.getUTCFullYear()),O=(C=+O)+(L=l(($-=k)/e))*o,L&&-i<=O&&O<=i&&($-=L*e,C=O),U=1),U&&(A.year=$,A.time=C,A.nano=ee),A}function g(A){var L=new Date(0);return L.setTime(A),L}function b($,O){$=+$||0;var U=l((O=(O|0)*s)/n)+l($/n),O=O%n+$%n,$=l(O/n);return $&&(U+=$,O-=$*n),new d(1e3*O,0,U*e)}function x(A,L,U,O,$,C){return function(k,T){var B=y(this);k=k||new Array(8),v(k,T|=0);var I=Math.floor(B.time/1e3),B=B.year*(t*r/e),q=l(B/s)+l(I/s),B=B%s+I%s,I=Math.floor(B/s);return I&&(q+=I,B-=I*s),ee(k,T+$,q),ee(k,T+C,B),k};function ee(k,T,q){k[T+A]=q>>24&255,k[T+L]=q>>16&255,k[T+U]=q>>8&255,k[T+O]=255&q}}function E(A,L,U,O,$,C){return function(k,T){v(k,T|=0);var q=ee(k,T+$);return b(ee(k,T+C),q)};function ee(k,T){return 16777216*k[T+A]+(k[T+L]<<16|k[T+U]<<8|k[T+O])}}function v(A,L){if(A=A&&A.length,A==null)throw new TypeError("Invalid Buffer");if(A<L+8)throw new RangeError("Out of range")}function _(A){return(9<A?"":"0")+(0|A)}function S(A,L){return(c+(0|A)).substr(-L)}}()});var ly=Oe((eP,cy)=>{cy.exports=Xf;var ay=128,AS=127,_S=~AS,IS=Math.pow(2,31);function Xf(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Xf.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=IS;)e[t++]=r&255|ay,r/=128;for(;r&_S;)e[t++]=r&255|ay,r>>>=7;return e[t]=r|0,Xf.bytes=t-n+1,e}});var hy=Oe((tP,fy)=>{fy.exports=Zf;var RS=128,uy=127;function Zf(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw Zf.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&uy)<<o:(s&uy)*Math.pow(2,o),o+=7}while(s>=RS);return Zf.bytes=i-n,t}});var py=Oe((rP,dy)=>{var kS=Math.pow(2,7),BS=Math.pow(2,14),TS=Math.pow(2,21),NS=Math.pow(2,28),CS=Math.pow(2,35),LS=Math.pow(2,42),OS=Math.pow(2,49),DS=Math.pow(2,56),PS=Math.pow(2,63);dy.exports=function(r){return r<kS?1:r<BS?2:r<TS?3:r<NS?4:r<CS?5:r<LS?6:r<OS?7:r<DS?8:r<PS?9:10}});var Bc=Oe((nP,my)=>{my.exports={encode:ly(),decode:hy(),encodingLength:py()}});var jy=Oe((xU,Wy)=>{"use strict";Wy.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(uA,0),c=~(4294967295<<i+1),l=Gy(o&c);return a+l-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(fA),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),l=~(255<<c),u=i&l;o|=u<<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(hA)}};function uA(r,e){return r+Gy(e)}function Gy(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function fA(r,e){return r[0]-e[0]}function hA(r){return r[1]}});var Bw=Oe((x7,kw)=>{"use strict";kw.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 B_={};Se(B_,{createVerifiedFetch:()=>Rh,verifiedFetch:()=>Qc});var $o=Symbol.for("@libp2p/content-routing");var zo=Symbol.for("@libp2p/peer-id");function Uh(r){return r!=null&&!!r[zo]}var Ko=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 me=(r,...e)=>{try{[...e]}catch{}};var Mn=class extends EventTarget{#e=new Map;constructor(){super(),me(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 ob(e,t))}},tl=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},ob=globalThis.CustomEvent??tl;function Fh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Fr(...r){let e=[];for(let t of r)Fh(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 Mr(...r){let e=[];for(let t of r)Fh(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()}))}function Ye(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 fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var is=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}},Vn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new is(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 is(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 rl=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Gt(r={}){return ib(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 ib(r,e){e=e??{};let t=e.onEnd,n=new Vn,o,i,s,a=fe(),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=fe()})}},l=y=>i!=null?i(y):(n.push(y),o),u=y=>(n=new Vn,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 l({done:!1,value:y})},p=y=>s?o:(s=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new Vn,p(),{done:!0}),m=y=>(p(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:p,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((E,v)=>{x=()=>{v(new rl)},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 d=o;return o={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(y){return d.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return d.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(y){return d.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return d.readableLength},onEmpty:y=>d.onEmpty(y)},o}var nl=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 ss(r,e,t,n){let o=new nl(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function a(){t?.removeEventListener("abort",u),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(p){a(),s(p);return}a(),i(f)},l=f=>{a(),s(f.detail)},u=()=>{a(),s(o)};t?.addEventListener("abort",u),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var as=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 Mh(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new as(t?.errorMessage,t?.errorCode));let n,o=new as(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 cs=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=fe(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new qt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function sb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ls=class{id;fn;options;priority;recipients;status;timeline;controller;constructor(e,t,n=0){this.id=sb(),this.status="queued",this.fn=e,this.priority=n,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,me(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),this.cleanup())}async join(e={}){let t=new cs(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 Mh(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function ab(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 lr=class extends Mn{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=ab(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 ls(e,t,t?.priority),o=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:i}),this.safeDispatchEvent("failure",{detail:{job:n,error: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 ss(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await ss(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ss(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=Gt({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 us=class extends lr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function cb(r){return r[Symbol.asyncIterator]!=null}function lb(r){if(cb(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ur=lb;function rt(r=0){return new Uint8Array(r)}function nt(r=0){return new Uint8Array(r)}var ub=Math.pow(2,7),fb=Math.pow(2,14),hb=Math.pow(2,21),ol=Math.pow(2,28),il=Math.pow(2,35),sl=Math.pow(2,42),al=Math.pow(2,49),ae=128,ze=127;function ot(r){if(r<ub)return 1;if(r<fb)return 2;if(r<hb)return 3;if(r<ol)return 4;if(r<il)return 5;if(r<sl)return 6;if(r<al)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function cl(r,e,t=0){switch(ot(r)){case 8:e[t++]=r&255|ae,r/=128;case 7:e[t++]=r&255|ae,r/=128;case 6:e[t++]=r&255|ae,r/=128;case 5:e[t++]=r&255|ae,r/=128;case 4:e[t++]=r&255|ae,r>>>=7;case 3:e[t++]=r&255|ae,r>>>=7;case 2:e[t++]=r&255|ae,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function db(r,e,t=0){switch(ot(r)){case 8:e.set(t++,r&255|ae),r/=128;case 7:e.set(t++,r&255|ae),r/=128;case 6:e.set(t++,r&255|ae),r/=128;case 5:e.set(t++,r&255|ae),r/=128;case 4:e.set(t++,r&255|ae),r>>>=7;case 3:e.set(t++,r&255|ae),r>>>=7;case 2:e.set(t++,r&255|ae),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function ll(r,e){let t=r[e],n=0;if(n+=t&ze,t<ae||(t=r[e+1],n+=(t&ze)<<7,t<ae)||(t=r[e+2],n+=(t&ze)<<14,t<ae)||(t=r[e+3],n+=(t&ze)<<21,t<ae)||(t=r[e+4],n+=(t&ze)*ol,t<ae)||(t=r[e+5],n+=(t&ze)*il,t<ae)||(t=r[e+6],n+=(t&ze)*sl,t<ae)||(t=r[e+7],n+=(t&ze)*al,t<ae))return n;throw new RangeError("Could not decode varint")}function pb(r,e){let t=r.get(e),n=0;if(n+=t&ze,t<ae||(t=r.get(e+1),n+=(t&ze)<<7,t<ae)||(t=r.get(e+2),n+=(t&ze)<<14,t<ae)||(t=r.get(e+3),n+=(t&ze)<<21,t<ae)||(t=r.get(e+4),n+=(t&ze)*ol,t<ae)||(t=r.get(e+5),n+=(t&ze)*il,t<ae)||(t=r.get(e+6),n+=(t&ze)*sl,t<ae)||(t=r.get(e+7),n+=(t&ze)*al,t<ae))return n;throw new RangeError("Could not decode varint")}function Hn(r,e,t=0){return e==null&&(e=nt(ot(r))),e instanceof Uint8Array?cl(r,e,t):db(r,e,t)}function wn(r,e=0){return r instanceof Uint8Array?ll(r,e):pb(r,e)}function ue(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=nt(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function ne(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}var $h=Symbol.for("@achingbrain/uint8arraylist");function Hh(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 Wt(r){return!!r?.[$h]}var fr=class r{bufs;length;[$h]=!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(Wt(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(Wt(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=Hh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Hh(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(Wt(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 l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(u){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Wt(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,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let p=l;p>=0;p--){let h=this.get(f+p);if(n[p]!==h){u=Math.max(1,p-a[h]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=nt(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=rt(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=rt(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=rt(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=nt(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=rt(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=rt(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=rt(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=rt(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=rt(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(!ne(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 gb(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 $n=gb;function yb(r){return r[Symbol.asyncIterator]!=null}function wb(r,e){let t=0;if(yb(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=$n(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){yield await s;for await(let c of n)yield e(c,t++)}();let a=e;return function*(){yield s;for(let c of n)yield a(c,t++)}()}var Ke=wb;function bb(r){return r[Symbol.asyncIterator]!=null}function xb(...r){let e=[];for(let t of r)bb(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Gt({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 Vr=xb;function jt(r,...e){if(r==null)throw new Error("Empty pipeline");if(ul(r)){let n=r;r=()=>n.source}else if(Gh(r)||qh(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&ul(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++)ul(t[n])&&(t[n]=vb(t[n]));return Eb(...t)}var Eb=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},qh=r=>r?.[Symbol.asyncIterator]!=null,Gh=r=>r?.[Symbol.iterator]!=null,ul=r=>r==null?!1:r.sink!=null&&r.source!=null,vb=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Gt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(qh(i))o=async function*(){yield*i,n.end()};else if(Gh(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Vr(n,o())}return r.source};function Sb(r){return r[Symbol.asyncIterator]!=null}function Ab(r,e){return Sb(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 fs=Ab;var V=class extends Event{constructor(e,t){super(e),this.detail=t}};var fl=new Float32Array([-0]),Hr=new Uint8Array(fl.buffer);function Wh(r,e,t){fl[0]=r,e[t]=Hr[0],e[t+1]=Hr[1],e[t+2]=Hr[2],e[t+3]=Hr[3]}function jh(r,e){return Hr[0]=r[e],Hr[1]=r[e+1],Hr[2]=r[e+2],Hr[3]=r[e+3],fl[0]}var hl=new Float64Array([-0]),qe=new Uint8Array(hl.buffer);function Yh(r,e,t){hl[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 Xh(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],hl[0]}var _b=BigInt(Number.MAX_SAFE_INTEGER),Ib=BigInt(Number.MIN_SAFE_INTEGER),ft=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<_b&&e>Ib)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>Zh&&(o=0n,++n>Zh&&(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 ft(0,0);bn.toBigInt=function(){return 0n};bn.zzEncode=bn.zzDecode=function(){return this};bn.length=function(){return 1};var Zh=4294967296n;function Jh(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 Qh(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 dl(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 Ct(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function hs(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var pl=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,Ct(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 Ct(this,4);return hs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ct(this,4);return hs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ct(this,4);let e=jh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ct(this,4);let e=Xh(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 Ct(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Qh(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ct(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ct(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 ft(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 Ct(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 Ct(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 Ct(this,8);let e=hs(this.buf,this.pos+=4),t=hs(this.buf,this.pos+=4);return new ft(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=ll(this.buf,this.pos);return this.pos+=ot(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 ml(r){return new pl(r instanceof Uint8Array?r:r.subarray())}function St(r,e,t){let n=ml(r);return e.decode(n,void 0,t)}var Sl={};Se(Sl,{base10:()=>Db});var zn={};Se(zn,{coerce:()=>Yt,empty:()=>td,equals:()=>gl,fromHex:()=>kb,fromString:()=>yl,isBinary:()=>Bb,toHex:()=>Rb,toString:()=>wl});var td=new Uint8Array(0);function Rb(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))):td}function gl(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 Yt(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 Bb(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function yl(r){return new TextEncoder().encode(r)}function wl(r){return new TextDecoder().decode(r)}function Tb(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var d=0,y=0,g=0,b=m.length;g!==b&&m[g]===0;)g++,d++;for(var x=(b-g)*u+1>>>0,E=new Uint8Array(x);g!==b;){for(var v=m[g],_=0,S=x-1;(v!==0||_<y)&&S!==-1;S--,_++)v+=256*E[S]>>>0,E[S]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");y=_,g++}for(var A=x-y;A!==x&&E[A]===0;)A++;for(var L=c.repeat(d);A<x;++A)L+=r.charAt(E[A]);return L}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var d=0;if(m[d]!==" "){for(var y=0,g=0;m[d]===c;)y++,d++;for(var b=(m.length-d)*l+1>>>0,x=new Uint8Array(b);m[d];){var E=t[m.charCodeAt(d)];if(E===255)return;for(var v=0,_=b-1;(E!==0||v<g)&&_!==-1;_--,v++)E+=a*x[_]>>>0,x[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");g=v,d++}if(m[d]!==" "){for(var S=b-g;S!==b&&x[S]===0;)S++;for(var A=new Uint8Array(y+(b-S)),L=y;S!==b;)A[L++]=x[S++];return A}}}function h(m){var d=p(m);if(d)return d;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:p,decode:h}}var Nb=Tb,Cb=Nb,rd=Cb;var bl=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")}},xl=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 nd(this,e)}},El=class{decoders;constructor(e){this.decoders=e}or(e){return nd(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 nd(r,e){return new El({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var vl=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 bl(e,t,n),this.decoder=new xl(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Kn({name:r,prefix:e,encode:t,decode:n}){return new vl(r,e,t,n)}function $r({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=rd(t,r);return Kn({prefix:e,name:r,encode:n,decode:i=>Yt(o(i))})}function Lb(r,e,t,n){let o={};for(let u=0;u<e.length;++u)o[e[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function Ob(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 we({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Kn({prefix:e,name:r,encode(o){return Ob(o,n,t)},decode(o){return Lb(o,n,t,r)}})}var Db=$r({prefix:"9",name:"base10",alphabet:"0123456789"});var Al={};Se(Al,{base16:()=>Pb,base16upper:()=>Ub});var Pb=we({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ub=we({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var _l={};Se(_l,{base2:()=>Fb});var Fb=we({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Il={};Se(Il,{base256emoji:()=>zb});var od=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}"),Mb=od.reduce((r,e,t)=>(r[t]=e,r),[]),Vb=od.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Hb(r){return r.reduce((e,t)=>(e+=Mb[t],e),"")}function $b(r){let e=[];for(let t of r){let n=Vb[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var zb=Kn({prefix:"\u{1F680}",name:"base256emoji",encode:Hb,decode:$b});var Rl={};Se(Rl,{base32:()=>Pe,base32hex:()=>Gb,base32hexpad:()=>jb,base32hexpadupper:()=>Yb,base32hexupper:()=>Wb,base32pad:()=>Kb,base32padupper:()=>qb,base32upper:()=>id,base32z:()=>Xb});var Pe=we({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),id=we({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Kb=we({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qb=we({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gb=we({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Wb=we({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jb=we({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Yb=we({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xb=we({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var kl={};Se(kl,{base36:()=>zr,base36upper:()=>Zb});var zr=$r({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zb=$r({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Bl={};Se(Bl,{base58btc:()=>ge,base58flickr:()=>Jb});var ge=$r({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Jb=$r({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Nl={};Se(Nl,{base64:()=>it,base64pad:()=>Qb,base64url:()=>Tl,base64urlpad:()=>ex});var it=we({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Qb=we({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Tl=we({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ex=we({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Cl={};Se(Cl,{base8:()=>tx});var tx=we({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ll={};Se(Ll,{identity:()=>rx});var rx=Kn({prefix:"\0",name:"identity",encode:r=>wl(r),decode:r=>yl(r)});var eR=new TextEncoder,nx=new TextDecoder;var Kr=512;function sd(r){return JSON.parse(nx.decode(r))}var ht=85;var Dl={};Se(Dl,{identity:()=>Be});var ox=ld,ad=128,ix=127,sx=~ix,ax=Math.pow(2,31);function ld(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ax;)e[t++]=r&255|ad,r/=128;for(;r&sx;)e[t++]=r&255|ad,r>>>=7;return e[t]=r|0,ld.bytes=t-n+1,e}var cx=Ol,lx=128,cd=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&cd)<<o:(s&cd)*Math.pow(2,o),o+=7}while(s>=lx);return Ol.bytes=i-n,t}var ux=Math.pow(2,7),fx=Math.pow(2,14),hx=Math.pow(2,21),dx=Math.pow(2,28),px=Math.pow(2,35),mx=Math.pow(2,42),gx=Math.pow(2,49),yx=Math.pow(2,56),wx=Math.pow(2,63),bx=function(r){return r<ux?1:r<fx?2:r<hx?3:r<dx?4:r<px?5:r<mx?6:r<gx?7:r<yx?8:r<wx?9:10},xx={encode:ox,decode:cx,encodingLength:bx},Ex=xx,Go=Ex;function Wo(r,e=0){return[Go.decode(r,e),Go.decode.bytes]}function qn(r,e,t=0){return Go.encode(r,e,t),e}function Gn(r){return Go.encodingLength(r)}function Xt(r,e){let t=e.byteLength,n=Gn(r),o=n+Gn(t),i=new Uint8Array(o+t);return qn(r,i,0),qn(t,i,n),i.set(e,o),new Wn(r,t,e,i)}function Xe(r){let e=Yt(r),[t,n]=Wo(e),[o,i]=Wo(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Wn(t,o,s,e)}function ud(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&gl(r.bytes,t.bytes)}}var Wn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var fd=0,vx="identity",hd=Yt;function Sx(r){return Xt(fd,hd(r))}var Be={code:fd,name:vx,encode:hd,digest:Sx};var Fl={};Se(Fl,{sha256:()=>Re,sha512:()=>Ul});function xn({name:r,code:e,encode:t}){return new Pl(r,e,t)}var Pl=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?Xt(this.code,t):t.then(n=>Xt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function pd(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Re=xn({name:"sha2-256",code:18,encode:pd("SHA-256")}),Ul=xn({name:"sha2-512",code:19,encode:pd("SHA-512")});function md(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return _x(t,Ml(r),e??ge.encoder);default:return Ix(t,Ml(r),e??Pe.encoder)}}var gd=new WeakMap;function Ml(r){let e=gd.get(r);if(e==null){let t=new Map;return gd.set(r,t),t}return e}var z=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!==jo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Rx)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=Xt(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&&ud(e.multihash,n.multihash)}toString(e){return md(this,e)}toJSON(){return{"/":md(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??yd(n,o,i.bytes))}else if(t[kx]===!0){let{version:n,multihash:o,code:i}=t,s=Xe(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!==jo)throw new Error(`Version 0 CID must use dag-pb (code: ${jo}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=yd(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,jo,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=Yt(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 Wn(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,p]=Wo(e.subarray(t));return t+=p,f},o=n(),i=jo;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Ax(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 Ml(i).set(n,e),i}};function Ax(r,e){switch(r[0]){case"Q":{let t=e??ge;return[ge.prefix,t.decode(`${ge.prefix}${r}`)]}case ge.prefix:{let t=e??ge;return[ge.prefix,t.decode(r)]}case Pe.prefix:{let t=e??Pe;return[Pe.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!==ge.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 Ix(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 jo=112,Rx=18;function yd(r,e,t){let n=Gn(r),o=n+Gn(e),i=new Uint8Array(o+t.byteLength);return qn(r,i,0),qn(e,i,n),i.set(t,o),i}var kx=Symbol.for("@ipld/js-cid/CID");var qr={...Ll,..._l,...Cl,...Sl,...Al,...Rl,...kl,...Bl,...Nl,...Il},ER={...Fl,...Dl};function bd(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var wd=bd("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Vl=bd("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=nt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Bx={utf8:wd,"utf-8":wd,hex:qr.base16,latin1:Vl,ascii:Vl,binary:Vl,...qr},ms=Bx;function P(r,e="utf8"){let t=ms[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Hl(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return nt(s);o+s>e&&(n=nt(e),o=0);let a=n.subarray(o,o+=s);return o&7&&(o=(o|7)+1),a}}var En=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function $l(){}var Kl=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Tx=Hl();function Nx(r){return globalThis.Buffer!=null?nt(r):Tx(r)}var Xo=class{len;head;tail;states;constructor(){this.len=0,this.head=new En($l,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new En(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ql((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(gs,10,ft.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ft.fromBigInt(e);return this._push(gs,t.length(),t)}uint64Number(e){return this._push(cl,ot(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=ft.fromBigInt(e).zzEncode();return this._push(gs,t.length(),t)}sint64Number(e){let t=ft.fromNumber(e).zzEncode();return this._push(gs,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(zl,1,e?1:0)}fixed32(e){return this._push(Yo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ft.fromBigInt(e);return this._push(Yo,4,t.lo)._push(Yo,4,t.hi)}fixed64Number(e){let t=ft.fromNumber(e);return this._push(Yo,4,t.lo)._push(Yo,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(Wh,4,e)}double(e){return this._push(Yh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(zl,1,0):this.uint32(t)._push(Lx,t,e)}string(e){let t=Jh(e);return t!==0?this.uint32(t)._push(dl,t,e):this._push(zl,1,0)}fork(){return this.states=new Kl(this),this.head=this.tail=new En($l,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new En($l,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=Nx(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function zl(r,e,t){e[t]=r&255}function Cx(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ql=class extends En{next;constructor(e,t){super(Cx,e,t),this.next=void 0}};function gs(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 Yo(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 Lx(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Xo.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Ox,e,r),this},Xo.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Dx,e,r),this});function Ox(r,e,t){e.set(r,t)}function Dx(r,e,t){r.length<40?dl(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(P(r),t)}function Gl(){return new Xo}function _t(r,e){let t=Gl();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var jn;(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"})(jn||(jn={}));function ys(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function vn(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 ys("enum",jn.VARINT,t,n)}function It(r,e){return ys("message",jn.LENGTH_DELIMITED,r,e)}var Px=Symbol.for("nodejs.util.inspect.custom"),xd=Object.values(qr).map(r=>r.decoder).reduce((r,e)=>r.or(e),qr.identity.decoder),Ed=114,Wl=36,jl=37,Zo=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()})`}[zo]=!0;toString(){return this.string==null&&(this.string=ge.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return z.createV1(Ed,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ne(this.multihash.bytes,e);if(typeof e=="string")return Lt(e).equals(this);if(e?.multihash?.bytes!=null)return ne(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Px](){return`PeerId(${this.toString()})`}},Yn=class extends Zo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Xn=class extends Zo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Zn=class extends Zo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function Lt(r,e){if(e=e??xd,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Xe(ge.decode(`z${r}`));return r.startsWith("12D")?new Xn({multihash:t}):r.startsWith("16U")?new Zn({multihash:t}):new Yn({multihash:t})}return Jo(xd.decode(r))}function Jo(r){try{let e=Xe(r);if(e.code===Be.code){if(e.digest.length===Wl)return new Xn({multihash:e});if(e.digest.length===jl)return new Zn({multihash:e})}if(e.code===Re.code)return new Yn({multihash:e})}catch{return Ux(z.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Ux(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Ed)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Re.code)return new Yn({multihash:r.multihash});if(e.code===Be.code){if(e.digest.length===Wl)return new Xn({multihash:r.multihash});if(e.digest.length===jl)return new Zn({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function vd(r,e){return r.length===Wl?new Xn({multihash:Xt(Be.code,r),privateKey:e}):r.length===jl?new Zn({multihash:Xt(Be.code,r),privateKey:e}):new Yn({multihash:await Re.digest(r),publicKey:r,privateKey:e})}var Ze={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 fu={};Se(fu,{Ed25519PrivateKey:()=>In,Ed25519PublicKey:()=>ti,generateKeyPair:()=>W1,generateKeyPairFromSeed:()=>Yd,unmarshalEd25519PrivateKey:()=>q1,unmarshalEd25519PublicKey:()=>G1});function Rt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Jn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Fx(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Qn(r,...e){if(!Fx(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");Jn(r.outputLen),Jn(r.blockLen)}function eo(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 Sd(r,e){Qn(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var bs=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var ro=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Ot=(r,e)=>r<<32-e|r>>>e;var dk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Mx=async()=>{};async function Ad(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 Mx(),n+=i)}}function Yl(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Gr(r){return typeof r=="string"&&(r=Yl(r)),Qn(r),r}function xs(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Qn(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 to=class{clone(){return this._cloneInto()}},Vx={}.toString;function _d(r,e){if(e!==void 0&&Vx.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Es(r){let e=n=>r().update(Gr(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function no(r=32){if(bs&&typeof bs.getRandomValues=="function")return bs.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Hx(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,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,a,n)}var Id=(r,e,t)=>r&e^~r&t,Rd=(r,e,t)=>r&e^r&t^e&t,oo=class extends to{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=ro(this.buffer)}update(e){eo(this);let{view:t,buffer:n,blockLen:o}=this;e=Gr(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=ro(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){eo(this),Sd(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;Hx(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=ro(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],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 vs=BigInt(4294967295),Xl=BigInt(32);function kd(r,e=!1){return e?{h:Number(r&vs),l:Number(r>>Xl&vs)}:{h:Number(r>>Xl&vs)|0,l:Number(r&vs)|0}}function $x(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}=kd(r[o],e);[t[o],n[o]]=[i,s]}return[t,n]}var zx=(r,e)=>BigInt(r>>>0)<<Xl|BigInt(e>>>0),Kx=(r,e,t)=>r>>>t,qx=(r,e,t)=>r<<32-t|e>>>t,Gx=(r,e,t)=>r>>>t|e<<32-t,Wx=(r,e,t)=>r<<32-t|e>>>t,jx=(r,e,t)=>r<<64-t|e>>>t-32,Yx=(r,e,t)=>r>>>t-32|e<<64-t,Xx=(r,e)=>e,Zx=(r,e)=>r,Jx=(r,e,t)=>r<<t|e>>>32-t,Qx=(r,e,t)=>e<<t|r>>>32-t,e1=(r,e,t)=>e<<t-32|r>>>64-t,t1=(r,e,t)=>r<<t-32|e>>>64-t;function r1(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var n1=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),o1=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,i1=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),s1=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,a1=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),c1=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var l1={fromBig:kd,split:$x,toBig:zx,shrSH:Kx,shrSL:qx,rotrSH:Gx,rotrSL:Wx,rotrBH:jx,rotrBL:Yx,rotr32H:Xx,rotr32L:Zx,rotlSH:Jx,rotlSL:Qx,rotlBH:e1,rotlBL:t1,add:r1,add3L:n1,add3H:o1,add4L:i1,add4H:s1,add5H:c1,add5L:a1},j=l1;var[u1,f1]=j.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Wr=new Uint32Array(80),jr=new Uint32Array(80),Zl=class extends oo{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:p,Gh:h,Gl:m,Hh:d,Hl:y}=this;return[e,t,n,o,i,s,a,c,l,u,f,p,h,m,d,y]}set(e,t,n,o,i,s,a,c,l,u,f,p,h,m,d,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=l|0,this.El=u|0,this.Fh=f|0,this.Fl=p|0,this.Gh=h|0,this.Gl=m|0,this.Hh=d|0,this.Hl=y|0}process(e,t){for(let x=0;x<16;x++,t+=4)Wr[x]=e.getUint32(t),jr[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let E=Wr[x-15]|0,v=jr[x-15]|0,_=j.rotrSH(E,v,1)^j.rotrSH(E,v,8)^j.shrSH(E,v,7),S=j.rotrSL(E,v,1)^j.rotrSL(E,v,8)^j.shrSL(E,v,7),A=Wr[x-2]|0,L=jr[x-2]|0,U=j.rotrSH(A,L,19)^j.rotrBH(A,L,61)^j.shrSH(A,L,6),O=j.rotrSL(A,L,19)^j.rotrBL(A,L,61)^j.shrSL(A,L,6),$=j.add4L(S,O,jr[x-7],jr[x-16]),C=j.add4H($,_,U,Wr[x-7],Wr[x-16]);Wr[x]=C|0,jr[x]=$|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:p,Fh:h,Fl:m,Gh:d,Gl:y,Hh:g,Hl:b}=this;for(let x=0;x<80;x++){let E=j.rotrSH(f,p,14)^j.rotrSH(f,p,18)^j.rotrBH(f,p,41),v=j.rotrSL(f,p,14)^j.rotrSL(f,p,18)^j.rotrBL(f,p,41),_=f&h^~f&d,S=p&m^~p&y,A=j.add5L(b,v,S,f1[x],jr[x]),L=j.add5H(A,g,E,_,u1[x],Wr[x]),U=A|0,O=j.rotrSH(n,o,28)^j.rotrBH(n,o,34)^j.rotrBH(n,o,39),$=j.rotrSL(n,o,28)^j.rotrBL(n,o,34)^j.rotrBL(n,o,39),C=n&i^n&a^i&a,ee=o&s^o&c^s&c;g=d|0,b=y|0,d=h|0,y=m|0,h=f|0,m=p|0,{h:f,l:p}=j.add(l|0,u|0,L|0,U|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let k=j.add3L(U,$,ee);n=j.add3H(k,L,O,C),o=k|0}({h:n,l:o}=j.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=j.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=j.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=j.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:p}=j.add(this.Eh|0,this.El|0,f|0,p|0),{h,l:m}=j.add(this.Fh|0,this.Fl|0,h|0,m|0),{h:d,l:y}=j.add(this.Gh|0,this.Gl|0,d|0,y|0),{h:g,l:b}=j.add(this.Hh|0,this.Hl|0,g|0,b|0),this.set(n,o,i,s,a,c,l,u,f,p,h,m,d,y,g,b)}roundClean(){Wr.fill(0),jr.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 io=Es(()=>new Zl);var As={};Se(As,{abytes:()=>so,bitGet:()=>w1,bitLen:()=>y1,bitMask:()=>Qo,bitSet:()=>b1,bytesToHex:()=>dr,bytesToNumberBE:()=>pr,bytesToNumberLE:()=>Xr,concatBytes:()=>mr,createHmacDrbg:()=>eu,ensureBytes:()=>be,equalBytes:()=>m1,hexToBytes:()=>Sn,hexToNumber:()=>Ql,isBytes:()=>Yr,numberToBytesBE:()=>Zr,numberToBytesLE:()=>An,numberToHexUnpadded:()=>Cd,numberToVarBytesBE:()=>p1,utf8ToBytes:()=>g1,validateObject:()=>Zt});var Nd=BigInt(0),Ss=BigInt(1),h1=BigInt(2);function Yr(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function so(r){if(!Yr(r))throw new Error("Uint8Array expected")}var d1=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function dr(r){so(r);let e="";for(let t=0;t<r.length;t++)e+=d1[r[t]];return e}function Cd(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Ql(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var hr={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Bd(r){if(r>=hr._0&&r<=hr._9)return r-hr._0;if(r>=hr._A&&r<=hr._F)return r-(hr._A-10);if(r>=hr._a&&r<=hr._f)return r-(hr._a-10)}function Sn(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=Bd(r.charCodeAt(i)),a=Bd(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 pr(r){return Ql(dr(r))}function Xr(r){return so(r),Ql(dr(Uint8Array.from(r).reverse()))}function Zr(r,e){return Sn(r.toString(16).padStart(e*2,"0"))}function An(r,e){return Zr(r,e).reverse()}function p1(r){return Sn(Cd(r))}function be(r,e,t){let n;if(typeof e=="string")try{n=Sn(e)}catch(i){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${i}`)}else if(Yr(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 mr(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];so(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 m1(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 g1(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function y1(r){let e;for(e=0;r>Nd;r>>=Ss,e+=1);return e}function w1(r,e){return r>>BigInt(e)&Ss}function b1(r,e,t){return r|(t?Ss:Nd)<<BigInt(e)}var Qo=r=>(h1<<BigInt(r-1))-Ss,Jl=r=>new Uint8Array(r),Td=r=>Uint8Array.from(r);function eu(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=Jl(r),o=Jl(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>t(o,n,...f),c=(f=Jl())=>{o=a(Td([0]),f),n=a(),f.length!==0&&(o=a(Td([1]),f),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<e;){n=a();let h=n.slice();p.push(h),f+=n.length}return mr(...p)};return(f,p)=>{s(),c(f);let h;for(;!(h=p(l()));)c();return s(),h}}var x1={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"||Yr(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 Zt(r,e,t={}){let n=(o,i,s)=>{let a=x1[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 ke=BigInt(0),he=BigInt(1),_n=BigInt(2),E1=BigInt(3),tu=BigInt(4),Ld=BigInt(5),Od=BigInt(8),v1=BigInt(9),S1=BigInt(16);function ce(r,e){let t=r%e;return t>=ke?t:e+t}function A1(r,e,t){if(t<=ke||e<ke)throw new Error("Expected power/modulo > 0");if(t===he)return ke;let n=he;for(;e>ke;)e&he&&(n=n*r%t),r=r*r%t,e>>=he;return n}function de(r,e,t){let n=r;for(;e-- >ke;)n*=n,n%=t;return n}function _s(r,e){if(r===ke||e<=ke)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=ce(r,e),n=e,o=ke,i=he,s=he,a=ke;for(;t!==ke;){let l=n/t,u=n%t,f=o-s*l,p=i-a*l;n=t,t=u,o=s,i=a,s=f,a=p}if(n!==he)throw new Error("invert: does not exist");return ce(o,e)}function _1(r){let e=(r-he)/_n,t,n,o;for(t=r-he,n=0;t%_n===ke;t/=_n,n++);for(o=_n;o<r&&A1(o,e,r)!==r-he;o++);if(n===1){let s=(r+he)/tu;return function(c,l){let u=c.pow(l,s);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let i=(t+he)/_n;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),t),f=a.pow(c,i),p=a.pow(c,t);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let h=1;for(let d=a.sqr(p);h<l&&!a.eql(d,a.ONE);h++)d=a.sqr(d);let m=a.pow(u,he<<BigInt(l-h-1));u=a.sqr(m),f=a.mul(f,m),p=a.mul(p,u),l=h}return f}}function I1(r){if(r%tu===E1){let e=(r+he)/tu;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%Od===Ld){let e=(r-Ld)/Od;return function(n,o){let i=n.mul(o,_n),s=n.pow(i,e),a=n.mul(o,s),c=n.mul(n.mul(a,_n),s),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%S1,_1(r)}var Dd=(r,e)=>(ce(r,e)&he)===he,R1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ru(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=R1.reduce((n,o)=>(n[o]="function",n),e);return Zt(r,t)}function k1(r,e,t){if(t<ke)throw new Error("Expected power > 0");if(t===ke)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>ke;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function B1(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 nu(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Is(r,e,t=!1,n={}){if(r<=ke)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:i}=nu(r,e);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=I1(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:i,MASK:Qo(o),ZERO:ke,ONE:he,create:c=>ce(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ke<=c&&c<r},is0:c=>c===ke,isOdd:c=>(c&he)===he,neg:c=>ce(-c,r),eql:(c,l)=>c===l,sqr:c=>ce(c*c,r),add:(c,l)=>ce(c+l,r),sub:(c,l)=>ce(c-l,r),mul:(c,l)=>ce(c*l,r),pow:(c,l)=>k1(a,c,l),div:(c,l)=>ce(c*_s(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>_s(c,r),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>B1(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>t?An(c,i):Zr(c,i),fromBytes:c=>{if(c.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);return t?Xr(c):pr(c)}});return Object.freeze(a)}function Pd(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 Ud(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 ou(r){let e=Ud(r);return e+Math.ceil(e/2)}function Fd(r,e,t=!1){let n=r.length,o=Ud(e),i=ou(e);if(n<16||n<i||n>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);let s=t?pr(r):Xr(r),a=ce(s,e-he)+he;return t?An(a,o):Zr(a,o)}var N1=BigInt(0),iu=BigInt(1);function Rs(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>N1;)i&iu&&(s=s.add(a)),a=a.double(),i>>=iu;return s},precomputeWindow(o,i){let{windows:s,windowSize:a}=n(i),c=[],l=o,u=l;for(let f=0;f<s;f++){u=l,c.push(u);for(let p=1;p<a;p++)u=u.add(l),c.push(u);l=u.double()}return c},wNAF(o,i,s){let{windows:a,windowSize:c}=n(o),l=r.ZERO,u=r.BASE,f=BigInt(2**o-1),p=2**o,h=BigInt(o);for(let m=0;m<a;m++){let d=m*c,y=Number(s&f);s>>=h,y>c&&(y-=p,s+=iu);let g=d,b=d+Math.abs(y)-1,x=m%2!==0,E=y<0;y===0?u=u.add(t(x,i[g])):l=l.add(t(E,i[b]))}return{p:l,f:u}},wNAFCached(o,i,s,a){let c=o._WINDOW_SIZE||1,l=i.get(o);return l||(l=this.precomputeWindow(o,c),c!==1&&i.set(o,a(l))),this.wNAF(c,l,s)}}}function ei(r){return ru(r.Fp),Zt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nu(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Dt=BigInt(0),dt=BigInt(1),ks=BigInt(2),C1=BigInt(8),L1={zip215:!0};function O1(r){let e=ei(r);return Zt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Bs(r){let e=O1(r),{Fp:t,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=e,l=ks<<BigInt(a*8)-dt,u=t.create,f=e.uvRatio||((B,I)=>{try{return{isValid:!0,value:t.sqrt(B*t.inv(I))}}catch{return{isValid:!1,value:Dt}}}),p=e.adjustScalarBytes||(B=>B),h=e.domain||((B,I,M)=>{if(I.length||M)throw new Error("Contexts/pre-hash are not supported");return B}),m=B=>typeof B=="bigint"&&Dt<B,d=(B,I)=>m(B)&&m(I)&&B<I,y=B=>B===Dt||d(B,l);function g(B,I){if(d(B,I))return B;throw new Error(`Expected valid scalar < ${I}, got ${typeof B} ${B}`)}function b(B){return B===Dt?B:g(B,n)}let x=new Map;function E(B){if(!(B instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(I,M,K,W){if(this.ex=I,this.ey=M,this.ez=K,this.et=W,!y(I))throw new Error("x required");if(!y(M))throw new Error("y required");if(!y(K))throw new Error("z required");if(!y(W))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(I){if(I instanceof v)throw new Error("extended point not allowed");let{x:M,y:K}=I||{};if(!y(M)||!y(K))throw new Error("invalid affine point");return new v(M,K,dt,u(M*K))}static normalizeZ(I){let M=t.invertBatch(I.map(K=>K.ez));return I.map((K,W)=>K.toAffine(M[W])).map(v.fromAffine)}_setWindowSize(I){this._WINDOW_SIZE=I,x.delete(this)}assertValidity(){let{a:I,d:M}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:K,ey:W,ez:X,et:Z}=this,ie=u(K*K),Q=u(W*W),te=u(X*X),ve=u(te*te),ye=u(ie*I),Ce=u(te*u(ye+Q)),Le=u(ve+u(M*u(ie*Q)));if(Ce!==Le)throw new Error("bad point: equation left != right (1)");let Ie=u(K*W),$e=u(X*Z);if(Ie!==$e)throw new Error("bad point: equation left != right (2)")}equals(I){E(I);let{ex:M,ey:K,ez:W}=this,{ex:X,ey:Z,ez:ie}=I,Q=u(M*ie),te=u(X*W),ve=u(K*ie),ye=u(Z*W);return Q===te&&ve===ye}is0(){return this.equals(v.ZERO)}negate(){return new v(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:I}=e,{ex:M,ey:K,ez:W}=this,X=u(M*M),Z=u(K*K),ie=u(ks*u(W*W)),Q=u(I*X),te=M+K,ve=u(u(te*te)-X-Z),ye=Q+Z,Ce=ye-ie,Le=Q-Z,Ie=u(ve*Ce),$e=u(ye*Le),cr=u(ve*Le),yn=u(Ce*ye);return new v(Ie,$e,yn,cr)}add(I){E(I);let{a:M,d:K}=e,{ex:W,ey:X,ez:Z,et:ie}=this,{ex:Q,ey:te,ez:ve,et:ye}=I;if(M===BigInt(-1)){let Bh=u((X-W)*(te+Q)),Th=u((X+W)*(te-Q)),el=u(Th-Bh);if(el===Dt)return this.double();let Nh=u(Z*ks*ye),Ch=u(ie*ks*ve),Lh=Ch+Nh,Oh=Th+Bh,Dh=Ch-Nh,jw=u(Lh*el),Yw=u(Oh*Dh),Xw=u(Lh*Dh),Zw=u(el*Oh);return new v(jw,Yw,Zw,Xw)}let Ce=u(W*Q),Le=u(X*te),Ie=u(ie*K*ye),$e=u(Z*ve),cr=u((W+X)*(Q+te)-Ce-Le),yn=$e-Ie,Ho=$e+Ie,kh=u(Le-M*Ce),Kw=u(cr*yn),qw=u(Ho*kh),Gw=u(cr*kh),Ww=u(yn*Ho);return new v(Kw,qw,Ww,Gw)}subtract(I){return this.add(I.negate())}wNAF(I){return A.wNAFCached(this,x,I,v.normalizeZ)}multiply(I){let{p:M,f:K}=this.wNAF(g(I,n));return v.normalizeZ([M,K])[0]}multiplyUnsafe(I){let M=b(I);return M===Dt?S:this.equals(S)||M===dt?this:this.equals(_)?this.wNAF(M).p:A.unsafeLadder(this,M)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,n).is0()}toAffine(I){let{ex:M,ey:K,ez:W}=this,X=this.is0();I==null&&(I=X?C1:t.inv(W));let Z=u(M*I),ie=u(K*I),Q=u(W*I);if(X)return{x:Dt,y:dt};if(Q!==dt)throw new Error("invZ was invalid");return{x:Z,y:ie}}clearCofactor(){let{h:I}=e;return I===dt?this:this.multiplyUnsafe(I)}static fromHex(I,M=!1){let{d:K,a:W}=e,X=t.BYTES;I=be("pointHex",I,X);let Z=I.slice(),ie=I[X-1];Z[X-1]=ie&-129;let Q=Xr(Z);Q===Dt||(M?g(Q,l):g(Q,t.ORDER));let te=u(Q*Q),ve=u(te-dt),ye=u(K*te-W),{isValid:Ce,value:Le}=f(ve,ye);if(!Ce)throw new Error("Point.fromHex: invalid y coordinate");let Ie=(Le&dt)===dt,$e=(ie&128)!==0;if(!M&&Le===Dt&&$e)throw new Error("Point.fromHex: x=0 and x_0=1");return $e!==Ie&&(Le=u(-Le)),v.fromAffine({x:Le,y:Q})}static fromPrivateKey(I){return O(I).point}toRawBytes(){let{x:I,y:M}=this.toAffine(),K=An(M,t.BYTES);return K[K.length-1]|=I&dt?128:0,K}toHex(){return dr(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,dt,u(e.Gx*e.Gy)),v.ZERO=new v(Dt,dt,dt,Dt);let{BASE:_,ZERO:S}=v,A=Rs(v,a*8);function L(B){return ce(B,n)}function U(B){return L(Xr(B))}function O(B){let I=a;B=be("private key",B,I);let M=be("hashed private key",i(B),2*I),K=p(M.slice(0,I)),W=M.slice(I,2*I),X=U(K),Z=_.multiply(X),ie=Z.toRawBytes();return{head:K,prefix:W,scalar:X,point:Z,pointBytes:ie}}function $(B){return O(B).pointBytes}function C(B=new Uint8Array,...I){let M=mr(...I);return U(i(h(M,be("context",B),!!o)))}function ee(B,I,M={}){B=be("message",B),o&&(B=o(B));let{prefix:K,scalar:W,pointBytes:X}=O(I),Z=C(M.context,K,B),ie=_.multiply(Z).toRawBytes(),Q=C(M.context,ie,X,B),te=L(Z+Q*W);b(te);let ve=mr(ie,An(te,t.BYTES));return be("result",ve,a*2)}let k=L1;function T(B,I,M,K=k){let{context:W,zip215:X}=K,Z=t.BYTES;B=be("signature",B,2*Z),I=be("message",I),o&&(I=o(I));let ie=Xr(B.slice(Z,2*Z)),Q,te,ve;try{Q=v.fromHex(M,X),te=v.fromHex(B.slice(0,Z),X),ve=_.multiplyUnsafe(ie)}catch{return!1}if(!X&&Q.isSmallOrder())return!1;let ye=C(W,te.toRawBytes(),Q.toRawBytes(),I);return te.add(Q.multiplyUnsafe(ye)).subtract(ve).clearCofactor().equals(v.ZERO)}return _._setWindowSize(8),{CURVE:e,getPublicKey:$,sign:ee,verify:T,ExtendedPoint:v,utils:{getExtendedPublicKey:O,randomPrivateKey:()=>s(t.BYTES),precompute(B=8,I=v.BASE){return I._setWindowSize(B),I.multiply(BigInt(3)),I}}}}var au=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Md=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Dk=BigInt(0),D1=BigInt(1),su=BigInt(2),P1=BigInt(5),Vd=BigInt(10),U1=BigInt(20),F1=BigInt(40),Hd=BigInt(80);function M1(r){let e=au,n=r*r%e*r%e,o=de(n,su,e)*n%e,i=de(o,D1,e)*r%e,s=de(i,P1,e)*i%e,a=de(s,Vd,e)*s%e,c=de(a,U1,e)*a%e,l=de(c,F1,e)*c%e,u=de(l,Hd,e)*l%e,f=de(u,Hd,e)*l%e,p=de(f,Vd,e)*s%e;return{pow_p_5_8:de(p,su,e)*r%e,b2:n}}function V1(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function H1(r,e){let t=au,n=ce(e*e*e,t),o=ce(n*n*e,t),i=M1(r*o).pow_p_5_8,s=ce(r*n*i,t),a=ce(e*s*s,t),c=s,l=ce(s*Md,t),u=a===r,f=a===ce(-r,t),p=a===ce(-r*Md,t);return u&&(s=c),(f||p)&&(s=l),Dd(s,t)&&(s=ce(-s,t)),{isValid:u||f,value:s}}var gr=Is(au,void 0,!0),cu={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:gr,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:io,randomBytes:no,adjustScalarBytes:V1,uvRatio:H1},ao=Bs(cu);function $d(r,e,t){if(e.length>255)throw new Error("Context is too big");return xs(Yl("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var Pk=Bs({...cu,domain:$d}),Uk=Bs({...cu,domain:$d,prehash:io});var $1=(gr.ORDER+BigInt(3))/BigInt(8),Fk=gr.pow(su,$1),Mk=gr.sqrt(gr.neg(gr.ONE)),Vk=(gr.ORDER-BigInt(5))/BigInt(8),Hk=BigInt(486662);var $k=Pd(gr,gr.neg(BigInt(486664)));var zk=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Kk=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),qk=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Gk=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Wk=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var co=32,yr=64,Ts=32;function zd(){let r=ao.utils.randomPrivateKey(),e=ao.getPublicKey(r);return{privateKey:Wd(r,e),publicKey:e}}function Kd(r){if(r.length!==Ts)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:Wd(e,t),publicKey:t}}function qd(r,e){let t=r.subarray(0,Ts);return ao.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Gd(r,e,t){return ao.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Wd(r,e){let t=new Uint8Array(yr);for(let n=0;n<Ts;n++)t[n]=r[n],t[Ts+n]=e[n];return t}var lu={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function jd(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=Ze.get();t*=8;async function c(f,p){let h=a.getRandomValues(new Uint8Array(i)),m=a.getRandomValues(new Uint8Array(n)),d={name:e,iv:m};typeof p=="string"&&(p=P(p));let y;if(p.length===0){y=await a.subtle.importKey("jwk",lu,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",lu,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(d,y,f);return ue([h,d.iv,new Uint8Array(g)])}async function l(f,p){let h=f.subarray(0,i),m=f.subarray(i,i+n),d=f.subarray(i+n),y={name:e,iv:m};typeof p=="string"&&(p=P(p));let g;if(p.length===0)try{let x={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},E=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,E,{name:e,length:t},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",lu,{name:"AES-GCM"},!0,["decrypt"])}else{let x={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},E=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,E,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(y,g,d);return new Uint8Array(b)}return{encrypt:c,decrypt:l}}async function lo(r,e){let n=await jd().encrypt(r,e);return it.encode(n)}var pe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(pe||(pe={}));var uu;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(uu||(uu={}));(function(r){r.codec=()=>vn(uu)})(pe||(pe={}));var Jt;(function(r){let e;r.codec=()=>(e==null&&(e=It((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),pe.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=pe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>_t(t,r.codec()),r.decode=t=>St(t,r.codec())})(Jt||(Jt={}));var Qt;(function(r){let e;r.codec=()=>(e==null&&(e=It((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),pe.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=pe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>_t(t,r.codec()),r.decode=t=>St(t,r.codec())})(Qt||(Qt={}));var ti=class{_key;constructor(e){this._key=uo(e,co)}verify(e,t){return Gd(this._key,t,e)}marshal(){return this._key}get bytes(){return Jt.encode({Type:pe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}},In=class{_key;_publicKey;constructor(e,t){this._key=uo(e,yr),this._publicKey=uo(t,co)}sign(e){return qd(this._key,e)}get public(){return new ti(this._publicKey)}marshal(){return this._key}get bytes(){return Qt.encode({Type:pe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return Rt(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Be.digest(this.public.bytes);return ge.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return lo(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function q1(r){if(r.length>yr){r=uo(r,yr+co);let n=r.subarray(0,yr),o=r.subarray(yr,r.length);return new In(n,o)}r=uo(r,yr);let e=r.subarray(0,yr),t=r.subarray(co);return new In(e,t)}function G1(r){return r=uo(r,co),new ti(r)}async function W1(){let{privateKey:r,publicKey:e}=zd();return new In(r,e)}async function Yd(r){let{privateKey:e,publicKey:t}=Kd(r);return new In(e,t)}function uo(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}function G(r,e="utf8"){let t=ms[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Eu={};Se(Eu,{MAX_RSA_KEY_SIZE:()=>di,RsaPrivateKey:()=>go,RsaPublicKey:()=>hi,fromJwk:()=>xE,generateKeyPair:()=>EE,unmarshalRsaPrivateKey:()=>bu,unmarshalRsaPublicKey:()=>bE});function er(r){if(isNaN(r)||r<=0)throw new N("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return no(r)}var tn={};Se(tn,{exportToPem:()=>pE,importFromPem:()=>mE,jwkToPkcs1:()=>uE,jwkToPkix:()=>hE,pkcs1ToJwk:()=>lE,pkixToJwk:()=>fE});var Cs=class extends to{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ws(e);let n=Gr(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 eo(this),this.iHash.update(e),this}digestInto(e){eo(this),Qn(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()}},ri=(r,e,t)=>new Cs(r,e).update(t).digest();ri.create=(r,e)=>new Cs(r,e);function j1(r,e,t,n){ws(r);let o=_d({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(Jn(i),Jn(s),Jn(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Gr(e),l=Gr(t),u=new Uint8Array(s),f=ri.create(r,c),p=f._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:u,PRF:f,PRFSalt:p}}function Y1(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function hu(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=j1(r,e,t,n),u,f=new Uint8Array(4),p=ro(f),h=new Uint8Array(c.outputLen);for(let m=1,d=0;d<i;m++,d+=c.outputLen){let y=a.subarray(d,d+c.outputLen);p.setInt32(0,m,!1),(u=l._cloneInto(u)).update(f).digestInto(h),y.set(h.subarray(0,y.length)),await Ad(o-1,s,()=>{c._cloneInto(u).update(h).digestInto(h);for(let g=0;g<y.length;g++)y[g]^=h[g]})}return Y1(c,l,a,u,h)}var J=re(Xd());function Rn(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 Jr(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 l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*e);l[i-u-1]=Math.floor(o/f),o-=l[i-u-1]*f}return c}s*=Math.pow(2,e)}return new ArrayBuffer(0)}function Ds(...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 pu(){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=Rn(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,Rn(i,8)-n}function Zd(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=Jr(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Jr(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 Jd(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 st(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 vB=Math.log(2);function Ps(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function mu(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 vr(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 oi=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return mu(this.items)}},ni=[new Uint8Array([1])],Qd="0123456789";var po="",Ut=new ArrayBuffer(0),gu=new Uint8Array(0),ii="EndOfContent",tp="OCTET STRING",rp="BIT STRING";function Sr(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?J.BufferSourceConverter.toUint8Array(i.valueHex):gu}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,i){let s=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!vr(this,s,o,i))return-1;let a=o+i;return this.valueHexView=s.subarray(o,a),this.valueHexView.length?(this.blockLength=i,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Ut)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:J.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var br=class{constructor({blockLength:e=0,error:t=po,warnings:n=[],valueBeforeDecode:o=gu}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=J.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:J.Convert.ToHex(this.valueBeforeDecodeView)}}};br.NAME="baseBlock";var Ge=class extends br{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'")}};Ge.NAME="valueBlock";var Us=class extends Sr(br){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?J.BufferSourceConverter.toUint8Array(e.valueHex):gu,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",Ut}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=Jr(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=J.BufferSourceConverter.toUint8Array(e);if(!vr(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,l=this.valueHexView=new Uint8Array(255),u=255;for(;i[c]&128;){if(l[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let p=new Uint8Array(u);for(let h=0;h<l.length;h++)p[h]=l[h];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=i[c]&127;let f=new Uint8Array(c);for(let p=0;p<c;p++)f[p]=l[p];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=Rn(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Us.NAME="identificationBlock";var Fs=class extends br{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=J.BufferSourceConverter.toUint8Array(e);if(!vr(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=Rn(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=Jr(this.length,8);if(o.byteLength>127)return this.error="Too big length",Ut;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}}};Fs.NAME="lengthBlock";var F={},Ue=class extends br{constructor({name:e=po,optional:t=!1,primitiveSchema:n,...o}={},i){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Us(o),this.lenBlock=new Fs(o),this.valueBlock=i?new i(o):new Ge(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 oi;t||np(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?Ut: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():J.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${J.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 Jd(t,n)}};Ue.NAME="BaseBlock";function np(r){if(r instanceof F.Constructed)for(let e of r.valueBlock.value)np(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Ms=class extends Ue{constructor({value:e=po,...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}'`}};Ms.NAME="BaseStringBlock";var Vs=class extends Sr(Ge){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Vs.NAME="PrimitiveValueBlock";var op,Hs=class extends Ue{constructor(e={}){super(e,Vs),this.idBlock.isConstructed=!1}};op=Hs;F.Primitive=op;Hs.NAME="PRIMITIVE";function oE(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 xa(r,e=0,t=r.length){let n=e,o=new Ue({},Ge),i=new br;if(!vr(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=Ue;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=F.EndOfContent;break;case 1:c=F.Boolean;break;case 2:c=F.Integer;break;case 3:c=F.BitString;break;case 4:c=F.OctetString;break;case 5:c=F.Null;break;case 6:c=F.ObjectIdentifier;break;case 10:c=F.Enumerated;break;case 12:c=F.Utf8String;break;case 13:c=F.RelativeObjectIdentifier;break;case 14:c=F.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=F.Sequence;break;case 17:c=F.Set;break;case 18:c=F.NumericString;break;case 19:c=F.PrintableString;break;case 20:c=F.TeletexString;break;case 21:c=F.VideotexString;break;case 22:c=F.IA5String;break;case 23:c=F.UTCTime;break;case 24:c=F.GeneralizedTime;break;case 25:c=F.GraphicString;break;case 26:c=F.VisibleString;break;case 27:c=F.GeneralString;break;case 28:c=F.UniversalString;break;case 29:c=F.CharacterString;break;case 30:c=F.BmpString;break;case 31:c=F.DATE;break;case 32:c=F.TimeOfDay;break;case 33:c=F.DateTime;break;case 34:c=F.Duration;break;default:{let l=o.idBlock.isConstructed?new F.Constructed:new F.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?F.Constructed:F.Primitive}return o=oE(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 mo(r){if(!r.byteLength){let e=new Ue({},Ge);return e.error="Input buffer has zero length",{offset:-1,result:e}}return xa(J.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function iE(r,e){return r?1:e}var tr=class extends Ge{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=J.BufferSourceConverter.toUint8Array(e);if(!vr(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(;iE(this.isIndefiniteForm,n)>0;){let s=xa(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===ii)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ii?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){let n=t||new oi;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Ut:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};tr.NAME="ConstructedValueBlock";var ip,Qr=class extends Ue{constructor(e={}){super(e,tr),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=on;F.Constructed=Em;on.NAME="CONSTRUCTED";var da=class extends ze{fromBER(e,t,n){return t}toBER(e){return Mt}};da.override="EndOfContentValueBlock";var vm,pa=class extends Oe{constructor(e={}){super(e,da),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};vm=pa;F.EndOfContent=vm;pa.NAME=yi;var Sm,sn=class extends Oe{constructor(e={}){super(e,ze),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}`}};Sm=sn;F.Null=Sm;sn.NAME="NULL";var ma=class extends kr(ze){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=J.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=J.BufferSourceConverter.toUint8Array(e);return _r(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,Vu.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ma.NAME="BooleanValueBlock";var Am,ga=class extends Oe{constructor(e={}){super(e,ma),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}`}};Am=ga;F.Boolean=Am;ga.NAME="BOOLEAN";var ya=class extends kr(tr){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=tr.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===yi){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==ym)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?tr.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};ya.NAME="OctetStringValueBlock";var _m,Sr=class r extends Oe{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},ya),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=za(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?on.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${J.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 J.BufferSourceConverter.concat(e)}};_m=Sr;F.OctetString=_m;Sr.NAME=ym;var wa=class extends kr(tr){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=tr.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===yi){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==wm)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=J.BufferSourceConverter.toUint8Array(e);if(!_r(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=za(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 tr.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Mt;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}}};wa.NAME="BitStringValueBlock";var km,vo=class extends Oe{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},wa),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 on.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)}`}}};km=vo;F.BitString=km;vo.NAME=wm;var Im;function XE(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,l=0,f=c<s?s:c,u=0;for(let p=f;p>=0;p--,u++){switch(!0){case u<a.length:l=i[s-u]+a[c-u]+t[0];break;default:l=i[s-u]+t[0]}switch(t[0]=l/10,!0){case u>=i.length:i=sa(new Uint8Array([l%10]),i);break;default:i[s-u]=l%10}}return t[0]>0&&(i=sa(t,i)),i}function gm(r){if(r>=mi.length)for(let e=mi.length;e<=r;e++){let t=new Uint8Array([0]),n=mi[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=sa(t,n)),mi.push(n)}return mi[r]}function ZE(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,l,f=0;for(let u=c;u>=0;u--,f++)switch(l=i[s-f]-a[c-f]-t,!0){case l<0:t=1,i[s-f]=l+10;break;default:t=0,i[s-f]=l}if(t>0)for(let u=s-c+1;u>=0;u--,f++)if(l=i[s-f]-t,l<0)t=1,i[s-f]=l+10;else{t=0,i[s-f]=l;break}return i.slice()}var wi=class extends kr(ze){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=Vu.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(dm(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 l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=ZE(gm(n),t),s="-";break;default:t=XE(t,gm(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=mm.charAt(t[c]));return a===!1&&(s+=mm.charAt(0)),s}};Im=wi;wi.NAME="IntegerValueBlock";Object.defineProperty(Im.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Rm,Ae=class r extends Oe{constructor(e={}){super(e,wi),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return aa(),BigInt(this.valueBlock.toString())}static fromBigInt(e){aa();let t=BigInt(e),n=new gi,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(J.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${J.Convert.ToHex(a)}`)+t,f=J.BufferSourceConverter.toUint8Array(J.Convert.FromHex(l.toString(16)));f[0]|=128,n.write(f)}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()}`}};Rm=Ae;F.Integer=Rm;Ae.NAME="INTEGER";var Bm,ba=class extends Ae{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Bm=ba;F.Enumerated=Bm;ba.NAME="ENUMERATED";var bi=class extends kr(ze){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=J.BufferSourceConverter.toUint8Array(e);if(!_r(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=kn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){aa();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=nn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Mt;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=J.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}}};bi.NAME="sidBlock";var xa=class extends ze{constructor({value:e=So,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new bi;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,Mt;t.push(o)}return Mu(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 bi;if(o>Number.MAX_SAFE_INTEGER){aa();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}};xa.NAME="ObjectIdentifierValueBlock";var Tm,Vt=class extends Oe{constructor(e={}){super(e,xa),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()}}};Tm=Vt;F.ObjectIdentifier=Tm;Vt.NAME="OBJECT IDENTIFIER";var xi=class extends kr(vr){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=J.BufferSourceConverter.toUint8Array(e);if(!_r(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=kn(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=nn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Mt;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=J.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};xi.NAME="relativeSidBlock";var Ea=class extends ze{constructor({value:e=So,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new xi;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,Mt;n.push(i)}return Mu(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 xi;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}};Ea.NAME="RelativeObjectIdentifierValueBlock";var Nm,va=class extends Oe{constructor(e={}){super(e,Ea),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()}}};Nm=va;F.RelativeObjectIdentifier=Nm;va.NAME="RelativeObjectIdentifier";var Cm,Be=class extends on{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Cm=Be;F.Sequence=Cm;Be.NAME="SEQUENCE";var Lm,Sa=class extends on{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Lm=Sa;F.Set=Lm;Sa.NAME="SET";var Aa=class extends kr(ze){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=So}toJSON(){return{...super.toJSON(),value:this.value}}};Aa.NAME="StringValueBlock";var _a=class extends Aa{};_a.NAME="SimpleStringValueBlock";var Qe=class extends ua{constructor({...e}={}){super(e,_a)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,J.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}};Qe.NAME="SIMPLE STRING";var ka=class extends Qe{fromBuffer(e){this.valueBlock.valueHexView=J.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=J.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=J.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(J.Convert.FromUtf8String(e)),this.valueBlock.value=e}};ka.NAME="Utf8StringValueBlock";var Dm,Ar=class extends ka{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Dm=Ar;F.Utf8String=Dm;Ar.NAME="UTF8String";var Ia=class extends Qe{fromBuffer(e){this.valueBlock.value=J.Convert.ToUtf16String(e),this.valueBlock.valueHexView=J.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(J.Convert.FromUtf16String(e))}};Ia.NAME="BmpStringValueBlock";var Pm,Ra=class extends Ia{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Pm=Ra;F.BmpString=Pm;Ra.NAME="BMPString";var Ba=class extends Qe{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=nn(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}};Ba.NAME="UniversalStringValueBlock";var Om,Ta=class extends Ba{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Om=Ta;F.UniversalString=Om;Ta.NAME="UniversalString";var Um,Na=class extends Qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Um=Na;F.NumericString=Um;Na.NAME="NumericString";var Fm,Ca=class extends Qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Fm=Ca;F.PrintableString=Fm;Ca.NAME="PrintableString";var Vm,La=class extends Qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Vm=La;F.TeletexString=Vm;La.NAME="TeletexString";var Mm,Da=class extends Qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Mm=Da;F.VideotexString=Mm;Da.NAME="VideotexString";var Hm,Pa=class extends Qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Hm=Pa;F.IA5String=Hm;Pa.NAME="IA5String";var $m,Oa=class extends Qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};$m=Oa;F.GraphicString=$m;Oa.NAME="GraphicString";var Km,Ei=class extends Qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Km=Ei;F.VisibleString=Km;Ei.NAME="VisibleString";var qm,Ua=class extends Qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};qm=Ua;F.GeneralString=qm;Ua.NAME="GeneralString";var zm,Fa=class extends Qe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};zm=Fa;F.CharacterString=zm;Fa.NAME="CharacterString";var Gm,vi=class extends Ei{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,J.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]=st(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=st(this.month,2),t[2]=st(this.day,2),t[3]=st(this.hour,2),t[4]=st(this.minute,2),t[5]=st(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}}};Gm=vi;F.UTCTime=Gm;vi.NAME="UTCTime";var Wm,Va=class extends vi{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 u=new Number(e[e.length-1]);if(isNaN(u.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 u=1,p=n.indexOf("+"),h="";if(p===-1&&(p=n.indexOf("-"),u=-1),p!==-1){if(h=n.substring(p+1),n=n.substring(0,p),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(h.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*m,h.length===4){if(m=parseInt(h.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=u*m}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let u=new Number(`0${n.substring(l)}`);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");i=u.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*i;this.minute=Math.floor(u),u=60*(u-this.minute),this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*i;this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=1e3*i;this.millisecond=Math.floor(u)}break;default:throw new Error("Wrong input string for conversion")}let f=s.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let u=1;u<f.length;u++)switch(u){case 1:this.year=parseInt(f[u],10);break;case 2:this.month=parseInt(f[u],10);break;case 3:this.day=parseInt(f[u],10);break;case 4:this.hour=parseInt(f[u],10)+a;break;case 5:this.minute=parseInt(f[u],10)+c;break;case 6:this.second=parseInt(f[u],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let u=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=u.getUTCFullYear(),this.month=u.getUTCMonth(),this.day=u.getUTCDay(),this.hour=u.getUTCHours(),this.minute=u.getUTCMinutes(),this.second=u.getUTCSeconds(),this.millisecond=u.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(st(this.year,4)),t.push(st(this.month,2)),t.push(st(this.day,2)),t.push(st(this.hour,2)),t.push(st(this.minute,2)),t.push(st(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(st(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Wm=Va;F.GeneralizedTime=Wm;Va.NAME="GeneralizedTime";var jm,Ma=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};jm=Ma;F.DATE=jm;Ma.NAME="DATE";var Ym,Ha=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Ym=Ha;F.TimeOfDay=Ym;Ha.NAME="TimeOfDay";var Xm,$a=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Xm=$a;F.DateTime=Xm;$a.NAME="DateTime";var Zm,Ka=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Zm=Ka;F.Duration=Zm;Ka.NAME="Duration";var Jm,qa=class extends Ar{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Jm=qa;F.TIME=Jm;qa.NAME="TIME";function QE(r){let{result:e}=Ao(r),t=e.valueBlock.value;return{n:G(rr(t[1].toBigInt()),"base64url"),e:G(rr(t[2].toBigInt()),"base64url"),d:G(rr(t[3].toBigInt()),"base64url"),p:G(rr(t[4].toBigInt()),"base64url"),q:G(rr(t[5].toBigInt()),"base64url"),dp:G(rr(t[6].toBigInt()),"base64url"),dq:G(rr(t[7].toBigInt()),"base64url"),qi:G(rr(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function ev(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 Be({value:[new Ae({value:0}),Ae.fromBigInt(nr(O(r.n,"base64url"))),Ae.fromBigInt(nr(O(r.e,"base64url"))),Ae.fromBigInt(nr(O(r.d,"base64url"))),Ae.fromBigInt(nr(O(r.p,"base64url"))),Ae.fromBigInt(nr(O(r.q,"base64url"))),Ae.fromBigInt(nr(O(r.dp,"base64url"))),Ae.fromBigInt(nr(O(r.dq,"base64url"))),Ae.fromBigInt(nr(O(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function tv(r){let{result:e}=Ao(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:G(rr(t[0].toBigInt()),"base64url"),e:G(rr(t[1].toBigInt()),"base64url")}}function rv(r){if(r.n==null||r.e==null)throw new N("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Be({value:[new Be({value:[new Vt({value:"1.2.840.113549.1.1.1"}),new sn]}),new vo({valueHex:new Be({value:[Ae.fromBigInt(nr(O(r.n,"base64url"))),Ae.fromBigInt(nr(O(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function rr(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 nr(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 nv=16,$u=32,Ku=1e4;async function ov(r,e){let t=Je.get(),o=new Be({value:[new Ae({value:0}),new Be({value:[new Vt({value:"1.2.840.113549.1.1.1"}),new sn]}),new Sr({valueHex:r.marshal()})]}).toBER(),i=new Uint8Array(o,0,o.byteLength),s=er(nv),a=await Uu(mo,e,s,{c:Ku,dkLen:$u}),c=er(16),l=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},l,i),u=new Be({value:[new Sr({valueHex:s}),new Ae({value:Ku}),new Ae({value:$u}),new Be({value:[new Vt({value:"1.2.840.113549.2.11"}),new sn]})]}),p=new Be({value:[new Vt({value:"1.2.840.113549.1.5.13"}),new Be({value:[new Be({value:[new Vt({value:"1.2.840.113549.1.5.12"}),u]}),new Be({value:[new Vt({value:"2.16.840.1.101.3.4.1.42"}),new Sr({valueHex:c})]})]})]}),m=new Be({value:[p,new Sr({valueHex:f})]}).toBER(),d=new Uint8Array(m,0,m.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...G(d,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
8
|
-
`)}async function iv(r,e){let t=Je.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=O(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Ao(o),{iv:s,salt:a,iterations:c,keySize:l,cipherText:f}=sv(i),u=await Uu(mo,e,a,{c,dkLen:l}),p=await t.subtle.importKey("raw",u,"AES-CBC",!1,["decrypt"]),h=Si(await t.subtle.decrypt({name:"AES-CBC",iv:s},p,f)),{result:m}=Ao(h);n=Qm(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=O(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=Ao(o);n=Qm(i)}else throw new N("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return qu(n)}function sv(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=Si(i.valueBlock.value[0].getValue()),a=Ku,c=$u;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 l=e.valueBlock.value[1].valueBlock.value[1],f=l.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="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 u=Si(l.valueBlock.value[1].getValue());return{cipherText:Si(r.valueBlock.value[1].getValue()),salt:s,iterations:a,keySize:c,iv:u}}function Qm(r){return Si(r.valueBlock.value[2].getValue())}function Si(r){return new Uint8Array(r,0,r.byteLength)}async function eg(r){let e=await Je.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 ng(e);return{privateKey:t[0],publicKey:t[1]}}async function zu(r){let t=[await Je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await av(r)],n=await ng({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function tg(r,e){let t=await Je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Je.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function rg(r,e,t){let n=await Je.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Je.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function ng(r){if(r.privateKey==null||r.publicKey==null)throw new N("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Je.get().subtle.exportKey("jwk",r.privateKey),Je.get().subtle.exportKey("jwk",r.publicKey)])}async function av(r){return Je.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 Ga(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 O(r.n,"base64url").length*8}var _i=8192,Ai=class{_key;constructor(e){this._key=e}verify(e,t){return rg(this._key,t,e)}marshal(){return an.jwkToPkix(this._key)}get bytes(){return Jt.encode({Type:pe.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=ke.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}},_o=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return er(16)}sign(e){return tg(this._key,e)}get public(){if(this._publicKey==null)throw new N("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ai(this._publicKey)}marshal(){return an.jwkToPkcs1(this._key)}get bytes(){return Qt.encode({Type:pe.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=ke.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return G(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return an.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 qu(r){let e=an.pkcs1ToJwk(r);if(Ga(e)>_i)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await zu(e);return new _o(t.privateKey,t.publicKey)}function lv(r){let e=an.pkixToJwk(r);if(Ga(e)>_i)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Ai(e)}async function uv(r){if(Ga(r)>_i)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await zu(r);return new _o(e.privateKey,e.publicKey)}async function fv(r){if(r>_i)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await eg(r);return new _o(e.privateKey,e.publicKey)}var Zu={};Se(Zu,{Secp256k1PrivateKey:()=>Ii,Secp256k1PublicKey:()=>ki,generateKeyPair:()=>Av,unmarshalSecp256k1PrivateKey:()=>vv,unmarshalSecp256k1PublicKey:()=>Sv});var hv=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]),cn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ln=new Uint32Array(64),Wu=class extends po{constructor(){super(64,32,8,!1),this.A=cn[0]|0,this.B=cn[1]|0,this.C=cn[2]|0,this.D=cn[3]|0,this.E=cn[4]|0,this.F=cn[5]|0,this.G=cn[6]|0,this.H=cn[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 u=0;u<16;u++,t+=4)ln[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let p=ln[u-15],h=ln[u-2],m=Ut(p,7)^Ut(p,18)^p>>>3,d=Ut(h,17)^Ut(h,19)^h>>>10;ln[u]=d+ln[u-7]+m+ln[u-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){let p=Ut(a,6)^Ut(a,11)^Ut(a,25),h=f+p+$p(a,c,l)+hv[u]+ln[u]|0,d=(Ut(n,2)^Ut(n,13)^Ut(n,22))+Kp(n,o,i)|0;f=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+d|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(n,o,i,s,a,c,l,f)}roundClean(){ln.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var og=Gs(()=>new Wu);function dv(r){let e=hi(r);Zt(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:pv,hexToBytes:mv}=Ys,In={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=In;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:pv(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=In,t=typeof r=="string"?mv(r):r;go(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}=In._parseInt(t.subarray(2)),{d:s,l:a}=In._parseInt(i);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let f=l.toString(16);return f.length&1?`0${f}`:f},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),Tt=BigInt(1),MN=BigInt(2),ig=BigInt(3),HN=BigInt(4);function gv(r){let e=dv(r),{Fp:t}=e,n=e.toBytes||((m,d,y)=>{let w=d.toAffine();return wr(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),o=e.fromBytes||(m=>{let d=m.subarray(1),y=t.fromBytes(d.subarray(0,t.BYTES)),w=t.fromBytes(d.subarray(t.BYTES,2*t.BYTES));return{x:y,y:w}});function i(m){let{a:d,b:y}=e,w=t.sqr(m),x=t.mul(w,m);return t.add(t.add(x,t.mul(m,d)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function s(m){return typeof m=="bigint"&&Ir<m&&m<e.n}function a(m){if(!s(m))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(m){let{allowedPrivateKeyLengths:d,nByteLength:y,wrapPrivateKey:w,n:x}=e;if(d&&typeof m!="bigint"){if(en(m)&&(m=gr(m)),typeof m!="string"||!d.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let b;try{b=typeof m=="bigint"?m:yr(be("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return w&&(b=ce(b,x)),a(b),b}let l=new Map;function f(m){if(!(m instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(d,y,w){if(this.px=d,this.py=y,this.pz=w,d==null||!t.isValid(d))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(d){let{x:y,y:w}=d||{};if(!d||!t.isValid(y)||!t.isValid(w))throw new Error("invalid affine point");if(d instanceof u)throw new Error("projective point not allowed");let x=b=>t.eql(b,t.ZERO);return x(y)&&x(w)?u.ZERO:new u(y,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){let y=t.invertBatch(d.map(w=>w.pz));return d.map((w,x)=>w.toAffine(y[x])).map(u.fromAffine)}static fromHex(d){let y=u.fromAffine(o(be("pointHex",d)));return y.assertValidity(),y}static fromPrivateKey(d){return u.BASE.multiply(c(d))}_setWindowSize(d){this._WINDOW_SIZE=d,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:d,y}=this.toAffine();if(!t.isValid(d)||!t.isValid(y))throw new Error("bad point: x or y not FE");let w=t.sqr(y),x=i(d);if(!t.eql(w,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:d}=this.toAffine();if(t.isOdd)return!t.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){f(d);let{px:y,py:w,pz:x}=this,{px:b,py:A,pz:S}=d,R=t.eql(t.mul(y,S),t.mul(b,x)),v=t.eql(t.mul(w,S),t.mul(A,x));return R&&v}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:d,b:y}=e,w=t.mul(y,ig),{px:x,py:b,pz:A}=this,S=t.ZERO,R=t.ZERO,v=t.ZERO,E=t.mul(x,x),P=t.mul(b,b),U=t.mul(A,A),L=t.mul(x,b);return L=t.add(L,L),v=t.mul(x,A),v=t.add(v,v),S=t.mul(d,v),R=t.mul(w,U),R=t.add(S,R),S=t.sub(P,R),R=t.add(P,R),R=t.mul(S,R),S=t.mul(L,S),v=t.mul(w,v),U=t.mul(d,U),L=t.sub(E,U),L=t.mul(d,L),L=t.add(L,v),v=t.add(E,E),E=t.add(v,E),E=t.add(E,U),E=t.mul(E,L),R=t.add(R,E),U=t.mul(b,A),U=t.add(U,U),E=t.mul(U,L),S=t.sub(S,E),v=t.mul(U,P),v=t.add(v,v),v=t.add(v,v),new u(S,R,v)}add(d){f(d);let{px:y,py:w,pz:x}=this,{px:b,py:A,pz:S}=d,R=t.ZERO,v=t.ZERO,E=t.ZERO,P=e.a,U=t.mul(e.b,ig),L=t.mul(y,b),$=t.mul(w,A),C=t.mul(x,S),ee=t.add(y,w),I=t.add(b,A);ee=t.mul(ee,I),I=t.add(L,$),ee=t.sub(ee,I),I=t.add(y,x);let T=t.add(b,S);return I=t.mul(I,T),T=t.add(L,C),I=t.sub(I,T),T=t.add(w,x),R=t.add(A,S),T=t.mul(T,R),R=t.add($,C),T=t.sub(T,R),E=t.mul(P,I),R=t.mul(U,C),E=t.add(R,E),R=t.sub($,E),E=t.add($,E),v=t.mul(R,E),$=t.add(L,L),$=t.add($,L),C=t.mul(P,C),I=t.mul(U,I),$=t.add($,C),C=t.sub(L,C),C=t.mul(P,C),I=t.add(I,C),L=t.mul($,I),v=t.add(v,L),L=t.mul(T,I),R=t.mul(ee,R),R=t.sub(R,L),L=t.mul(ee,$),E=t.mul(T,E),E=t.add(E,L),new u(R,v,E)}subtract(d){return this.add(d.negate())}is0(){return this.equals(u.ZERO)}wNAF(d){return h.wNAFCached(this,l,d,y=>{let w=t.invertBatch(y.map(x=>x.pz));return y.map((x,b)=>x.toAffine(w[b])).map(u.fromAffine)})}multiplyUnsafe(d){let y=u.ZERO;if(d===Ir)return y;if(a(d),d===Tt)return this;let{endo:w}=e;if(!w)return h.unsafeLadder(this,d);let{k1neg:x,k1:b,k2neg:A,k2:S}=w.splitScalar(d),R=y,v=y,E=this;for(;b>Ir||S>Ir;)b&Tt&&(R=R.add(E)),S&Tt&&(v=v.add(E)),E=E.double(),b>>=Tt,S>>=Tt;return x&&(R=R.negate()),A&&(v=v.negate()),v=new u(t.mul(v.px,w.beta),v.py,v.pz),R.add(v)}multiply(d){a(d);let y=d,w,x,{endo:b}=e;if(b){let{k1neg:A,k1:S,k2neg:R,k2:v}=b.splitScalar(y),{p:E,f:P}=this.wNAF(S),{p:U,f:L}=this.wNAF(v);E=h.constTimeNegate(A,E),U=h.constTimeNegate(R,U),U=new u(t.mul(U.px,b.beta),U.py,U.pz),w=E.add(U),x=P.add(L)}else{let{p:A,f:S}=this.wNAF(y);w=A,x=S}return u.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(d,y,w){let x=u.BASE,b=(S,R)=>R===Ir||R===Tt||!S.equals(x)?S.multiplyUnsafe(R):S.multiply(R),A=b(this,y).add(b(d,w));return A.is0()?void 0:A}toAffine(d){let{px:y,py:w,pz:x}=this,b=this.is0();d==null&&(d=b?t.ONE:t.inv(x));let A=t.mul(y,d),S=t.mul(w,d),R=t.mul(x,d);if(b)return{x:t.ZERO,y:t.ZERO};if(!t.eql(R,t.ONE))throw new Error("invZ was invalid");return{x:A,y:S}}isTorsionFree(){let{h:d,isTorsionFree:y}=e;if(d===Tt)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:d,clearCofactor:y}=e;return d===Tt?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return this.assertValidity(),n(u,this,d)}toHex(d=!0){return gr(this.toRawBytes(d))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let p=e.nBitLength,h=Js(u,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:s}}function yv(r){let e=hi(r);return Zt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function sg(r){let e=yv(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(I){return Ir<I&&I<t.ORDER}function a(I){return ce(I,n)}function c(I){return Xs(I,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:u,isWithinCurveOrder:p}=gv({...e,toBytes(I,T,z){let B=T.toAffine(),_=t.toBytes(B.x),V=wr;return z?V(Uint8Array.from([T.hasEvenY()?2:3]),_):V(Uint8Array.from([4]),_,t.toBytes(B.y))},fromBytes(I){let T=I.length,z=I[0],B=I.subarray(1);if(T===o&&(z===2||z===3)){let _=yr(B);if(!s(_))throw new Error("Point is not on curve");let V=u(_),K;try{K=t.sqrt(V)}catch(Z){let ie=Z instanceof Error?": "+Z.message:"";throw new Error("Point is not on curve"+ie)}let W=(K&Tt)===Tt;return(z&1)===1!==W&&(K=t.neg(K)),{x:_,y:K}}else if(T===i&&z===4){let _=t.fromBytes(B.subarray(0,t.BYTES)),V=t.fromBytes(B.subarray(t.BYTES,2*t.BYTES));return{x:_,y:V}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),h=I=>gr(rn(I,e.nByteLength));function m(I){let T=n>>Tt;return I>T}function d(I){return m(I)?a(-I):I}let y=(I,T,z)=>yr(I.slice(T,z));class w{constructor(T,z,B){this.r=T,this.s=z,this.recovery=B,this.assertValidity()}static fromCompact(T){let z=e.nByteLength;return T=be("compactSignature",T,z*2),new w(y(T,0,z),y(T,z,2*z))}static fromDER(T){let{r:z,s:B}=In.toSig(be("DER",T));return new w(z,B)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(T){return new w(this.r,this.s,T)}recoverPublicKey(T){let{r:z,s:B,recovery:_}=this,V=v(be("msgHash",T));if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");let K=_===2||_===3?z+e.n:z;if(K>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=_&1?"03":"02",X=l.fromHex(W+h(K)),Z=c(K),ie=a(-V*Z),Q=a(B*Z),te=l.BASE.multiplyAndAddUnsafe(X,ie,Q);if(!te)throw new Error("point at infinify");return te.assertValidity(),te}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return vn(this.toDERHex())}toDERHex(){return In.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return vn(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let x={isValidPrivateKey(I){try{return f(I),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let I=Bu(e.n);return em(e.randomBytes(I),e.n)},precompute(I=8,T=l.BASE){return T._setWindowSize(I),T.multiply(BigInt(3)),T}};function b(I,T=!0){return l.fromPrivateKey(I).toRawBytes(T)}function A(I){let T=en(I),z=typeof I=="string",B=(T||z)&&I.length;return T?B===o||B===i:z?B===2*o||B===2*i:I instanceof l}function S(I,T,z=!0){if(A(I))throw new Error("first arg must be private key");if(!A(T))throw new Error("second arg must be public key");return l.fromHex(T).multiply(f(I)).toRawBytes(z)}let R=e.bits2int||function(I){let T=yr(I),z=I.length*8-e.nBitLength;return z>0?T>>BigInt(z):T},v=e.bits2int_modN||function(I){return a(R(I))},E=fi(e.nBitLength);function P(I){if(typeof I!="bigint")throw new Error("bigint expected");if(!(Ir<=I&&I<E))throw new Error(`bigint expected < 2^${e.nBitLength}`);return rn(I,e.nByteLength)}function U(I,T,z=L){if(["recovered","canonical"].some(ye=>ye in z))throw new Error("sign() legacy options not supported");let{hash:B,randomBytes:_}=e,{lowS:V,prehash:K,extraEntropy:W}=z;V==null&&(V=!0),I=be("msgHash",I),K&&(I=be("prehashed msgHash",B(I)));let X=v(I),Z=f(T),ie=[P(Z),P(X)];if(W!=null&&W!==!1){let ye=W===!0?_(t.BYTES):W;ie.push(be("extraEntropy",ye))}let Q=wr(...ie),te=X;function ve(ye){let Te=R(ye);if(!p(Te))return;let Ne=c(Te),_e=l.BASE.multiply(Te).toAffine(),Ve=a(_e.x);if(Ve===Ir)return;let sr=a(Ne*a(te+Ve*Z));if(sr===Ir)return;let hn=(_e.x===Ve?0:2)|Number(_e.y&Tt),Oo=sr;return V&&m(sr)&&(Oo=d(sr),hn^=1),new w(Ve,Oo,hn)}return{seed:Q,k2sig:ve}}let L={lowS:e.lowS,prehash:!1},$={lowS:e.lowS,prehash:!1};function C(I,T,z=L){let{seed:B,k2sig:_}=U(I,T,z),V=e;return _u(V.hash.outputLen,V.nByteLength,V.hmac)(B,_)}l.BASE._setWindowSize(8);function ee(I,T,z,B=$){let _=I;if(T=be("msgHash",T),z=be("publicKey",z),"strict"in B)throw new Error("options.strict was renamed to lowS");let{lowS:V,prehash:K}=B,W,X;try{if(typeof _=="string"||en(_))try{W=w.fromDER(_)}catch(_e){if(!(_e instanceof In.Err))throw _e;W=w.fromCompact(_)}else if(typeof _=="object"&&typeof _.r=="bigint"&&typeof _.s=="bigint"){let{r:_e,s:Ve}=_;W=new w(_e,Ve)}else throw new Error("PARSE");X=l.fromHex(z)}catch(_e){if(_e.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(V&&W.hasHighS())return!1;K&&(T=e.hash(T));let{r:Z,s:ie}=W,Q=v(T),te=c(ie),ve=a(Q*te),ye=a(Z*te),Te=l.BASE.multiplyAndAddUnsafe(X,ve,ye)?.toAffine();return Te?a(Te.x)===Z:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:S,sign:C,verify:ee,ProjectivePoint:l,Signature:w,utils:x}}function wv(r){return{hash:r,hmac:(e,...t)=>pi(r,e,zs(...t)),randomBytes:ho}}function ag(r,e){let t=n=>sg({...r,...wv(n)});return Object.freeze({...t(e),create:t})}var ug=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),cg=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),bv=BigInt(1),ju=BigInt(2),lg=(r,e)=>(r+e/ju)/e;function xv(r){let e=ug,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,f=l*l*r%e,u=de(f,t,e)*f%e,p=de(u,t,e)*f%e,h=de(p,ju,e)*l%e,m=de(h,o,e)*h%e,d=de(m,i,e)*m%e,y=de(d,a,e)*d%e,w=de(y,c,e)*y%e,x=de(w,a,e)*d%e,b=de(x,t,e)*f%e,A=de(b,s,e)*m%e,S=de(A,n,e)*l%e,R=de(S,ju,e);if(!Yu.eql(Yu.sqr(R),r))throw new Error("Cannot find square root");return R}var Yu=Zs(ug,void 0,void 0,{sqrt:xv}),Ht=ag({a:BigInt(0),b:BigInt(7),Fp:Yu,n:cg,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=cg,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-bv*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=lg(i*r,e),c=lg(-n*r,e),l=ce(r-a*t-c*o,e),f=ce(-a*n-c*i,e),u=l>s,p=f>s;if(u&&(l=e-l),p&&(f=e-f),l>s||f>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:p,k2:f}}}},og),XN=BigInt(0);var ZN=Ht.ProjectivePoint;function fg(){return Ht.utils.randomPrivateKey()}function hg(r,e){let t=ke.digest(e instanceof Uint8Array?e:e.subarray());if(Rt(t))return t.then(({digest:n})=>Ht.sign(n,r).toDERRawBytes()).catch(n=>{throw new N(String(n),"ERR_INVALID_INPUT")});try{return Ht.sign(t.digest,r).toDERRawBytes()}catch(n){throw new N(String(n),"ERR_INVALID_INPUT")}}function dg(r,e,t){let n=ke.digest(t instanceof Uint8Array?t:t.subarray());if(Rt(n))return n.then(({digest:o})=>Ht.verify(e,o,r)).catch(o=>{throw new N(String(o),"ERR_INVALID_INPUT")});try{return Ht.verify(e,n.digest,r)}catch(o){throw new N(String(o),"ERR_INVALID_INPUT")}}function pg(r){return Ht.ProjectivePoint.fromHex(r).toRawBytes(!0)}function mg(r){try{Ht.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}function Xu(r){try{Ht.ProjectivePoint.fromHex(r)}catch(e){throw new N(String(e),"ERR_INVALID_PUBLIC_KEY")}}function gg(r){try{return Ht.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}var ki=class{_key;constructor(e){Xu(e),this._key=e}verify(e,t){return dg(this._key,t,e)}marshal(){return pg(this._key)}get bytes(){return Jt.encode({Type:pe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=ke.digest(this.bytes),t;return Rt(e)?{bytes:t}=await e:t=e.bytes,t}},Ii=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??gg(e),mg(this._key),Xu(this._publicKey)}sign(e){return hg(this._key,e)}get public(){return new ki(this._publicKey)}marshal(){return this._key}get bytes(){return Qt.encode({Type:pe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=ke.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return G(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 vv(r){return new Ii(r)}function Sv(r){return new ki(r)}async function Av(){let r=fg();return new Ii(r)}var Rn={rsa:Gu,ed25519:Ou,secp256k1:Zu};function yg(r){let e=Object.keys(Rn).join(" / ");return new N(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Ju(r){let e=Jt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case pe.RSA:return Rn.rsa.unmarshalRsaPublicKey(t);case pe.Ed25519:return Rn.ed25519.unmarshalEd25519PublicKey(t);case pe.Secp256k1:return Rn.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw yg(e.Type??"unknown")}}async function wg(r){let e=Qt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case pe.RSA:return Rn.rsa.unmarshalRsaPrivateKey(t);case pe.Ed25519:return Rn.ed25519.unmarshalEd25519PrivateKey(t);case pe.Secp256k1:return Rn.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw yg(e.Type??"RSA")}}var ef=re(Qu(),1);var _v=Math.LN2*Math.LN2,ja=class r{static create(e,t=.005){let n=kv(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=Iv(e.hashes??8),this.bits=e.bits??1024,this.buffer=tt(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=O(e));for(let t=0;t<this.seeds.length;t++){let o=ef.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(o)}}has(e){typeof e=="string"&&(e=O(e));for(let t=0;t<this.seeds.length;t++){let o=ef.default.x86.hash32(e,this.seeds[t])%this.bits;if(!this.getbit(o))return!1}return!0}clear(){this.buffer.fill(0)}setbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;let o=this.buffer[t];o|=1<<n,this.buffer[t]=o}getbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;return(this.buffer[t]&1<<n)!==0}};function kv(r,e=.005){let t=Math.round(-1*r*Math.log(e)/_v),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function Iv(r){let e,t,n=[];for(let o=0;o<r;o++)for(e=new lr(er(4)),n[o]=e.getUint32(0,!0),t=0;t<o;t++)if(n[o]===n[t]){o--;break}return n}var Bi=class extends On{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),me(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=ja.create(this.maxProviders)}async retrieve(e,t={}){let n=Et.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=fe();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let s=!1,a=new ar({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,f)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});try{return await i.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.providers.some(t=>this.equals(t,e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=fe(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new N(`Found ${i} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var Ya=class{blockstore;datastore;pins;logger;routing;dagWalkers;hashers;dns;log;constructor(e){this.logger=e.logger??nd(),this.log=this.logger.forComponent("helia"),this.hashers=Lp(e.hashers),this.dagWalkers=Tp(e.dagWalkers),this.dns=e.dns??Zo();let t={blockstore:e.blockstore,datastore:e.datastore,hashers:this.hashers,dagWalkers:this.dagWalkers,logger:this.logger,blockBrokers:[],dns:this.dns,...e.components??{}};this.routing=t.routing=new Cs(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[Uo]!=null&&i.push(o[Uo]),o[Fo]!=null&&i.push(o[Fo]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new $s(t);this.pins=new Ns(e.datastore,n,this.dagWalkers),this.blockstore=new Ls(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await Cp(this.datastore),await Pr(this.blockstore,this.datastore,this.routing)}async stop(){await Or(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 cr(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 M("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new M("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};function Rv(r){return r[Symbol.asyncIterator]!=null}function Bv(r){if(Rv(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 tf=Bv;var Xa=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let p=Number.parseInt(u,e);if(!Number.isNaN(p))return p});if(f===void 0)break;if(i*=e,i+=f,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Eg=45,Tv=15,ko=new Xa;function rf(r){if(!(r.length>Tv))return ko.new(r).parseWith(()=>ko.readIPv4Addr())}function nf(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Eg))return ko.new(r).parseWith(()=>ko.readIPv6Addr())}function Za(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Eg))return ko.new(r).parseWith(()=>ko.readIPAddr())}function Io(r){return!!rf(r)}function Ro(r){return!!nf(r)}function Ja(r){return!!Za(r)}var Sg=re(vg(),1),Nv=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Cv=Nv.map(r=>new Sg.Netmask(r));function Lv(r){for(let e of Cv)if(e.contains(r))return!0;return!1}function Dv(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Ag(r){return Io(r)?Lv(r):Ro(r)?Dv(r):void 0}var nC=parseInt("0xFFFF",16),oC=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Ig=Io,Vv=Ro,of=function(r){let e=0;if(r=r.toString().trim(),Ig(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(Vv(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=Ig(t[n]),s;i&&(s=of(t[n]),t[n]=G(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,G(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")},Rg=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 Bo={},sf={},Hv=[[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"]];Hv.forEach(r=>{let e=$v(...r);sf[e.code]=e,Bo[e.name]=e});function $v(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function Y(r){if(typeof r=="number"){if(sf[r]!=null)return sf[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Bo[r]!=null)return Bo[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var VC=Y("ip4"),MC=Y("ip6"),HC=Y("ipcidr");function cf(r,e){switch(Y(r).code){case 4:case 41:return qv(e);case 42:return Ng(e);case 6:case 273:case 33:case 132:return Lg(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ng(e);case 421:return jv(e);case 444:return Cg(e);case 445:return Cg(e);case 466:return Wv(e);default:return G(e,"base16")}}function lf(r,e){switch(Y(r).code){case 4:return Bg(e);case 41:return Bg(e);case 42:return Tg(e);case 6:case 273:case 33:case 132:return uf(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Tg(e);case 421:return zv(e);case 444:return Yv(e);case 445:return Xv(e);case 466:return Gv(e);default:return O(e,"base16")}}var af=Object.values(Hr).map(r=>r.decoder),Kv=function(){let r=af[0].or(af[1]);return af.slice(2).forEach(e=>r=r.or(e)),r}();function Bg(r){if(!Ja(r))throw new Error("invalid ip address");return of(r)}function qv(r){let e=Rg(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!Ja(e))throw new Error("invalid ip address");return e}function uf(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function Lg(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Tg(r){let e=O(r),t=Uint8Array.from(Hn(e.length));return ue([t,e],t.length+e.length)}function Ng(r){let e=pn(r);if(r=r.slice(nt(e)),r.length!==e)throw new Error("inconsistent lengths");return G(r)}function zv(r){let e;r[0]==="Q"||r[0]==="1"?e=je(ge.decode(`z${r}`)).bytes:e=q.parse(r).multihash.bytes;let t=Uint8Array.from(Hn(e.length));return ue([t,e],t.length+e.length)}function Gv(r){let e=Kv.decode(r),t=Uint8Array.from(Hn(e.length));return ue([t,e],t.length+e.length)}function Wv(r){let e=pn(r),t=r.slice(nt(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+G(t,"base64url")}function jv(r){let e=pn(r),t=r.slice(nt(e));if(t.length!==e)throw new Error("inconsistent lengths");return G(t,"base58btc")}function Yv(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=De.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=uf(n);return ue([t,o],t.length+o.length)}function Xv(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=De.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=uf(n);return ue([t,o],t.length+o.length)}function Cg(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=G(e,"base32"),o=Lg(t);return`${n}:${o}`}function Dg(r){r=ff(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=Y(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw Og("invalid address: "+r);if(a.path===!0){n=ff(o.slice(i).join("/")),e.push([a.code,lf(a.code,n)]),t.push([a.code,n]);break}let c=lf(a.code,o[i]);e.push([a.code,c]),t.push([a.code,cf(a.code,c)])}return{string:Pg(t),bytes:df(e),tuples:e,stringTuples:t,path:n}}function hf(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=pn(r,o),s=nt(i),a=Y(i),c=Zv(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw Og("Invalid address Uint8Array: "+G(r,"base16"));e.push([i,l]);let f=cf(i,l);if(t.push([i,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:Pg(t),tuples:e,stringTuples:t,path:n}}function Pg(r){let e=[];return r.map(t=>{let n=Y(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),ff(e.join("/"))}function df(r){return ue(r.map(e=>{let t=Y(e[0]),n=Uint8Array.from(Hn(t.code));return e.length>1&&e[1]!=null&&(n=ue([n,e[1]])),n}))}function Zv(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=pn(e instanceof Uint8Array?e:Uint8Array.from(e));return t+nt(t)}}function ff(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Og(r){return new Error("Error parsing address: "+r)}var Jv=Symbol.for("nodejs.util.inspect.custom"),pf=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Qv=[Y("dns").code,Y("dns4").code,Y("dns6").code,Y("dnsaddr").code],Qa=class r{bytes;#e;#t;#r;#s;[pf]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=hf(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=Dg(e)}else if(Fg(e))t=hf(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=Y("tcp"),a=Y("udp"),c=Y("ip4"),l=Y("ip6"),f=Y("dns6"),u=Y("ip6zone");for(let[h,m]of this.stringTuples())h===u.code&&(i=`%${m??""}`),Qv.includes(h)&&(t=s.name,o=443,n=`${m??""}${i}`,e=h===f.code?6:4),(h===s.code||h===a.code)&&(t=Y(h).name,o=parseInt(m??"")),(h===c.code||h===l.code)&&(t=Y(h).name,n=`${m??""}${i}`,e=h===l.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({},Y(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>Y(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(df(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Bo.p2p.code&&e.push([n,o]),n===Bo["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?G(ge.decode(`z${n}`),"base58btc"):G(q.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#s}equals(e){return ne(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=Ug.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=>Bn(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)}[Jv](){return`Multiaddr(${this.#e})`}};var Ug=new Map;function Fg(r){return!!r?.[pf]}function Bn(r){return new Qa(r)}var e2=r=>r.toString().split("/").slice(1),Ni=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),se=r=>({match:e=>Ni(t=>t===r).match(e),pattern:r}),rc=()=>({match:r=>Ni(e=>typeof e=="string").match(r),pattern:"{string}"}),nc=()=>({match:r=>Ni(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Ue=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ge.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ec=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{il.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),et=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),bt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),le=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function Ee(...r){function e(o){let i=e2(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matches:t,exactMatch:n}}var gf=le(se("dns4"),rc()),yf=le(se("dns6"),rc()),wf=le(se("dnsaddr"),rc()),Vg=le(se("dns"),rc()),g3=Ee(gf),y3=Ee(yf),w3=Ee(wf),Mg=Ee(bt(Vg,wf,gf,yf)),Hg=le(se("ip4"),Ni(Io)),$g=le(se("ip6"),Ni(Ro)),Kg=bt(Hg,$g),or=bt(Kg,Vg,gf,yf,wf),b3=Ee(or),x3=Ee(Hg),E3=Ee($g),v3=Ee(Kg),oc=le(or,se("tcp"),nc()),Ci=le(or,se("udp"),nc()),t2=bt(oc,Ci),S3=Ee(oc),A3=Ee(Ci),bf=le(Ci,se("quic")),ic=le(Ci,se("quic-v1")),r2=bt(bf,ic),_3=Ee(bf),k3=Ee(ic),mf=bt(or,oc,Ci,bf,ic),qg=bt(le(mf,se("ws"),et(Ue()))),I3=Ee(qg),zg=bt(le(mf,se("wss"),et(Ue())),le(mf,se("tls"),se("ws"),et(Ue()))),R3=Ee(zg),Gg=le(t2,se("webrtc-direct"),ec(),et(ec()),et(Ue())),B3=Ee(Gg),Wg=le(ic,se("webtransport"),ec(),ec(),et(Ue())),T3=Ee(Wg),tc=bt(qg,zg,le(oc,et(Ue())),le(r2,et(Ue())),le(or,et(Ue())),Gg,Wg,Ue()),N3=Ee(tc),n2=le(tc,se("p2p-circuit"),Ue()),C3=Ee(n2),o2=bt(le(tc,se("p2p-circuit"),se("webrtc"),Ue()),le(tc,se("webrtc"),et(Ue())),se("webrtc")),L3=Ee(o2),i2=bt(le(or,se("tcp"),nc(),se("http"),et(Ue())),le(or,se("http"),et(Ue()))),jg=Ee(i2),s2=bt(le(or,se("tcp"),bt(le(se("443"),se("http")),le(nc(),se("https"))),et(Ue())),le(or,se("tls"),se("http"),et(Ue())),le(or,se("https"),et(Ue()))),Yg=Ee(s2);var a2=[Y("tcp").code,Y("dns").code,Y("dnsaddr").code,Y("dns4").code,Y("dns6").code];function Xg(r){let e;try{e=Y("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function Zg(r){return r.some(([e,t])=>e===Y("tls").code)}function xt(r,e,t){let n=Jg[Y(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${Y(r).name}`);let o=n(e,t);return r===Y("ip6").code?`[${o}]`:o}var Jg={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${xt(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${xt(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${xt(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${xt(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=Zg(e),n=Xg(e);if(t&&n!==null)return`https://${n}`;let o=t?"https://":"http://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=xt(i[0],i[1]??"",e);return s=s.replace("tcp://",""),`${o}${s}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return xt(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return xt(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=xt(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=Zg(e),n=Xg(e);if(t&&n!==null)return`wss://${n}`;let o=t?"wss://":"ws://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=xt(i[0],i[1]??"",e);return s=s.replace("tcp://",""),`${o}${s}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=xt(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${xt(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${xt(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${xt(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function Qg(r,e){let n=Bn(r).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=Y(o[0]),s=Jg[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return e?.assumeHttp!==!1&&a2.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var Tn=class{url;#e=0;#t=0;#r=0;#s=0;log;constructor(e,t){this.url=e instanceof URL?e:new URL(e),this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}async getRawBlock(e,t){let n=new URL(this.url.toString());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(this.log("GET %s %d",n,o.status),!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 c2=!1,l2=!1,xf=class extends Bi{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??c2,this.allowLocal=t.allowLocal??l2}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n.signal);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){for await(let n of this.routing.findProviders(e,t)){let o=u2(n.multiaddrs,this.allowInsecure,this.allowLocal);if(o.length===0)continue;let i=Qg(o[0]);this.log("found http-gateway provider %p %s for cid %c",n.id,i,e),yield new Tn(i,this.logger)}}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}};function u2(r,e,t){return r.filter(n=>Yg.matches(n)||e&&jg.matches(n)?t||Mg.matches(n)?!0:Ag(n.toOptions().host)===!1:!1)}function e0(r,e){return new xf(r,e)}var sc=class{components;gateways;routing;log;logger;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.gateways=(t.gateways??t0).map(n=>new Tn(n,e.logger))}addGateway(e){this.gateways.push(new Tn(e,this.components.logger))}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(`Block for CID ${e} from gateway ${i.url} failed validation`)}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 o.length>0?new AggregateError(o,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return e0({logger:this.logger,routing:this.routing},e)}};var t0=["https://trustless-gateway.link","https://cloudflare-ipfs.com","https://4everland.io"];function Li(r={}){return e=>new sc(e,r)}async function*ac(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 _f=re(Le(),1);var m0=re(cc(),1);var r0="ERR_IPNS_EXPIRED_RECORD",Di="ERR_UNRECOGNIZED_VALIDITY",n0="ERR_SIGNATURE_CREATION",Rr="ERR_SIGNATURE_VERIFICATION";var vf="ERR_UNDEFINED_PARAMETER",o0="ERR_INVALID_RECORD_DATA",i0="ERR_INVALID_VALUE",s0="ERR_INVALID_EMBEDDED_KEY",a0="ERR_MISSING_PRIVATE_KEY",c0="ERR_RECORD_TOO_LARGE";var Fe;(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=()=>wn(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=_t((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=>At(o,r.codec()),r.decode=o=>St(o,r.codec())})(Fe||(Fe={}));var at=re(Le(),1);var l0=Ye("ipns:utils"),u0=O("/ipns/"),f2=114,f0=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw l0.error(n),(0,at.default)(n,vf)}let t;if(e.pubKey!=null){try{t=Ju(e.pubKey)}catch(o){throw l0.error(o),o}if(!(await rd(e.pubKey)).equals(r))throw(0,at.default)(new Error("Embedded public key did not match PeerID"),s0)}else r.publicKey!=null&&(t=Ju(r.publicKey));if(t!=null)return t;throw(0,at.default)(new Error("no public key is available"),vf)},h0=(r,e,t)=>{let n=O(e);return ue([r,t,n])},lc=r=>{let e=O("ipns-signature:");return ue([e,r])},Br=r=>"signatureV1"in r?Fe.encode({value:O(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:O(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Fe.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data});function Ge(r){let e=Fe.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,at.default)(new Error("missing data or signatureV2"),Rr);let t=p0(e.data),n=Af(t.Value),o=G(t.Validity);if(e.value!=null&&e.signatureV1!=null)return h2(e),{value:n,validityType:Fe.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:Fe.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 To=r=>ue([u0,r.toBytes()]),No=r=>Go(r.slice(u0.length)),d0=(r,e,t,n,o)=>{let i;if(e===Fe.ValidityType.EOL)i=0;else throw(0,at.default)(new Error("Unknown validity type"),Di);return zr({Value:r,Validity:t,ValidityType:i,Sequence:n,TTL:o})},p0=r=>{let e=Ze(r);if(e.ValidityType===0)e.ValidityType=Fe.ValidityType.EOL;else throw(0,at.default)(new Error("Unknown validity type"),Di);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e},Af=r=>{if(r!=null){if(hh(r))return`/ipns/${r.toCID().toString(Vr)}`;if(r instanceof Uint8Array){let n=G(r);n.startsWith("/")&&(r=n)}let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e;let t=q.asCID(r);if(t!=null)return t.code===f2?`/ipns/${t.toString(Vr)}`:`/ipfs/${t.toV1().toString()}`;try{return r instanceof Uint8Array?`/ipfs/${q.decode(r).toV1().toString()}`:`/ipfs/${q.parse(e).toV1().toString()}`}catch{}}throw(0,at.default)(new Error("Value must be a valid content path starting with /"),i0)},h2=r=>{if(r.data==null)throw(0,at.default)(new Error("Record data is missing"),o0);let e=p0(r.data);if(!ne(e.Value,r.value??new Uint8Array(0)))throw(0,at.default)(new Error('Field "value" did not match between protobuf and CBOR'),Rr);if(!ne(e.Validity,r.validity??new Uint8Array(0)))throw(0,at.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Rr);if(e.ValidityType!==r.validityType)throw(0,at.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Rr);if(e.Sequence!==r.sequence)throw(0,at.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Rr);if(e.TTL!==r.ttl)throw(0,at.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Rr)};var d2=Ye("ipns"),p2=$e.code,g0=60*60*1e9,m2="/ipns/",k4=m2.length,y0={v1Compatible:!0,ttlNs:g0};async function w0(r,e,t,n,o=y0){let i=new m0.default(Date.now()+Number(n)),s=Fe.ValidityType.EOL,a=BigInt(o.ttlNs!=null?o.ttlNs:g0);return g2(r,e,t,s,i.toString(),a,o)}var g2=async(r,e,t,n,o,i,s=y0)=>{t=BigInt(t);let a=O(o),c=Af(e),l=O(c);if(r.privateKey==null)throw(0,_f.default)(new Error("Missing private key"),a0);let f=await wg(r.privateKey),u=d0(l,n,a,t,i),p=lc(u),h=await f.sign(p),m;if(r.publicKey!=null){let d=je(r.toBytes());(d.code!==p2||!ne(r.publicKey,d.digest))&&(m=r.publicKey)}if(s.v1Compatible===!0){let d=await y2(f,l,n,a),y={value:c,signatureV1:d,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:h,data:u};return m!=null&&(y.pubKey=m),y}else{let d={value:c,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:h,data:u};return m!=null&&(d.pubKey=m),d}};var y2=async(r,e,t,n)=>{try{let o=h0(e,t,n);return await r.sign(o)}catch(o){throw d2.error("record signature creation failed",o),(0,_f.default)(new Error("record signature creation failed"),n0)}};var Pi=re(Le(),1),b0=re(cc(),1);var uc=Ye("ipns:validator"),w2=1024*10,b2=async(r,e)=>{let t=Ge(e),n;try{let o=lc(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw uc.error("record signature verification failed"),(0,Pi.default)(new Error("record signature verification failed"),Rr);if(t.validityType===Fe.ValidityType.EOL){if(b0.default.fromString(t.validity).toDate().getTime()<Date.now())throw uc.error("record has expired"),(0,Pi.default)(new Error("record has expired"),r0)}else if(t.validityType!=null)throw uc.error("unrecognized validity type"),(0,Pi.default)(new Error("unrecognized validity type"),Di);uc("ipns record for %s is valid",t.value)};async function Oi(r,e){if(e.byteLength>w2)throw(0,Pi.default)(new Error("record too large"),c0);let t=No(r),n=Ge(e),o=await f0(t,n);await b2(o,e)}async function*Ui(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))}function x2(r){return r[Symbol.asyncIterator]!=null}function E2(r){if(x2(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var fc=E2;var kf=O("/ipns/");function x0(r){return ne(r.subarray(0,kf.byteLength),kf)}var E0=r=>Go(r.slice(kf.length)),hc=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*He(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!x0(e))return;let o=E0(e),i=Ge(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!x0(e))throw new N("Not found","ERR_NOT_FOUND");let n=E0(e);try{let o=await this.client.getIPNS(n,t);return Br(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}},dc=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await fc(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 ct=Ye("delegated-routing-v1-http-api-client"),v0={concurrentRequests:4,timeout:3e4},pc=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,me(1/0,this.shutDownController.signal),this.httpQueue=new ot({concurrency:t.concurrentRequests??v0.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??v0.timeout,this.contentRouting=new hc(this),this.peerRouting=new dc(this)}get[Uo](){return this.contentRouting}get[Fo](){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={}){ct("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=We([this.shutDownController.signal,n,t.signal]);me(1/0,n,o);let i=fe(),s=fe();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=`${this.clientUrl}routing/v1/providers/${e.toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let p of u.Providers){let h=this.#e(p);h!=null&&(yield h)}}else for await(let u of Ui(ac(l.body))){let p=this.#e(u);p!=null&&(yield p)}}catch(a){ct.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),ct("getProviders finished: %c",e)}}async*getPeers(e,t={}){ct("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=We([this.shutDownController.signal,n,t.signal]);me(1/0,n,o);let i=fe(),s=fe();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let p of u.Peers){let h=this.#e(p);h!=null&&(yield h)}}else for await(let u of Ui(ac(l.body))){let p=this.#e(u);p!=null&&(yield p)}}catch(a){ct.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),ct("getPeers finished: %c",e)}}async getIPNS(e,t={}){ct("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=We([this.shutDownController.signal,n,t.signal]);me(1/0,n,o);let i=fe(),s=fe();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await i.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(ct("getIPNS GET %s %d",a,l.status),l.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new N("GET ipns response had no body","ERR_BAD_RESPONSE");let f=await l.arrayBuffer(),u=new Uint8Array(f,0,f.byteLength);return t.validate!==!1&&await Oi(To(e),u),Ge(u)}catch(c){throw ct.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),ct("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){ct("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=We([this.shutDownController.signal,o,n.signal]);me(1/0,o,i);let s=fe(),a=fe();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await s.promise;let l=Br(t),u=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i});if(ct("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new N("PUT ipns response had status other than 200","ERR_BAD_RESPONSE")}catch(l){throw ct.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),ct("putIPNS finished: %c",e)}}#e(e){let t=[],n=e.Addrs?.map(Bn)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Ct(e.ID),Addrs:n,Protocols:t}}};function S0(r,e={}){return new pc(new URL(r),e)}var A0=O("/ipns/");function _0(r){return ne(r.subarray(0,A0.byteLength),A0)}var If=class{client;constructor(e){this.client=S0(e)}async provide(e,t){}async*findProviders(e,t){yield*He(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols}))}async put(e,t,n){if(!_0(e))return;let o=No(e),i=Ge(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!_0(e))throw new N("Not found","ERR_NOT_FOUND");let n=No(e);try{let o=await this.client.getIPNS(n,t);return Br(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}async findPeer(e,t){let n=await fc(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 Fi(r){return new If(new URL(r))}var k0=re(Le(),1);function mc(r){return r=r??new Error("Not Found"),(0,k0.default)(r,"ERR_NOT_FOUND")}var I0="SHARDING";function S2(r){return r[Symbol.asyncIterator]!=null}function A2(r,e){return S2(r)?async function*(){yield*(await tf(r)).sort(e)}():function*(){yield*tf(r).sort(e)}()}var gc=A2;var Tr=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 cr(this.putMany(e,n)),e=[],await cr(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=yt(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>yt(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>gc(o,i),n)),e.offset!=null){let o=0,i=e.offset;n=yt(n,()=>o++>=i)}return e.limit!=null&&(n=ss(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=yt(n,i=>i.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>yt(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>gc(o,i),n)),e.offset!=null){let o=e.offset,i=0;n=yt(n,()=>i++>=o)}return e.limit!=null&&(n=ss(n,e.limit)),n}};var Mi=class extends Tr{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 mc();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 xe(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new xe(e)}};var KL=new xe(I0);var tD=Ye("datastore:core:tiered");async function B0(r={}){let e=r.datastore??new Mi,t=r.blockstore??new ui,n=new Ya({...r,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Li()],routers:r.routers??[Fi("https://delegated-ipfs.dev")]});return r.start!==!1&&await n.start(),n}var Tf=re(yc(),1);var Nf=40;function Cf(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=Tf.default.decode(r);return e.seek(Tf.default.decode.bytes),t}function Lf(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 un={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},Hi={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":un.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(un.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Hi["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=Hi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:un.Int,CarV1HeaderOrV2Pragma:r=>{if(un.Map(r)===void 0)return;let 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=Hi["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=Hi.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}},$i={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":un.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(un.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=$i["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=$i["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:un.Int,CarV1HeaderOrV2Pragma:r=>{if(un.Map(r)===void 0)return;let 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=$i["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=$i.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}},Df={toTyped:Hi.CarV1HeaderOrV2Pragma,toRepresentation:$i.CarV1HeaderOrV2Pragma};var MD=Zl();var K2=re(yc(),1);var zD=[new k(g.map,2),new k(g.string,"version"),new k(g.uint,1),new k(g.string,"roots")],GD=new k(g.tag,42);async function Pf(r,e){let t=Cf(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=En(n);if(Df.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=Lf(await r.exactly(Nf,!0));r.seek(i.dataOffset-r.pos);let s=await Pf(r,1);return Object.assign(s,i)}function Ki(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 Of=re(yc(),1),H0=1;function Uf(r){let e=ii({version:H0,roots:r}),t=Of.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function $0(r){return{async setRoots(e){let t=Uf(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(Of.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 H0}}}function wc(){}function K0(){let r=[],e=null,t=wc,n=!1,o=null,i=wc,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=wc,l()}})),e),a={write(l){r.push(l);let f=s();return i(),f},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(f=>{i=()=>(o=null,i=wc,f(c.next()))})),o)}};return{writer:a,iterator:c}}var qi=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=q.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=W2(e);let{encoder:t,iterator:n}=q0(),o=new r(e,t),i=new bc(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=q0();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new bc(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=Ki(e);await Pf(n);let o=Uf(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}},bc=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 q0(){let r=K0(),{writer:e,iterator:t}=r;return{encoder:$0(e),iterator:t}}function W2(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=q.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=q.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var j2=1,Ff=class{components;constructor(e,t){this.components=e}async import(e,t){await cr(this.components.blockstore.putMany(He(e.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),t))}async export(e,t,n){let o=fe(),i=Array.isArray(e)?e:[e],s=new ot({concurrency:j2});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,l)=>{await t.put({cid:c,bytes:l})},n)}).catch(()=>{});try{await o.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:o}=qi.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 z0(r,e={}){return new Ff(r,e)}var Vf=re(cc(),1);function G0(r,e){let t=e.map((n,o)=>({record:Ge(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===Fe.ValidityType.EOL&&o.record.validityType===Fe.ValidityType.EOL){let a=Vf.default.fromString(n.record.validity).toDate(),c=Vf.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 Y2=32;async function W0(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:[it.TXT]})).Answer.sort((l,f)=>l.data.localeCompare(f.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let f=l.data;if(f.startsWith('"')&&f.endsWith('"')&&(f=f.substring(1,f.length-1)),!f.startsWith("dnslink="))continue;n("%s TXT %s",l.name,f),f=f.replace("dnslink=","");let[,u,p,...h]=f.split("/");if(u==="ipfs")try{return{value:`/ipfs/${q.parse(p)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}else if(u==="ipns"){try{return{value:`/ipns/${Ct(p)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}return await xc(p,e-1,t,n,o)}else{if(u==="dnslink")return await xc(p,e-1,t,n,o);n('unknown protocol "%s" in DNSLink record for domain: %s',u,r);continue}}catch(f){n.error("could not parse DNS link record for domain %s, %s",r,l.data,f)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=(await t.query(r,{...o,types:[it.CNAME]})).Answer.sort((l,f)=>l.data.localeCompare(f.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await xc(l.data,e-1,t,n,o)}catch(f){n.error("domain %s cname %s had no DNSLink records",r,l.data,f)}throw new N(`No DNSLink records found for domain: ${r}`,"ERR_DNSLINK_NOT_FOUND")}async function xc(r,e,t,n,o={}){if(e===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await W0(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 W0(r,e,t,n,o)}}async function j0(r,e,t,n={}){return xc(r,n.maxRecursiveDepth??Y2,e,t,n)}var Mf=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 M("ipns:routing:helia:error",o))}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){t.onProgress?.(new M("ipns:routing:helia:error",n))}throw new Error("Not found")}};function Y0(r){return new Mf(r)}var zi;(function(r){let e;r.codec=()=>(e==null&&(e=_t((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:tt(0),value:tt(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=>At(t,r.codec()),r.decode=(t,n)=>St(t,r.codec(),n)})(zi||(zi={}));function X0(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 Z0(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),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,l))}var Nr=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 zi.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:X0(this.timeReceived)}}static deserialize(e){let t=zi.decode(e);return new r(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=Z0(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 Ec=globalThis.CustomEvent??Event;async function*Nn(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=fe(),a=fe(),c=!1,l,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(i.length===t&&(s=fe(),await s.promise),f)break;let d={done:!1};i.push(d),m().then(y=>{d.done=!0,d.ok=!0,d.value=y,o.dispatchEvent(new Ec("task-complete"))},y=>{d.done=!0,d.err=y,o.dispatchEvent(new Ec("task-complete"))})}c=!0,o.dispatchEvent(new Ec("task-complete"))}catch(m){l=m,o.dispatchEvent(new Ec("task-complete"))}});function u(){return n?i[0]?.done:!!i.find(m=>m.done)}function*p(){for(;i.length>0&&i[0].done;){let m=i[0];if(i.shift(),m.ok)yield m.value;else throw f=!0,s.resolve(),m.err;s.resolve()}}function*h(){for(;u();)for(let m=0;m<i.length;m++)if(i[m].done){let d=i[m];if(i.splice(m,1),m--,d.ok)yield d.value;else throw f=!0,s.resolve(),d.err;s.resolve()}}for(;;){if(u()||(a=fe(),await a.promise),l!=null)throw l;if(n?yield*p():yield*h(),c&&i.length===0)break}}var J0;(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"})(J0||(J0={}));function vc(r){return new xe("/dht/record/"+G(r,"base32"),!1)}function Q0(r){return{async put(e,t,n={}){try{let o=vc(e);try{let s=await r.get(o),a=Nr.deserialize(s);if(ne(a.value,t))return}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}let i=new Nr(e,t,new Date);n.onProgress?.(new M("ipns:routing:datastore:put")),await r.put(o,i.serialize(),n)}catch(o){throw n.onProgress?.(new M("ipns:routing:datastore:error",o)),o}},async get(e,t={}){try{let n=vc(e);t.onProgress?.(new M("ipns:routing:datastore:get"));let o=await r.get(n,t),i=Nr.deserialize(o);return{record:i.value,created:i.timeReceived}}catch(n){throw t.onProgress?.(new M("ipns:routing:datastore:error",n)),n}},async has(e,t={}){let n=vc(e);return r.has(n,t)},async delete(e,t){let n=vc(e);return r.delete(n,t)}}}var Cr=Ye("helia:ipns"),Z2=60*1e3,Kf=60*Z2,J2=24*Kf,Hf=23*Kf,Q2=BigInt(Kf)*1000000n,$f=class{routers;localStore;timeout;dns;log;constructor(e,t=[]){this.routers=[Y0(e.routing),...t],this.localStore=Q0(e.datastore),this.dns=e.dns,this.log=e.logger.forComponent("helia:ipns")}async publish(e,t,n={}){try{let o=1n,i=To(e);if(await this.localStore.has(i,n)){let{record:c}=await this.localStore.get(i,n);o=Ge(c).sequence+1n}let s=await w0(e,t,o,n.lifetime??J2,n),a=Br(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 M("ipns:publish:error",o)),o}}async resolve(e,t={}){let n=To(e),o=await this.#t(n,t);return{...await this.#e(o.value,t),record:o}}async resolveDNSLink(e,t={}){let n=await j0(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 M("ipns:republish:start"));let i=Date.now()-n,s=Hf-i;s<0&&(s=e.interval??Hf),setTimeout(()=>{t().catch(a=>{Cr.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{t().catch(n=>{Cr.error("error republishing",n)})},e.interval??Hf)}async#e(e,t={}){let n=e.split("/");try{let o=n[1];if(o==="ipns"){let{cid:i}=await this.resolve(Ct(n[2]),t),s=n.slice(3).join("/");return{cid:i,path:s}}else if(o==="ipfs"){let i=q.parse(n[2]),s=n.slice(3).join("/");return{cid:i,path:s}}}catch(o){Cr.error("error parsing ipfs path",o)}throw Cr.error("invalid ipfs path %s",e),new Error("Invalid value")}async#t(e,t={}){let n=[];if(await this.localStore.has(e,t))if(Cr("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 Oi(e,a),this.log("record was valid");let l=Ge(a),f=Number((l.ttl??Q2)/1000000n);if(c.getTime()+f>Date.now())return this.log("record TTL was valid"),l;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(e,t)}else Cr("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");Cr("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(l){Cr.error("error finding IPNS record",l);return}try{await Oi(e,c),n.push(c)}catch(l){i++,Cr.error("error finding IPNS record",l)}})),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[G0(e,n)];return await this.localStore.put(e,s,t),Ge(s)}};function ey(r,{routers:e=[]}={}){return new $f(r,e)}var Rc=re(Le(),1);function eS(r){return r[Symbol.asyncIterator]!=null}function tS(r){if(eS(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 ty=tS;var Ty=re(Le(),1);var ry=re(Le(),1);function Co(r,e,t,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let f=q.asCID(a[l]);if(f!=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:f,name:l,path:c,toResolve:i}};a=a[l]}else throw(0,ry.default)(new Error(`No property named ${l} 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 rS=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=En(c);return Co(l,c,r,e,t,n,i)},ny=rS;var nS=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Os(c);return Co(l,c,r,e,t,n,i)},oy=nS;var iy=re(Le(),1);function oS(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 Cn=oS;var Gi=re(Le(),1),iS=(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,Gi.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(o>n)throw(0,Gi.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(i<0n)throw(0,Gi.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,Gi.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:o,end:i}},Lo=iS;var sS=r=>{async function*e(t={}){let{start:n,end:o}=Lo(r.length,t.offset,t.length),i=Cn(r,0n,n,o);t.onProgress?.(new M("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},aS=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,iy.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:sS(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},sy=aS;var cS=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Vh(c);return Co(l,c,r,e,t,n,i)},ay=cS;var cy=re(Le(),1);var lS=r=>{async function*e(t={}){let{start:n,end:o}=Lo(r.length,t.offset,t.length),i=Cn(r,0n,n,o);t.onProgress?.(new M("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},uS=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,cy.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:lS(c),depth:i,size:BigInt(c.length),node:c}}},ly=uS;var ji=re(Le(),1);var qf=re(Le(),1);var $t;(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=()=>wn(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=_t((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),Sc.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=Sc.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>At(o,r.codec()),r.decode=o=>St(o,r.codec())})($t||($t={}));var Sc;(function(r){let e;r.codec=()=>(e==null&&(e=_t((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=>At(t,r.codec()),r.decode=t=>St(t,r.codec())})(Sc||(Sc={}));var uy;(function(r){let e;r.codec=()=>(e==null&&(e=_t((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=>At(t,r.codec()),r.decode=t=>St(t,r.codec())})(uy||(uy={}));var fy={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},fS=["directory","hamt-sharded-directory"],hy=parseInt("0644",8),dy=parseInt("0755",8),ir=class r{static unmarshal(e){let t=$t.decode(e),n=new r({type:fy[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(fy).includes(t))throw(0,qf.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()?dy:hy:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return fS.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=$t.DataType.Raw;break;case"directory":e=$t.DataType.Directory;break;case"file":e=$t.DataType.File;break;case"metadata":e=$t.DataType.Metadata;break;case"symlink":e=$t.DataType.Symlink;break;case"hamt-sharded-directory":e=$t.DataType.HAMTShard;break;default:throw(0,qf.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===hy&&!this.isDirectory()&&(n=void 0),n===dy&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),$t.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 Ac=re(Qu(),1);function hS(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 $O=mn({name:"murmur3-32",code:35,encode:r=>hS(Ac.default.x86.hash32(r))}),py=mn({name:"murmur3-128",code:34,encode:r=>Kn.fromHex(Ac.default.x64.hash128(r))}),KO=mn({name:"murmur3-x64-64",code:34,encode:r=>Kn.fromHex(Ac.default.x64.hash128(r)).subarray(0,8)});var Wi=re(Le(),1);var wy=re(yy(),1);var Ln=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 wy.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 by(this,e,t)}toJSON(){return this.serialize(yS,wS)}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"?O(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(gS);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 gS(r){return!!r}function yS(r,e){return r.key}function wS(r){return r}async function by(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof Ln)await by(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var bS=[255,254,252,248,240,224,192,128],xS=[1,3,7,15,31,63,127,255],_c=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=ES(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 ES(r,e,t){let n=vS(e,t);return(r&n)>>>e}function vS(r,e){return bS[r]&xS[Math.min(e+r-1,7)]}function xy(r){function e(t){return t instanceof kc?t:new kc(t,r)}return e}var kc=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 _c(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Ey(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:xy(r.hashFn)};return new Ln(e)}var SS=async function(r){return(await py.encode(r)).slice(0,8).reverse()},AS=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 Ln({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},vy=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),_S=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},Sy=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw(0,Wi.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let u;try{u=ir.unmarshal(r.Data)}catch(h){throw(0,Wi.default)(h,"ERR_NOT_UNIXFS")}if(u.type!=="hamt-sharded-directory")throw(0,Wi.default)(new Error("not a HAMT"),"ERR_NOT_UNIXFS");if(u.fanout==null)throw(0,Wi.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let p=Ey({hashFn:SS,bits:Math.log2(Number(u.fanout))});n={rootBucket:p,hamtDepth:1,lastBucket:p}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await AS(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=vy(s.pos,i),c=_S(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=vy(n.lastBucket._posAtParent,i));let l=r.Links.find(u=>{if(u.Name==null)return!1;let p=u.Name.substring(0,i),h=u.Name.substring(i);return!(p!==a||h!==""&&h!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===e)return l.Hash;n.hamtDepth++;let f=await t.get(l.Hash,o);return r=Xt(f),Sy(r,e,t,n,o)},Ay=Sy;var kS=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,f=c.length??e.Links.length,u=e.Links.slice(l,f);c.onProgress?.(new M("unixfs:exporter:walk:directory",{cid:r})),yield*Gt(u,p=>He(p,h=>async()=>{let m=h.Name??"",d=`${n}/${m}`;return(await o(h.Hash,m,d,[],i+1,s,c)).entry}),p=>Nn(p,{ordered:!0,concurrency:c.blockReadConcurrency}),p=>yt(p,h=>h!=null))}return a},_y=kS;var Dn=re(Le(),1);async function ky(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=Cn(e,n,o,i);t.push(l);return}if(e.Data==null)throw(0,Dn.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=ir.unmarshal(e.Data)}catch(l){throw(0,Dn.default)(l,"ERR_NOT_UNIXFS")}if(a.data!=null){let l=a.data,f=Cn(l,n,o,i);t.push(f),n+=BigInt(f.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw(0,Dn.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let f=e.Links[l],u=n,p=u+a.blockSizes[l];if((o>=u&&o<p||i>=u&&i<=p||o<u&&i>p)&&c.push({link:f,blockStart:n}),n=p,n>i)break}await Gt(c,l=>He(l,f=>async()=>{let u=await r.get(f.link.Hash,s);return{...f,block:u}}),l=>Nn(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:f,block:u,blockStart:p}of l){let h;switch(f.Hash.code){case Ot:h=Xt(u);break;case ut:h=u;break;default:t.end((0,Dn.default)(new Error(`Unsupported codec: ${f.Hash.code}`),"ERR_NOT_UNIXFS"));return}let m=new ot({concurrency:1});m.on("error",d=>{t.end(d)}),m.add(async()=>{s.onProgress?.(new M("unixfs:exporter:walk:file",{cid:f.Hash})),await ky(r,h,t,p,o,i,s)}),await m.onIdle()}}),n>=i&&t.end()}var IS=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:f,end:u}=Lo(l,c.offset,c.length);if(u===0n)return;let p=0n,h=u-f,m=qt();c.onProgress?.(new M("unixfs:exporter:walk:file",{cid:r})),ky(s,e,m,0n,f,u,c).catch(d=>{m.end(d)});for await(let d of m)if(d!=null){if(p+=BigInt(d.byteLength),p>h)throw m.end(),(0,Dn.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");p===h&&m.end(),c.onProgress?.(new M("unixfs:exporter:progress:unixfs:file",{bytesRead:p,totalBytes:h,fileSize:l})),yield d}if(p<h)throw(0,Dn.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return a},zf=IS;var Ic=re(Le(),1);var RS=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new M("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),Iy(e,n,o,i,s,c)}return a};async function*Iy(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw(0,Ic.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=ir.unmarshal(r.Data)}catch(f){throw(0,Ic.default)(f,"ERR_NOT_UNIXFS")}if(a.fanout==null)throw(0,Ic.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let c=(a.fanout-1n).toString(16).length,l=Gt(s,f=>He(f,u=>async()=>{let p=u.Name!=null?u.Name.substring(c):null;if(p!=null&&p!==""){let h=await t(u.Hash,p,`${e}/${p}`,[],n+1,o,i);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await o.get(u.Hash,i);return r=Xt(h),i.onProgress?.(new M("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:Iy(r,e,t,n,o,i)}}}),f=>Nn(f,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:f}of l)yield*f}var Ry=RS;var BS=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,TS={raw:zf,file:zf,directory:_y,"hamt-sharded-directory":Ry,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},NS=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Xt(c),f,u;if(e==null&&(e=r.toString()),l.Data==null)throw(0,ji.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{f=ir.unmarshal(l.Data)}catch(h){throw(0,ji.default)(h,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let h;if(f?.type==="hamt-sharded-directory"?h=await Ay(l,n[0],s):h=BS(l,n[0]),h==null)throw(0,ji.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let m=n.shift(),d=`${t}/${m}`;u={cid:h,toResolve:n,name:m??"",path:d}}let p=TS[f.type](r,l,f,t,o,i,s);if(p==null)throw(0,ji.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return f.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:p,unixfs:f,depth:i,node:l,size:f.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:p,unixfs:f,depth:i,node:l,size:f.fileSize()},next:u}},By=NS;var CS={[Ot]:By,[ut]:ly,[jr]:ny,[Xr]:oy,[$e.code]:sy,[Mr]:ay},Ny=async(r,e,t,n,o,i,s)=>{let a=CS[r.code];if(a==null)throw(0,Ty.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return a(r,e,t,n,Ny,o,i,s)},Cy=Ny;var LS=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),DS=r=>{if(r instanceof Uint8Array)return{cid:q.decode(r),toResolve:[]};let e=q.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=LS(r);return{cid:q.parse(t[0]),toResolve:t.slice(1)}}throw(0,Rc.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")};async function*Gf(r,e,t={}){let{cid:n,toResolve:o}=DS(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await Cy(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw(0,Rc.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 Do(r,e,t={}){let n=await ty(Gf(r,e,t));if(n==null)throw(0,Rc.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}async function*Ly(r,e,t={}){let n=await Do(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))}}function Bc(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 Dy(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 Py(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 Oy({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 Uy({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 PS(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 OS(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 Yi=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=Dy(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=OS(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??PS(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}=Py(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 Uy({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function Fy(r){let e=Ze(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(ai(e))}function Vy(r){let e=US(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function US(r){return r.replace(/[^\x00-\x7F]/g,"_")}function My({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 FS={[jr]:["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"],[Xr]:["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"],[Mr]:["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"],[Ot]:["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"],[ut]:["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 Hy(r,e){let t=FS[r.code];if(e!=null)return VS(e,t)}function VS(r,e){let t=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:MS(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 MS(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 Tc={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 $y(r){if(r!=null)return Tc[r]}function Wf(r){let e=r.get("accept");return!!(e!=null&&Object.values(Tc).includes(e))}function jf(r){let e=r?.format;return!!(e!=null&&Object.keys(Tc).includes(e))}function Ky({query:r,headers:e}){return Wf(e)||jf(r)}function qy({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),!Ky({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=$y(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=i;return!Wf(o)&&jf(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 zy(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(l){n?.onProgress?.(new M("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:f,done:u}=await i.next();if(n?.signal?.aborted===!0){l.error(new Kt(n.signal.reason??"signal aborted by user")),l.close();return}if(u===!0){f!=null&&(n?.onProgress?.(new M("verified-fetch:request:progress:chunk")),l.enqueue(f)),l.close();return}n?.onProgress?.(new M("verified-fetch:request:progress:chunk")),l.enqueue(f)}}),firstChunk:s}}var _U=O("ustar\0","binary"),kU=O("ustar ","binary"),IU=O(" \0","binary");var Xy=re(Wy(),1);function $S(r){return r[Symbol.asyncIterator]!=null}function KS(r){if($S(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 jy=KS;var qS="0000000000000000000",zS="7777777777777777777",GS=48,WS=O("ustar\0","binary"),jS=O("00","binary"),YS=parseInt("7777",8),XS=257,ZS=263,JS=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}},QS=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},fn=function(r,e){let t=r.toString(8);return t.length>e?O(zS.slice(0,e)+" "):O(qS.slice(0,e-t.length)+t+" ")},Yf=function(r){let e=O(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function Yy(r){let e="";r.name!=null&&(e+=Yf(" path="+r.name+`
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
`));return O(e)}function Nc(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),O(t).byteLength!==t.length)return null;for(;O(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 O(t).byteLength>100||O(n).byteLength>155||r.linkname!=null&&O(r.linkname).byteLength>100?null:(e.set(O(t),0),e.set(fn(r.mode&YS,6),100),e.set(fn(r.uid,6),108),e.set(fn(r.gid,6),116),e.set(fn(r.size,11),124),e.set(fn(r.mtime.getTime()/1e3|0,11),136),e[156]=GS+JS(r.type),r.linkname!=null&&e.set(O(r.linkname),157),e.set(WS,XS),e.set(jS,ZS),r.uname!=null&&e.set(O(r.uname),265),r.gname!=null&&e.set(O(r.gname),297),e.set(fn(r.devmajor??0,6),329),e.set(fn(r.devminor??0,6),337),n!=null&&e.set(O(n),345),e.set(fn(QS(e),6),148),e)}var{S_IFMT:tA,S_IFBLK:rA,S_IFCHR:nA,S_IFDIR:oA,S_IFIFO:iA,S_IFLNK:sA}=Xy.default,aA=parseInt("755",8),cA=parseInt("644",8),Zy=new Uint8Array(1024);function lA(r=0){switch(r&tA){case rA:return"block-device";case nA:return"character-device";case oA:return"directory";case iA:return"fifo";case sA:return"symlink";default:return"file"}}function Zf(r){return r&=511,r!==0?Zy.subarray(0,512-r):new Uint8Array(0)}function Xf(r){if(r.pax==null){let e=Nc(r);if(e!=null)return e}return uA(r)}function uA(r){let e=Yy(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 lr(Nc(t)??new Uint8Array(0),e,Zf(e.length),Nc({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function Cc(){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??lA(e.mode),mode:e.mode??(e.type==="directory"?aA:cA),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=O(t)),t instanceof Uint8Array||zt(t)){n.size=t.length,yield Xf(n),yield zt(t)?t.subarray():t,yield Zf(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=G(await jy(t)),yield Xf(n);continue}if(yield Xf(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield zt(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield Zf(n.size)}yield Zy}}var fA=["file","raw","directory"];function hA(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 Jy(r){if(!fA.includes(r.type))throw new N("Not a UnixFS node","ERR_NOT_UNIXFS");let e={header:hA(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*Qy(r,e,t){let n=await Do(r,e,t);if(n.type==="file"||n.type==="raw"){yield*Gt([Jy(n)],Cc());return}if(n.type==="directory"){yield*Gt(Ly(r,e,t),o=>He(o,i=>Jy(i)),Cc());return}throw new N("Not a UnixFS node","ERR_NOT_UNIXFS")}var ew=re($l(),1),Lc=class{lru;constructor(e){this.lru=(0,ew.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 tw=new Lc(1e3),dA=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,pA=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,mA=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,gA=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function yA(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 wA(r){for(let e of[dA,pA,mA,gA]){let t=r.match(e);if(yA(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function bA(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 xA=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function EA(r){return xA.test(r)&&r.includes("-")&&!r.includes(".")}function vA(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function rw({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}=wA(r),l,f,u=[],p;if(i==="ipfs")try{l=q.parse(s)}catch(d){o.error(d),u.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(p=tw.get(s),p!=null)l=p.cid,f=p.path,o.trace("resolved %s to %c from cache",s,l);else{o.trace("Attempting to resolve PeerId for %s",s);let d=null;try{d=Ct(s),p=await e.resolve(d,n),l=p?.cid,f=p?.path,o.trace("resolved %s to %c",s,l)}catch(y){n?.signal?.throwIfAborted(),d==null?(o.error('could not parse PeerId string "%s"',s,y),u.push(new TypeError(`Could not parse PeerId in ipns url "${s}", ${y.message}`))):(o.error("could not resolve PeerId %c",d,y),u.push(new TypeError(`Could not resolve PeerId "${s}", ${y.message}`)))}if(l==null){let y=s;EA(s)&&(y=vA(s),o.trace('decoded dnslink from "%s" to "%s"',s,y)),o.trace("Attempting to resolve DNSLink for %s",y);try{p=await e.resolveDNSLink(y,n),l=p?.cid,f=p?.path,o.trace("resolved %s to %c",y,l)}catch(w){n?.signal?.throwIfAborted(),o.error('could not resolve DnsLink for "%s"',s,w),u.push(w)}}}if(l==null)throw u.length===1?u[0]:new AggregateError(u,`Invalid resource. Cannot determine CID from URL "${r}"`);let h=bA(p);p!=null&&(h=h??60*2,o.trace("caching %s resolved to %s with TTL: %s",s,l,h),tw.set(s,p,h*1e3));let m={};if(c!=null&&c.length>0){let d=c.split("&");for(let y of d){let[w,x]=y.split("=");m[w]=decodeURIComponent(x)}m.download!=null&&(m.download=m.download==="true"),m.filename!=null&&(m.filename=m.filename.toString())}return{protocol:i,cid:l,path:SA(f,a??""),query:m,ttl:h,ipfsPath:`/${i}/${s}${a!=null&&a!==""?`/${a}`:""}`}}function SA(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 nw(r,{ipns:e,logger:t},n){if(typeof r=="string")return rw({urlString:r,ipns:e,logger:t},n);let o=q.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function Jf(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function Lr(r,e){Jf(r,"type",e)}function Dr(r,e){Jf(r,"url",e)}function ow(r){Jf(r,"redirected",!0)}function Pn(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&ow(n),Lr(n,"basic"),Dr(n,r),n.headers.set("Accept-Ranges","bytes"),n}function Pc(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return Lr(n,"basic"),Dr(n,r),n}function Qf(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Lr(n,"basic"),Dr(n,r),n}function Po(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return Lr(n,"basic"),Dr(n,r),n}function Oc(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return Lr(n,"basic"),Dr(n,r),n}function Uc(r,e,t){e instanceof Error&&(e=e.message);let n=new Response(e,{...t??{},status:400,statusText:"Bad Request"});return Lr(n,"basic"),Dr(n,r),n}function iw(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return Lr(n,"basic"),Dr(n,r),n}function eh(r,e,{byteRangeContext:t,log:n},o){if(!t.isRangeRequest)return Pn(r,e,o);if(!t.isValidRangeRequest)return Dc(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),Dc(r,e,o)}return o?.redirected===!0&&ow(i),Lr(i,"basic"),Dr(i,r),i.headers.set("Accept-Ranges","bytes"),i}function Dc(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return Lr(n,"basic"),Dr(n,r),n}async function th(r,e,t){let n=[],o;for await(let i of Gf(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 sw(r){return r.type==="object"}function AA(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var _A=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function kA({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(_A.includes(o??""))return o}}var Fc=class{helia;ipns;log;contentTypeParser;constructor({helia:e,ipns:t},n){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??ey(e),this.contentTypeParser=n?.contentTypeParser,this.log.trace("created VerifiedFetch instance")}async handleIPNSRecord({resource:e,cid:t,path:n,options:o}){if(n!==""||!e.startsWith("ipns://"))return Uc(e,"Invalid IPNS name");let i;try{i=Ct(e.replace("ipns://",""))}catch(u){return this.log.error("could not parse peer id from IPNS url %s",e),Uc(e,u)}let s=ue([O("/ipns/"),i.toBytes()]),a=new xe("/dht/record/"+G(s,"base32"),!1),c=await this.helia.datastore.get(a,o),l=Nr.deserialize(c),f=Pn(e,l.value);return f.headers.set("content-type","application/vnd.ipfs.ipns-record"),f}async handleCar({resource:e,cid:t,options:n}){let o=z0(this.helia),i=Bc(o.stream(t,n)),s=Pn(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!==Ot&&t.code!==ut)return Po("only UnixFS data can be returned in a TAR file");let i=Bc(Qy(`/ipfs/${t}/${n}`,this.helia.blockstore,o)),s=Pn(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 l=Os(s);a=ii(l)}catch(l){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",l),Po(e)}else a=s;let c=Pn(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 u=await th(this.helia.blockstore,`${t.toString()}/${n}`,i);a=u.ipfsRoots;let p=u.terminalElement;if(p==null)return Oc(e);sw(p)&&(s=p)}catch(u){return i?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT"].includes(u.code)?Oc(e):(this.log.error("error walking path %s",n,u),Pc(e,"Error walking path"))}let c=s?.node??await this.helia.blockstore.get(t,i),l;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")l=c;else if(o==="application/vnd.ipld.dag-json")try{let u=En(c);l=_p(u)}catch(u){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",u),Po(e)}else try{l=Fy(c)}catch(u){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',u),Po(e);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",u),l=c}let f=Pn(e,l);return o==null&&(o=l instanceof Uint8Array?"application/octet-stream":"application/json"),f.headers.set("content-type",o),a!=null&&f.headers.set("X-Ipfs-Roots",a.map(u=>u.toV1().toString()).join(",")),f}async handleDagPb({cid:e,path:t,resource:n,options:o}){let i,s,a=!1,c=new Yi(this.helia.logger,o?.headers);try{let p=await th(this.helia.blockstore,`${e.toString()}/${t}`,o);s=p.ipfsRoots,i=p.terminalElement}catch(p){return o?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(p.code)?Oc(n.toString()):(this.log.error("error walking path %s",t,p),Pc(n.toString(),"Error walking path"))}let l=i?.cid??e;if(i?.type==="directory"){let p=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),iw(n,`${n}/`);n=`${n}/`,a=!0}let m="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",e,t);let d=await Do(`/ipfs/${p}/${m}`,this.helia.blockstore,{signal:o?.signal,onProgress:o?.onProgress});this.log.trace("found root file at %c/%s with cid %c",p,m,d.cid),t=m,l=d.cid}catch(d){return o?.signal?.throwIfAborted(),this.log("error loading path %c/%s",p,m,d),Qf("Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented")}finally{o?.onProgress?.(new M("verified-fetch:request:end",{cid:p,path:m}))}}c.isRangeRequest&&c.isValidRangeRequest&&i.type==="file"&&(c.setFileSize(i.unixfs.fileSize()),this.log.trace("fileSize for rangeRequest %d",c.getFileSize()));let f=c.offset,u=c.length;this.log.trace("calling exporter for %c/%s with offset=%o & length=%o",l,t,f,u);try{let h=(await Do(l,this.helia.blockstore,{signal:o?.signal,onProgress:o?.onProgress})).content({signal:o?.signal,onProgress:o?.onProgress,offset:f,length:u});this.log("got async iterator for %c/%s",e,t);let{stream:m,firstChunk:d}=await zy(h,t??"",this.helia.logger,{onProgress:o?.onProgress,signal:o?.signal});c.setBody(m);let y=eh(n,c.getBody(),{byteRangeContext:c,log:this.log},{redirected:a});return await this.setContentType(d,t,y),s!=null&&y.headers.set("X-Ipfs-Roots",s.map(w=>w.toV1().toString()).join(",")),y}catch(p){return o?.signal?.throwIfAborted(),this.log.error("error streaming %c/%s",e,t,p),c.isRangeRequest&&p.code==="ERR_INVALID_PARAMS"?Dc(n):Pc(n.toString(),"Unable to stream content")}}async handleRaw({resource:e,cid:t,path:n,options:o,accept:i}){let s=new Yi(this.helia.logger,o?.headers),a=await this.helia.blockstore.get(t,o);s.setBody(a);let c=eh(e,s.getBody(),{byteRangeContext:s,log:this.log},{redirected:!1});return await this.setContentType(a,n,c,kA({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(IA(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={[Ot]:this.handleDagPb,[Xr]:this.handleJson,[Mr]:this.handleJson,[jr]:this.handleDagCbor,[ut]:this.handleRaw,[$e.code]:this.handleRaw};async fetch(e,t){this.log("fetch %s",e);let n=AA(t);n?.onProgress?.(new M("verified-fetch:request:start",{resource:e}));let o,i,s,a,c,l;try{let y=await nw(e,{ipns:this.ipns,logger:this.helia.logger},n);o=y.cid,i=y.path,s=y.query,a=y.ttl,c=y.protocol,l=y.ipfsPath}catch(y){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",e,y),Uc(e.toString(),y)}n?.onProgress?.(new M("verified-fetch:request:resolve",{cid:o,path:i}));let f=qy({query:s,headers:n?.headers,logger:this.helia.logger}),u=Hy(o,f);if(this.log("output type %s",u),f!=null&&u==null)return Po(e.toString());let p,h,m={resource:e.toString(),cid:o,path:i,accept:u,options:n};if(u==="application/vnd.ipfs.ipns-record")h="ipns-record",p=await this.handleIPNSRecord(m);else if(u==="application/vnd.ipld.car")h="car",s.download=!0,s.filename=s.filename??`${o.toString()}.car`,p=await this.handleCar(m);else if(u==="application/vnd.ipld.raw")h="raw",s.download=!0,s.filename=s.filename??`${o.toString()}.bin`,p=await this.handleRaw(m);else if(u==="application/x-tar")h="tar",s.download=!0,s.filename=s.filename??`${o.toString()}.tar`,p=await this.handleTar(m);else{this.log.trace('finding handler for cid code "%s" and output type "%s"',o.code,u);let y=this.codecHandlers[o.code];if(y==null)return Qf(`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"',y.name),p=await y.call(this,m)}p.headers.set("etag",My({cid:o,reqFormat:h,weak:!1})),Oy({response:p,ttl:a,protocol:c}),p.headers.set("X-Ipfs-Path",l);let d;return s.download===!0&&(d="attachment"),s.filename!=null&&(d==null&&(d="inline"),d=`${d}; ${Vy(s.filename)}`),d!=null&&p.headers.set("Content-Disposition",d),n?.onProgress?.(new M("verified-fetch:request:end",{cid:o,path:i})),p}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function IA(r){return r?.then!=null}var Xi,Vc=async function(e,t){return Xi==null&&(Xi=await rh()),Xi(e,t)};Vc.start=async function(){await Xi?.start()};Vc.stop=async function(){await Xi?.stop()};async function rh(r,e){RA(r)||(r=await B0({blockBrokers:[Li({gateways:r?.gateways})],routers:(r?.routers??["https://delegated-ipfs.dev"]).map(o=>Fi(o)),dns:BA(r?.dnsResolvers)}));let t=new Fc({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 RA(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function BA(r){if(r!=null)return Array.isArray(r)?Zo({resolvers:{".":r}}):Zo({resolvers:r})}return xw(TA);})();
|
|
7
|
+
`)}`:`${t} :`}};ip=Qr;F.Constructed=ip;Qr.NAME="CONSTRUCTED";var $s=class extends Ge{fromBER(e,t,n){return t}toBER(e){return Ut}};$s.override="EndOfContentValueBlock";var sp,zs=class extends Ue{constructor(e={}){super(e,$s),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};sp=zs;F.EndOfContent=sp;zs.NAME=ii;var ap,en=class extends Ue{constructor(e={}){super(e,Ge),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}`}};ap=en;F.Null=ap;en.NAME="NULL";var Ks=class extends Sr(Ge){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=J.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=J.BufferSourceConverter.toUint8Array(e);return vr(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,pu.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Ks.NAME="BooleanValueBlock";var cp,qs=class extends Ue{constructor(e={}){super(e,Ks),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}`}};cp=qs;F.Boolean=cp;qs.NAME="BOOLEAN";var Gs=class extends Sr(tr){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=tr.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===ii){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==tp)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?tr.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Gs.NAME="OctetStringValueBlock";var lp,xr=class r extends Ue{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},Gs),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=xa(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?Qr.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${J.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 J.BufferSourceConverter.concat(e)}};lp=xr;F.OctetString=lp;xr.NAME=tp;var Ws=class extends Sr(tr){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=tr.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===ii){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==rp)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=J.BufferSourceConverter.toUint8Array(e);if(!vr(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=xa(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 tr.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Ut;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}}};Ws.NAME="BitStringValueBlock";var up,ho=class extends Ue{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},Ws),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 Qr.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)}`}}};up=ho;F.BitString=up;ho.NAME=rp;var fp;function sE(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,l=0,u=c<s?s:c,f=0;for(let p=u;p>=0;p--,f++){switch(!0){case f<a.length:l=i[s-f]+a[c-f]+t[0];break;default:l=i[s-f]+t[0]}switch(t[0]=l/10,!0){case f>=i.length:i=Ds(new Uint8Array([l%10]),i);break;default:i[s-f]=l%10}}return t[0]>0&&(i=Ds(t,i)),i}function ep(r){if(r>=ni.length)for(let e=ni.length;e<=r;e++){let t=new Uint8Array([0]),n=ni[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=Ds(t,n)),ni.push(n)}return ni[r]}function aE(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,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=i[s-u]-a[c-u]-t,!0){case l<0:t=1,i[s-u]=l+10;break;default:t=0,i[s-u]=l}if(t>0)for(let f=s-c+1;f>=0;f--,u++)if(l=i[s-u]-t,l<0)t=1,i[s-u]=l+10;else{t=0,i[s-u]=l;break}return i.slice()}var si=class extends Sr(Ge){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=pu.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Zd(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 l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=aE(ep(n),t),s="-";break;default:t=sE(t,ep(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=Qd.charAt(t[c]));return a===!1&&(s+=Qd.charAt(0)),s}};fp=si;si.NAME="IntegerValueBlock";Object.defineProperty(fp.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var hp,Ae=class r extends Ue{constructor(e={}){super(e,si),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Ps(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Ps();let t=BigInt(e),n=new oi,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(J.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${J.Convert.ToHex(a)}`)+t,u=J.BufferSourceConverter.toUint8Array(J.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let 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()}`}};hp=Ae;F.Integer=hp;Ae.NAME="INTEGER";var dp,js=class extends Ae{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};dp=js;F.Enumerated=dp;js.NAME="ENUMERATED";var ai=class extends Sr(Ge){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=J.BufferSourceConverter.toUint8Array(e);if(!vr(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=Rn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Ps();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=Jr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Ut;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=J.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}}};ai.NAME="sidBlock";var Ys=class extends Ge{constructor({value:e=po,...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.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,Ut;t.push(o)}return mu(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 ai;if(o>Number.MAX_SAFE_INTEGER){Ps();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}while(n!==-1)}toString(){let 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}};Ys.NAME="ObjectIdentifierValueBlock";var pp,Pt=class extends Ue{constructor(e={}){super(e,Ys),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()}}};pp=Pt;F.ObjectIdentifier=pp;Pt.NAME="OBJECT IDENTIFIER";var ci=class extends Sr(br){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=J.BufferSourceConverter.toUint8Array(e);if(!vr(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=Rn(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=Jr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Ut;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=J.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};ci.NAME="relativeSidBlock";var Xs=class extends Ge{constructor({value:e=po,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new ci;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,Ut;n.push(i)}return mu(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 ci;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}};Xs.NAME="RelativeObjectIdentifierValueBlock";var mp,Zs=class extends Ue{constructor(e={}){super(e,Xs),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()}}};mp=Zs;F.RelativeObjectIdentifier=mp;Zs.NAME="RelativeObjectIdentifier";var gp,Te=class extends Qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};gp=Te;F.Sequence=gp;Te.NAME="SEQUENCE";var yp,Js=class extends Qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};yp=Js;F.Set=yp;Js.NAME="SET";var Qs=class extends Sr(Ge){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=po}toJSON(){return{...super.toJSON(),value:this.value}}};Qs.NAME="StringValueBlock";var ea=class extends Qs{};ea.NAME="SimpleStringValueBlock";var Je=class extends Ms{constructor({...e}={}){super(e,ea)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,J.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}};Je.NAME="SIMPLE STRING";var ta=class extends Je{fromBuffer(e){this.valueBlock.valueHexView=J.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=J.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=J.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(J.Convert.FromUtf8String(e)),this.valueBlock.value=e}};ta.NAME="Utf8StringValueBlock";var wp,Er=class extends ta{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};wp=Er;F.Utf8String=wp;Er.NAME="UTF8String";var ra=class extends Je{fromBuffer(e){this.valueBlock.value=J.Convert.ToUtf16String(e),this.valueBlock.valueHexView=J.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(J.Convert.FromUtf16String(e))}};ra.NAME="BmpStringValueBlock";var bp,na=class extends ra{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};bp=na;F.BmpString=bp;na.NAME="BMPString";var oa=class extends Je{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=Jr(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}};oa.NAME="UniversalStringValueBlock";var xp,ia=class extends oa{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};xp=ia;F.UniversalString=xp;ia.NAME="UniversalString";var Ep,sa=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Ep=sa;F.NumericString=Ep;sa.NAME="NumericString";var vp,aa=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};vp=aa;F.PrintableString=vp;aa.NAME="PrintableString";var Sp,ca=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Sp=ca;F.TeletexString=Sp;ca.NAME="TeletexString";var Ap,la=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Ap=la;F.VideotexString=Ap;la.NAME="VideotexString";var _p,ua=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};_p=ua;F.IA5String=_p;ua.NAME="IA5String";var Ip,fa=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Ip=fa;F.GraphicString=Ip;fa.NAME="GraphicString";var Rp,li=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Rp=li;F.VisibleString=Rp;li.NAME="VisibleString";var kp,ha=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};kp=ha;F.GeneralString=kp;ha.NAME="GeneralString";var Bp,da=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Bp=da;F.CharacterString=Bp;da.NAME="CharacterString";var Tp,ui=class extends li{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,J.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]=st(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=st(this.month,2),t[2]=st(this.day,2),t[3]=st(this.hour,2),t[4]=st(this.minute,2),t[5]=st(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}}};Tp=ui;F.UTCTime=Tp;ui.NAME="UTCTime";var Np,pa=class extends ui{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,p=n.indexOf("+"),h="";if(p===-1&&(p=n.indexOf("-"),f=-1),p!==-1){if(h=n.substring(p+1),n=n.substring(0,p),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(h.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*m,h.length===4){if(m=parseInt(h.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=f*m}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");i=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*i;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*i;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*i;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=s.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(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(st(this.year,4)),t.push(st(this.month,2)),t.push(st(this.day,2)),t.push(st(this.hour,2)),t.push(st(this.minute,2)),t.push(st(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(st(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Np=pa;F.GeneralizedTime=Np;pa.NAME="GeneralizedTime";var Cp,ma=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Cp=ma;F.DATE=Cp;ma.NAME="DATE";var Lp,ga=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Lp=ga;F.TimeOfDay=Lp;ga.NAME="TimeOfDay";var Op,ya=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Op=ya;F.DateTime=Op;ya.NAME="DateTime";var Dp,wa=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Dp=wa;F.Duration=Dp;wa.NAME="Duration";var Pp,ba=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Pp=ba;F.TIME=Pp;ba.NAME="TIME";function lE(r){let{result:e}=mo(r),t=e.valueBlock.value;return{n:G(rr(t[1].toBigInt()),"base64url"),e:G(rr(t[2].toBigInt()),"base64url"),d:G(rr(t[3].toBigInt()),"base64url"),p:G(rr(t[4].toBigInt()),"base64url"),q:G(rr(t[5].toBigInt()),"base64url"),dp:G(rr(t[6].toBigInt()),"base64url"),dq:G(rr(t[7].toBigInt()),"base64url"),qi:G(rr(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function uE(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 Te({value:[new Ae({value:0}),Ae.fromBigInt(nr(P(r.n,"base64url"))),Ae.fromBigInt(nr(P(r.e,"base64url"))),Ae.fromBigInt(nr(P(r.d,"base64url"))),Ae.fromBigInt(nr(P(r.p,"base64url"))),Ae.fromBigInt(nr(P(r.q,"base64url"))),Ae.fromBigInt(nr(P(r.dp,"base64url"))),Ae.fromBigInt(nr(P(r.dq,"base64url"))),Ae.fromBigInt(nr(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function fE(r){let{result:e}=mo(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:G(rr(t[0].toBigInt()),"base64url"),e:G(rr(t[1].toBigInt()),"base64url")}}function hE(r){if(r.n==null||r.e==null)throw new N("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Te({value:[new Te({value:[new Pt({value:"1.2.840.113549.1.1.1"}),new en]}),new ho({valueHex:new Te({value:[Ae.fromBigInt(nr(P(r.n,"base64url"))),Ae.fromBigInt(nr(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function rr(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 nr(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 dE=16,yu=32,wu=1e4;async function pE(r,e){let t=Ze.get(),o=new Te({value:[new Ae({value:0}),new Te({value:[new Pt({value:"1.2.840.113549.1.1.1"}),new en]}),new xr({valueHex:r.marshal()})]}).toBER(),i=new Uint8Array(o,0,o.byteLength),s=er(dE),a=await hu(io,e,s,{c:wu,dkLen:yu}),c=er(16),l=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=await t.subtle.encrypt({name:"AES-CBC",iv:c},l,i),f=new Te({value:[new xr({valueHex:s}),new Ae({value:wu}),new Ae({value:yu}),new Te({value:[new Pt({value:"1.2.840.113549.2.11"}),new en]})]}),p=new Te({value:[new Pt({value:"1.2.840.113549.1.5.13"}),new Te({value:[new Te({value:[new Pt({value:"1.2.840.113549.1.5.12"}),f]}),new Te({value:[new Pt({value:"2.16.840.1.101.3.4.1.42"}),new xr({valueHex:c})]})]})]}),m=new Te({value:[p,new xr({valueHex:u})]}).toBER(),d=new Uint8Array(m,0,m.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...G(d,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
8
|
+
`)}async function mE(r,e){let t=Ze.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=P(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=mo(o),{iv:s,salt:a,iterations:c,keySize:l,cipherText:u}=gE(i),f=await hu(io,e,a,{c,dkLen:l}),p=await t.subtle.importKey("raw",f,"AES-CBC",!1,["decrypt"]),h=fi(await t.subtle.decrypt({name:"AES-CBC",iv:s},p,u)),{result:m}=mo(h);n=Up(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=P(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=mo(o);n=Up(i)}else throw new N("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return bu(n)}function gE(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=fi(i.valueBlock.value[0].getValue()),a=wu,c=yu;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 l=e.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="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=fi(l.valueBlock.value[1].getValue());return{cipherText:fi(r.valueBlock.value[1].getValue()),salt:s,iterations:a,keySize:c,iv:f}}function Up(r){return fi(r.valueBlock.value[2].getValue())}function fi(r){return new Uint8Array(r,0,r.byteLength)}async function Fp(r){let e=await Ze.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 Hp(e);return{privateKey:t[0],publicKey:t[1]}}async function xu(r){let t=[await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await yE(r)],n=await Hp({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Mp(r,e){let t=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ze.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Vp(r,e,t){let n=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ze.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function Hp(r){if(r.privateKey==null||r.publicKey==null)throw new N("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ze.get().subtle.exportKey("jwk",r.privateKey),Ze.get().subtle.exportKey("jwk",r.publicKey)])}async function yE(r){return Ze.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 Ea(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 P(r.n,"base64url").length*8}var di=8192,hi=class{_key;constructor(e){this._key=e}verify(e,t){return Vp(this._key,t,e)}marshal(){return tn.jwkToPkix(this._key)}get bytes(){return Jt.encode({Type:pe.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}},go=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return er(16)}sign(e){return Mp(this._key,e)}get public(){if(this._publicKey==null)throw new N("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new hi(this._publicKey)}marshal(){return tn.jwkToPkcs1(this._key)}get bytes(){return Qt.encode({Type:pe.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return G(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return tn.exportToPem(this,e);if(t==="libp2p-key")return lo(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function bu(r){let e=tn.pkcs1ToJwk(r);if(Ea(e)>di)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await xu(e);return new go(t.privateKey,t.publicKey)}function bE(r){let e=tn.pkixToJwk(r);if(Ea(e)>di)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new hi(e)}async function xE(r){if(Ea(r)>di)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await xu(r);return new go(e.privateKey,e.publicKey)}async function EE(r){if(r>di)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Fp(r);return new go(e.privateKey,e.publicKey)}var Iu={};Se(Iu,{Secp256k1PrivateKey:()=>mi,Secp256k1PublicKey:()=>pi,generateKeyPair:()=>OE,unmarshalSecp256k1PrivateKey:()=>CE,unmarshalSecp256k1PublicKey:()=>LE});var vE=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]),rn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),nn=new Uint32Array(64),vu=class extends oo{constructor(){super(64,32,8,!1),this.A=rn[0]|0,this.B=rn[1]|0,this.C=rn[2]|0,this.D=rn[3]|0,this.E=rn[4]|0,this.F=rn[5]|0,this.G=rn[6]|0,this.H=rn[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)nn[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let p=nn[f-15],h=nn[f-2],m=Ot(p,7)^Ot(p,18)^p>>>3,d=Ot(h,17)^Ot(h,19)^h>>>10;nn[f]=d+nn[f-7]+m+nn[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let p=Ot(a,6)^Ot(a,11)^Ot(a,25),h=u+p+Id(a,c,l)+vE[f]+nn[f]|0,d=(Ot(n,2)^Ot(n,13)^Ot(n,22))+Rd(n,o,i)|0;u=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+d|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,l,u)}roundClean(){nn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var $p=Es(()=>new vu);function SE(r){let e=ei(r);Zt(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:AE,hexToBytes:_E}=As,kn={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=kn;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:AE(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=kn,t=typeof r=="string"?_E(r):r;so(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}=kn._parseInt(t.subarray(2)),{d:s,l:a}=kn._parseInt(i);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let u=l.toString(16);return u.length&1?`0${u}`:u},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}`}},Ar=BigInt(0),Bt=BigInt(1),jB=BigInt(2),zp=BigInt(3),YB=BigInt(4);function IE(r){let e=SE(r),{Fp:t}=e,n=e.toBytes||((m,d,y)=>{let g=d.toAffine();return mr(Uint8Array.from([4]),t.toBytes(g.x),t.toBytes(g.y))}),o=e.fromBytes||(m=>{let d=m.subarray(1),y=t.fromBytes(d.subarray(0,t.BYTES)),g=t.fromBytes(d.subarray(t.BYTES,2*t.BYTES));return{x:y,y:g}});function i(m){let{a:d,b:y}=e,g=t.sqr(m),b=t.mul(g,m);return t.add(t.add(b,t.mul(m,d)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function s(m){return typeof m=="bigint"&&Ar<m&&m<e.n}function a(m){if(!s(m))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(m){let{allowedPrivateKeyLengths:d,nByteLength:y,wrapPrivateKey:g,n:b}=e;if(d&&typeof m!="bigint"){if(Yr(m)&&(m=dr(m)),typeof m!="string"||!d.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:pr(be("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return g&&(x=ce(x,b)),a(x),x}let l=new Map;function u(m){if(!(m instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(d,y,g){if(this.px=d,this.py=y,this.pz=g,d==null||!t.isValid(d))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(d){let{x:y,y:g}=d||{};if(!d||!t.isValid(y)||!t.isValid(g))throw new Error("invalid affine point");if(d 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(d){let y=t.invertBatch(d.map(g=>g.pz));return d.map((g,b)=>g.toAffine(y[b])).map(f.fromAffine)}static fromHex(d){let y=f.fromAffine(o(be("pointHex",d)));return y.assertValidity(),y}static fromPrivateKey(d){return f.BASE.multiply(c(d))}_setWindowSize(d){this._WINDOW_SIZE=d,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:d,y}=this.toAffine();if(!t.isValid(d)||!t.isValid(y))throw new Error("bad point: x or y not FE");let g=t.sqr(y),b=i(d);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:d}=this.toAffine();if(t.isOdd)return!t.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){u(d);let{px:y,py:g,pz:b}=this,{px:x,py:E,pz:v}=d,_=t.eql(t.mul(y,v),t.mul(x,b)),S=t.eql(t.mul(g,v),t.mul(E,b));return _&&S}negate(){return new f(this.px,t.neg(this.py),this.pz)}double(){let{a:d,b:y}=e,g=t.mul(y,zp),{px:b,py:x,pz:E}=this,v=t.ZERO,_=t.ZERO,S=t.ZERO,A=t.mul(b,b),L=t.mul(x,x),U=t.mul(E,E),O=t.mul(b,x);return O=t.add(O,O),S=t.mul(b,E),S=t.add(S,S),v=t.mul(d,S),_=t.mul(g,U),_=t.add(v,_),v=t.sub(L,_),_=t.add(L,_),_=t.mul(v,_),v=t.mul(O,v),S=t.mul(g,S),U=t.mul(d,U),O=t.sub(A,U),O=t.mul(d,O),O=t.add(O,S),S=t.add(A,A),A=t.add(S,A),A=t.add(A,U),A=t.mul(A,O),_=t.add(_,A),U=t.mul(x,E),U=t.add(U,U),A=t.mul(U,O),v=t.sub(v,A),S=t.mul(U,L),S=t.add(S,S),S=t.add(S,S),new f(v,_,S)}add(d){u(d);let{px:y,py:g,pz:b}=this,{px:x,py:E,pz:v}=d,_=t.ZERO,S=t.ZERO,A=t.ZERO,L=e.a,U=t.mul(e.b,zp),O=t.mul(y,x),$=t.mul(g,E),C=t.mul(b,v),ee=t.add(y,g),k=t.add(x,E);ee=t.mul(ee,k),k=t.add(O,$),ee=t.sub(ee,k),k=t.add(y,b);let T=t.add(x,v);return k=t.mul(k,T),T=t.add(O,C),k=t.sub(k,T),T=t.add(g,b),_=t.add(E,v),T=t.mul(T,_),_=t.add($,C),T=t.sub(T,_),A=t.mul(L,k),_=t.mul(U,C),A=t.add(_,A),_=t.sub($,A),A=t.add($,A),S=t.mul(_,A),$=t.add(O,O),$=t.add($,O),C=t.mul(L,C),k=t.mul(U,k),$=t.add($,C),C=t.sub(O,C),C=t.mul(L,C),k=t.add(k,C),O=t.mul($,k),S=t.add(S,O),O=t.mul(T,k),_=t.mul(ee,_),_=t.sub(_,O),O=t.mul(ee,$),A=t.mul(T,A),A=t.add(A,O),new f(_,S,A)}subtract(d){return this.add(d.negate())}is0(){return this.equals(f.ZERO)}wNAF(d){return h.wNAFCached(this,l,d,y=>{let g=t.invertBatch(y.map(b=>b.pz));return y.map((b,x)=>b.toAffine(g[x])).map(f.fromAffine)})}multiplyUnsafe(d){let y=f.ZERO;if(d===Ar)return y;if(a(d),d===Bt)return this;let{endo:g}=e;if(!g)return h.unsafeLadder(this,d);let{k1neg:b,k1:x,k2neg:E,k2:v}=g.splitScalar(d),_=y,S=y,A=this;for(;x>Ar||v>Ar;)x&Bt&&(_=_.add(A)),v&Bt&&(S=S.add(A)),A=A.double(),x>>=Bt,v>>=Bt;return b&&(_=_.negate()),E&&(S=S.negate()),S=new f(t.mul(S.px,g.beta),S.py,S.pz),_.add(S)}multiply(d){a(d);let y=d,g,b,{endo:x}=e;if(x){let{k1neg:E,k1:v,k2neg:_,k2:S}=x.splitScalar(y),{p:A,f:L}=this.wNAF(v),{p:U,f:O}=this.wNAF(S);A=h.constTimeNegate(E,A),U=h.constTimeNegate(_,U),U=new f(t.mul(U.px,x.beta),U.py,U.pz),g=A.add(U),b=L.add(O)}else{let{p:E,f:v}=this.wNAF(y);g=E,b=v}return f.normalizeZ([g,b])[0]}multiplyAndAddUnsafe(d,y,g){let b=f.BASE,x=(v,_)=>_===Ar||_===Bt||!v.equals(b)?v.multiplyUnsafe(_):v.multiply(_),E=x(this,y).add(x(d,g));return E.is0()?void 0:E}toAffine(d){let{px:y,py:g,pz:b}=this,x=this.is0();d==null&&(d=x?t.ONE:t.inv(b));let E=t.mul(y,d),v=t.mul(g,d),_=t.mul(b,d);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(_,t.ONE))throw new Error("invZ was invalid");return{x:E,y:v}}isTorsionFree(){let{h:d,isTorsionFree:y}=e;if(d===Bt)return!0;if(y)return y(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:d,clearCofactor:y}=e;return d===Bt?this:y?y(f,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return this.assertValidity(),n(f,this,d)}toHex(d=!0){return dr(this.toRawBytes(d))}}f.BASE=new f(e.Gx,e.Gy,t.ONE),f.ZERO=new f(t.ZERO,t.ONE,t.ZERO);let p=e.nBitLength,h=Rs(f,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:s}}function RE(r){let e=ei(r);return Zt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Kp(r){let e=RE(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(k){return Ar<k&&k<t.ORDER}function a(k){return ce(k,n)}function c(k){return _s(k,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:p}=IE({...e,toBytes(k,T,q){let B=T.toAffine(),I=t.toBytes(B.x),M=mr;return q?M(Uint8Array.from([T.hasEvenY()?2:3]),I):M(Uint8Array.from([4]),I,t.toBytes(B.y))},fromBytes(k){let T=k.length,q=k[0],B=k.subarray(1);if(T===o&&(q===2||q===3)){let I=pr(B);if(!s(I))throw new Error("Point is not on curve");let M=f(I),K;try{K=t.sqrt(M)}catch(Z){let ie=Z instanceof Error?": "+Z.message:"";throw new Error("Point is not on curve"+ie)}let W=(K&Bt)===Bt;return(q&1)===1!==W&&(K=t.neg(K)),{x:I,y:K}}else if(T===i&&q===4){let I=t.fromBytes(B.subarray(0,t.BYTES)),M=t.fromBytes(B.subarray(t.BYTES,2*t.BYTES));return{x:I,y:M}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),h=k=>dr(Zr(k,e.nByteLength));function m(k){let T=n>>Bt;return k>T}function d(k){return m(k)?a(-k):k}let y=(k,T,q)=>pr(k.slice(T,q));class g{constructor(T,q,B){this.r=T,this.s=q,this.recovery=B,this.assertValidity()}static fromCompact(T){let q=e.nByteLength;return T=be("compactSignature",T,q*2),new g(y(T,0,q),y(T,q,2*q))}static fromDER(T){let{r:q,s:B}=kn.toSig(be("DER",T));return new g(q,B)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(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:q,s:B,recovery:I}=this,M=S(be("msgHash",T));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");let K=I===2||I===3?q+e.n:q;if(K>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=I&1?"03":"02",X=l.fromHex(W+h(K)),Z=c(K),ie=a(-M*Z),Q=a(B*Z),te=l.BASE.multiplyAndAddUnsafe(X,ie,Q);if(!te)throw new Error("point at infinify");return te.assertValidity(),te}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Sn(this.toDERHex())}toDERHex(){return kn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Sn(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let b={isValidPrivateKey(k){try{return u(k),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let k=ou(e.n);return Fd(e.randomBytes(k),e.n)},precompute(k=8,T=l.BASE){return T._setWindowSize(k),T.multiply(BigInt(3)),T}};function x(k,T=!0){return l.fromPrivateKey(k).toRawBytes(T)}function E(k){let T=Yr(k),q=typeof k=="string",B=(T||q)&&k.length;return T?B===o||B===i:q?B===2*o||B===2*i:k instanceof l}function v(k,T,q=!0){if(E(k))throw new Error("first arg must be private key");if(!E(T))throw new Error("second arg must be public key");return l.fromHex(T).multiply(u(k)).toRawBytes(q)}let _=e.bits2int||function(k){let T=pr(k),q=k.length*8-e.nBitLength;return q>0?T>>BigInt(q):T},S=e.bits2int_modN||function(k){return a(_(k))},A=Qo(e.nBitLength);function L(k){if(typeof k!="bigint")throw new Error("bigint expected");if(!(Ar<=k&&k<A))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Zr(k,e.nByteLength)}function U(k,T,q=O){if(["recovered","canonical"].some(ye=>ye in q))throw new Error("sign() legacy options not supported");let{hash:B,randomBytes:I}=e,{lowS:M,prehash:K,extraEntropy:W}=q;M==null&&(M=!0),k=be("msgHash",k),K&&(k=be("prehashed msgHash",B(k)));let X=S(k),Z=u(T),ie=[L(Z),L(X)];if(W!=null&&W!==!1){let ye=W===!0?I(t.BYTES):W;ie.push(be("extraEntropy",ye))}let Q=mr(...ie),te=X;function ve(ye){let Ce=_(ye);if(!p(Ce))return;let Le=c(Ce),Ie=l.BASE.multiply(Ce).toAffine(),$e=a(Ie.x);if($e===Ar)return;let cr=a(Le*a(te+$e*Z));if(cr===Ar)return;let yn=(Ie.x===$e?0:2)|Number(Ie.y&Bt),Ho=cr;return M&&m(cr)&&(Ho=d(cr),yn^=1),new g($e,Ho,yn)}return{seed:Q,k2sig:ve}}let O={lowS:e.lowS,prehash:!1},$={lowS:e.lowS,prehash:!1};function C(k,T,q=O){let{seed:B,k2sig:I}=U(k,T,q),M=e;return eu(M.hash.outputLen,M.nByteLength,M.hmac)(B,I)}l.BASE._setWindowSize(8);function ee(k,T,q,B=$){let I=k;if(T=be("msgHash",T),q=be("publicKey",q),"strict"in B)throw new Error("options.strict was renamed to lowS");let{lowS:M,prehash:K}=B,W,X;try{if(typeof I=="string"||Yr(I))try{W=g.fromDER(I)}catch(Ie){if(!(Ie instanceof kn.Err))throw Ie;W=g.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){let{r:Ie,s:$e}=I;W=new g(Ie,$e)}else throw new Error("PARSE");X=l.fromHex(q)}catch(Ie){if(Ie.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(M&&W.hasHighS())return!1;K&&(T=e.hash(T));let{r:Z,s:ie}=W,Q=S(T),te=c(ie),ve=a(Q*te),ye=a(Z*te),Ce=l.BASE.multiplyAndAddUnsafe(X,ve,ye)?.toAffine();return Ce?a(Ce.x)===Z:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:v,sign:C,verify:ee,ProjectivePoint:l,Signature:g,utils:b}}function kE(r){return{hash:r,hmac:(e,...t)=>ri(r,e,xs(...t)),randomBytes:no}}function qp(r,e){let t=n=>Kp({...r,...kE(n)});return Object.freeze({...t(e),create:t})}var jp=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Gp=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),BE=BigInt(1),Su=BigInt(2),Wp=(r,e)=>(r+e/Su)/e;function TE(r){let e=jp,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=de(u,t,e)*u%e,p=de(f,t,e)*u%e,h=de(p,Su,e)*l%e,m=de(h,o,e)*h%e,d=de(m,i,e)*m%e,y=de(d,a,e)*d%e,g=de(y,c,e)*y%e,b=de(g,a,e)*d%e,x=de(b,t,e)*u%e,E=de(x,s,e)*m%e,v=de(E,n,e)*l%e,_=de(v,Su,e);if(!Au.eql(Au.sqr(_),r))throw new Error("Cannot find square root");return _}var Au=Is(jp,void 0,void 0,{sqrt:TE}),Ft=qp({a:BigInt(0),b:BigInt(7),Fp:Au,n:Gp,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Gp,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-BE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=Wp(i*r,e),c=Wp(-n*r,e),l=ce(r-a*t-c*o,e),u=ce(-a*n-c*i,e),f=l>s,p=u>s;if(f&&(l=e-l),p&&(u=e-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:p,k2:u}}}},$p),o8=BigInt(0);var i8=Ft.ProjectivePoint;function Yp(){return Ft.utils.randomPrivateKey()}function Xp(r,e){let t=Re.digest(e instanceof Uint8Array?e:e.subarray());if(Rt(t))return t.then(({digest:n})=>Ft.sign(n,r).toDERRawBytes()).catch(n=>{throw new N(String(n),"ERR_INVALID_INPUT")});try{return Ft.sign(t.digest,r).toDERRawBytes()}catch(n){throw new N(String(n),"ERR_INVALID_INPUT")}}function Zp(r,e,t){let n=Re.digest(t instanceof Uint8Array?t:t.subarray());if(Rt(n))return n.then(({digest:o})=>Ft.verify(e,o,r)).catch(o=>{throw new N(String(o),"ERR_INVALID_INPUT")});try{return Ft.verify(e,n.digest,r)}catch(o){throw new N(String(o),"ERR_INVALID_INPUT")}}function Jp(r){return Ft.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Qp(r){try{Ft.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}function _u(r){try{Ft.ProjectivePoint.fromHex(r)}catch(e){throw new N(String(e),"ERR_INVALID_PUBLIC_KEY")}}function em(r){try{return Ft.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}var pi=class{_key;constructor(e){_u(e),this._key=e}verify(e,t){return Zp(this._key,t,e)}marshal(){return Jp(this._key)}get bytes(){return Jt.encode({Type:pe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return Rt(e)?{bytes:t}=await e:t=e.bytes,t}},mi=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??em(e),Qp(this._key),_u(this._publicKey)}sign(e){return Xp(this._key,e)}get public(){return new pi(this._publicKey)}marshal(){return this._key}get bytes(){return Qt.encode({Type:pe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return G(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return lo(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function CE(r){return new mi(r)}function LE(r){return new pi(r)}async function OE(){let r=Yp();return new mi(r)}var Bn={rsa:Eu,ed25519:fu,secp256k1:Iu};function tm(r){let e=Object.keys(Bn).join(" / ");return new N(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Ru(r){let e=Jt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case pe.RSA:return Bn.rsa.unmarshalRsaPublicKey(t);case pe.Ed25519:return Bn.ed25519.unmarshalEd25519PublicKey(t);case pe.Secp256k1:return Bn.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw tm(e.Type??"unknown")}}async function rm(r){let e=Qt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case pe.RSA:return Bn.rsa.unmarshalRsaPrivateKey(t);case pe.Ed25519:return Bn.ed25519.unmarshalEd25519PrivateKey(t);case pe.Secp256k1:return Bn.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw tm(e.Type??"RSA")}}var mt=re(lm(),1);mt.default.formatters.b=r=>r==null?"undefined":ge.baseEncode(r);mt.default.formatters.t=r=>r==null?"undefined":Pe.baseEncode(r);mt.default.formatters.m=r=>r==null?"undefined":it.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 WE(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 um(){return{forComponent(r){return Qe(r)}}}function Qe(r){let e=WE(`${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})}var Tu=re(hm(),1);var wi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Nu=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},dm=r=>globalThis.DOMException===void 0?new Nu(r):new DOMException(r),pm=r=>{let e=r.reason===void 0?dm("This operation was aborted."):r.reason;return e instanceof Error?e:dm(e)};function bi(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,c=new Promise((l,u)=>{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:p}=e;p.aborted&&u(pm(p)),p.addEventListener("abort",()=>{u(pm(p))})}if(t===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new wi;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){u(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${t} milliseconds`,u(f))},t),(async()=>{try{l(await r)}catch(p){u(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function Cu(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{#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=Cu(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 at=class extends Tu.default{#e;#n;#s=0;#u;#g;#a=0;#f;#c;#r;#t;#i=0;#m;#l;#h;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:xi,...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.#n=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#u=e.intervalCap,this.#g=e.interval,this.#r=new e.queueClass,this.#t=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#h=e.throwOnTimeout===!0,this.#l=e.autoStart===!1}get#b(){return this.#n||this.#s<this.#u}get#d(){return this.#i<this.#m}#x(){this.#i--,this.#w(),this.emit("next")}#E(){this.#p(),this.#A(),this.#c=void 0}get#y(){let e=Date.now();if(this.#f===void 0){let t=this.#a-e;if(t<0)this.#s=this.#e?this.#i:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#E()},t)),!0}return!1}#w(){if(this.#r.size===0)return this.#f&&clearInterval(this.#f),this.#f=void 0,this.emit("empty"),this.#i===0&&this.emit("idle"),!1;if(!this.#l){let e=!this.#y;if(this.#b&&this.#d){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#A(),!0):!1}}return!1}#A(){this.#n||this.#f!==void 0||(this.#f=setInterval(()=>{this.#p()},this.#g),this.#a=Date.now()+this.#g)}#p(){this.#s===0&&this.#i===0&&this.#f&&(clearInterval(this.#f),this.#f=void 0),this.#s=this.#e?this.#i:0,this.#R()}#R(){for(;this.#w(););}get concurrency(){return this.#m}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.#m=e,this.#R()}async#k(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.#h,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#i++,this.#s++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=bi(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#k(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof wi&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#x()}},t),this.emit("add"),this.#w()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#l?(this.#l=!1,this.#R(),this):this}pause(){this.#l=!0}clear(){this.#r=new this.#t}async onEmpty(){this.#r.size!==0&&await this.#v("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#v("next",()=>this.#r.size<e)}async onIdle(){this.#i===0&&this.#r.size===0||await this.#v("idle")}async#v(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#i}get isPaused(){return this.#l}};function Ia(r){let e=[ct.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Lu=60;function Ra(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:ct[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ct[e.type],TTL:e.TTL??e.ttl??Lu,data:e.data instanceof Uint8Array?G(e.data):e.data}))}}var XE=4;function Ou(r,e={}){let t=new at({concurrency:e.queryConcurrency??XE});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),Ia(o.types).forEach(a=>{i.append("type",ct[a])}),o.onProgress?.(new V("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=Ra(await a.json());return o.onProgress?.(new V("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function mm(){return[Ou("https://cloudflare-dns.com/dns-query"),Ou("https://dns.google/resolve")]}var ym=re(Du(),1);var Pu=class{lru;constructor(e){this.lru=(0,ym.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 Ra({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:ct[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??Lu)*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 wm(r){return new Pu(r)}var ZE=1e3,ka=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=wm(e.cacheSize??ZE),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["."]=mm())}async query(e,t={}){let n=Ia(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new V("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 l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new V("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var ct;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ct||(ct={}));function Ei(r={}){return new ka(r)}var JE=["string","number","bigint","symbol"],QE=["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 bm(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(JE.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(ev(r))return"Buffer";let t=tv(r);return t||"Object"}function ev(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function tv(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(QE.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 R=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 xo=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",rv=new TextDecoder,nv=new TextEncoder;function Ba(r){return xo&&globalThis.Buffer.isBuffer(r)}function vi(r){return r instanceof Uint8Array?Ba(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Sm=xo?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Em(r,e,t):(r,e,t)=>t-e>64?rv.decode(r.subarray(e,t)):Em(r,e,t),Ta=xo?r=>r.length>64?globalThis.Buffer.from(r):xm(r):r=>r.length>64?nv.encode(r):xm(r),or=r=>Uint8Array.from(r),Eo=xo?(r,e,t)=>Ba(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Am=xo?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),vi(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},_m=xo?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Im(r,e){if(Ba(r)&&Ba(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 xm(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 Em(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,l,u;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(u=(o&31)<<6|a&63,u>127&&(i=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(o&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(i=u))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return Uu(n)}var vm=4096;function Uu(r){let e=r.length;if(e<=vm)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=vm));return t}var ov=256,Si=class{constructor(e=ov){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=_m(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=Eo(n,0,this.cursor)}else t=Am(this.chunks,this.cursor);return e&&this.reset(),t}};var H="CBOR decode error:",_r="CBOR encode error:",Ai=[];Ai[23]=1;Ai[24]=2;Ai[25]=3;Ai[26]=5;Ai[27]=9;function Ir(r,e,t){if(r.length-e<t)throw new Error(`${H} not enough data for type`)}var Ne=[24,256,65536,4294967296,BigInt("18446744073709551616")];function gt(r,e,t){Ir(r,e,1);let n=r[e];if(t.strict===!0&&n<Ne[0])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function yt(r,e,t){Ir(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Ne[1])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function wt(r,e,t){Ir(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Ne[2])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function bt(r,e,t){Ir(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<Ne[3])throw new Error(`${H} 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(`${H} integers outside of the safe integer range are not supported`)}function Rm(r,e,t,n){return new R(w.uint,gt(r,e+1,n),2)}function km(r,e,t,n){return new R(w.uint,yt(r,e+1,n),3)}function Bm(r,e,t,n){return new R(w.uint,wt(r,e+1,n),5)}function Tm(r,e,t,n){return new R(w.uint,bt(r,e+1,n),9)}function Tt(r,e){return Fe(r,0,e.value)}function Fe(r,e,t){if(t<Ne[0]){let n=Number(t);r.push([e|n])}else if(t<Ne[1]){let n=Number(t);r.push([e|24,n])}else if(t<Ne[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Ne[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<Ne[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(`${H} encountered BigInt larger than allowable range`)}}Tt.encodedSize=function(e){return Fe.encodedSize(e.value)};Fe.encodedSize=function(e){return e<Ne[0]?1:e<Ne[1]?2:e<Ne[2]?3:e<Ne[3]?5:9};Tt.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Nm(r,e,t,n){return new R(w.negint,-1-gt(r,e+1,n),2)}function Cm(r,e,t,n){return new R(w.negint,-1-yt(r,e+1,n),3)}function Lm(r,e,t,n){return new R(w.negint,-1-wt(r,e+1,n),5)}var Fu=BigInt(-1),Om=BigInt(1);function Dm(r,e,t,n){let o=bt(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new R(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${H} integers outside of the safe integer range are not supported`);return new R(w.negint,Fu-BigInt(o),9)}function Na(r,e){let t=e.value,n=typeof t=="bigint"?t*Fu-Om:t*-1-1;Fe(r,e.type.majorEncoded,n)}Na.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Fu-Om:t*-1-1;return n<Ne[0]?1:n<Ne[1]?2:n<Ne[2]?3:n<Ne[3]?5:9};Na.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function _i(r,e,t,n){Ir(r,e,t+n);let o=Eo(r,e+t,e+t+n);return new R(w.bytes,o,t+n)}function Pm(r,e,t,n){return _i(r,e,1,t)}function Um(r,e,t,n){return _i(r,e,2,gt(r,e+1,n))}function Fm(r,e,t,n){return _i(r,e,3,yt(r,e+1,n))}function Mm(r,e,t,n){return _i(r,e,5,wt(r,e+1,n))}function Vm(r,e,t,n){let o=bt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer bytes lengths not supported`);return _i(r,e,9,o)}function Ca(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===w.string?Ta(r.value):r.value),r.encodedBytes}function vo(r,e){let t=Ca(e);Fe(r,e.type.majorEncoded,t.length),r.push(t)}vo.encodedSize=function(e){let t=Ca(e);return Fe.encodedSize(t.length)+t.length};vo.compareTokens=function(e,t){return sv(Ca(e),Ca(t))};function sv(r,e){return r.length<e.length?-1:r.length>e.length?1:Im(r,e)}function Ii(r,e,t,n,o){let i=t+n;Ir(r,e,i);let s=new R(w.string,Sm(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Eo(r,e+t,e+i)),s}function Hm(r,e,t,n){return Ii(r,e,1,t,n)}function $m(r,e,t,n){return Ii(r,e,2,gt(r,e+1,n),n)}function zm(r,e,t,n){return Ii(r,e,3,yt(r,e+1,n),n)}function Km(r,e,t,n){return Ii(r,e,5,wt(r,e+1,n),n)}function qm(r,e,t,n){let o=bt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer string lengths not supported`);return Ii(r,e,9,o,n)}var Gm=vo;function So(r,e,t,n){return new R(w.array,n,t)}function Wm(r,e,t,n){return So(r,e,1,t)}function jm(r,e,t,n){return So(r,e,2,gt(r,e+1,n))}function Ym(r,e,t,n){return So(r,e,3,yt(r,e+1,n))}function Xm(r,e,t,n){return So(r,e,5,wt(r,e+1,n))}function Zm(r,e,t,n){let o=bt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer array lengths not supported`);return So(r,e,9,o)}function Jm(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return So(r,e,1,1/0)}function La(r,e){Fe(r,w.array.majorEncoded,e.value)}La.compareTokens=Tt.compareTokens;La.encodedSize=function(e){return Fe.encodedSize(e.value)};function Ao(r,e,t,n){return new R(w.map,n,t)}function Qm(r,e,t,n){return Ao(r,e,1,t)}function eg(r,e,t,n){return Ao(r,e,2,gt(r,e+1,n))}function tg(r,e,t,n){return Ao(r,e,3,yt(r,e+1,n))}function rg(r,e,t,n){return Ao(r,e,5,wt(r,e+1,n))}function ng(r,e,t,n){let o=bt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer map lengths not supported`);return Ao(r,e,9,o)}function og(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return Ao(r,e,1,1/0)}function Oa(r,e){Fe(r,w.map.majorEncoded,e.value)}Oa.compareTokens=Tt.compareTokens;Oa.encodedSize=function(e){return Fe.encodedSize(e.value)};function ig(r,e,t,n){return new R(w.tag,t,1)}function sg(r,e,t,n){return new R(w.tag,gt(r,e+1,n),2)}function ag(r,e,t,n){return new R(w.tag,yt(r,e+1,n),3)}function cg(r,e,t,n){return new R(w.tag,wt(r,e+1,n),5)}function lg(r,e,t,n){return new R(w.tag,bt(r,e+1,n),9)}function Da(r,e){Fe(r,w.tag.majorEncoded,e.value)}Da.compareTokens=Tt.compareTokens;Da.encodedSize=function(e){return Fe.encodedSize(e.value)};var hv=20,dv=21,pv=22,mv=23;function ug(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${H} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new R(w.null,null,1):new R(w.undefined,void 0,1)}function fg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return new R(w.break,void 0,1)}function Mu(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${H} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${H} Infinity values are not supported`)}return new R(w.float,r,e)}function hg(r,e,t,n){return Mu(Vu(r,e+1),3,n)}function dg(r,e,t,n){return Mu(Hu(r,e+1),5,n)}function pg(r,e,t,n){return Mu(wg(r,e+1),9,n)}function Pa(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|hv]);else if(n===!0)r.push([w.float.majorEncoded|dv]);else if(n===null)r.push([w.float.majorEncoded|pv]);else if(n===void 0)r.push([w.float.majorEncoded|mv]);else{let o,i=!1;(!t||t.float64!==!0)&&(gg(n),o=Vu(Mt,1),n===o||Number.isNaN(n)?(Mt[0]=249,r.push(Mt.slice(0,3)),i=!0):(yg(n),o=Hu(Mt,1),n===o&&(Mt[0]=250,r.push(Mt.slice(0,5)),i=!0))),i||(gv(n),o=wg(Mt,1),Mt[0]=251,r.push(Mt.slice(0,9)))}}Pa.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){gg(n);let o=Vu(Mt,1);if(n===o||Number.isNaN(n))return 3;if(yg(n),o=Hu(Mt,1),n===o)return 5}return 9};var mg=new ArrayBuffer(9),Nt=new DataView(mg,1),Mt=new Uint8Array(mg,0);function gg(r){if(r===1/0)Nt.setUint16(0,31744,!1);else if(r===-1/0)Nt.setUint16(0,64512,!1);else if(Number.isNaN(r))Nt.setUint16(0,32256,!1);else{Nt.setFloat32(0,r);let e=Nt.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Nt.setUint16(0,31744,!1);else if(t===0)Nt.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Nt.setUint16(0,0):o<-14?Nt.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Nt.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Vu(r,e){if(r.length-e<2)throw new Error(`${H} 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 yg(r){Nt.setFloat32(0,r,!1)}function Hu(r,e){if(r.length-e<4)throw new Error(`${H} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function gv(r){Nt.setFloat64(0,r,!1)}function wg(r,e){if(r.length-e<8)throw new Error(`${H} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Pa.compareTokens=Tt.compareTokens;function oe(r,e,t){throw new Error(`${H} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Ua(r){return()=>{throw new Error(`${H} ${r}`)}}var D=[];for(let r=0;r<=23;r++)D[r]=oe;D[24]=Rm;D[25]=km;D[26]=Bm;D[27]=Tm;D[28]=oe;D[29]=oe;D[30]=oe;D[31]=oe;for(let r=32;r<=55;r++)D[r]=oe;D[56]=Nm;D[57]=Cm;D[58]=Lm;D[59]=Dm;D[60]=oe;D[61]=oe;D[62]=oe;D[63]=oe;for(let r=64;r<=87;r++)D[r]=Pm;D[88]=Um;D[89]=Fm;D[90]=Mm;D[91]=Vm;D[92]=oe;D[93]=oe;D[94]=oe;D[95]=Ua("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)D[r]=Hm;D[120]=$m;D[121]=zm;D[122]=Km;D[123]=qm;D[124]=oe;D[125]=oe;D[126]=oe;D[127]=Ua("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)D[r]=Wm;D[152]=jm;D[153]=Ym;D[154]=Xm;D[155]=Zm;D[156]=oe;D[157]=oe;D[158]=oe;D[159]=Jm;for(let r=160;r<=183;r++)D[r]=Qm;D[184]=eg;D[185]=tg;D[186]=rg;D[187]=ng;D[188]=oe;D[189]=oe;D[190]=oe;D[191]=og;for(let r=192;r<=215;r++)D[r]=ig;D[216]=sg;D[217]=ag;D[218]=cg;D[219]=lg;D[220]=oe;D[221]=oe;D[222]=oe;D[223]=oe;for(let r=224;r<=243;r++)D[r]=Ua("simple values are not supported");D[244]=oe;D[245]=oe;D[246]=oe;D[247]=ug;D[248]=Ua("simple values are not supported");D[249]=hg;D[250]=dg;D[251]=pg;D[252]=oe;D[253]=oe;D[254]=oe;D[255]=fg;var Vt=[];for(let r=0;r<24;r++)Vt[r]=new R(w.uint,r,1);for(let r=-1;r>=-24;r--)Vt[31-r]=new R(w.negint,r,1);Vt[64]=new R(w.bytes,new Uint8Array(0),1);Vt[96]=new R(w.string,"",1);Vt[128]=new R(w.array,0,1);Vt[160]=new R(w.map,0,1);Vt[244]=new R(w.false,!1,1);Vt[245]=new R(w.true,!0,1);Vt[246]=new R(w.null,null,1);function $u(r){switch(r.type){case w.false:return or([244]);case w.true:return or([245]);case w.null:return or([246]);case w.bytes:return r.value.length?void 0:or([64]);case w.string:return r.value===""?or([96]):void 0;case w.array:return r.value===0?or([128]):void 0;case w.map:return r.value===0?or([160]):void 0;case w.uint:return r.value<24?or([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return or([31-Number(r.value)])}}var wv={float64:!1,mapSorter:xv,quickEncodeToken:$u};function Ku(){let r=[];return r[w.uint.major]=Tt,r[w.negint.major]=Na,r[w.bytes.major]=vo,r[w.string.major]=Gm,r[w.array.major]=La,r[w.map.major]=Oa,r[w.tag.major]=Da,r[w.float.major]=Pa,r}var bg=Ku(),zu=new Si,Fa=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(`${_r} object contains circular references`);return new r(t,e)}},on={null:new R(w.null,null),undefined:new R(w.undefined,void 0),true:new R(w.true,!0),false:new R(w.false,!1),emptyArray:new R(w.array,0),emptyMap:new R(w.map,0)},sn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new R(w.float,r):r>=0?new R(w.uint,r):new R(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new R(w.uint,r):new R(w.negint,r)},Uint8Array(r,e,t,n){return new R(w.bytes,r)},string(r,e,t,n){return new R(w.string,r)},boolean(r,e,t,n){return r?on.true:on.false},null(r,e,t,n){return on.null},undefined(r,e,t,n){return on.undefined},ArrayBuffer(r,e,t,n){return new R(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new R(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[on.emptyArray,new R(w.break)]:on.emptyArray;n=Fa.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Ri(s,t,n);return t.addBreakTokens?[new R(w.array,r.length),o,new R(w.break)]:[new R(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?[on.emptyMap,new R(w.break)]:on.emptyMap;n=Fa.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[Ri(l,t,n),Ri(o?r.get(l):r[l],t,n)];return bv(a,t),t.addBreakTokens?[new R(w.map,s),a,new R(w.break)]:[new R(w.map,s),a]}};sn.Map=sn.Object;sn.Buffer=sn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))sn[`${r}Array`]=sn.DataView;function Ri(r,e={},t){let n=bm(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||sn[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=sn[n];if(!i)throw new Error(`${_r} unsupported type: ${n}`);return i(r,n,e,t)}function bv(r,e){e.mapSorter&&r.sort(e.mapSorter)}function xv(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=bg[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function xg(r,e,t,n){if(Array.isArray(e))for(let o of e)xg(r,o,t,n);else t[e.type.major](r,e,n)}function qu(r,e,t){let n=Ri(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 Si(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return vi(a.chunks[0])}}return zu.reset(),xg(zu,n,e,t),zu.toBytes(!0)}function an(r,e){return e=Object.assign({},wv,e),qu(r,bg,e)}var Ev={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Ma=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=Vt[e];if(t===void 0){let n=D[e];if(!n)throw new Error(`${H} 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}},ki=Symbol.for("DONE"),Va=Symbol.for("BREAK");function vv(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=_o(e,t);if(i===Va){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed array`)}if(i===ki)throw new Error(`${H} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function Sv(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=_o(e,t);if(a===Va){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed map`)}if(a===ki)throw new Error(`${H} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${H} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${H} found repeat map key "${a}"`);let c=_o(e,t);if(c===ki)throw new Error(`${H} 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 _o(r,e){if(r.done())return ki;let t=r.next();if(t.type===w.break)return Va;if(t.type.terminal)return t.value;if(t.type===w.array)return vv(t,r,e);if(t.type===w.map)return Sv(t,r,e);if(t.type===w.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=_o(r,e);return e.tags[t.value](n)}throw new Error(`${H} tag not supported (${t.value})`)}throw new Error("unsupported")}function Gu(r,e){if(!(r instanceof Uint8Array))throw new Error(`${H} data to decode must be a Uint8Array`);e=Object.assign({},Ev,e);let t=e.tokenizer||new Ma(r,e),n=_o(t,e);if(n===ki)throw new Error(`${H} did not find any content to decode`);if(n===Va)throw new Error(`${H} got unexpected break`);return[n,r.subarray(t.pos())]}function tt(r,e){let[t,n]=Gu(r,e);if(n.length>0)throw new Error(`${H} too many terminals, data makes no sense`);return t}var Rr="/",Eg=new TextEncoder().encode(Rr),$a=Eg[0],xe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=P(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]!==$a)throw new Error("Invalid key")}toString(e="utf8"){return G(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=Eg),this._buf[0]!==$a){let e=new Uint8Array(this._buf.byteLength+1);e.fill($a,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===$a;)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 Av(this.baseNamespace())}name(){return _v(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(),...Iv(e.map(t=>t.namespaces()))])}};function Av(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function _v(r){let e=r.split(":");return e[e.length-1]}function Iv(r){return[].concat(...r)}var _g="/pin/",vg="/pinned-block/",Wu=zr,Sg=1;function Ag(r){return r.version===0&&(r=r.toV1()),new xe(`${_g}${r.toString(Wu)}`)}var za=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers=n}async*add(e,t={}){let n=Ag(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 lr({concurrency:Sg});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#n(a,c=>c.pinnedBy.find(l=>ne(l,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,an(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#n(e,t,n){let o=new xe(`${vg}${Wu.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=tt(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,an(i),n),n.onProgress?.(new V("helia:pin:add",e))}}async*rm(e,t={}){let n=Ag(e),o=await this.datastore.get(n,t),i=tt(o);await this.datastore.delete(n,t);let s=new lr({concurrency:Sg});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#n(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>ne(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:_g+(e.cid!=null?`${e.cid.toString(zr)}`:"")},e)){let o=z.parse(t.toString().substring(5),zr),i=tt(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new xe(`${vg}${Wu.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var Rv=5,Ka=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Rv}async start(){await Fr(...this.routers)}async stop(){await Mr(...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 us({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Vr(n.toGenerator(),...Io(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}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(Io(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(Io(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(Io(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=Vr(...Io(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");for await(let n of Vr(...Io(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Io(r,e){return r.filter(t=>t[e]!=null)}var cn={},Ro=r=>{r.addEventListener("message",e=>{Ro.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Ro.dispatchEvent("message",r,e)})};Ro.addEventListener=(r,e)=>{cn[r]==null&&(cn[r]=[]),cn[r].push(e)};Ro.removeEventListener=(r,e)=>{cn[r]!=null&&(cn[r]=cn[r].filter(t=>t===e))};Ro.dispatchEvent=function(r,e,t){cn[r]!=null&&cn[r].forEach(n=>n(e,t))};var ju=Ro;var Yu="lock:worker:request-read",Xu="lock:worker:release-read",Zu="lock:master:grant-read",Ju="lock:worker:request-write",Qu="lock:worker:release-write",ef="lock:master:grant-write";var Ig=(r=21)=>Math.random().toString().substring(2);var Rg=(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 l=u=>{if(u==null||u.data==null)return;let f={type:u.data.type,name:u.data.name,identifier:u.data.identifier};f.type===n&&f.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},kg=(r,e,t,n)=>async()=>{let o=Ig();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)})},kv={singleProcess:!1},Bg=r=>{if(r=Object.assign({},kv,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return ju.addEventListener("message",Rg(t,"requestReadLock",Yu,Xu,Zu)),ju.addEventListener("message",Rg(t,"requestWriteLock",Ju,Qu,ef)),t}return{isWorker:!0,readLock:t=>kg(t,Yu,Zu,Xu),writeLock:t=>kg(t,Ju,ef,Qu)}};var Cn={},ln;async function tf(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>bi((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Bv=(r,e)=>{if(ln.isWorker===!0)return{readLock:ln.readLock(r,e),writeLock:ln.writeLock(r,e)};let t=new at({concurrency:1}),n;return{async readLock(){if(n!=null)return tf(n,e);n=new at({concurrency:e.concurrency,autoStart:!1});let o=n,i=tf(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,tf(t,e)}}},Tv={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function rf(r){let e=Object.assign({},Tv,r);return ln==null&&(ln=Bg(e),ln.isWorker!==!0&&(ln.addEventListener("requestReadLock",t=>{Cn[t.data.name]!=null&&Cn[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),ln.addEventListener("requestWriteLock",async t=>{Cn[t.data.name]!=null&&Cn[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Cn[e.name]==null&&(Cn[e.name]=Bv(e.name,e)),Cn[e.name]}var qa=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=rf({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Fr(this.child),this.started=!0}async stop(){await Mr(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();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={}){t?.signal?.throwIfAborted();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={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Tg=42;function Nv(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Cv(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=z.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new R(w.tag,Tg),new R(w.bytes,t)]}function Lv(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Ov(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 nf={float64:!0,typeEncoders:{Object:Cv,undefined:Lv,number:Ov}},PN={...nf,typeEncoders:{...nf.typeEncoders}};function Dv(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return z.decode(r.subarray(1))}var Ga={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Ga.tags[Tg]=Dv;var UN={...Ga,tags:Ga.tags.slice()};var un=113,Bi=r=>an(r,nf),Ln=r=>tt(Nv(r),Ga);var of=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(`${_r} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=Ta(JSON.stringify(t.value));e.push(n.length>32?vi(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(`${_r} 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 Pv(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${_r} 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(`${_r} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${_r} unexpected duplicate map keys, this is not supported`)}var Uv={addBreakTokens:!0,mapSorter:Pv};function Ni(r,e){return e=Object.assign({},Uv,e),qu(r,new of,e)}var fn=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(`${H} 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(`${H} 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 R(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(`${H} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${H} 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 R(w.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new R(s>=0?w.uint:w.negint,s,this._pos-e):new R(s>=0?w.uint:w.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${H} 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 R(w.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${H} 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(`${H} 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(`${H} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(i&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(i&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(i&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,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(`${H} 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(`${H} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new R(w.string,Uu(t),this._pos-e);default:if(i<32)throw new Error(`${H} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${H} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new R(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new R(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new R(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new R(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new R(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(`${H} 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 R(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} 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 R(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 R(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} 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 R(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${H} 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(`${H} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Ci(r,e){return e=Object.assign({tokenizer:new fn(r,e)},e),tt(r,e)}function Fv(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Mv(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=z.asCID(r);if(!e)return null;let t=e.toString();return[new R(w.map,1/0,1),new R(w.string,"/",1),new R(w.string,t,t.length),new R(w.break,void 0,1)]}function Wa(r){let e=it.encode(r).slice(1);return[new R(w.map,1/0,1),new R(w.string,"/",1),new R(w.map,1/0,1),new R(w.string,"bytes",5),new R(w.string,e,e.length),new R(w.break,void 0,1),new R(w.break,void 0,1)]}function Ht(r){return Wa(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function Vv(r){return Wa(new Uint8Array(r))}function Hv(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function $v(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 zv={typeEncoders:{Object:Mv,Buffer:Wa,Uint8Array:Wa,Int8Array:Ht,Uint16Array:Ht,Int16Array:Ht,Uint32Array:Ht,Int32Array:Ht,Float32Array:Ht,Float64Array:Ht,Uint8ClampedArray:Ht,BigInt64Array:Ht,BigUint64Array:Ht,DataView:Ht,ArrayBuffer:Vv,undefined:Hv,number:$v}},sf=class extends fn{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 R(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=it.decode(`m${i.value}`);return new R(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},af={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};af.tags[42]=z.parse;var hn=297,Cg=r=>Ni(r,zv),ja=r=>{let e=Fv(r),t=Object.assign(af,{tokenizer:new sf(e,af)});return Ci(e,t)};var eC=new TextDecoder;var tC=new TextEncoder;var Kv=new TextDecoder;function cf(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 Xa(r,e){let t;[t,e]=cf(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 Lg(r,e){let t;return[t,e]=cf(r,e),[t&7,t>>3,e]}function qv(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=Lg(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]=Xa(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]=Xa(r,n),e.Name=Kv.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]=cf(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 Og(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=Lg(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]=Xa(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Xa(r,t),n.push(qv(l))}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 nC=new TextEncoder,oC=2**32,iC=2**31;var cC=new TextEncoder;function Dg(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var $t=112;function ir(r){let e=Dg(r),t=Og(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=z.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 Gv={codec:$t,*walk(r){yield*ir(r).Links.map(t=>t.Hash)}},Wv={codec:ht,*walk(){}},Pg=42,jv={codec:un,*walk(r){let e=[],t=[];t[Pg]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let o=z.decode(n.subarray(1));return e.push(o),o},tt(r,{tags:t}),yield*e}},uf=class extends fn{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 R(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=it.decode(`m${i.value}`);return new R(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Yv={codec:hn,*walk(r){let e=[],t=[];t[Pg]=n=>{let o=z.parse(n);return e.push(o),o},Ci(r,{tags:t,tokenizer:new uf(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}},Xv={codec:Kr,*walk(){}};function Ug(r=[]){let e={};return[Gv,Wv,jv,Yv,Xv,...r].forEach(t=>{e[t.codec]=t}),e}var ff=new xe("/version"),Fg=1;async function Mg(r){if(!await r.has(ff)){await r.put(ff,P(`${Fg}`));return}let e=await r.get(ff),t=G(e);if(parseInt(t,10)!==Fg)throw new Error("Unknown datastore version, a datastore migration may be required")}function Vg(r=[]){let e={};return[Re,Ul,Be,...r].forEach(t=>{e[t.code]=t}),e}var kr=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 ko={};Se(ko,{abortedError:()=>t2,closeFailedError:()=>Jv,deleteFailedError:()=>$g,getFailedError:()=>Qv,hasFailedError:()=>e2,notFoundError:()=>Li,openFailedError:()=>Zv,putFailedError:()=>Hg});var Br=re(De(),1);function Zv(r){return r=r??new Error("Open failed"),(0,Br.default)(r,"ERR_OPEN_FAILED")}function Jv(r){return r=r??new Error("Close failed"),(0,Br.default)(r,"ERR_CLOSE_FAILED")}function Hg(r){return r=r??new Error("Put failed"),(0,Br.default)(r,"ERR_PUT_FAILED")}function Qv(r){return r=r??new Error("Get failed"),(0,Br.default)(r,"ERR_GET_FAILED")}function $g(r){return r=r??new Error("Delete failed"),(0,Br.default)(r,"ERR_DELETE_FAILED")}function e2(r){return r=r??new Error("Has failed"),(0,Br.default)(r,"ERR_HAS_FAILED")}function Li(r){return r=r??new Error("Not Found"),(0,Br.default)(r,"ERR_NOT_FOUND")}function t2(r){return r=r??new Error("Aborted"),(0,Br.default)(r,"ERR_ABORTED")}var Oi=class extends kr{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(Pe.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(Pe.encode(e.multihash.bytes));if(t==null)throw Li();return t}has(e){return this.data.has(Pe.encode(e.multihash.bytes))}async delete(e){this.data.delete(Pe.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:z.createV1(ht,Xe(Pe.decode(e))),block:t}}};function r2(r){return r[Symbol.asyncIterator]!=null}function n2(r,e){let t=0;if(r2(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=$n(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var xt=n2;var qC=Qe("blockstore:core:tiered");var zg={...ko};var Za=0,Ja=class extends kr{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Za||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Za)return e.multihash.digest;if(this.child==null)throw zg.notFoundError();return this.child.get(e)}has(e){return e.multihash.code===Za?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Za&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function o2(r){return r[Symbol.asyncIterator]!=null}function Kg(r){return r?.then!=null}function i2(r,e){let t=0;if(o2(r))return async function*(){for await(let c of r){let l=e(c,t++);Kg(l)&&await l,yield c}}();let n=$n(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=e(c,t++);Kg(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var hf=i2;var Qa=class{child;hashers;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Ja(e.blockstore),this.hashers=e.hashers??{}}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new V("blocks:put:duplicate",e)),e):(n.onProgress?.(new V("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new V("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=xt(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new V("blocks:put-many:duplicate",i)),!s}),o=hf(n,async({cid:i,block:s})=>{t.onProgress?.(new V("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,t)))});t.onProgress?.(new V("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)){t.onProgress?.(new V("blocks:get:providers:get",e));let n=await qg(e,this.components.blockBrokers,this.hashers[e.multihash.code],{...t,log:this.log});return t.onProgress?.(new V("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),t.onProgress?.(new V("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n,t))),n}return t.onProgress?.(new V("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new V("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(hf(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){t.onProgress?.(new V("blocks:get-many:providers:get",n));let o=await qg(n,this.components.blockBrokers,this.hashers[n.multihash.code],{...t,log:this.log});t.onProgress?.(new V("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new V("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(n,o,t)))}}))}async delete(e,t={}){t.onProgress?.(new V("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new V("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 V("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},ec=class extends Qa{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await Fr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Mr(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new df({blockstore:this.child,blockBrokers:n,hashers:this.hashers,logger:this.logger},{root:e})}},df=class extends Qa{closeController;constructor(e,t){super(e),this.closeController=new AbortController,me(1/0,this.closeController.signal),this.log=e.logger.forComponent(`helia:session-storage${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=Ye([this.closeController.signal,n.signal]);me(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ye([this.closeController.signal,e.signal]);me(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function s2(r){return typeof r.retrieve=="function"}var a2=(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(!ne(n.digest,r.multihash.digest))throw new N("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function qg(r,e,t,n){let o=a2(r,t),i=new AbortController,s=Ye([i.signal,n.signal]);me(1/0,i.signal,s);let a=[];for(let c of e)s2(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async f=>{await o(f),l=!0}});return l||await o(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var pf=re(ku(),1);var c2=Math.LN2*Math.LN2,tc=class r{static create(e,t=.005){let n=l2(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=u2(e.hashes??8),this.bits=e.bits??1024,this.buffer=rt(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.seeds.length;t++){let o=pf.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(o)}}has(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.seeds.length;t++){let o=pf.default.x86.hash32(e,this.seeds[t])%this.bits;if(!this.getbit(o))return!1}return!0}clear(){this.buffer.fill(0)}setbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;let o=this.buffer[t];o|=1<<n,this.buffer[t]=o}getbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;return(this.buffer[t]&1<<n)!==0}};function l2(r,e=.005){let t=Math.round(-1*r*Math.log(e)/c2),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function u2(r){let e,t,n=[];for(let o=0;o<r;o++)for(e=new fr(er(4)),n[o]=e.getUint32(0,!0),t=0;t<o;t++)if(n[o]===n[t]){o--;break}return n}var Di=class extends Mn{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),me(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=tc.create(this.maxProviders)}async retrieve(e,t={}){let n=it.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=fe();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let s=!1,a=new lr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let u=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(u)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,u)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});try{return await i.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.providers.some(t=>this.equals(t,e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=fe(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new N(`Found ${i} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var rc=class{blockstore;datastore;pins;logger;routing;dagWalkers;hashers;dns;metrics;log;constructor(e){this.logger=e.logger??um(),this.log=this.logger.forComponent("helia"),this.hashers=Vg(e.hashers),this.dagWalkers=Ug(e.dagWalkers),this.dns=e.dns??Ei(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,hashers:this.hashers,dagWalkers:this.dagWalkers,logger:this.logger,blockBrokers:[],dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new Ka(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[$o]!=null&&i.push(o[$o]),o[Ko]!=null&&i.push(o[Ko]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new ec(t);this.pins=new za(e.datastore,n,this.dagWalkers),this.blockstore=new qa(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await Mg(this.datastore),await Fr(this.blockstore,this.datastore,this.routing)}async stop(){await Mr(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 ur(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 V("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new V("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};var nc=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let p=Number.parseInt(f,e);if(!Number.isNaN(p))return p});if(u===void 0)break;if(i*=e,i+=u,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Gg=45,f2=15,Bo=new nc;function mf(r){if(!(r.length>f2))return Bo.new(r).parseWith(()=>Bo.readIPv4Addr())}function gf(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Gg))return Bo.new(r).parseWith(()=>Bo.readIPv6Addr())}function oc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Gg))return Bo.new(r).parseWith(()=>Bo.readIPAddr())}function To(r){return!!mf(r)}function No(r){return!!gf(r)}function ic(r){return!!oc(r)}var jg=re(Wg(),1),h2=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],d2=h2.map(r=>new jg.Netmask(r));function p2(r){for(let e of d2)if(e.contains(r))return!0;return!1}function m2(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Yg(r){return To(r)?p2(r):No(r)?m2(r):void 0}var t3=parseInt("0xFFFF",16),r3=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Jg=To,x2=No,yf=function(r){let e=0;if(r=r.toString().trim(),Jg(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(x2(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=Jg(t[n]),s;i&&(s=yf(t[n]),t[n]=G(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,G(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")},Qg=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 Co={},wf={},v2=[[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"]];v2.forEach(r=>{let e=S2(...r);wf[e.code]=e,Co[e.name]=e});function S2(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function Y(r){if(typeof r=="number"){if(wf[r]!=null)return wf[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Co[r]!=null)return Co[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var U3=Y("ip4"),F3=Y("ip6"),M3=Y("ipcidr");function xf(r,e){switch(Y(r).code){case 4:case 41:return _2(e);case 42:return r0(e);case 6:case 273:case 33:case 132:return o0(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return r0(e);case 421:return B2(e);case 444:return n0(e);case 445:return n0(e);case 466:return k2(e);default:return G(e,"base16")}}function Ef(r,e){switch(Y(r).code){case 4:return e0(e);case 41:return e0(e);case 42:return t0(e);case 6:case 273:case 33:case 132:return vf(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return t0(e);case 421:return I2(e);case 444:return T2(e);case 445:return N2(e);case 466:return R2(e);default:return P(e,"base16")}}var bf=Object.values(qr).map(r=>r.decoder),A2=function(){let r=bf[0].or(bf[1]);return bf.slice(2).forEach(e=>r=r.or(e)),r}();function e0(r){if(!ic(r))throw new Error("invalid ip address");return yf(r)}function _2(r){let e=Qg(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ic(e))throw new Error("invalid ip address");return e}function vf(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function o0(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function t0(r){let e=P(r),t=Uint8Array.from(Hn(e.length));return ue([t,e],t.length+e.length)}function r0(r){let e=wn(r);if(r=r.slice(ot(e)),r.length!==e)throw new Error("inconsistent lengths");return G(r)}function I2(r){let e;r[0]==="Q"||r[0]==="1"?e=Xe(ge.decode(`z${r}`)).bytes:e=z.parse(r).multihash.bytes;let t=Uint8Array.from(Hn(e.length));return ue([t,e],t.length+e.length)}function R2(r){let e=A2.decode(r),t=Uint8Array.from(Hn(e.length));return ue([t,e],t.length+e.length)}function k2(r){let e=wn(r),t=r.slice(ot(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+G(t,"base64url")}function B2(r){let e=wn(r),t=r.slice(ot(e));if(t.length!==e)throw new Error("inconsistent lengths");return G(t,"base58btc")}function T2(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=Pe.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=vf(n);return ue([t,o],t.length+o.length)}function N2(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=Pe.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=vf(n);return ue([t,o],t.length+o.length)}function n0(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=G(e,"base32"),o=o0(t);return`${n}:${o}`}function i0(r){r=Sf(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=Y(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw a0("invalid address: "+r);if(a.path===!0){n=Sf(o.slice(i).join("/")),e.push([a.code,Ef(a.code,n)]),t.push([a.code,n]);break}let c=Ef(a.code,o[i]);e.push([a.code,c]),t.push([a.code,xf(a.code,c)])}return{string:s0(t),bytes:_f(e),tuples:e,stringTuples:t,path:n}}function Af(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=wn(r,o),s=ot(i),a=Y(i),c=C2(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw a0("Invalid address Uint8Array: "+G(r,"base16"));e.push([i,l]);let u=xf(i,l);if(t.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:s0(t),tuples:e,stringTuples:t,path:n}}function s0(r){let e=[];return r.map(t=>{let n=Y(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Sf(e.join("/"))}function _f(r){return ue(r.map(e=>{let t=Y(e[0]),n=Uint8Array.from(Hn(t.code));return e.length>1&&e[1]!=null&&(n=ue([n,e[1]])),n}))}function C2(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=wn(e instanceof Uint8Array?e:Uint8Array.from(e));return t+ot(t)}}function Sf(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function a0(r){return new Error("Error parsing address: "+r)}var L2=Symbol.for("nodejs.util.inspect.custom"),If=Symbol.for("@multiformats/js-multiaddr/multiaddr"),O2=[Y("dns").code,Y("dns4").code,Y("dns6").code,Y("dnsaddr").code],sc=class r{bytes;#e;#n;#s;#u;[If]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Af(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=i0(e)}else if(l0(e))t=Af(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#n=t.tuples,this.#s=t.stringTuples,this.#u=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,i="",s=Y("tcp"),a=Y("udp"),c=Y("ip4"),l=Y("ip6"),u=Y("dns6"),f=Y("ip6zone");for(let[h,m]of this.stringTuples())h===f.code&&(i=`%${m??""}`),O2.includes(h)&&(t=s.name,o=443,n=`${m??""}${i}`,e=h===u.code?6:4),(h===s.code||h===a.code)&&(t=Y(h).name,o=parseInt(m??"")),(h===c.code||h===l.code)&&(t=Y(h).name,n=`${m??""}${i}`,e=h===l.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.#n.map(([e])=>Object.assign({},Y(e)))}protoCodes(){return this.#n.map(([e])=>e)}protoNames(){return this.#n.map(([e])=>Y(e).name)}tuples(){return this.#n}stringTuples(){return this.#s}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(_f(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Co.p2p.code&&e.push([n,o]),n===Co["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?G(ge.decode(`z${n}`),"base58btc"):G(z.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#u}equals(e){return ne(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=c0.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=>Tr(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)}[L2](){return`Multiaddr(${this.#e})`}};var c0=new Map;function l0(r){return!!r?.[If]}function Tr(r){return new sc(r)}var D2=r=>r.toString().split("/").slice(1),Ui=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),se=r=>({match:e=>Ui(t=>t===r).match(e),pattern:r}),lc=()=>({match:r=>Ui(e=>typeof e=="string").match(r),pattern:"{string}"}),uc=()=>({match:r=>Ui(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Me=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ge.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ac=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Tl.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Ve=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Et=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),le=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function Ee(...r){function e(o){let i=D2(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matches:t,exactMatch:n}}var kf=le(se("dns4"),lc()),Bf=le(se("dns6"),lc()),Tf=le(se("dnsaddr"),lc()),u0=le(se("dns"),lc()),p4=Ee(kf),m4=Ee(Bf),g4=Ee(Tf),f0=Ee(Et(u0,Tf,kf,Bf)),h0=le(se("ip4"),Ui(To)),d0=le(se("ip6"),Ui(No)),p0=Et(h0,d0),sr=Et(p0,u0,kf,Bf,Tf),y4=Ee(sr),w4=Ee(h0),b4=Ee(d0),x4=Ee(p0),fc=le(sr,se("tcp"),uc()),Fi=le(sr,se("udp"),uc()),P2=Et(fc,Fi),E4=Ee(fc),v4=Ee(Fi),Nf=le(Fi,se("quic")),hc=le(Fi,se("quic-v1")),U2=Et(Nf,hc),S4=Ee(Nf),A4=Ee(hc),Rf=Et(sr,fc,Fi,Nf,hc),m0=Et(le(Rf,se("ws"),Ve(Me()))),_4=Ee(m0),g0=Et(le(Rf,se("wss"),Ve(Me())),le(Rf,se("tls"),se("ws"),Ve(Me()))),I4=Ee(g0),y0=le(P2,se("webrtc-direct"),ac(),Ve(ac()),Ve(Me())),R4=Ee(y0),w0=le(hc,se("webtransport"),Ve(ac()),Ve(ac()),Ve(Me())),k4=Ee(w0),cc=Et(m0,g0,le(fc,Ve(Me())),le(U2,Ve(Me())),le(sr,Ve(Me())),y0,w0,Me()),B4=Ee(cc),F2=le(cc,se("p2p-circuit"),Me()),T4=Ee(F2),M2=Et(le(cc,se("p2p-circuit"),se("webrtc"),Me()),le(cc,se("webrtc"),Ve(Me())),se("webrtc")),N4=Ee(M2),V2=Et(le(sr,se("tcp"),uc(),se("http"),Ve(Me())),le(sr,se("http"),Ve(Me()))),b0=Ee(V2),H2=Et(le(sr,se("tcp"),Et(le(se("443"),se("http")),le(uc(),se("https"))),Ve(Me())),le(sr,se("tls"),se("http"),Ve(Me())),le(sr,se("https"),Ve(Me()))),x0=Ee(H2);var $2=[Y("tcp").code,Y("dns").code,Y("dnsaddr").code,Y("dns4").code,Y("dns6").code];function E0(r){let e;try{e=Y("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function v0(r){return r.some(([e,t])=>e===Y("tls").code)}function vt(r,e,t){let n=S0[Y(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${Y(r).name}`);let o=n(e,t);return r===Y("ip6").code?`[${o}]`:o}var S0={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${vt(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${vt(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${vt(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${vt(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=v0(e),n=E0(e);if(t&&n!==null)return`https://${n}`;let o=t?"https://":"http://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=vt(i[0],i[1]??"",e);return s=s.replace("tcp://",""),`${o}${s}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return vt(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return vt(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=vt(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=v0(e),n=E0(e);if(t&&n!==null)return`wss://${n}`;let o=t?"wss://":"ws://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=vt(i[0],i[1]??"",e);return s=s.replace("tcp://",""),`${o}${s}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=vt(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${vt(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${vt(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${vt(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function A0(r,e){let n=Tr(r).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=Y(o[0]),s=S0[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return e?.assumeHttp!==!1&&$2.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var dc=class{url;#e=0;#n=0;#s=0;#u=0;#g=new Map;log;constructor(e,t){this.url=e instanceof URL?e:new URL(e),this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#a(e){let t=e.multihash.bytes;return it.encode(t)}async getRawBlock(e,t){let n=new URL(this.url.toString());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`);let o=this.#a(e),i=new AbortController,s=()=>{i.abort()};t?.addEventListener("abort",s);try{let a=this.#g.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#n++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#u++,new Uint8Array(await c.arrayBuffer())}),this.#g.set(o,a)),await a}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#n++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",s),this.#g.delete(o)}}reliability(){return this.#e===0?1:this.#s>0?-1/0:this.#u/(this.#e+this.#n*3)}incrementInvalidBlocks(){this.#s++}getStats(){return{attempts:this.#e,errors:this.#n,invalidBlocks:this.#s,successes:this.#u,pendingResponses:this.#g.size}}};function z2(r,e,t){return r.filter(n=>x0.matches(n)||e&&b0.matches(n)?t||f0.matches(n)?!0:Yg(n.toOptions().host)===!1:!1)}async function*pc(r,e,t,n,o,i){for await(let s of e.findProviders(r,i)){let a=z2(s.multiaddrs,n,o);if(a.length===0)continue;let c=A0(a[0]);yield new dc(c,t)}}var Cf=class extends Di{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??mc,this.allowLocal=t.allowLocal??gc}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n.signal);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*pc(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}};function _0(r,e){return new Cf(r,e)}var yc=class{allowInsecure;allowLocal;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??mc,this.allowLocal=t.allowLocal??gc}async retrieve(e,t={}){let n=[];for await(let o of pc(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let i=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",e,o.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return _0({logger:this.logger,routing:this.routing},e)}};var mc=!1,gc=!1;function Mi(r={}){return e=>new yc(e,r)}async function*wc(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 Uf=re(De(),1);var M0=re(bc(),1);var I0="ERR_IPNS_EXPIRED_RECORD",Vi="ERR_UNRECOGNIZED_VALIDITY",R0="ERR_SIGNATURE_CREATION",Nr="ERR_SIGNATURE_VERIFICATION";var Of="ERR_UNDEFINED_PARAMETER",k0="ERR_INVALID_RECORD_DATA",B0="ERR_INVALID_VALUE",T0="ERR_INVALID_EMBEDDED_KEY",N0="ERR_MISSING_PRIVATE_KEY",C0="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=()=>vn(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=It((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=>_t(o,r.codec()),r.decode=o=>St(o,r.codec())})(He||(He={}));var lt=re(De(),1);var L0=Qe("ipns:utils"),O0=P("/ipns/"),K2=114,D0=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw L0.error(n),(0,lt.default)(n,Of)}let t;if(e.pubKey!=null){try{t=Ru(e.pubKey)}catch(o){throw L0.error(o),o}if(!(await vd(e.pubKey)).equals(r))throw(0,lt.default)(new Error("Embedded public key did not match PeerID"),T0)}else r.publicKey!=null&&(t=Ru(r.publicKey));if(t!=null)return t;throw(0,lt.default)(new Error("no public key is available"),Of)},P0=(r,e,t)=>{let n=P(e);return ue([r,t,n])},xc=r=>{let e=P("ipns-signature:");return ue([e,r])},Cr=r=>"signatureV1"in r?He.encode({value:P(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:P(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 je(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"),Nr);let t=F0(e.data),n=Pf(t.Value),o=G(t.Validity);if(e.value!=null&&e.signatureV1!=null)return q2(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 Lo=r=>ue([O0,r.toBytes()]),Oo=r=>Jo(r.slice(O0.length)),U0=(r,e,t,n,o)=>{let i;if(e===He.ValidityType.EOL)i=0;else throw(0,lt.default)(new Error("Unknown validity type"),Vi);return an({Value:r,Validity:t,ValidityType:i,Sequence:n,TTL:o})},F0=r=>{let e=tt(r);if(e.ValidityType===0)e.ValidityType=He.ValidityType.EOL;else throw(0,lt.default)(new Error("Unknown validity type"),Vi);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e},Pf=r=>{if(r!=null){if(Uh(r))return`/ipns/${r.toCID().toString(zr)}`;if(r instanceof Uint8Array){let n=G(r);n.startsWith("/")&&(r=n)}let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e;let t=z.asCID(r);if(t!=null)return t.code===K2?`/ipns/${t.toString(zr)}`:`/ipfs/${t.toV1().toString()}`;try{return r instanceof Uint8Array?`/ipfs/${z.decode(r).toV1().toString()}`:`/ipfs/${z.parse(e).toV1().toString()}`}catch{}}throw(0,lt.default)(new Error("Value must be a valid content path starting with /"),B0)},q2=r=>{if(r.data==null)throw(0,lt.default)(new Error("Record data is missing"),k0);let e=F0(r.data);if(!ne(e.Value,r.value??new Uint8Array(0)))throw(0,lt.default)(new Error('Field "value" did not match between protobuf and CBOR'),Nr);if(!ne(e.Validity,r.validity??new Uint8Array(0)))throw(0,lt.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Nr);if(e.ValidityType!==r.validityType)throw(0,lt.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Nr);if(e.Sequence!==r.sequence)throw(0,lt.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Nr);if(e.TTL!==r.ttl)throw(0,lt.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Nr)};var G2=Qe("ipns"),W2=Be.code,V0=60*60*1e9,j2="/ipns/",kL=j2.length,H0={v1Compatible:!0,ttlNs:V0};async function $0(r,e,t,n,o=H0){let i=new M0.default(Date.now()+Number(n)),s=He.ValidityType.EOL,a=BigInt(o.ttlNs!=null?o.ttlNs:V0);return Y2(r,e,t,s,i.toString(),a,o)}var Y2=async(r,e,t,n,o,i,s=H0)=>{t=BigInt(t);let a=P(o),c=Pf(e),l=P(c);if(r.privateKey==null)throw(0,Uf.default)(new Error("Missing private key"),N0);let u=await rm(r.privateKey),f=U0(l,n,a,t,i),p=xc(f),h=await u.sign(p),m;if(r.publicKey!=null){let d=Xe(r.toBytes());(d.code!==W2||!ne(r.publicKey,d.digest))&&(m=r.publicKey)}if(s.v1Compatible===!0){let d=await X2(u,l,n,a),y={value:c,signatureV1:d,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:h,data:f};return m!=null&&(y.pubKey=m),y}else{let d={value:c,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:h,data:f};return m!=null&&(d.pubKey=m),d}};var X2=async(r,e,t,n)=>{try{let o=P0(e,t,n);return await r.sign(o)}catch(o){throw G2.error("record signature creation failed",o),(0,Uf.default)(new Error("record signature creation failed"),R0)}};var Hi=re(De(),1),z0=re(bc(),1);var Ec=Qe("ipns:validator"),Z2=1024*10,J2=async(r,e)=>{let t=je(e),n;try{let o=xc(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw Ec.error("record signature verification failed"),(0,Hi.default)(new Error("record signature verification failed"),Nr);if(t.validityType===He.ValidityType.EOL){if(z0.default.fromString(t.validity).toDate().getTime()<Date.now())throw Ec.error("record has expired"),(0,Hi.default)(new Error("record has expired"),I0)}else if(t.validityType!=null)throw Ec.error("unrecognized validity type"),(0,Hi.default)(new Error("unrecognized validity type"),Vi);Ec("ipns record for %s is valid",t.value)};async function $i(r,e){if(e.byteLength>Z2)throw(0,Hi.default)(new Error("record too large"),C0);let t=Oo(r),n=je(e),o=await D0(t,n);await J2(o,e)}async function*zi(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))}function Q2(r){return r[Symbol.asyncIterator]!=null}function eS(r){if(Q2(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var vc=eS;var Ff=P("/ipns/");function K0(r){return ne(r.subarray(0,Ff.byteLength),Ff)}var q0=r=>Jo(r.slice(Ff.length)),Sc=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*Ke(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!K0(e))return;let o=q0(e),i=je(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!K0(e))throw new N("Not found","ERR_NOT_FOUND");let n=q0(e);try{let o=await this.client.getIPNS(n,t);return Cr(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}},Ac=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await vc(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 ut=Qe("delegated-routing-v1-http-api-client"),G0={concurrentRequests:4,timeout:3e4},_c=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,me(1/0,this.shutDownController.signal),this.httpQueue=new at({concurrency:t.concurrentRequests??G0.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??G0.timeout,this.contentRouting=new Sc(this),this.peerRouting=new Ac(this)}get[$o](){return this.contentRouting}get[Ko](){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={}){ut("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ye([this.shutDownController.signal,n,t.signal]);me(1/0,n,o);let i=fe(),s=fe();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=`${this.clientUrl}routing/v1/providers/${e.toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let p of f.Providers){let h=this.#e(p);h!=null&&(yield h)}}else for await(let f of zi(wc(l.body))){let p=this.#e(f);p!=null&&(yield p)}}catch(a){ut.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),ut("getProviders finished: %c",e)}}async*getPeers(e,t={}){ut("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ye([this.shutDownController.signal,n,t.signal]);me(1/0,n,o);let i=fe(),s=fe();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let p of f.Peers){let h=this.#e(p);h!=null&&(yield h)}}else for await(let f of zi(wc(l.body))){let p=this.#e(f);p!=null&&(yield p)}}catch(a){ut.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),ut("getPeers finished: %c",e)}}async getIPNS(e,t={}){ut("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ye([this.shutDownController.signal,n,t.signal]);me(1/0,n,o);let i=fe(),s=fe();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await i.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(ut("getIPNS GET %s %d",a,l.status),l.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new N("GET ipns response had no body","ERR_BAD_RESPONSE");let u=await l.arrayBuffer(),f=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await $i(Lo(e),f),je(f)}catch(c){throw ut.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),ut("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){ut("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=Ye([this.shutDownController.signal,o,n.signal]);me(1/0,o,i);let s=fe(),a=fe();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await s.promise;let l=Cr(t),f=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i});if(ut("putIPNS PUT %s %d",c,f.status),f.status!==200)throw new N("PUT ipns response had status other than 200","ERR_BAD_RESPONSE")}catch(l){throw ut.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),ut("putIPNS finished: %c",e)}}#e(e){let t=[],n=e.Addrs?.map(Tr)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Lt(e.ID),Addrs:n,Protocols:t}}};function W0(r,e={}){return new _c(new URL(r),e)}var j0=P("/ipns/");function Y0(r){return ne(r.subarray(0,j0.byteLength),j0)}var Mf=class{client;constructor(e){this.client=W0(e)}async provide(e,t){}async*findProviders(e,t){yield*Ke(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols}))}async put(e,t,n){if(!Y0(e))return;let o=Oo(e),i=je(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!Y0(e))throw new N("Not found","ERR_NOT_FOUND");let n=Oo(e);try{let o=await this.client.getIPNS(n,t);return Cr(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}async findPeer(e,t){let n=await vc(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 Ki(r){return new Mf(new URL(r))}var X0="[a-fA-F\\d:]",dn=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${X0})|(?<=${X0})(?=\\s|$))`:"",zt="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",_e="[a-fA-F\\d]{1,4}",Ic=`
|
|
9
|
+
(?:
|
|
10
|
+
(?:${_e}:){7}(?:${_e}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
11
|
+
(?:${_e}:){6}(?:${zt}|:${_e}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
|
|
12
|
+
(?:${_e}:){5}(?::${zt}|(?::${_e}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
|
|
13
|
+
(?:${_e}:){4}(?:(?::${_e}){0,1}:${zt}|(?::${_e}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
|
|
14
|
+
(?:${_e}:){3}(?:(?::${_e}){0,2}:${zt}|(?::${_e}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
|
|
15
|
+
(?:${_e}:){2}(?:(?::${_e}){0,3}:${zt}|(?::${_e}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
|
|
16
|
+
(?:${_e}:){1}(?:(?::${_e}){0,4}:${zt}|(?::${_e}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
17
|
+
(?::(?:(?::${_e}){0,5}:${zt}|(?::${_e}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
18
|
+
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
19
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),tS=new RegExp(`(?:^${zt}$)|(?:^${Ic}$)`),rS=new RegExp(`^${zt}$`),nS=new RegExp(`^${Ic}$`),Vf=r=>r&&r.exact?tS:new RegExp(`(?:${dn(r)}${zt}${dn(r)})|(?:${dn(r)}${Ic}${dn(r)})`,"g");Vf.v4=r=>r&&r.exact?rS:new RegExp(`${dn(r)}${zt}${dn(r)}`,"g");Vf.v6=r=>r&&r.exact?nS:new RegExp(`${dn(r)}${Ic}${dn(r)}`,"g");var Hf=Vf;function $f(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function Z0(){return!1}var{toString:oS}=Object.prototype;function zf(r){return oS.call(r)==="[object RegExp]"}var J0={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Kf(r,e={}){if(!zf(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(J0).map(o=>(typeof e[o]=="boolean"?e[o]:r[o])?J0[o]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function qf(r,e,{timeout:t}={}){try{return $f(()=>Kf(r).test(e),{timeout:t})()}catch(n){if(Z0(n))return!1;throw n}}var iS=15,sS=45,Q0={timeout:400};function Gf(r){return r.length>sS?!1:qf(Hf.v6({exact:!0}),r,Q0)}function ey(r){return r.length>iS?!1:qf(Hf.v4({exact:!0}),r,Q0)}var ty={http:"80",https:"443",ws:"80",wss:"443"},aS=["http","https","ws","wss"];function ry(r,e){e=e??{};let t=e.defaultDnsType??"dns4",{scheme:n,hostname:o,port:i}=cS(r),a="/"+[lS(o,t),uS(i,n),fS(n)].filter(c=>!!c).reduce((c,l)=>c.concat(l),[]).join("/");return Tr(a)}function cS(r){let[e]=r.split(":");aS.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:o}=new URL(r);if(o==null||o===""){let i=hS(e);i!=null&&(o=i),i==null&&t==="http:"&&(o="80")}return{scheme:e,hostname:n,port:o}}function lS(r,e){if(!(r==null||r==="")){if(ey(r))return["ip4",r];if(Gf(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(Gf(t))return["ip6",t]}return[e,r]}}function uS(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function fS(r){if(r.match(/^tcp$|^udp$/)==null)return[r]}function hS(r){if(!(r==null||r===""||ty[r]==null))return ty[r]}var dS=["https://trustless-gateway.link","https://4everland.io"],pS=2336,mS=Symbol.for("nodejs.util.inspect.custom"),Wf=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Be.digest(P(this.url))}[mS](){return`PeerId(${this.url})`}[zo]=!0;toString(){return this.toCID().toString()}toCID(){return z.createV1(pS,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=G(e)),e.toString()===this.toString())}};function gS(r){return r=r.toString(),{id:new Wf(new URL(r)),multiaddrs:[ry(r)]}}var jf=class{gateways;constructor(e={}){this.gateways=(e.gateways??dS).map(t=>gS(t))}async*findProviders(e,t){yield*this.gateways.toSorted(()=>Math.random()>.5?1:-1).map(n=>({...n,protocols:["transport-ipfs-gateway-http"]}))}};function qi(r={}){return new jf(r)}var ny=re(De(),1);function Rc(r){return r=r??new Error("Not Found"),(0,ny.default)(r,"ERR_NOT_FOUND")}var oy="SHARDING";function wS(r){return r[Symbol.asyncIterator]!=null}function bS(r){if(wS(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 Yf=bS;function xS(r){return r[Symbol.asyncIterator]!=null}function ES(r,e){return xS(r)?async function*(){yield*(await Yf(r)).sort(e)}():function*(){yield*Yf(r).sort(e)}()}var kc=ES;var Lr=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 ur(this.putMany(e,n)),e=[],await ur(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=xt(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>xt(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>kc(o,i),n)),e.offset!=null){let o=0,i=e.offset;n=xt(n,()=>o++>=i)}return e.limit!=null&&(n=fs(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=xt(n,i=>i.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>xt(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>kc(o,i),n)),e.offset!=null){let o=e.offset,i=0;n=xt(n,()=>i++>=o)}return e.limit!=null&&(n=fs(n,e.limit)),n}};var Wi=class extends Lr{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 Rc();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 xe(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new xe(e)}};var yD=new xe(oy);var BD=Qe("datastore:core:tiered");async function sy(r={}){let e=r.datastore??new Wi,t=r.blockstore??new Oi,n=new rc({...r,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Mi()],routers:r.routers??[Ki("https://delegated-ipfs.dev"),qi()]});return r.start!==!1&&await n.start(),n}var Jf=re(Bc(),1);var Qf=40;function eh(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=Jf.default.decode(r);return e.seek(Jf.default.decode.bytes),t}function th(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 pn={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},ji={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":pn.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(pn.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=ji["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=ji["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:pn.Int,CarV1HeaderOrV2Pragma:r=>{if(pn.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=ji["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=ji.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}},Yi={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":pn.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(pn.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Yi["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=Yi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:pn.Int,CarV1HeaderOrV2Pragma:r=>{if(pn.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=Yi["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=Yi.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}},rh={toTyped:ji.CarV1HeaderOrV2Pragma,toRepresentation:Yi.CarV1HeaderOrV2Pragma};var pP=Ku();var VS=re(Bc(),1);var bP=[new R(w.map,2),new R(w.string,"version"),new R(w.uint,1),new R(w.string,"roots")],xP=new R(w.tag,42);async function nh(r,e){let t=eh(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=Ln(n);if(rh.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=th(await r.exactly(Qf,!0));r.seek(i.dataOffset-r.pos);let s=await nh(r,1);return Object.assign(s,i)}function Xi(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 oh=re(Bc(),1),wy=1;function ih(r){let e=Bi({version:wy,roots:r}),t=oh.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function by(r){return{async setRoots(e){let t=ih(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(oh.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 wy}}}function Tc(){}function xy(){let r=[],e=null,t=Tc,n=!1,o=null,i=Tc,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=Tc,l()}})),e),a={write(l){r.push(l);let u=s();return i(),u},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(u=>{i=()=>(o=null,i=Tc,u(c.next()))})),o)}};return{writer:a,iterator:c}}var Zi=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=z.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=KS(e);let{encoder:t,iterator:n}=Ey(),o=new r(e,t),i=new Nc(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=Ey();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new Nc(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=Xi(e);await nh(n);let o=ih(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}},Nc=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 Ey(){let r=xy(),{writer:e,iterator:t}=r;return{encoder:by(e),iterator:t}}function KS(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=z.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=z.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var qS=1,sh=class{components;constructor(e,t){this.components=e}async import(e,t){await ur(this.components.blockstore.putMany(Ke(e.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),t))}async export(e,t,n){let o=fe(),i=Array.isArray(e)?e:[e],s=new at({concurrency:qS});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,l)=>{await t.put({cid:c,bytes:l})},n)}).catch(()=>{});try{await o.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:o}=Zi.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 vy(r,e={}){return new sh(r,e)}var ah=re(bc(),1);function Sy(r,e){let t=e.map((n,o)=>({record:je(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=ah.default.fromString(n.record.validity).toDate(),c=ah.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 GS=32;async function Ay(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:[ct.TXT]})).Answer.sort((l,u)=>l.data.localeCompare(u.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;n("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,f,p,...h]=u.split("/");if(f==="ipfs")try{return{value:`/ipfs/${z.parse(p)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}else if(f==="ipns"){try{return{value:`/ipns/${Lt(p)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}return await Cc(p,e-1,t,n,o)}else{if(f==="dnslink")return await Cc(p,e-1,t,n,o);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(u){n.error("could not parse DNS link record for domain %s, %s",r,l.data,u)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=(await t.query(r,{...o,types:[ct.CNAME]})).Answer.sort((l,u)=>l.data.localeCompare(u.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await Cc(l.data,e-1,t,n,o)}catch(u){n.error("domain %s cname %s had no DNSLink records",r,l.data,u)}throw new N(`No DNSLink records found for domain: ${r}`,"ERR_DNSLINK_NOT_FOUND")}async function Cc(r,e,t,n,o={}){if(e===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await Ay(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 Ay(r,e,t,n,o)}}async function _y(r,e,t,n={}){return Cc(r,n.maxRecursiveDepth??GS,e,t,n)}var ch=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 V("ipns:routing:helia:error",o))}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){t.onProgress?.(new V("ipns:routing:helia:error",n))}throw new Error("Not found")}};function Iy(r){return new ch(r)}var Ji;(function(r){let e;r.codec=()=>(e==null&&(e=It((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:rt(0),value:rt(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=>_t(t,r.codec()),r.decode=(t,n)=>St(t,r.codec(),n)})(Ji||(Ji={}));function Ry(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 ky(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),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,l))}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 Ji.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:Ry(this.timeReceived)}}static deserialize(e){let t=Ji.decode(e);return new r(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=ky(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 Lc=globalThis.CustomEvent??Event;async function*On(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=fe(),a=fe(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(i.length===t&&(s=fe(),await s.promise),u)break;let d={done:!1};i.push(d),m().then(y=>{d.done=!0,d.ok=!0,d.value=y,o.dispatchEvent(new Lc("task-complete"))},y=>{d.done=!0,d.err=y,o.dispatchEvent(new Lc("task-complete"))})}c=!0,o.dispatchEvent(new Lc("task-complete"))}catch(m){l=m,o.dispatchEvent(new Lc("task-complete"))}});function f(){return n?i[0]?.done:!!i.find(m=>m.done)}function*p(){for(;i.length>0&&i[0].done;){let m=i[0];if(i.shift(),m.ok)yield m.value;else throw u=!0,s.resolve(),m.err;s.resolve()}}function*h(){for(;f();)for(let m=0;m<i.length;m++)if(i[m].done){let d=i[m];if(i.splice(m,1),m--,d.ok)yield d.value;else throw u=!0,s.resolve(),d.err;s.resolve()}}for(;;){if(f()||(a=fe(),await a.promise),l!=null)throw l;if(n?yield*p():yield*h(),c&&i.length===0)break}}var By;(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"})(By||(By={}));function Oc(r){return new xe("/dht/record/"+G(r,"base32"),!1)}function Ty(r){return{async put(e,t,n={}){try{let o=Oc(e);try{let s=await r.get(o),a=Or.deserialize(s);if(ne(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 V("ipns:routing:datastore:put")),await r.put(o,i.serialize(),n)}catch(o){throw n.onProgress?.(new V("ipns:routing:datastore:error",o)),o}},async get(e,t={}){try{let n=Oc(e);t.onProgress?.(new V("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 V("ipns:routing:datastore:error",n)),n}},async has(e,t={}){let n=Oc(e);return r.has(n,t)},async delete(e,t){let n=Oc(e);return r.delete(n,t)}}}var Dr=Qe("helia:ipns"),jS=60*1e3,fh=60*jS,YS=24*fh,lh=23*fh,XS=BigInt(fh)*1000000n,uh=class{routers;localStore;timeout;dns;log;constructor(e,t=[]){this.routers=[Iy(e.routing),...t],this.localStore=Ty(e.datastore),this.dns=e.dns,this.log=e.logger.forComponent("helia:ipns")}async publish(e,t,n={}){try{let o=1n,i=Lo(e);if(await this.localStore.has(i,n)){let{record:c}=await this.localStore.get(i,n);o=je(c).sequence+1n}let s=await $0(e,t,o,n.lifetime??YS,n),a=Cr(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 V("ipns:publish:error",o)),o}}async resolve(e,t={}){let n=Lo(e),o=await this.#n(n,t);return{...await this.#e(o.value,t),record:o}}async resolveDNSLink(e,t={}){let n=await _y(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 V("ipns:republish:start"));let i=Date.now()-n,s=lh-i;s<0&&(s=e.interval??lh),setTimeout(()=>{t().catch(a=>{Dr.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{t().catch(n=>{Dr.error("error republishing",n)})},e.interval??lh)}async#e(e,t={}){let n=e.split("/");try{let o=n[1];if(o==="ipns"){let{cid:i}=await this.resolve(Lt(n[2]),t),s=n.slice(3).join("/");return{cid:i,path:s}}else if(o==="ipfs"){let i=z.parse(n[2]),s=n.slice(3).join("/");return{cid:i,path:s}}}catch(o){Dr.error("error parsing ipfs path",o)}throw Dr.error("invalid ipfs path %s",e),new Error("Invalid value")}async#n(e,t={}){let n=[];if(await this.localStore.has(e,t))if(Dr("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 $i(e,a),this.log("record was valid");let l=je(a),u=Number((l.ttl??XS)/1000000n);if(c.getTime()+u>Date.now())return this.log("record TTL was valid"),l;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(e,t)}else Dr("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");Dr("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(l){Dr.error("error finding IPNS record",l);return}try{await $i(e,c),n.push(c)}catch(l){i++,Dr.error("error finding IPNS record",l)}})),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[Sy(e,n)];return await this.localStore.put(e,s,t),je(s)}};function Ny(r,{routers:e=[]}={}){return new uh(r,e)}var Vc=re(De(),1);function ZS(r){return r[Symbol.asyncIterator]!=null}function JS(r){if(ZS(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 Cy=JS;var aw=re(De(),1);var Ly=re(De(),1);function Do(r,e,t,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let u=z.asCID(a[l]);if(u!=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:u,name:l,path:c,toResolve:i}};a=a[l]}else throw(0,Ly.default)(new Error(`No property named ${l} 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 QS=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Ln(c);return Do(l,c,r,e,t,n,i)},Oy=QS;var eA=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=ja(c);return Do(l,c,r,e,t,n,i)},Dy=eA;var Py=re(De(),1);function tA(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 Dn=tA;var Qi=re(De(),1),rA=(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,Qi.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(o>n)throw(0,Qi.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(i<0n)throw(0,Qi.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,Qi.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:o,end:i}},Po=rA;var nA=r=>{async function*e(t={}){let{start:n,end:o}=Po(r.length,t.offset,t.length),i=Dn(r,0n,n,o);t.onProgress?.(new V("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},oA=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,Py.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=Xe(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:nA(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},Uy=oA;var iA=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=sd(c);return Do(l,c,r,e,t,n,i)},Fy=iA;var My=re(De(),1);var sA=r=>{async function*e(t={}){let{start:n,end:o}=Po(r.length,t.offset,t.length),i=Dn(r,0n,n,o);t.onProgress?.(new V("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},aA=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,My.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:sA(c),depth:i,size:BigInt(c.length),node:c}}},Vy=aA;var ts=re(De(),1);var hh=re(De(),1);var Kt;(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=()=>vn(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=It((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),Dc.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=Dc.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>_t(o,r.codec()),r.decode=o=>St(o,r.codec())})(Kt||(Kt={}));var Dc;(function(r){let e;r.codec=()=>(e==null&&(e=It((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=>_t(t,r.codec()),r.decode=t=>St(t,r.codec())})(Dc||(Dc={}));var Hy;(function(r){let e;r.codec=()=>(e==null&&(e=It((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=>_t(t,r.codec()),r.decode=t=>St(t,r.codec())})(Hy||(Hy={}));var $y={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},cA=["directory","hamt-sharded-directory"],zy=parseInt("0644",8),Ky=parseInt("0755",8),ar=class r{static unmarshal(e){let t=Kt.decode(e),n=new r({type:$y[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($y).includes(t))throw(0,hh.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()?Ky:zy:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return cA.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=Kt.DataType.Raw;break;case"directory":e=Kt.DataType.Directory;break;case"file":e=Kt.DataType.File;break;case"metadata":e=Kt.DataType.Metadata;break;case"symlink":e=Kt.DataType.Symlink;break;case"hamt-sharded-directory":e=Kt.DataType.HAMTShard;break;default:throw(0,hh.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===zy&&!this.isDirectory()&&(n=void 0),n===Ky&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Kt.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 Pc=re(ku(),1);function lA(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 gU=xn({name:"murmur3-32",code:35,encode:r=>lA(Pc.default.x86.hash32(r))}),qy=xn({name:"murmur3-128",code:34,encode:r=>zn.fromHex(Pc.default.x64.hash128(r))}),yU=xn({name:"murmur3-x64-64",code:34,encode:r=>zn.fromHex(Pc.default.x64.hash128(r)).subarray(0,8)});var es=re(De(),1);var Yy=re(jy(),1);var Pn=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 Yy.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 Xy(this,e,t)}toJSON(){return this.serialize(pA,mA)}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"?P(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(dA);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 dA(r){return!!r}function pA(r,e){return r.key}function mA(r){return r}async function Xy(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof Pn)await Xy(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var gA=[255,254,252,248,240,224,192,128],yA=[1,3,7,15,31,63,127,255],Uc=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 gA[r]&yA[Math.min(e+r-1,7)]}function Zy(r){function e(t){return t instanceof Fc?t:new Fc(t,r)}return e}var Fc=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 Uc(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Jy(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:Zy(r.hashFn)};return new Pn(e)}var xA=async function(r){return(await qy.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 Pn({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},Qy=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),vA=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},ew=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw(0,es.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let f;try{f=ar.unmarshal(r.Data)}catch(h){throw(0,es.default)(h,"ERR_NOT_UNIXFS")}if(f.type!=="hamt-sharded-directory")throw(0,es.default)(new Error("not a HAMT"),"ERR_NOT_UNIXFS");if(f.fanout==null)throw(0,es.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let p=Jy({hashFn:xA,bits:Math.log2(Number(f.fanout))});n={rootBucket:p,hamtDepth:1,lastBucket:p}}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=Qy(s.pos,i),c=vA(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=Qy(n.lastBucket._posAtParent,i));let l=r.Links.find(f=>{if(f.Name==null)return!1;let p=f.Name.substring(0,i),h=f.Name.substring(i);return!(p!==a||h!==""&&h!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===e)return l.Hash;n.hamtDepth++;let u=await t.get(l.Hash,o);return r=ir(u),ew(r,e,t,n,o)},tw=ew;var SA=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??e.Links.length,f=e.Links.slice(l,u);c.onProgress?.(new V("unixfs:exporter:walk:directory",{cid:r})),yield*jt(f,p=>Ke(p,h=>async()=>{let m=h.Name??"",d=`${n}/${m}`;return(await o(h.Hash,m,d,[],i+1,s,c)).entry}),p=>On(p,{ordered:!0,concurrency:c.blockReadConcurrency}),p=>xt(p,h=>h!=null))}return a},rw=SA;var Un=re(De(),1);async function nw(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=Dn(e,n,o,i);t.push(l);return}if(e.Data==null)throw(0,Un.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=ar.unmarshal(e.Data)}catch(l){throw(0,Un.default)(l,"ERR_NOT_UNIXFS")}if(a.data!=null){let l=a.data,u=Dn(l,n,o,i);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw(0,Un.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],f=n,p=f+a.blockSizes[l];if((o>=f&&o<p||i>=f&&i<=p||o<f&&i>p)&&c.push({link:u,blockStart:n}),n=p,n>i)break}await jt(c,l=>Ke(l,u=>async()=>{let f=await r.get(u.link.Hash,s);return{...u,block:f}}),l=>On(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:p}of l){let h;switch(u.Hash.code){case $t:h=ir(f);break;case ht:h=f;break;default:t.end((0,Un.default)(new Error(`Unsupported codec: ${u.Hash.code}`),"ERR_NOT_UNIXFS"));return}let m=new at({concurrency:1});m.on("error",d=>{t.end(d)}),m.add(async()=>{s.onProgress?.(new V("unixfs:exporter:walk:file",{cid:u.Hash})),await nw(r,h,t,p,o,i,s)}),await m.onIdle()}}),n>=i&&t.end()}var AA=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=Po(l,c.offset,c.length);if(f===0n)return;let p=0n,h=f-u,m=Gt();c.onProgress?.(new V("unixfs:exporter:walk:file",{cid:r})),nw(s,e,m,0n,u,f,c).catch(d=>{m.end(d)});for await(let d of m)if(d!=null){if(p+=BigInt(d.byteLength),p>h)throw m.end(),(0,Un.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");p===h&&m.end(),c.onProgress?.(new V("unixfs:exporter:progress:unixfs:file",{bytesRead:p,totalBytes:h,fileSize:l})),yield d}if(p<h)throw(0,Un.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return a},dh=AA;var Mc=re(De(),1);var _A=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new V("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),ow(e,n,o,i,s,c)}return a};async function*ow(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw(0,Mc.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=ar.unmarshal(r.Data)}catch(u){throw(0,Mc.default)(u,"ERR_NOT_UNIXFS")}if(a.fanout==null)throw(0,Mc.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let c=(a.fanout-1n).toString(16).length,l=jt(s,u=>Ke(u,f=>async()=>{let p=f.Name!=null?f.Name.substring(c):null;if(p!=null&&p!==""){let h=await t(f.Hash,p,`${e}/${p}`,[],n+1,o,i);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await o.get(f.Hash,i);return r=ir(h),i.onProgress?.(new V("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:ow(r,e,t,n,o,i)}}}),u=>On(u,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var iw=_A;var IA=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,RA={raw:dh,file:dh,directory:rw,"hamt-sharded-directory":iw,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},kA=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=ir(c),u,f;if(e==null&&(e=r.toString()),l.Data==null)throw(0,ts.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{u=ar.unmarshal(l.Data)}catch(h){throw(0,ts.default)(h,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let h;if(u?.type==="hamt-sharded-directory"?h=await tw(l,n[0],s):h=IA(l,n[0]),h==null)throw(0,ts.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let m=n.shift(),d=`${t}/${m}`;f={cid:h,toResolve:n,name:m??"",path:d}}let p=RA[u.type](r,l,u,t,o,i,s);if(p==null)throw(0,ts.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return u.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:p,unixfs:u,depth:i,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:e,path:t,cid:r,content:p,unixfs:u,depth:i,node:l,size:u.fileSize()},next:f}},sw=kA;var BA={[$t]:sw,[ht]:Vy,[un]:Oy,[hn]:Dy,[Be.code]:Uy,[Kr]:Fy},cw=async(r,e,t,n,o,i,s)=>{let a=BA[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,cw,o,i,s)},lw=cw;var TA=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),NA=r=>{if(r instanceof Uint8Array)return{cid:z.decode(r),toResolve:[]};let e=z.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=TA(r);return{cid:z.parse(t[0]),toResolve:t.slice(1)}}throw(0,Vc.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")};async function*ph(r,e,t={}){let{cid:n,toResolve:o}=NA(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await lw(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw(0,Vc.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 Uo(r,e,t={}){let n=await Cy(ph(r,e,t));if(n==null)throw(0,Vc.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}async function*uw(r,e,t={}){let n=await Uo(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))}}function fw(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Hc(r,e={}){let t=fw(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await t.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var Fo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,dw=new Set,mh=typeof process=="object"&&process?process:{},pw=(r,e,t,n)=>{typeof mh.emitWarning=="function"?mh.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`)},$c=globalThis.AbortController,hw=globalThis.AbortSignal;if(typeof $c>"u"){hw=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},$c=class{constructor(){e()}signal=new hw;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=mh.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=!1,pw("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var CA=r=>!dw.has(r),kF=Symbol("type"),mn=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),mw=r=>mn(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Mo:null:null,Mo=class extends Array{constructor(e){super(e),this.fill(0)}},gh=class r{heap;length;static#e=!1;static create(e){let t=mw(e);if(!t)return[];r.#e=!0;let n=new r(e,t);return r.#e=!1,n}constructor(e,t){if(!r.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},zc=class r{#e;#n;#s;#u;#g;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#f;#c;#r;#t;#i;#m;#l;#h;#b;#d;#x;#E;#y;#w;#A;#p;static unsafeExposeInternals(e){return{starts:e.#E,ttls:e.#y,sizes:e.#x,keyMap:e.#c,keyList:e.#r,valList:e.#t,next:e.#i,prev:e.#m,get head(){return e.#l},get tail(){return e.#h},free:e.#b,isBackgroundFetch:t=>e.#o(t),backgroundFetch:(t,n,o,i)=>e.#L(t,n,o,i),moveToTail:t=>e.#T(t),indexes:t=>e.#_(t),rindexes:t=>e.#I(t),isStale:t=>e.#S(t)}}get max(){return this.#e}get maxSize(){return this.#n}get calculatedSize(){return this.#f}get size(){return this.#a}get fetchMethod(){return this.#g}get dispose(){return this.#s}get disposeAfter(){return this.#u}constructor(e){let{max:t=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:f,noUpdateTTL:p,maxSize:h=0,maxEntrySize:m=0,sizeCalculation:d,fetchMethod:y,noDeleteOnFetchRejection:g,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:x,allowStaleOnFetchAbort:E,ignoreFetchAbort:v}=e;if(t!==0&&!mn(t))throw new TypeError("max option must be a nonnegative integer");let _=t?mw(t):Array;if(!_)throw new Error("invalid max value: "+t);if(this.#e=t,this.#n=h,this.maxEntrySize=m||this.#n,this.sizeCalculation=d,this.sizeCalculation){if(!this.#n&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#g=y,this.#A=!!y,this.#c=new Map,this.#r=new Array(t).fill(void 0),this.#t=new Array(t).fill(void 0),this.#i=new _(t),this.#m=new _(t),this.#l=0,this.#h=0,this.#b=gh.create(t),this.#a=0,this.#f=0,typeof l=="function"&&(this.#s=l),typeof u=="function"?(this.#u=u,this.#d=[]):(this.#u=void 0,this.#d=void 0),this.#w=!!this.#s,this.#p=!!this.#u,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!g,this.allowStaleOnFetchRejection=!!x,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!v,this.maxEntrySize!==0){if(this.#n!==0&&!mn(this.#n))throw new TypeError("maxSize must be a positive integer if specified");if(!mn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=mn(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!mn(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}if(this.#e===0&&this.ttl===0&&this.#n===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#n){let S="LRU_CACHE_UNBOUNDED";CA(S)&&(dw.add(S),pw("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",S,r))}}getRemainingTTL(e){return this.#c.has(e)?1/0:0}#R(){let e=new Mo(this.#e),t=new Mo(this.#e);this.#y=e,this.#E=t,this.#O=(i,s,a=Fo.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#S(i)&&this.delete(this.#r[i])},s+1);c.unref&&c.unref()}},this.#k=i=>{t[i]=e[i]!==0?Fo.now():0},this.#v=(i,s)=>{if(e[s]){let a=e[s],c=t[s];if(!a||!c)return;i.ttl=a,i.start=c,i.now=n||o();let l=i.now-c;i.remainingTTL=a-l}};let n=0,o=()=>{let i=Fo.now();if(this.ttlResolution>0){n=i;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#c.get(i);if(s===void 0)return 0;let a=e[s],c=t[s];if(!a||!c)return 1/0;let l=(n||o())-c;return a-l},this.#S=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(n||o())-s>a}}#k=()=>{};#v=()=>{};#O=()=>{};#S=()=>!1;#F(){let e=new Mo(this.#e);this.#f=0,this.#x=e,this.#B=t=>{this.#f-=e[t],e[t]=0},this.#D=(t,n,o,i)=>{if(this.#o(n))return 0;if(!mn(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,t),!mn(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(t,n,o)=>{if(e[t]=n,this.#n){let i=this.#n-e[t];for(;this.#f>i;)this.#C(!0)}this.#f+=e[t],o&&(o.entrySize=n,o.totalCalculatedSize=this.#f)}}#B=e=>{};#N=(e,t,n)=>{};#D=(e,t,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#h;!(!this.#P(t)||((e||!this.#S(t))&&(yield t),t===this.#l));)t=this.#m[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#l;!(!this.#P(t)||((e||!this.#S(t))&&(yield t),t===this.#h));)t=this.#i[t]}#P(e){return e!==void 0&&this.#c.get(this.#r[e])===e}*entries(){for(let e of this.#_())this.#t[e]!==void 0&&this.#r[e]!==void 0&&!this.#o(this.#t[e])&&(yield[this.#r[e],this.#t[e]])}*rentries(){for(let e of this.#I())this.#t[e]!==void 0&&this.#r[e]!==void 0&&!this.#o(this.#t[e])&&(yield[this.#r[e],this.#t[e]])}*keys(){for(let e of this.#_()){let t=this.#r[e];t!==void 0&&!this.#o(this.#t[e])&&(yield t)}}*rkeys(){for(let e of this.#I()){let t=this.#r[e];t!==void 0&&!this.#o(this.#t[e])&&(yield t)}}*values(){for(let e of this.#_())this.#t[e]!==void 0&&!this.#o(this.#t[e])&&(yield this.#t[e])}*rvalues(){for(let e of this.#I())this.#t[e]!==void 0&&!this.#o(this.#t[e])&&(yield this.#t[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#_()){let o=this.#t[n],i=this.#o(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#r[n],this))return this.get(this.#r[n],t)}}forEach(e,t=this){for(let n of this.#_()){let o=this.#t[n],i=this.#o(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#r[n],this)}}rforEach(e,t=this){for(let n of this.#I()){let o=this.#t[n],i=this.#o(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#r[n],this)}}purgeStale(){let e=!1;for(let t of this.#I({allowStale:!0}))this.#S(t)&&(this.delete(this.#r[t]),e=!0);return e}info(e){let t=this.#c.get(e);if(t===void 0)return;let n=this.#t[t],o=this.#o(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#y&&this.#E){let s=this.#y[t],a=this.#E[t];if(s&&a){let c=s-(Fo.now()-a);i.ttl=c,i.start=Date.now()}}return this.#x&&(i.size=this.#x[t]),i}dump(){let e=[];for(let t of this.#_({allowStale:!0})){let n=this.#r[t],o=this.#t[t],i=this.#o(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let s={value:i};if(this.#y&&this.#E){s.ttl=this.#y[t];let a=Fo.now()-this.#E[t];s.start=Math.floor(Date.now()-a)}this.#x&&(s.size=this.#x[t]),e.unshift([n,s])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let o=Date.now()-n.start;n.start=Fo.now()-o}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,u=this.#D(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.delete(e),this;let f=this.#a===0?void 0:this.#c.get(e);if(f===void 0)f=this.#a===0?this.#h:this.#b.length!==0?this.#b.pop():this.#a===this.#e?this.#C(!1):this.#a,this.#r[f]=e,this.#t[f]=t,this.#c.set(e,f),this.#i[this.#h]=f,this.#m[f]=this.#h,this.#h=f,this.#a++,this.#N(f,u,c),c&&(c.set="add"),l=!1;else{this.#T(f);let p=this.#t[f];if(t!==p){if(this.#A&&this.#o(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:h}=p;h!==void 0&&!s&&(this.#w&&this.#s?.(h,e,"set"),this.#p&&this.#d?.push([h,e,"set"]))}else s||(this.#w&&this.#s?.(p,e,"set"),this.#p&&this.#d?.push([p,e,"set"]));if(this.#B(f),this.#N(f,u,c),this.#t[f]=t,c){c.set="replace";let h=p&&this.#o(p)?p.__staleWhileFetching:p;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(o!==0&&!this.#y&&this.#R(),this.#y&&(l||this.#O(f,o,i),c&&this.#v(c,f)),!s&&this.#p&&this.#d){let p=this.#d,h;for(;h=p?.shift();)this.#u?.(...h)}return this}pop(){try{for(;this.#a;){let e=this.#t[this.#l];if(this.#C(!0),this.#o(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#p&&this.#d){let e=this.#d,t;for(;t=e?.shift();)this.#u?.(...t)}}}#C(e){let t=this.#l,n=this.#r[t],o=this.#t[t];return this.#A&&this.#o(o)?o.__abortController.abort(new Error("evicted")):(this.#w||this.#p)&&(this.#w&&this.#s?.(o,n,"evict"),this.#p&&this.#d?.push([o,n,"evict"])),this.#B(t),e&&(this.#r[t]=void 0,this.#t[t]=void 0,this.#b.push(t)),this.#a===1?(this.#l=this.#h=0,this.#b.length=0):this.#l=this.#i[t],this.#c.delete(n),this.#a--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=t,i=this.#c.get(e);if(i!==void 0){let s=this.#t[i];if(this.#o(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#S(i))o&&(o.has="stale",this.#v(o,i));else return n&&this.#k(i),o&&(o.has="hit",this.#v(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,o=this.#c.get(e);if(o===void 0||!n&&this.#S(o))return;let i=this.#t[o];return this.#o(i)?i.__staleWhileFetching:i}#L(e,t,n,o){let i=t===void 0?void 0:this.#t[t];if(this.#o(i))return i;let s=new $c,{signal:a}=n;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:n,context:o},l=(d,y=!1)=>{let{aborted:g}=s.signal,b=n.ignoreFetchAbort&&d!==void 0;if(n.status&&(g&&!y?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,b&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),g&&!b&&!y)return f(s.signal.reason);let x=h;return this.#t[t]===h&&(d===void 0?x.__staleWhileFetching?this.#t[t]=x.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,d,c.options))),d},u=d=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=d),f(d)),f=d=>{let{aborted:y}=s.signal,g=y&&n.allowStaleOnFetchAbort,b=g||n.allowStaleOnFetchRejection,x=b||n.noDeleteOnFetchRejection,E=h;if(this.#t[t]===h&&(!x||E.__staleWhileFetching===void 0?this.delete(e):g||(this.#t[t]=E.__staleWhileFetching)),b)return n.status&&E.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw d},p=(d,y)=>{let g=this.#g?.(e,i,c);g&&g instanceof Promise&&g.then(b=>d(b===void 0?void 0:b),y),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(d(void 0),n.allowStaleOnFetchAbort&&(d=b=>l(b,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(p).then(l,u),m=Object.assign(h,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,m,{...c.options,status:void 0}),t=this.#c.get(e)):this.#t[t]=m,m}#o(e){if(!this.#A)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof $c}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:d,forceRefresh:y=!1,status:g,signal:b}=t;if(!this.#A)return g&&(g.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:g});let x={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:h,status:g,signal:b},E=this.#c.get(e);if(E===void 0){g&&(g.fetch="miss");let v=this.#L(e,E,x,d);return v.__returned=v}else{let v=this.#t[E];if(this.#o(v)){let U=n&&v.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",U&&(g.returnedStale=!0)),U?v.__staleWhileFetching:v.__returned=v}let _=this.#S(E);if(!y&&!_)return g&&(g.fetch="hit"),this.#T(E),o&&this.#k(E),g&&this.#v(g,E),v;let S=this.#L(e,E,x,d),L=S.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=_?"stale":"refresh",L&&_&&(g.returnedStale=!0)),L?S.__staleWhileFetching:S.__returned=S}}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,a=this.#c.get(e);if(a!==void 0){let c=this.#t[a],l=this.#o(c);return s&&this.#v(s,a),this.#S(a)?(s&&(s.get="stale"),l?(s&&n&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.delete(e),s&&n&&(s.returnedStale=!0),n?c:void 0)):(s&&(s.get="hit"),l?c.__staleWhileFetching:(this.#T(a),o&&this.#k(a),c))}else s&&(s.get="miss")}#U(e,t){this.#m[t]=e,this.#i[e]=t}#T(e){e!==this.#h&&(e===this.#l?this.#l=this.#i[e]:this.#U(this.#m[e],this.#i[e]),this.#U(this.#h,e),this.#h=e)}delete(e){let t=!1;if(this.#a!==0){let n=this.#c.get(e);if(n!==void 0)if(t=!0,this.#a===1)this.clear();else{this.#B(n);let o=this.#t[n];if(this.#o(o)?o.__abortController.abort(new Error("deleted")):(this.#w||this.#p)&&(this.#w&&this.#s?.(o,e,"delete"),this.#p&&this.#d?.push([o,e,"delete"])),this.#c.delete(e),this.#r[n]=void 0,this.#t[n]=void 0,n===this.#h)this.#h=this.#m[n];else if(n===this.#l)this.#l=this.#i[n];else{let i=this.#m[n];this.#i[i]=this.#i[n];let s=this.#i[n];this.#m[s]=this.#m[n]}this.#a--,this.#b.push(n)}}if(this.#p&&this.#d?.length){let n=this.#d,o;for(;o=n?.shift();)this.#u?.(...o)}return t}clear(){for(let e of this.#I({allowStale:!0})){let t=this.#t[e];if(this.#o(t))t.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#w&&this.#s?.(t,n,"delete"),this.#p&&this.#d?.push([t,n,"delete"])}}if(this.#c.clear(),this.#t.fill(void 0),this.#r.fill(void 0),this.#y&&this.#E&&(this.#y.fill(0),this.#E.fill(0)),this.#x&&this.#x.fill(0),this.#l=0,this.#h=0,this.#b.length=0,this.#f=0,this.#a=0,this.#p&&this.#d){let e=this.#d,t;for(;t=e?.shift();)this.#u?.(...t)}}};function gw(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 yw(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 ww({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 bw({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 LA(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 OA(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 rs=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=gw(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=OA(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??LA(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}=yw(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 bw({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function xw(r){let e=tt(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(Ni(e))}function Ew(r){let e=DA(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function DA(r){return r.replace(/[^\x00-\x7F]/g,"_")}function vw({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 PA={[un]:["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"],[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"],[Kr]:["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"],[$t]:["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"],[ht]:["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 Sw(r,e){let t=PA[r.code];if(e!=null)return UA(e,t)}function UA(r,e){let t=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:FA(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 FA(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 Kc={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 Aw(r){if(r!=null)return Kc[r]}function yh(r){let e=r.get("accept");return!!(e!=null&&Object.values(Kc).includes(e))}function wh(r){let e=r?.format;return!!(e!=null&&Object.keys(Kc).includes(e))}function _w({query:r,headers:e}){return yh(e)||wh(r)}function Iw({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),!_w({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=Aw(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=i;return!yh(o)&&wh(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 Rw(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(l){n?.onProgress?.(new V("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await i.next();if(n?.signal?.aborted===!0){l.error(new qt(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new V("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new V("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var i7=P("ustar\0","binary"),s7=P("ustar ","binary"),a7=P(" \0","binary");var Cw=re(Bw(),1);function VA(r){return r[Symbol.asyncIterator]!=null}function HA(r){if(VA(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 Tw=HA;var $A="0000000000000000000",zA="7777777777777777777",KA=48,qA=P("ustar\0","binary"),GA=P("00","binary"),WA=parseInt("7777",8),jA=257,YA=263,XA=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}},ZA=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},gn=function(r,e){let t=r.toString(8);return t.length>e?P(zA.slice(0,e)+" "):P($A.slice(0,e-t.length)+t+" ")},bh=function(r){let e=P(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function Nw(r){let e="";r.name!=null&&(e+=bh(" path="+r.name+`
|
|
20
|
+
`)),r.linkname!=null&&(e+=bh(" linkpath="+r.linkname+`
|
|
21
|
+
`));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=bh(" "+n+"="+t[n]+`
|
|
22
|
+
`));return P(e)}function qc(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),P(t).byteLength!==t.length)return null;for(;P(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 P(t).byteLength>100||P(n).byteLength>155||r.linkname!=null&&P(r.linkname).byteLength>100?null:(e.set(P(t),0),e.set(gn(r.mode&WA,6),100),e.set(gn(r.uid,6),108),e.set(gn(r.gid,6),116),e.set(gn(r.size,11),124),e.set(gn(r.mtime.getTime()/1e3|0,11),136),e[156]=KA+XA(r.type),r.linkname!=null&&e.set(P(r.linkname),157),e.set(qA,jA),e.set(GA,YA),r.uname!=null&&e.set(P(r.uname),265),r.gname!=null&&e.set(P(r.gname),297),e.set(gn(r.devmajor??0,6),329),e.set(gn(r.devminor??0,6),337),n!=null&&e.set(P(n),345),e.set(gn(ZA(e),6),148),e)}var{S_IFMT:QA,S_IFBLK:e_,S_IFCHR:t_,S_IFDIR:r_,S_IFIFO:n_,S_IFLNK:o_}=Cw.default,i_=parseInt("755",8),s_=parseInt("644",8),Lw=new Uint8Array(1024);function a_(r=0){switch(r&QA){case e_:return"block-device";case t_:return"character-device";case r_:return"directory";case n_:return"fifo";case o_:return"symlink";default:return"file"}}function Eh(r){return r&=511,r!==0?Lw.subarray(0,512-r):new Uint8Array(0)}function xh(r){if(r.pax==null){let e=qc(r);if(e!=null)return e}return c_(r)}function c_(r){let e=Nw(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 fr(qc(t)??new Uint8Array(0),e,Eh(e.length),qc({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function Gc(){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??a_(e.mode),mode:e.mode??(e.type==="directory"?i_:s_),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=P(t)),t instanceof Uint8Array||Wt(t)){n.size=t.length,yield xh(n),yield Wt(t)?t.subarray():t,yield Eh(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=G(await Tw(t)),yield xh(n);continue}if(yield xh(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield Wt(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield Eh(n.size)}yield Lw}}var l_=["file","raw","directory"];function u_(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 Ow(r){if(!l_.includes(r.type))throw new N("Not a UnixFS node","ERR_NOT_UNIXFS");let e={header:u_(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*Dw(r,e,t){let n=await Uo(r,e,t);if(n.type==="file"||n.type==="raw"){yield*jt([Ow(n)],Gc());return}if(n.type==="directory"){yield*jt(uw(r,e,t),o=>Ke(o,i=>Ow(i)),Gc());return}throw new N("Not a UnixFS node","ERR_NOT_UNIXFS")}var Pw=re(Du(),1),Wc=class{lru;constructor(e){this.lru=(0,Pw.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 Uw=new Wc(1e3),f_=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,h_=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,d_=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,p_=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function m_(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 vh(r){for(let e of[f_,h_,d_,p_]){let t=r.match(e);if(m_(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function g_(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 y_=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function w_(r){return y_.test(r)&&r.includes("-")&&!r.includes(".")}function b_(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function Fw({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}=vh(r),l,u,f=[],p;if(i==="ipfs")try{l=z.parse(s)}catch(d){o.error(d),f.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(p=Uw.get(s),p!=null)l=p.cid,u=p.path,o.trace("resolved %s to %c from cache",s,l);else{o.trace("Attempting to resolve PeerId for %s",s);let d=null;try{d=Lt(s),p=await e.resolve(d,n),l=p?.cid,u=p?.path,o.trace("resolved %s to %c",s,l)}catch(y){n?.signal?.throwIfAborted(),d==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",d,y),f.push(new TypeError(`Could not resolve PeerId "${s}", ${y.message}`)))}if(l==null){let y=s;w_(s)&&(y=b_(s),o.trace('decoded dnslink from "%s" to "%s"',s,y)),o.trace("Attempting to resolve DNSLink for %s",y);try{p=await e.resolveDNSLink(y,n),l=p?.cid,u=p?.path,o.trace("resolved %s to %c",y,l)}catch(g){n?.signal?.throwIfAborted(),o.error('could not resolve DnsLink for "%s"',s,g),f.push(g)}}}if(l==null)throw f.length===1?f[0]:new AggregateError(f,`Invalid resource. Cannot determine CID from URL "${r}"`);let h=g_(p);p!=null&&(h=h??60*2,o.trace("caching %s resolved to %s with TTL: %s",s,l,h),Uw.set(s,p,h*1e3));let m={};if(c!=null&&c.length>0){let d=c.split("&");for(let y of d){let[g,b]=y.split("=");m[g]=decodeURIComponent(b)}m.download!=null&&(m.download=m.download==="true"),m.filename!=null&&(m.filename=m.filename.toString())}return{protocol:i,cid:l,path:x_(u,a??""),query:m,ttl:h,ipfsPath:`/${i}/${s}${a!=null&&a!==""?`/${a}`:""}`}}function x_(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 Mw(r,{ipns:e,logger:t},n){if(typeof r=="string")return Fw({urlString:r,ipns:e,logger:t},n);let o=z.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function Vw(r){let e=z.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${z.parse(r.toString())}`}catch{}let{protocol:t,cidOrPeerIdOrDnsLink:n}=vh(r.toString());return`${t}://${n}`}function Sh(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function Pr(r,e){Sh(r,"type",e)}function Ur(r,e){Sh(r,"url",e)}function Hw(r){Sh(r,"redirected",!0)}function Fn(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&Hw(n),Pr(n,"basic"),Ur(n,r),n.headers.set("Accept-Ranges","bytes"),n}function Yc(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return Pr(n,"basic"),Ur(n,r),n}function Ah(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Pr(n,"basic"),Ur(n,r),n}function Vo(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return Pr(n,"basic"),Ur(n,r),n}function Xc(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return Pr(n,"basic"),Ur(n,r),n}function Zc(r,e,t){e instanceof Error&&(e=e.message);let n=new Response(e,{...t??{},status:400,statusText:"Bad Request"});return Pr(n,"basic"),Ur(n,r),n}function $w(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return Pr(n,"basic"),Ur(n,r),n}function _h(r,e,{byteRangeContext:t,log:n},o){if(!t.isRangeRequest)return Fn(r,e,o);if(!t.isValidRangeRequest)return jc(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),jc(r,e,o)}return o?.redirected===!0&&Hw(i),Pr(i,"basic"),Ur(i,r),i.headers.set("Accept-Ranges","bytes"),i}function jc(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return Pr(n,"basic"),Ur(n,r),n}async function Ih(r,e,t){let n=[],o;for await(let i of ph(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 zw(r){return r.type==="object"}var E_=100,v_=60*1e3;function S_(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var A_=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function __({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(A_.includes(o??""))return o}}var Jc=class{helia;ipns;log;contentTypeParser;blockstoreSessions;constructor({helia:e,ipns:t},n){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??Ny(e),this.contentTypeParser=n?.contentTypeParser,this.blockstoreSessions=new zc({max:n?.sessionCacheSize??E_,ttl:n?.sessionTTLms??v_,dispose:o=>{o.close()}}),this.log.trace("created VerifiedFetch instance")}getBlockstore(e,t,n,o){if(!n)return this.helia.blockstore;let i=this.blockstoreSessions.get(t);return i==null&&(i=this.helia.blockstore.createSession(e,o),this.blockstoreSessions.set(t,i)),i}async handleIPNSRecord({resource:e,cid:t,path:n,options:o}){if(n!==""||!e.startsWith("ipns://"))return Zc(e,"Invalid IPNS name");let i;try{i=Lt(e.replace("ipns://",""))}catch(f){return this.log.error("could not parse peer id from IPNS url %s",e),Zc(e,f)}let s=ue([P("/ipns/"),i.toBytes()]),a=new xe("/dht/record/"+G(s,"base32"),!1),c=await this.helia.datastore.get(a,o),l=Or.deserialize(c),u=Fn(e,l.value);return u.headers.set("content-type","application/vnd.ipfs.ipns-record"),u}async handleCar({resource:e,cid:t,session:n,cacheKey:o,options:i}){let s=this.getBlockstore(t,o,n,i),a=vy({blockstore:s,dagWalkers:this.helia.dagWalkers}),c=Hc(a.stream(t,i)),l=Fn(e,c);return l.headers.set("content-type","application/vnd.ipld.car; version=1"),l}async handleTar({resource:e,cid:t,path:n,session:o,cacheKey:i,options:s}){if(t.code!==$t&&t.code!==ht)return Vo("only UnixFS data can be returned in a TAR file");let a=this.getBlockstore(t,i,o,s),c=Hc(Dw(`/ipfs/${t}/${n}`,a,s)),l=Fn(e,c);return l.headers.set("content-type","application/x-tar"),l}async handleJson({resource:e,cid:t,path:n,accept:o,session:i,cacheKey:s,options:a}){this.log.trace("fetching %c/%s",t,n);let l=await this.getBlockstore(t,s,i,a).get(t,a),u;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let p=ja(l);u=Bi(p)}catch(p){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",p),Vo(e)}else u=l;let f=Fn(e,u);return f.headers.set("content-type",o??"application/json"),f}async handleDagCbor({resource:e,cid:t,path:n,accept:o,session:i,cacheKey:s,options:a}){this.log.trace("fetching %c/%s",t,n);let c,l,u=this.getBlockstore(t,s,i,a);try{let m=await Ih(u,`${t.toString()}/${n}`,a);l=m.ipfsRoots;let d=m.terminalElement;if(d==null)return Xc(e);zw(d)&&(c=d)}catch(m){return a?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT"].includes(m.code)?Xc(e):(this.log.error("error walking path %s",n,m),Yc(e,"Error walking path"))}let f=c?.node??await u.get(t,a),p;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")p=f;else if(o==="application/vnd.ipld.dag-json")try{let m=Ln(f);p=Cg(m)}catch(m){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",m),Vo(e)}else try{p=xw(f)}catch(m){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',m),Vo(e);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",m),p=f}let h=Fn(e,p);return o==null&&(o=p instanceof Uint8Array?"application/octet-stream":"application/json"),h.headers.set("content-type",o),l!=null&&h.headers.set("X-Ipfs-Roots",l.map(m=>m.toV1().toString()).join(",")),h}async handleDagPb({cid:e,path:t,resource:n,cacheKey:o,session:i,options:s}){let a,c,l=!1,u=new rs(this.helia.logger,s?.headers),f=this.getBlockstore(e,o,i,s);try{let d=await Ih(f,`${e.toString()}/${t}`,s);c=d.ipfsRoots,a=d.terminalElement}catch(d){return s?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(d.code)?Xc(n.toString()):(this.log.error("error walking path %s",t,d),Yc(n.toString(),"Error walking path"))}let p=a?.cid??e;if(a?.type==="directory"){let d=a.cid;if(t===""?!n.toString().endsWith("/"):!t.endsWith("/")){if(s?.redirect==="error")throw this.log('could not redirect to %s/ as redirect option was set to "error"',n),new TypeError("Failed to fetch");if(s?.redirect==="manual")return this.log("returning 301 permanent redirect to %s/",n),$w(n,`${n}/`);n=`${n}/`,l=!0}let g="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",e,t);let b=await Uo(`/ipfs/${d}/${g}`,this.helia.blockstore,{signal:s?.signal,onProgress:s?.onProgress});this.log.trace("found root file at %c/%s with cid %c",d,g,b.cid),t=g,p=b.cid}catch(b){return s?.signal?.throwIfAborted(),this.log("error loading path %c/%s",d,g,b),Ah("Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented")}finally{s?.onProgress?.(new V("verified-fetch:request:end",{cid:d,path:g}))}}u.isRangeRequest&&u.isValidRangeRequest&&a.type==="file"&&(u.setFileSize(a.unixfs.fileSize()),this.log.trace("fileSize for rangeRequest %d",u.getFileSize()));let h=u.offset,m=u.length;this.log.trace("calling exporter for %c/%s with offset=%o & length=%o",p,t,h,m);try{let y=(await Uo(p,this.helia.blockstore,{signal:s?.signal,onProgress:s?.onProgress})).content({signal:s?.signal,onProgress:s?.onProgress,offset:h,length:m});this.log("got async iterator for %c/%s",e,t);let{stream:g,firstChunk:b}=await Rw(y,t??"",this.helia.logger,{onProgress:s?.onProgress,signal:s?.signal});u.setBody(g);let x=_h(n,u.getBody(),{byteRangeContext:u,log:this.log},{redirected:l});return await this.setContentType(b,t,x),c!=null&&x.headers.set("X-Ipfs-Roots",c.map(E=>E.toV1().toString()).join(",")),x}catch(d){return s?.signal?.throwIfAborted(),this.log.error("error streaming %c/%s",e,t,d),u.isRangeRequest&&d.code==="ERR_INVALID_PARAMS"?jc(n):Yc(n.toString(),"Unable to stream content")}}async handleRaw({resource:e,cid:t,path:n,session:o,cacheKey:i,options:s,accept:a}){let c=new rs(this.helia.logger,s?.headers),u=await this.getBlockstore(t,i,o,s).get(t,s);c.setBody(u);let f=_h(e,c.getBody(),{byteRangeContext:c,log:this.log},{redirected:!1});return await this.setContentType(u,n,f,__({headers:s?.headers,accept:a})),f}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(I_(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={[$t]:this.handleDagPb,[hn]:this.handleJson,[Kr]:this.handleJson,[un]:this.handleDagCbor,[ht]:this.handleRaw,[Be.code]:this.handleRaw};async fetch(e,t){this.log("fetch %s",e);let n=S_(t);n?.onProgress?.(new V("verified-fetch:request:start",{resource:e}));let o,i,s,a,c,l;try{let g=await Mw(e,{ipns:this.ipns,logger:this.helia.logger},n);o=g.cid,i=g.path,s=g.query,a=g.ttl,c=g.protocol,l=g.ipfsPath}catch(g){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",e,g),Zc(e.toString(),g)}n?.onProgress?.(new V("verified-fetch:request:resolve",{cid:o,path:i}));let u=Iw({query:s,headers:n?.headers,logger:this.helia.logger}),f=Sw(o,u);if(this.log("output type %s",f),u!=null&&f==null)return Vo(e.toString());let p,h,m=Vw(e),d={resource:e.toString(),cid:o,path:i,accept:f,cacheKey:m,session:n?.session??!0,options:n};if(f==="application/vnd.ipfs.ipns-record")h="ipns-record",p=await this.handleIPNSRecord(d);else if(f==="application/vnd.ipld.car")h="car",s.download=!0,s.filename=s.filename??`${o.toString()}.car`,p=await this.handleCar(d);else if(f==="application/vnd.ipld.raw")h="raw",s.download=!0,s.filename=s.filename??`${o.toString()}.bin`,p=await this.handleRaw(d);else if(f==="application/x-tar")h="tar",s.download=!0,s.filename=s.filename??`${o.toString()}.tar`,p=await this.handleTar(d);else{this.log.trace('finding handler for cid code "%s" and output type "%s"',o.code,f);let g=this.codecHandlers[o.code];if(g==null)return Ah(`Support for codec with code ${o.code} is not yet implemented. Please open an issue at https://github.com/ipfs/helia-verified-fetch/issues/new`);this.log.trace('calling handler "%s"',g.name),p=await g.call(this,d)}p.headers.set("etag",vw({cid:o,reqFormat:h,weak:!1})),ww({response:p,ttl:a,protocol:c}),p.headers.set("X-Ipfs-Path",l);let y;return s.download===!0&&(y="attachment"),s.filename!=null&&(y==null&&(y="inline"),y=`${y}; ${Ew(s.filename)}`),y!=null&&p.headers.set("Content-Disposition",y),n?.onProgress?.(new V("verified-fetch:request:end",{cid:o,path:i})),p}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function I_(r){return r?.then!=null}var ns,Qc=async function(e,t){return ns==null&&(ns=await Rh()),ns(e,t)};Qc.start=async function(){await ns?.start()};Qc.stop=async function(){await ns?.stop()};async function Rh(r,e){R_(r)||(r=await sy({blockBrokers:[Mi({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})],routers:[...(r?.routers??["https://delegated-ipfs.dev"]).map(o=>Ki(o)),qi({gateways:r?.gateways??[]})],dns:k_(r?.dnsResolvers)}));let t=new Jc({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 R_(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function k_(r){if(r!=null)return Array.isArray(r)?Ei({resolvers:{".":r}}):Ei({resolvers:r})}return nb(B_);})();
|
|
12
23
|
/*! Bundled license information:
|
|
13
24
|
|
|
14
25
|
pvtsutils/build/index.js:
|