helia 7.1.11 → 7.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +3 -3
- package/dist/index.min.js.map +2 -2
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +2 -2
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Helia = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Helia=(()=>{var R_=Object.create;var _f=Object.defineProperty;var D_=Object.getOwnPropertyDescriptor;var N_=Object.getOwnPropertyNames;var O_=Object.getPrototypeOf,B_=Object.prototype.hasOwnProperty;var un=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},we=(r,e)=>{for(var t in e)_f(r,t,{get:e[t],enumerable:!0})},F7=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of N_(e))!B_.call(r,s)&&s!==t&&_f(r,s,{get:()=>e[s],enumerable:!(n=D_(e,s))||n.enumerable});return r};var jo=(r,e,t)=>(t=r!=null?R_(O_(r)):{},F7(e||!r||!r.__esModule?_f(t,"default",{value:r,enumerable:!0}):t,r)),M_=r=>F7(_f({},"__esModule",{value:!0}),r);var B3=un(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.Netmask4Impl=void 0;Pa.ip2long=_a;Pa.long2ip=Un;function Un(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,s=r&255;return[e,t,n,s].join(".")}var XL=48,QL=97,ZL=65;function JL(r){let e=0,t=10,n="9",s=0;r.length>1&&r[s]==="0"&&(r[s+1]==="x"||r[s+1]==="X"?(s+=2,t=16):"0"<=r[s+1]&&r[s+1]<="9"&&(s++,t=8,n="7"));let o=s;for(;s<r.length;){if("0"<=r[s]&&r[s]<=n)e=e*t+(r.charCodeAt(s)-XL)>>>0;else if(t===16)if("a"<=r[s]&&r[s]<="f")e=e*t+(10+r.charCodeAt(s)-QL)>>>0;else if("A"<=r[s]&&r[s]<="F")e=e*t+(10+r.charCodeAt(s)-ZL)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");s++}if(s===o)throw new Error("empty octet");return[e,s]}function _a(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,s]=JL(r);r=r.substring(s),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var O3=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let s=e.split("/",2);e=s[0],n=s[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=_a(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let s=32;s>=0;s--)if(this.maskLong===4294967295<<32-s>>>0){this.bitmask=s;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(_a(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Un(this.netLong),this.mask=Un(this.maskLong),this.hostmask=Un(~this.maskLong),this.first=this.bitmask<=30?Un(this.netLong+1):this.base,this.last=this.bitmask<=30?Un(this.netLong+this.size-2):Un(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Un(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(_a(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(Un(this.netLong+this.size*e),this.mask)}forEach(e){let t=_a(this.first),n=_a(this.last),s=0;for(;t<=n;)e(Un(t),t,s),s++,t++}toString(){return this.base+"/"+this.bitmask}};Pa.Netmask4Impl=O3});var Kw=un(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.Netmask6Impl=void 0;La.ip6bigint=U3;La.bigint2ip6=mi;var eR=B3(),M3=(1n<<128n)-1n;function U3(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),s=(0,eR.ip2long)(n),o=r.substring(0,t+1)+"0:0";return $w(o)&~0xffffffffn|BigInt(s)}return $w(r)}function $w(r){let e=r.indexOf("::"),t;if(e!==-1){let s=r.substring(0,e),o=r.substring(e+2),i=s===""?[]:s.split(":"),a=o===""?[]:o.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let s=0;s<8;s++){let o=t[s];if(o.length===0||o.length>4)throw new Error('Invalid IPv6: bad group "'+o+'"');let i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+o+'"');n=n<<16n|BigInt(i)}return n}function mi(r){if(r<0n||r>M3)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,s=-1,o=0;for(let i=0;i<8;i++)e[i]===0?s===-1?(s=i,o=1):o++:(o>n&&o>=2&&(t=s,n=o),s=-1,o=0);if(o>n&&o>=2&&(t=s,n=o),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var F3=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let s=e.indexOf("/");s!==-1?(n=parseInt(e.substring(s+1),10),e=e.substring(0,s)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=M3>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=U3(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=mi(this.netBigint),this.mask=mi(this.maskBigint),this.hostmask=mi(~this.maskBigint&M3),this.first=this.base,this.last=mi(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(U3(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(mi(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),s=this.netBigint+n-1n,o=0;for(;t<=s;)e(mi(t),Number(t),o),o++,t++}toString(){return this.base+"/"+this.bitmask}};La.Netmask6Impl=F3});var Hw=un(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.long2ip=no.ip2long=no.Netmask=void 0;var nh=B3();Object.defineProperty(no,"ip2long",{enumerable:!0,get:function(){return nh.ip2long}});Object.defineProperty(no,"long2ip",{enumerable:!0,get:function(){return nh.long2ip}});var tR=Kw(),$3=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new tR.Netmask6Impl(e,t):this._impl=new nh.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof nh.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};no.Netmask=$3});var dv=un((uae,uv)=>{"use strict";function MB(r){return r>=55296&&r<=56319}function UB(r){return r>=56320&&r<=57343}uv.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var s=t.length,o=0,i,a,c=0;c<s;c+=1){if(i=t.charCodeAt(c),a=t[c],MB(i)&&UB(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),o+=e(a),o===n)return t.slice(0,c+1);if(o>n)return t.slice(0,c-a.length+1)}return t}});var hv=un((dae,fv)=>{"use strict";function FB(r){return r>=55296&&r<=56319}function $B(r){return r>=56320&&r<=57343}fv.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,s=null,o=null,i=0;i<t;i++)s=e.charCodeAt(i),$B(s)?o!=null&&FB(o)?n+=1:n+=3:s<=127?n+=1:s>=128&&s<=2047?n+=2:s>=2048&&s<=65535&&(n+=3),o=s;return n}});var mv=un((fae,pv)=>{"use strict";var KB=dv(),HB=hv();pv.exports=KB.bind(null,HB)});var e6=un((hae,yv)=>{"use strict";var VB=mv(),qB=/[\/\?<>\\:\*\|"]/g,zB=/[\x00-\x1f\x80-\x9f]/g,WB=/^\.+$/,GB=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function jB(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function gv(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(qB,e).replace(zB,e).replace(WB,e).replace(GB,e);return t=jB(t,e),VB(t,255)}yv.exports=function(r,e){var t=e&&e.replacement||"",n=gv(r,t);return t===""?n:gv(n,"")}});var wv=un(Tc=>{"use strict";var XB="[object ArrayBuffer]",Rs=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===XB}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==s[o])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let s=new Uint8Array(n),o=0;for(let i of t){let a=this.toUint8Array(i);s.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}},r6="string",QB=/^[0-9a-f\s]+$/i,ZB=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,JB=/^[a-zA-Z0-9-_]+$/,up=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n.buffer}static toString(e){let t=Rs.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return decodeURIComponent(escape(n))}},cn=class{static toString(e,t=!1){let n=Rs.toArrayBuffer(e),s=new DataView(n),o="";for(let i=0;i<n.byteLength;i+=2){let a=s.getUint16(i,t);o+=String.fromCharCode(a)}return o}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),s=new DataView(n);for(let o=0;o<e.length;o++)s.setUint16(o*2,e.charCodeAt(o),t);return n}},dp=class r{static isHex(e){return typeof e===r6&&QB.test(e)}static isBase64(e){return typeof e===r6&&ZB.test(e)}static isBase64Url(e){return typeof e===r6&&JB.test(e)}static ToString(e,t="utf8"){let n=Rs.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 cn.toString(n,!0);case"utf16":case"utf16be":return cn.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 cn.fromString(e,!0);case"utf16":case"utf16be":return cn.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Rs.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 up.fromString(e);case"utf16":case"utf16be":return cn.fromString(e);case"utf16le":case"usc2":return cn.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 up.toString(e);case"utf16":case"utf16be":return cn.toString(e);case"utf16le":case"usc2":return cn.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return n.buffer}static ToBinary(e){let t=Rs.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return n}static ToHex(e){let t=Rs.toUint8Array(e),n="",s=t.length;for(let o=0;o<s;o++){let i=t[o];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let s=0;s<t.length;s=s+2){let o=t.slice(s,s+2);n[s/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,t=!1){return cn.toString(e,t)}static FromUtf16String(e,t=!1){return cn.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,"")||""}};dp.DEFAULT_UTF8_ENCODING="utf8";function eM(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let s=arguments[n];for(let o in s)t[o]=s[o]}return t}function tM(...r){let e=r.map(s=>s.byteLength).reduce((s,o)=>s+o),t=new Uint8Array(e),n=0;return r.map(s=>new Uint8Array(s)).forEach(s=>{for(let o of s)t[n++]=o}),t.buffer}function rM(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)if(t[s]!==n[s])return!1;return!0}Tc.BufferSourceConverter=Rs;Tc.Convert=dp;Tc.assign=eM;Tc.combine=tM;Tc.isEqual=rM});var qS=un((vde,x6)=>{"use strict";var rU=Object.prototype.hasOwnProperty,yr="~";function gd(){}Object.create&&(gd.prototype=Object.create(null),new gd().__proto__||(yr=!1));function nU(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function VS(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new nU(t,n||r,s),i=yr?yr+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],o]:r._events[i].push(o):(r._events[i]=o,r._eventsCount++),r}function Wm(r,e){--r._eventsCount===0?r._events=new gd:delete r._events[e]}function sr(){this._events=new gd,this._eventsCount=0}sr.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)rU.call(t,n)&&e.push(yr?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};sr.prototype.listeners=function(e){var t=yr?yr+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s<o;s++)i[s]=n[s].fn;return i};sr.prototype.listenerCount=function(e){var t=yr?yr+e:e,n=this._events[t];return n?n.fn?1:n.length:0};sr.prototype.emit=function(e,t,n,s,o,i){var a=yr?yr+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,s),!0;case 5:return c.fn.call(c.context,t,n,s,o),!0;case 6:return c.fn.call(c.context,t,n,s,o,i),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,h;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,s);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[d].fn.apply(c[d].context,u)}}return!0};sr.prototype.on=function(e,t,n){return VS(this,e,t,n,!1)};sr.prototype.once=function(e,t,n){return VS(this,e,t,n,!0)};sr.prototype.removeListener=function(e,t,n,s){var o=yr?yr+e:e;if(!this._events[o])return this;if(!t)return Wm(this,o),this;var i=this._events[o];if(i.fn)i.fn===t&&(!s||i.once)&&(!n||i.context===n)&&Wm(this,o);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||s&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[o]=c.length===1?c[0]:c:Wm(this,o)}return this};sr.prototype.removeAllListeners=function(e){var t;return e?(t=yr?yr+e:e,this._events[t]&&Wm(this,t)):(this._events=new gd,this._eventsCount=0),this};sr.prototype.off=sr.prototype.removeListener;sr.prototype.addListener=sr.prototype.on;sr.prefixed=yr;sr.EventEmitter=sr;typeof x6<"u"&&(x6.exports=sr)});var GS=un((qde,WS)=>{WS.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var zI=un(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.parseCookie=VI;us.parse=VI;us.stringifyCookie=lH;us.stringifySetCookie=c2;us.serialize=c2;us.parseSetCookie=uH;us.stringifySetCookie=c2;us.serialize=c2;var KI=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,HI=/^[\u0021-\u003A\u003C-\u007E]*$/,sH=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,oH=/^[\u0020-\u003A\u003D-\u007E]*$/,iH=/^-?\d+$/,aH=Object.prototype.toString,cH=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function VI(r,e){let t=new cH,n=r.length;if(n<2)return t;let s=e?.decode||qI,o=0;do{let i=L5(r,o,n);if(i===-1)break;let a=P5(r,o,n);if(i>a){o=r.lastIndexOf(";",i-1)+1;continue}let c=Uo(r,o,i);t[c]===void 0&&(t[c]=s(Uo(r,i+1,a))),o=a+1}while(o<n);return t}function lH(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let s of Object.keys(r)){let o=r[s];if(o===void 0)continue;if(!KI.test(s))throw new TypeError(`cookie name is invalid: ${s}`);let i=t(o);if(!HI.test(i))throw new TypeError(`cookie val is invalid: ${o}`);n.push(`${s}=${i}`)}return n.join("; ")}function c2(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},o=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!KI.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let i=n.value?o(n.value):"";if(!HI.test(i))throw new TypeError(`argument val is invalid: ${n.value}`);let a=n.name+"="+i;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);a+="; Max-Age="+n.maxAge}if(n.domain){if(!sH.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!oH.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!dH(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.partitioned&&(a+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return a}function uH(r,e){let t=e?.decode||qI,n=r.length,s=P5(r,0,n),o=L5(r,0,s),i=o===-1?{name:"",value:t(Uo(r,0,s))}:{name:Uo(r,0,o),value:t(Uo(r,o+1,s))},a=s+1;for(;a<n;){let c=P5(r,a,n),l=L5(r,a,c),u=l===-1?Uo(r,a,c):Uo(r,a,l),d=l===-1?void 0:Uo(r,l+1,c);switch(u.toLowerCase()){case"httponly":i.httpOnly=!0;break;case"secure":i.secure=!0;break;case"partitioned":i.partitioned=!0;break;case"domain":i.domain=d;break;case"path":i.path=d;break;case"max-age":d&&iH.test(d)&&(i.maxAge=Number(d));break;case"expires":if(!d)break;let f=new Date(d);Number.isFinite(f.valueOf())&&(i.expires=f);break;case"priority":if(!d)break;let h=d.toLowerCase();(h==="low"||h==="medium"||h==="high")&&(i.priority=h);break;case"samesite":if(!d)break;let p=d.toLowerCase();(p==="lax"||p==="strict"||p==="none")&&(i.sameSite=p);break}a=c+1}return i}function P5(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function L5(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Uo(r,e,t){let n=e,s=t;do{let o=r.charCodeAt(n);if(o!==32&&o!==9)break}while(++n<s);for(;s>n;){let o=r.charCodeAt(s-1);if(o!==32&&o!==9)break;s--}return r.slice(n,s)}function qI(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function dH(r){return aH.call(r)==="[object Date]"}});var bq={};we(bq,{DEFAULT_CID_PEER_FILTER_SIZE:()=>I3,DEFAULT_SESSION_MAX_PROVIDERS:()=>T3,DEFAULT_SESSION_MIN_PROVIDERS:()=>A3,InsufficientProvidersError:()=>Kl,InvalidCodecError:()=>C3,NoEvictionError:()=>li,NoRoutersAvailableError:()=>ro,UnknownCodecError:()=>Vl,UnknownCryptoError:()=>ql,UnknownHashAlgorithmError:()=>Hl,createHelia:()=>wq,createHeliaLight:()=>k_,isPrivateKey:()=>Cw,isPublicKey:()=>S3});var $7=Symbol.for("@libp2p/connection");var Yo=Symbol.for("@libp2p/content-routing");var jt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},fa=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},ha=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},v=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},dn=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},xl=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},vl=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var Xo=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},pa=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},fn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},ma=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var On=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Qo=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},Re=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},ga=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Bn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Pf=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},ya=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Lf=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},xe=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Zo=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Mn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Nr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Qs=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Jo=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Sl=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Rf=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},wa=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},hn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Df=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},Zs=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Nf=class extends Zs{constructor(e,t){super(!0,e,t)}},Of=class extends Zs{constructor(e,t){super(!1,e,t)}};var ei=Symbol.for("@libp2p/peer-discovery");var Bf=Symbol.for("@libp2p/peer-id");function vr(r){return!!r?.[Bf]}var ti=Symbol.for("@libp2p/peer-routing");var ri="keep-alive";function Mf(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function yt(...r){let e=[];for(let t of r)Mf(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 Dt(...r){let e=[];for(let t of r)Mf(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Js=Symbol.for("@libp2p/transport");var Al;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Al||(Al={}));function U_(r){return typeof r?.handleEvent=="function"}function F_(r){return r===!0||r===!1}function $_(r){return F_(r)?r:r?.capture??!1}function _g(r){let e={capture:$_(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function K7(r,e){return _g(r).capture===_g(e).capture}var ge=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let s=_g(n);if(s?.signal?.aborted===!0)return;let o=l=>{s.once&&this.removeEventListener(e,t,s),U_(t)?t.handleEvent(l):t(l)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==t?!1:K7(l.options,s)))return;super.addEventListener(e,o,s);let c=()=>{this.removeEventListener(e,t,s)};s.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:o,options:s,onAbort:c})}removeEventListener(e,t,n){let s=this.#e.get(e);if(s==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,s.filter(o=>o.callback===t&&K7(o.options,n)?(super.removeEventListener(e,o.wrapper,n),o.options?.signal?.removeEventListener("abort",o.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Ae=Symbol.for("@libp2p/service-capabilities"),Or=Symbol.for("@libp2p/service-dependencies");var P=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function he(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var oz=new Uint8Array(0);function V7(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 Sr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return ni(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return ni(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function q7(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var H7=4096;function z7(r){let e=r.length;if(e<=H7)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=H7));return t}function K_(r){return r?.buffer instanceof ArrayBuffer}function ni(r){return K_(r)?r:r.slice()}var Og={};we(Og,{base32:()=>xt,base32hex:()=>Q_,base32hexpad:()=>J_,base32hexpadupper:()=>eP,base32hexupper:()=>Z_,base32pad:()=>Y_,base32padupper:()=>X_,base32upper:()=>j_,base32z:()=>tP});function H_(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),s=0;s<n.length;s++)n[s]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=o,t){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=o),l!==a&&(n[l]=o)}}var u=r.length,d=r.charAt(0),f=Math.log(u)/Math.log(256),h=Math.log(256)/Math.log(u);function p(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 b=0,E=0,S=0,T=m.length;S!==T&&m[S]===0;)S++,b++;for(var C=(T-S)*h+1>>>0,k=new Uint8Array(C);S!==T;){for(var O=m[S],N=0,K=C-1;(O!==0||N<E)&&K!==-1;K--,N++)O+=256*k[K]>>>0,k[K]=O%u>>>0,O=O/u>>>0;if(O!==0)throw new Error("Non-zero carry");E=N,S++}for(var ee=C-E;ee!==C&&k[ee]===0;)ee++;for(var J=d.repeat(b);ee<C;++ee)J+=r.charAt(k[ee]);return J}function g(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var b=0;if(m[b]!==" "){for(var E=0,S=0;m[b]===d;)E++,b++;for(var T=(m.length-b)*f+1>>>0,C=new Uint8Array(T);m[b];){var k=n[m.charCodeAt(b)];if(k===255)return;for(var O=0,N=T-1;(k!==0||O<S)&&N!==-1;N--,O++)k+=u*C[N]>>>0,C[N]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");S=O,b++}if(m[b]!==" "){for(var K=T-S;K!==T&&C[K]===0;)K++;for(var ee=new Uint8Array(E+(T-K)),J=E;K!==T;)ee[J++]=C[K++];return ee}}}function y(m){var b=g(m);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:g,decode:y}}var V_=H_,q_=V_,W7=q_;var Lg=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")}},Rg=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return G7(this,e)}},Dg=class{decoders;constructor(e){this.decoders=e}or(e){return G7(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 G7(r,e){return new Dg({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ng=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Lg(e,t,n),this.decoder=new Rg(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ba({name:r,prefix:e,encode:t,decode:n}){return new Ng(r,e,t,n)}function eo({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:s,decode:o}=W7(t,r,n);return ba({prefix:e,name:r,encode:s,decode:i=>Sr(o(i))})}function z_(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function W_(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function G_(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let s=r[n].toLowerCase(),o=r[n].toUpperCase();s!==r[n]&&(t[s]=n),o!==r[n]&&(t[o]=n)}return t}function dt({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:s=!1}){let o=G_(n,s);return ba({prefix:e,name:r,encode(i){return W_(i,n,t)},decode(i){return z_(i,o,t,r)}})}var xt=dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),j_=dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Y_=dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),X_=dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Q_=dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Z_=dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),J_=dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),eP=dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),tP=dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Bg={};we(Bg,{base36:()=>cr,base36upper:()=>rP});var cr=eo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),rP=eo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Mg={};we(Mg,{base58btc:()=>Se,base58flickr:()=>nP});var Se=eo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nP=eo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qe={};we(Qe,{Digest:()=>si,create:()=>lr,decode:()=>Ce,equals:()=>Fg,hasCode:()=>vP});var sP=X7,j7=128,oP=127,iP=~oP,aP=Math.pow(2,31);function X7(r,e,t){e=e||[],t=t||0;for(var n=t;r>=aP;)e[t++]=r&255|j7,r/=128;for(;r&iP;)e[t++]=r&255|j7,r>>>=7;return e[t]=r|0,X7.bytes=t-n+1,e}var cP=Ug,lP=128,Y7=127;function Ug(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ug.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Y7)<<s:(i&Y7)*Math.pow(2,s),s+=7}while(i>=lP);return Ug.bytes=o-n,t}var uP=Math.pow(2,7),dP=Math.pow(2,14),fP=Math.pow(2,21),hP=Math.pow(2,28),pP=Math.pow(2,35),mP=Math.pow(2,42),gP=Math.pow(2,49),yP=Math.pow(2,56),wP=Math.pow(2,63),bP=function(r){return r<uP?1:r<dP?2:r<fP?3:r<hP?4:r<pP?5:r<mP?6:r<gP?7:r<yP?8:r<wP?9:10},EP={encode:sP,decode:cP,encodingLength:bP},xP=EP,Tl=xP;function Il(r,e=0){let t=Tl.decode(r,e),n=Tl.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Ea(r,e,t=0){return Tl.encode(r,e,t),e}function xa(r){return Tl.encodingLength(r)}function lr(r,e){let t=e.byteLength,n=xa(r),s=n+xa(t),o=new Uint8Array(s+t);return Ea(r,o,0),Ea(t,o,n),o.set(e,s),new si(r,t,e,o)}function Ce(r){let e=Sr(r),[t,n]=Il(e),[s,o]=Il(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new si(t,s,i,e)}function Fg(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&V7(r.bytes,t.bytes)}}var si=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=ni(n),this.bytes=ni(s)}};function vP(r,e){return r.code===e}function Q7(r,e){let{bytes:t,version:n}=r;return n===0?AP(t,$g(r),e??Se.encoder):TP(t,$g(r),e??xt.encoder)}var Z7=new WeakMap;function $g(r){let e=Z7.get(r);if(e==null){let t=new Map;return Z7.set(r,t),t}return e}var $=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=ni(s),this["/"]=this.bytes}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!==Cl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==IP)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=lr(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&&Fg(e.multihash,n.multihash)}toString(e){return Q7(this,e)}toJSON(){return{"/":Q7(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??J7(n,s,o.bytes))}else if(t[CP]===!0){let{version:n,multihash:s,code:o}=t,i=Ce(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Cl)throw new Error(`Version 0 CID must use dag-pb (code: ${Cl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=J7(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Cl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Sr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new si(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=Il(e.subarray(t));return t+=f,d},s=n(),o=Cl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=SP(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $g(o).set(n,e),o}};function SP(r,e){switch(r[0]){case"Q":{let t=e??Se;return[Se.prefix,t.decode(`${Se.prefix}${r}`)]}case Se.prefix:{let t=e??Se;return[Se.prefix,t.decode(r)]}case xt.prefix:{let t=e??xt;return[xt.prefix,t.decode(r)]}case cr.prefix:{let t=e??cr;return[cr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function AP(r,e,t){let{prefix:n}=t;if(n!==Se.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function TP(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Cl=112,IP=18;function J7(r,e,t){let n=xa(r),s=n+xa(e),o=new Uint8Array(s+t.byteLength);return Ea(r,o,0),Ea(e,o,n),o.set(t,s),o}var CP=Symbol.for("@ipld/js-cid/CID");var kP=20;function kl({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Kg(r,e,t,n,s)}var Kg=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??kP,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ew(n,this.code,t?.truncate):n.then(s=>ew(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ew(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return lr(e,r)}var Hg={};we(Hg,{base64:()=>We,base64pad:()=>_l,base64url:()=>fe,base64urlpad:()=>_P});var We=dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_l=dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fe=dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_P=dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Vg={};we(Vg,{identity:()=>ot});var rw=0,PP="identity",nw=Sr;function LP(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return lr(rw,nw(r))}var ot={code:rw,name:PP,encode:nw,digest:LP};function pe(r=0){return new Uint8Array(r)}function it(r=0){return new Uint8Array(r)}function RP(r){return r?.buffer instanceof ArrayBuffer}function Ff(r){if(RP(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ke(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=it(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return Ff(t)}function se(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 ow=Symbol.for("@achingbrain/uint8arraylist");function sw(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function va(r){return!!r?.[ow]}var V=class r{bufs;length;[ow]=!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(va(n)){t+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}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(va(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=sw(this.bufs,e);return t.buf[t.index]}set(e,t){let n=sw(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(va(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ke(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ke(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=n,o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!va(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let d=0;d<o;d++)i[d]=-1;for(let d=0;d<s;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=pe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=pe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!se(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};function DP(r){return r.buffer instanceof ArrayBuffer}function re(r){return DP(r)?r:r.slice()}var NP=parseInt("11111",2),qg=parseInt("10000000",2),OP=parseInt("01111111",2),iw={0:Pl,1:Pl,2:BP,3:FP,4:$P,5:UP,6:MP,16:Pl,22:Pl,48:Pl};function pn(r,e={offset:0}){let t=r[e.offset]&NP;if(e.offset++,iw[t]!=null)return iw[t](r,e);throw new Error("No decoder for tag 0x"+t.toString(16).padStart(2,"0"))}function Ll(r,e){let t=0;if((r[e.offset]&qg)===qg){let n=r[e.offset]&OP,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Pl(r,e){Ll(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=pn(r,e);if(n===null)break;t.push(n)}return t}function BP(r,e){let t=Ll(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function MP(r,e){let t=Ll(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function UP(r,e){return e.offset++,null}function FP(r,e){let t=Ll(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function $P(r,e){let t=Ll(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function KP(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new V;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function $f(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=KP(r.byteLength);return new V(Uint8Array.from([e.byteLength|qg]),e)}function ur(r){let e=new V,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new V(Uint8Array.from([2]),$f(e),e)}function Rl(r){let e=Uint8Array.from([0]),t=new V(e,r);return new V(Uint8Array.from([3]),$f(t),t)}function aw(r){return new V(Uint8Array.from([4]),$f(r),r)}function mn(r,e=48){let t=new V;for(let n of r)t.append(re(n.subarray()));return new V(Uint8Array.from([e]),$f(t),t)}var Ge=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"};var HP=Math.pow(2,7),VP=Math.pow(2,14),qP=Math.pow(2,21),zg=Math.pow(2,28),Wg=Math.pow(2,35),Gg=Math.pow(2,42),jg=Math.pow(2,49),Me=128,Yt=127;function Te(r){if(r<HP)return 1;if(r<VP)return 2;if(r<qP)return 3;if(r<zg)return 4;if(r<Wg)return 5;if(r<Gg)return 6;if(r<jg)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Sa(r,e,t=0){switch(Te(r)){case 8:e[t++]=r&255|Me,r/=128;case 7:e[t++]=r&255|Me,r/=128;case 6:e[t++]=r&255|Me,r/=128;case 5:e[t++]=r&255|Me,r/=128;case 4:e[t++]=r&255|Me,r>>>=7;case 3:e[t++]=r&255|Me,r>>>=7;case 2:e[t++]=r&255|Me,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function zP(r,e,t=0){switch(Te(r)){case 8:e.set(t++,r&255|Me),r/=128;case 7:e.set(t++,r&255|Me),r/=128;case 6:e.set(t++,r&255|Me),r/=128;case 5:e.set(t++,r&255|Me),r/=128;case 4:e.set(t++,r&255|Me),r>>>=7;case 3:e.set(t++,r&255|Me),r>>>=7;case 2:e.set(t++,r&255|Me),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Yg(r,e){let t=r[e],n=0;if(n+=t&Yt,t<Me||(t=r[e+1],n+=(t&Yt)<<7,t<Me)||(t=r[e+2],n+=(t&Yt)<<14,t<Me)||(t=r[e+3],n+=(t&Yt)<<21,t<Me)||(t=r[e+4],n+=(t&Yt)*zg,t<Me)||(t=r[e+5],n+=(t&Yt)*Wg,t<Me)||(t=r[e+6],n+=(t&Yt)*Gg,t<Me)||(t=r[e+7],n+=(t&Yt)*jg,t<Me))return n;throw new RangeError("Could not decode varint")}function WP(r,e){let t=r.get(e),n=0;if(n+=t&Yt,t<Me||(t=r.get(e+1),n+=(t&Yt)<<7,t<Me)||(t=r.get(e+2),n+=(t&Yt)<<14,t<Me)||(t=r.get(e+3),n+=(t&Yt)<<21,t<Me)||(t=r.get(e+4),n+=(t&Yt)*zg,t<Me)||(t=r.get(e+5),n+=(t&Yt)*Wg,t<Me)||(t=r.get(e+6),n+=(t&Yt)*Gg,t<Me)||(t=r.get(e+7),n+=(t&Yt)*jg,t<Me))return n;throw new RangeError("Could not decode varint")}function Xt(r,e,t=0){return e==null&&(e=it(Te(r))),e instanceof Uint8Array?Sa(r,e,t):zP(r,e,t)}function Br(r,e=0){return r instanceof Uint8Array?Yg(r,e):WP(r,e)}var Xg=new Float32Array([-0]),to=new Uint8Array(Xg.buffer);function cw(r,e,t){Xg[0]=r,e[t]=to[0],e[t+1]=to[1],e[t+2]=to[2],e[t+3]=to[3]}function lw(r,e){return to[0]=r[e],to[1]=r[e+1],to[2]=r[e+2],to[3]=r[e+3],Xg[0]}var Qg=new Float64Array([-0]),Qt=new Uint8Array(Qg.buffer);function uw(r,e,t){Qg[0]=r,e[t]=Qt[0],e[t+1]=Qt[1],e[t+2]=Qt[2],e[t+3]=Qt[3],e[t+4]=Qt[4],e[t+5]=Qt[5],e[t+6]=Qt[6],e[t+7]=Qt[7]}function dw(r,e){return Qt[0]=r[e],Qt[1]=r[e+1],Qt[2]=r[e+2],Qt[3]=r[e+3],Qt[4]=r[e+4],Qt[5]=r[e+5],Qt[6]=r[e+6],Qt[7]=r[e+7],Qg[0]}var GP=BigInt(Number.MAX_SAFE_INTEGER),jP=BigInt(Number.MIN_SAFE_INTEGER),Mr=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 oi;if(e<GP&&e>jP)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>fw&&(s=0n,++n>fw&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return oi;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):oi}},oi=new Mr(0,0);oi.toBigInt=function(){return 0n};oi.zzEncode=oi.zzDecode=function(){return this};oi.length=function(){return 1};var fw=4294967296n;function hw(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 pw(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Zg(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function gn(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Kf(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Jg=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=re(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,gn(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 gn(this,4);return Kf(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw gn(this,4);return Kf(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw gn(this,4);let e=lw(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw gn(this,4);let e=dw(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 gn(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return pw(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw gn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw gn(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Mr(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 gn(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 gn(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 gn(this,8);let e=Kf(this.buf,this.pos+=4),t=Kf(this.buf,this.pos+=4);return new Mr(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=Yg(this.buf,this.pos);return this.pos+=Te(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 Dl(r){return new Jg(r instanceof Uint8Array?r:r.subarray())}function ae(r,e,t){let n=Dl(r);return e.decode(n,void 0,t)}var e3={};we(e3,{base10:()=>YP});var YP=eo({prefix:"9",name:"base10",alphabet:"0123456789"});var t3={};we(t3,{base16:()=>XP,base16upper:()=>QP});var XP=dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),QP=dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var r3={};we(r3,{base2:()=>ZP});var ZP=dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var n3={};we(n3,{base256emoji:()=>nL});var gw=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}"),JP=gw.reduce((r,e,t)=>(r[t]=e,r),[]),eL=gw.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function tL(r){return r.reduce((e,t)=>(e+=JP[t],e),"")}function rL(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=eL[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var nL=ba({prefix:"\u{1F680}",name:"base256emoji",encode:tL,decode:rL});var s3={};we(s3,{base8:()=>sL});var sL=dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var o3={};we(o3,{identity:()=>oL});var oL=ba({prefix:"\0",name:"identity",encode:r=>z7(Sr(r)),decode:r=>Sr(q7(r))});var Hf={};we(Hf,{code:()=>lL,decode:()=>dL,encode:()=>uL,name:()=>cL});var iL=new TextEncoder,aL=new TextDecoder,cL="json",lL=512;function uL(r){return iL.encode(JSON.stringify(r))}function dL(r){return JSON.parse(aL.decode(r))}var ii={};we(ii,{code:()=>hs,decode:()=>pL,encode:()=>hL,name:()=>fL});var fL="raw",hs=85;function hL(r){return Sr(r)}function pL(r){return Sr(r)}var a3={};we(a3,{sha256:()=>je,sha512:()=>i3});function yw(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var je=kl({name:"sha2-256",code:18,encode:yw("SHA-256")}),i3=kl({name:"sha2-512",code:19,encode:yw("SHA-512")});var ai={...o3,...r3,...s3,...e3,...t3,...Og,...Bg,...Mg,...Hg,...n3},hW={...a3,...Vg};function bw(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ww=bw("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),c3=bw("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=it(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),mL={utf8:ww,"utf-8":ww,hex:ai.base16,latin1:c3,ascii:c3,binary:c3,...ai},Vf=mL;function A(r,e="utf8"){let t=Vf[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function l3(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return it(i);s+i>e&&(n=it(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var ci=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function u3(){}var f3=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},gL=l3();function yL(r){return globalThis.Buffer!=null?it(r):gL(r)}var Ol=class{len;head;tail;states;constructor(){this.len=0,this.head=new ci(u3,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ci(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new h3((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(qf,10,Mr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Mr.fromBigInt(e);return this._push(qf,t.length(),t)}uint64Number(e){return this._push(Sa,Te(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=Mr.fromBigInt(e).zzEncode();return this._push(qf,t.length(),t)}sint64Number(e){let t=Mr.fromNumber(e).zzEncode();return this._push(qf,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(d3,1,e?1:0)}fixed32(e){return this._push(Nl,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Mr.fromBigInt(e);return this._push(Nl,4,t.lo)._push(Nl,4,t.hi)}fixed64Number(e){let t=Mr.fromNumber(e);return this._push(Nl,4,t.lo)._push(Nl,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(cw,4,e)}double(e){return this._push(uw,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(d3,1,0):this.uint32(t)._push(bL,t,e)}string(e){let t=hw(e);return t!==0?this.uint32(t)._push(Zg,t,e):this._push(d3,1,0)}fork(){return this.states=new f3(this),this.head=this.tail=new ci(u3,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 ci(u3,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=yL(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function d3(r,e,t){e[t]=r&255}function wL(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var h3=class extends ci{next;constructor(e,t){super(wL,e,t),this.next=void 0}};function qf(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 Nl(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 bL(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Ol.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(EL,e,r),this},Ol.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(xL,e,r),this});function EL(r,e,t){e.set(r,t)}function xL(r,e,t){r.length<40?Zg(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(A(r),t)}function p3(){return new Ol}function ce(r,e){let t=p3();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*le(r,e,t){let n=Dl(r);yield*e.stream(n,".",void 0,t)}var zf={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Wf(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function at(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i,a){};return Wf("enum",zf.VARINT,t,n,s)}function ue(r,e,t){return Wf("message",zf.LENGTH_DELIMITED,r,e,t)}var ye=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Bl=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var Gf;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Gf||(Gf={}));var m3;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(m3||(m3={}));(function(r){r.codec=()=>at(m3)})(Gf||(Gf={}));var Ar;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),i.int32(o.Type)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Ar||(Ar={}));var dr;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),i.int32(o.Type)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(dr||(dr={}));var vL=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),SL=Uint8Array.from([6,5,43,129,4,0,34]),AL=Uint8Array.from([6,5,43,129,4,0,35]),Ew={ext:!0,kty:"EC",crv:"P-256"},xw={ext:!0,kty:"EC",crv:"P-384"},vw={ext:!0,kty:"EC",crv:"P-521"},Aa=32,Ta=48,Ia=66,Ml=class{type="ECDSA";code=3;jwk;constructor(e){this.jwk=e}toMultihash(){return ot.digest(this.toProtobuf())}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return Ar.encode({Type:this.code,Data:kL(this.jwk)})}async verify(e,t,n){let s=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!1,["verify"]),o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,re(t),re(e));return n?.signal?.throwIfAborted(),o}},jf=class{type="ECDSA";code=3;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return dr.encode({Type:this.code,Data:_L(this.jwk)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!0,["sign"]),s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,re(e));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}},g3=class{type="ECDSA";code=3;async generatePrivateKey(e){let t=e?.curve??"P-256",n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:t},!0,["sign","verify"]),s=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey);return e?.signal?.throwIfAborted(),new jf(s,new Ml(o))}async publicKeyFromProtobuf(e,t){let n=Ar.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let s=CL(n.Data);return new Ml(s)}async privateKeyFromProtobuf(e,t){let n=dr.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");let s=IL(n.Data),o=TL(s);return t?.signal?.throwIfAborted(),new jf(s,new Ml(o))}};function y3(){return new g3}function TL(r){return{crv:r.crv,ext:!0,key_ops:["verify"],kty:"EC",x:r.x,y:r.y}}function IL(r){let e=pn(r),t=e[1],n=fe.baseEncode(t),s=e[2][1][0],o=1,i,a;if(t.byteLength===Aa)return i=fe.baseEncode(s.subarray(o,o+Aa)),a=fe.baseEncode(s.subarray(o+Aa)),{...Ew,key_ops:["sign"],d:n,x:i,y:a};if(t.byteLength===Ta)return i=fe.baseEncode(s.subarray(o,o+Ta)),a=fe.baseEncode(s.subarray(o+Ta)),{...xw,key_ops:["sign"],d:n,x:i,y:a};if(t.byteLength===Ia)return i=fe.baseEncode(s.subarray(o,o+Ia)),a=fe.baseEncode(s.subarray(o+Ia)),{...vw,key_ops:["sign"],d:n,x:i,y:a};throw new Ge(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function CL(r){let t=pn(r)[1][1][0],n=1,s,o;if(t.byteLength===Aa*2+1)return s=fe.baseEncode(t.subarray(n,n+Aa)),o=fe.baseEncode(t.subarray(n+Aa)),{...Ew,key_ops:["verify"],x:s,y:o};if(t.byteLength===Ta*2+1)return s=fe.baseEncode(t.subarray(n,n+Ta)),o=fe.baseEncode(t.subarray(n+Ta)),{...xw,key_ops:["verify"],x:s,y:o};if(t.byteLength===Ia*2+1)return s=fe.baseEncode(t.subarray(n,n+Ia)),o=fe.baseEncode(t.subarray(n+Ia)),{...vw,key_ops:["verify"],x:s,y:o};throw new Ge(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function kL(r){return mn([ur(Uint8Array.from([1])),mn([Sw(r.crv)],160),mn([Rl(new V(Uint8Array.from([4]),fe.baseDecode(r.x??""),fe.baseDecode(r.y??"")))],161)]).subarray()}function _L(r){return mn([ur(Uint8Array.from([1])),aw(fe.baseDecode(r.d??"")),mn([Sw(r.crv)],160),mn([Rl(new V(Uint8Array.from([4]),fe.baseDecode(r.x??""),fe.baseDecode(r.y??"")))],161)]).subarray()}function Sw(r){if(r==="P-256")return vL;if(r==="P-384")return SL;if(r==="P-521")return AL;throw new Ge(`Invalid curve ${r}`)}var PL=32,Ul=class{type="Ed25519";code=1;jwk;constructor(e){this.jwk=e}toMultihash(){return ot.digest(this.toProtobuf())}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return Ar.encode({Type:this.code,Data:fe.baseDecode(this.jwk.x??"")})}async verify(e,t,n){let s=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!1,["verify"]),o=await crypto.subtle.verify({name:"Ed25519"},s,re(t),re(e));return n?.signal?.throwIfAborted(),o}},Yf=class{type="Ed25519";code=1;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return dr.encode({Type:this.code,Data:Ke([fe.baseDecode(this.jwk.d??""),fe.baseDecode(this.jwk.x??"")],64)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!0,["sign"]),s=await crypto.subtle.sign({name:"Ed25519"},n,re(e));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}},w3=class{type="Ed25519";code=1;async generatePrivateKey(e){let t=await crypto.subtle.generateKey("Ed25519",!0,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",t.privateKey),s=await crypto.subtle.exportKey("jwk",t.publicKey);return e?.signal?.throwIfAborted(),new Yf(n,new Ul(s))}async publicKeyFromProtobuf(e,t){let n=Ar.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let s=NL(n.Data);return new Ul(s)}async privateKeyFromProtobuf(e,t){let n=dr.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");let s=await LL(n.Data,t),o=DL(s);return new Yf(s,new Ul(o))}};function b3(){return new w3}async function LL(r,e){let t=r.subarray(0,PL),n=RL(t),s=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),o=await crypto.subtle.exportKey("jwk",s);return e?.signal?.throwIfAborted(),o}var Aw=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4]);function RL(r){return Ke([Aw,Uint8Array.from([r.byteLength]),r],Aw.byteLength+1+r.byteLength)}function DL(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:r.x}}function NL(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:fe.baseEncode(r)}}var v3=8192,Fl=class{type="RSA";code=0;_raw;digest;jwk;constructor(e,t){if(Iw(e)>v3)throw new Ge("Key size is too large");this.jwk=e,this.digest=t}toMultihash(){return this.digest}toCID(){return $.createV1(114,this.toMultihash())}toString(){return this.toCID().toString(cr)}toProtobuf(){return $L(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async verify(e,t,n){let s=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]),o=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,re(t),re(e));return n?.signal?.throwIfAborted(),o}},Xf=class{type="RSA";code=0;publicKey;jwk;constructor(e,t){if(Iw(e)>v3)throw new Ge("Key size is too large");this.jwk=e,this.publicKey=t}toProtobuf(){return KL(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),s=await crypto.subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,re(e));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}},x3=class{type="RSA";code=0;async generatePrivateKey(e){let t=e?.bits??2048;if(t>v3)throw new Ge("Key size is too large");let n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),s=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey),i=await E3(s);return e?.signal?.throwIfAborted(),new Xf(s,new Fl(o,i))}async publicKeyFromProtobuf(e,t){let n=Ar.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");let s=UL(n.Data),o=await E3(s);return t?.signal?.throwIfAborted(),new Fl(s,o)}async privateKeyFromProtobuf(e,t){let n=dr.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");let s=pn(n.Data),o=OL(s),i=FL(o),a=await E3(i);return t?.signal?.throwIfAborted(),new Xf(o,new Fl(i,a))}};function $l(){return new x3}function OL(r){return{alg:"RS256",kty:"RSA",n:fe.baseEncode(r[1]),e:fe.baseEncode(r[2]),ext:!0,key_ops:["sign"],d:fe.baseEncode(r[3]),p:fe.baseEncode(r[4]),q:fe.baseEncode(r[5]),dp:fe.baseEncode(r[6]),dq:fe.baseEncode(r[7]),qi:fe.baseEncode(r[8])}}function BL(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 Ge("JWK was missing components");return mn([ur(Uint8Array.from([0])),ur(fe.baseDecode(r.n)),ur(fe.baseDecode(r.e)),ur(fe.baseDecode(r.d)),ur(fe.baseDecode(r.p)),ur(fe.baseDecode(r.q)),ur(fe.baseDecode(r.dp)),ur(fe.baseDecode(r.dq)),ur(fe.baseDecode(r.qi))]).subarray()}var ML=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Tw(r){if(r.n==null||r.e==null)throw new Ge("JWK public key was missing components");return mn([ML,Rl(mn([ur(fe.baseDecode(r.n)),ur(fe.baseDecode(r.e))]))]).subarray()}function UL(r){let e=pn(r);if(e.length<2||e[0]?.[0]!=="1.2.840.113549.1.1.1")throw new Error("PKIX certificate was invalid");let t=pn(e[1]);return{kty:"RSA",n:fe.baseEncode(t[0]),e:fe.baseEncode(t[1])}}function FL(r){return{key_ops:["verify"],ext:!0,alg:"RS256",kty:"RSA",n:r.n,e:"AQAB"}}function Iw(r){if(r.kty!=="RSA")throw new Ge("Invalid key type");if(r.n==null)throw new Ge("Invalid key modulus");return fe.baseDecode(r.n).length*8}async function E3(r){let e=Ar.encode({Type:0,Data:Tw(r)});return je.digest(e)}function $L(r,e){return Ar.encode({Type:r,Data:Tw(e)})}function KL(r,e){return dr.encode({Type:r,Data:BL(e)})}function S3(r){return r==null?!1:typeof r.type=="string"&&typeof r.code=="number"&&typeof r.verify=="function"}function Cw(r){return r==null?!1:typeof r.type=="string"&&typeof r.code=="number"&&typeof r.sign=="function"&&S3(r.publicKey)}var A3=1,T3=5,I3=100;var Kl=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},ro=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},Hl=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},Vl=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},C3=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}},ql=class extends Error{static name="UnknownCryptoError";name="UnknownCryptoError"},li=class extends Error{static name="NoEvictionError";name="NoEvictionError"};var k3={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},kw={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},_w=new globalThis.TextEncoder;function HL(r,e){let t=k3[e],n=kw[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function VL(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=k3[e],s=kw[e],o=r;for(;o.length>0;){let i=_w.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function _3(r,{size:e=32,utf8Buffer:t}={}){if(!k3[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return VL(r,e,t);r=_w.encode(r)}return HL(r,e)}var zl={hash:r=>Number(_3(r,{size:32})),hashV:(r,e)=>qL(zl.hash(r,e))};function qL(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),A(e,"base16")}var P3=64,yn=class{fp;h;seed;constructor(e,t,n,s=2){if(s>P3)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=pe(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?se(this.fp,e.fp):!1}};function ui(r,e){return Math.floor(Math.random()*(e-r))+r}var di=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof yn))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof yn))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof yn))throw new TypeError("Invalid Fingerprint");let t=ui(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof yn))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var zL=500,Wl=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??zl,this.seed=e.seed??ui(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=A(e));let t=new yn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new di(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new di(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[ui(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new di(this.bucketSize));for(let a=0;a<zL;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new di(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=A(e));let t=new yn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=A(e));let t=new yn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},WL={1:.5,2:.84,4:.95,8:.98};function GL(r=.001){return r>.002?2:r>1e-5?4:8}function Pw(r,e=.001){let t=GL(e),n=WL[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),P3);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Qf=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??zl,this.seed=e.seed??ui(0,Math.pow(2,10)),this.filterSeries=[new Wl({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=A(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Wl({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=A(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=A(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Ut(r,e=.001,t){return new Qf({...Pw(r,e),...t??{}})}function L3(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function me(r){let e=L3(r);if(e==null)throw new v(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Zf=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Lw=45,jL=15,Ca=new Zf;function Jf(r){if(!(r.length>jL))return Ca.new(r).parseWith(()=>Ca.readIPv4Addr())}function eh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Lw))return Ca.new(r).parseWith(()=>Ca.readIPv6Addr())}function ka(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Lw)return;let t=Ca.new(r).parseWith(()=>Ca.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function Rw(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function Dw(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function R3(r){switch(r.length){case fi:return r.join(".");case hi:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Nw(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function Ow(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var fi=4,hi=16,pj=parseInt("0xFFFF",16),YL=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Gl(r,e){e.length===hi&&r.length===fi&&Rw(e,0,11)&&(e=e.slice(12)),e.length===fi&&r.length===hi&&Dw(r,YL,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function Bw(r,e){if(typeof e=="string"&&(e=ka(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function D3(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=fi,s=Jf(e);if(s==null&&(n=hi,s=eh(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=N3(o,8*n);return{network:Gl(s,i),mask:i}}function N3(r,e){if(e!==8*fi&&e!==8*hi)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var pi=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=D3(e));else{let n=ka(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=ka(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=N3(s,8*n.length);this.network=Gl(n,this.mask)}}contains(e){return Bw({network:this.network,mask:this.mask},e)}toString(){let e=Nw(this.mask),t=e!==-1?String(e):Ow(this.mask);return R3(this.network)+"/"+t}};function Mw(r,e){return new pi(r).contains(e)}function th(r){try{let e=me(r);return e.type==="ip6"?Mw("2000::/3",e.host):!1}catch{return!1}}function Uw(r){try{let e=me(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Fw(r){if(typeof r!="string"||!/^[0-9a-fA-FxX.:]+$/.test(r))return!1;let e=r.includes(":")?`[${r}]`:r,t;try{t=new URL(`http://${e}`)}catch{return!1}if(t.href!==`http://${t.hostname}/`)return!1;let n=t.hostname;if(n.startsWith("["))return n==="[::1]";let s=n.split(".");return s.length===4&&s[0]==="127"&&s.every(o=>/^\d{1,3}$/.test(o))}function jl(r){try{let e=me(r);switch(e.type){case"ip4":case"ip6":return Fw(e.host);default:return!1}}catch{return!1}}function Ft(r){return L3(r)!==null}function wn(r){return!!Jf(r)}function rh(r){return!!eh(r)}var Vw=jo(Hw(),1),rR=["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"],nR=rR.map(r=>new Vw.Netmask(r));function K3(r){for(let e of nR)if(e.contains(r))return!0;return!1}function sR(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function oR(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return K3(s)}function iR(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function aR(r){let e=r.split(":"),t=e[e.length-1];return K3(t)}function cR(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Ra(r){if(wn(r))return K3(r);if(sR(r))return oR(r);if(iR(r))return aR(r);if(rh(r))return cR(r)}function ft(r){try{let e=me(r);switch(e.type){case"ip4":case"ip6":return Ra(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function ps(r,e){if(r.byteLength!==e.byteLength)throw new Error("Inputs should have the same length");for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Jr(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=it(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return Ff(t)}function _(r,e="utf8"){let t=Vf[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var $t=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ms=class extends Error{static name="ValidationError";name="ValidationError"},sh=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},oh=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function V3(r){return e=>_(e,r)}function q3(r){return e=>A(e,r)}function Da(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function gi(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function qw(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=A(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=gi(n);return Ke([t,s],t.length+s.length)}function zw(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=xt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=gi(n);return Ke([t,s],t.length+s.length)}function z3(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=_(e,"base32"),s=Da(t);return`${n}:${s}`}var W3=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new $t("Invalid byte value in IP address");e[n]=s}),e},Ww=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=wn(t[n]),i;o&&(i=W3(t[n]),t[n]=_(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,_(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new $t("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},Gw=function(r){if(r.byteLength!==4)throw new $t("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},jw=function(r){if(r.byteLength!==16)throw new $t("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new $t(`Invalid IPv6 address "${t}"`)}};function Yw(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new $t(`Invalid IPv6 address "${r}"`)}}var H3=Object.values(ai).map(r=>r.decoder),lR=(function(){let r=H3[0].or(H3[1]);return H3.slice(2).forEach(e=>r=r.or(e)),r})();function Xw(r){return lR.decode(r)}function Qw(r){return e=>r.encoder.encode(e)}function uR(r){if(parseInt(r).toString()!==r)throw new ms("Value must be an integer")}function dR(r){if(r<0)throw new ms("Value must be a positive integer, or zero")}function fR(r){return e=>{if(e>r)throw new ms(`Value must be smaller than or equal to ${r}`)}}function hR(...r){return e=>{for(let t of r)t(e)}}var Yl=hR(uR,dR,fR(65535));var Nt=-1,G3=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new oh(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},ys=new G3,CR=[{code:4,name:"ip4",size:32,valueToBytes:W3,bytesToValue:Gw,validate:r=>{if(!wn(r))throw new ms(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:gi,bytesToValue:Da,validate:Yl},{code:273,name:"udp",size:16,valueToBytes:gi,bytesToValue:Da,validate:Yl},{code:33,name:"dccp",size:16,valueToBytes:gi,bytesToValue:Da,validate:Yl},{code:41,name:"ip6",size:128,valueToBytes:Ww,bytesToValue:jw,stringToValue:Yw,validate:r=>{if(!rh(r))throw new ms(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Nt},{code:43,name:"ipcidr",size:8,bytesToValue:V3("base10"),valueToBytes:q3("base10")},{code:53,name:"dns",size:Nt},{code:54,name:"dns4",size:Nt},{code:55,name:"dns6",size:Nt},{code:56,name:"dnsaddr",size:Nt},{code:132,name:"sctp",size:16,valueToBytes:gi,bytesToValue:Da,validate:Yl},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Nt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Nt,bytesToValue:V3("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?q3("base58btc")(r):$.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:z3,valueToBytes:qw},{code:445,name:"onion3",size:296,bytesToValue:z3,valueToBytes:zw},{code:446,name:"garlic64",size:Nt},{code:447,name:"garlic32",size:Nt},{code:448,name:"tls"},{code:449,name:"sni",size:Nt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Nt,bytesToValue:Qw(fe),valueToBytes:Xw},{code:480,name:"http"},{code:481,name:"http-path",size:Nt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Nt}];CR.forEach(r=>{ys.addProtocol(r)});function Zw(r){let e=[],t=0;for(;t<r.length;){let n=Br(r,t),s=ys.getProtocol(n),o=Te(n),i=kR(s,r,t+o),a=0;i>0&&s.size===Nt&&(a=Te(i));let c=o+a+i,l={code:n,name:s.name,bytes:re(r.subarray(t,t+c))};if(i>0){let u=t+o+a,d=r.subarray(u,u+i);l.value=s.bytesToValue?.(d)??_(d)}e.push(l),t+=c}return e}function Jw(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=ys.getProtocol(n.code),o=Te(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??A(n.value),a=i.byteLength,s.size===Nt&&(c=Te(a)));let l=new Uint8Array(o+c+a),u=0;Sa(n.code,l,u),u+=o,i!=null&&(s.size===Nt&&(Sa(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ke(t,e)}function eb(r){if(r.charAt(0)!=="/")throw new $t('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ys.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new $t(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new $t(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new $t("Incomplete multiaddr");return e}function tb(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ys.getProtocol(e.code);if(t==null)throw new $t(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function kR(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Br(e,t)}var _R=Symbol.for("nodejs.util.inspect.custom"),r4=Symbol.for("@multiformats/multiaddr");function PR(r){if(r==null&&(r="/"),en(r))return r.getComponents();if(r instanceof Uint8Array)return Zw(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),eb(r);if(Array.isArray(r))return r;throw new $t("Must be a string, Uint8Array, Component[], or another Multiaddr")}var uh=class r{[r4]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=PR(e),t.validate!==!1&&LR(this)}get bytes(){return this.#r==null&&(this.#r=Jw(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=tb(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new sh(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return se(this.bytes,e.bytes)}[_R](){return`Multiaddr(${this.toString()})`}};function LR(r){r.getComponents().forEach(e=>{let t=ys.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function en(r){return!!r?.[r4]}function W(r){return new uh(r)}var Ue=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),de=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),rb=r=>({match:e=>r.match(e)===!1?e:!1}),Ie=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Zt=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),_e=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function Fe(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var RR=de(421),nb=Fe(RR),fh=de(54),hh=de(55),ph=de(56),s4=de(53),nX=Fe(fh,Ie(de(421))),sX=Fe(hh,Ie(de(421))),oX=Fe(ph,Ie(de(421))),mh=Fe(Zt(s4,ph,fh,hh),Ie(de(421))),sb=_e(de(4),Ie(de(43))),ob=_e(Ie(de(42)),de(41),Ie(de(43))),o4=Zt(sb,ob),Ma=Zt(o4,s4,fh,hh,ph),ib=Fe(Zt(o4,_e(Zt(s4,ph,fh,hh),Ie(de(421))))),i4=Fe(sb),a4=Fe(ob),ab=Fe(o4),c4=_e(Ma,de(6)),tu=_e(Ma,de(273)),wi=Fe(_e(c4,Ie(de(421)))),iX=Fe(tu),l4=_e(tu,Ue(460),Ie(de(421))),gh=_e(tu,Ue(461),Ie(de(421))),DR=Zt(l4,gh),aX=Fe(l4),cb=Fe(gh),n4=Zt(Ma,c4,tu,l4,gh),lb=Zt(_e(n4,Ue(477),Ie(de(421)))),ws=Fe(lb),ub=Zt(_e(n4,Ue(478),Ie(de(421))),_e(n4,Ue(448),Ie(de(449)),Ue(477),Ie(de(421)))),bi=Fe(ub),db=_e(tu,Ue(280),Ie(de(466)),Ie(de(466)),Ie(de(421))),ru=Fe(db),fb=_e(gh,Ue(465),Ie(de(466)),Ie(de(466)),Ie(de(421))),u4=Fe(fb),dh=Zt(lb,ub,_e(c4,Ie(de(421))),_e(DR,Ie(de(421))),_e(Ma,Ie(de(421))),db,fb,de(421)),Ua=Fe(dh),NR=_e(Ie(dh),Ue(290),rb(Ue(281)),Ie(de(421))),Ot=Fe(NR),OR=Zt(_e(dh,Ue(290),Ue(281),Ie(de(421))),_e(dh,Ue(281),Ie(de(421))),_e(Ue(281),Ie(de(421)))),nu=Fe(OR),BR=_e(Ma,Zt(_e(de(6,"80")),_e(de(6),Ue(480)),Ue(480)),Ie(de(481)),Ie(de(421))),hb=Fe(BR),MR=_e(Ma,Zt(_e(de(6,"443")),_e(de(6,"443"),Ue(480)),_e(de(6),Ue(443)),_e(de(6),Ue(448),Ue(480)),_e(Ue(448),Ue(480)),Ue(448),Ue(443)),Ie(de(481)),Ie(de(421))),pb=Fe(MR),UR=Zt(_e(de(777),Ie(de(421)))),cX=Fe(UR),FR=Zt(_e(de(400),Ie(de(421)))),lX=Fe(FR);function mb(r,e){let t=wi.exactMatch(r),n=wi.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let s=bi.exactMatch(r),o=bi.exactMatch(e);if(s&&!o)return-1;if(!s&&o)return 1;let i=ws.exactMatch(r),a=ws.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=nu.exactMatch(r),l=nu.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=ru.exactMatch(r),d=ru.exactMatch(e);if(u&&!d)return-1;if(!u&&d)return 1;let f=u4.exactMatch(r),h=u4.exactMatch(e);return f&&!h?-1:!f&&h?1:0}function gb(r,e){let t=jl(r),n=jl(e);return t&&!n?1:!t&&n?-1:0}function yb(r,e){let t=ft(r),n=ft(e);return t&&!n?1:!t&&n?-1:0}function wb(r,e){let t=Ot.exactMatch(r),n=Ot.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function Ye(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var yh=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Fa=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new yh(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 yh(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 d4=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Kt(r={}){return $R(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 $R(r,e){e=e??{};let t=e.onEnd,n=new Fa,s,o,i,a=Ye(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,m)=>{o=b=>{o=null,n.push(b);try{y(r(n))}catch(E){m(E)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ye()})}},l=y=>o!=null?o(y):(n.push(y),s),u=y=>(n=new Fa,o!=null?o({error:y}):(n.push({error:y}),s)),d=y=>{if(i)return s;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})},f=y=>i?s:(i=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new Fa,f(),{done:!0}),p=y=>(f(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async y=>{let m=y?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let b,E;m!=null&&(b=new Promise((S,T)=>{E=()=>{T(new d4)},m.addEventListener("abort",E)}));try{await Promise.race([a.promise,b])}finally{E!=null&&m!=null&&m?.removeEventListener("abort",E)}}},t==null)return s;let g=s;return s={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(y){return g.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(y){return g.end(y),t!=null&&(t(y),t=void 0),s},get readableLength(){return g.readableLength},onEmpty:y=>g.onEmpty(y)},s}var f4=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},bb=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function fr(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((d,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){f(bb(i));return}if(i&&(c=()=>{f(bb(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new f4;a=o.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?d():s instanceof Error?f(s):(h.message=s??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var KR=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function HR(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=KR(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),o(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=fr(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function tn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=HR(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function bs(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var wh=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},bh=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Ei=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Eh=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},xh=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function VR(r){return r.reason}function be(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??VR;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;return Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})]).finally(()=>{s!=null&&e.removeEventListener("abort",s)})}var vh=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ye(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function qR(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Eb=new WeakMap,Sh=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=qR(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 jt),this.cleanup())}async join(e){let t=new vh(e);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 be(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof t=="object"&&t!==null){let n=Eb.get(t);if(n==null&&(n=new WeakSet,Eb.set(t,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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.deferred.reject(e.signal?.reason??new jt),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var ht=class extends ge{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=bs(this.emitEmpty.bind(this),1),this.emitIdle=bs(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new bh;let n=new Sh(e,t);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new jt)}),this.clear()}async onEmpty(e){this.size!==0&&await tn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await tn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await tn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Kt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new jt("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var zR=Math.pow(2,20)*4,$n=class extends ge{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??zR,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new V,this.writeBuffer=new V,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(s){this.log.error("processSendQueue threw - %e",s)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new xh)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),be(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Kt(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new On(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new Nf(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new On("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new On("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new On(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new On(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new Of(new ma))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new Zs))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new V(o);this.writeBuffer.consume(o.byteLength);let a;try{a=this.sendData(o)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Df(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Qo(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Qo(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var oo=class extends $n{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await tn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await tn(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Ah(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var io=class extends ge{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await be(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new fn;let t=this.onCreateStream({...this.streamOptions,...e});return Ah(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Eh(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let s=this.streams.findIndex(o=>o===e);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var ao=class extends $n{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await tn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await tn(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.maybeDispatchEnd(),this.log("closed readable end gracefully"))}};var $a=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var WR=1.2,GR=2,jR=5e3,YR=6e4,XR=5e3,xn=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??XR;this.success=new $a(t),this.failure=new $a(t),this.next=new $a(t),this.failureMultiplier=e.failureMultiplier??GR,this.timeoutMultiplier=e.timeoutMultiplier??WR,this.minTimeout=e.minTimeout??jR,this.maxTimeout=e.maxTimeout??YR,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),s=he([e.signal,n]);return s.start=Date.now(),s.timeout=t,s}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var h4=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ye(),this.haveNext=Ye()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ye(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ye(),await be(this.readNext.promise,t?.signal,t)}};function xb(){return new h4}function vb(r){return r[Symbol.asyncIterator]!=null}async function QR(r,e,t){try{await Promise.all(r.map(async n=>{for(;;){let{value:s,done:o}=await n.next();if(o===!0)break;await e.push(s,{signal:t}),t.throwIfAborted()}})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*ZR(r){let e=new AbortController,t=xb(),n=r.map(s=>vb(s)?s[Symbol.asyncIterator]():s[Symbol.iterator]());QR(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let s of n)try{Promise.resolve(s.return?.()).catch(()=>{})}catch{}}}function*JR(r){for(let e of r)yield*e}function eD(...r){let e=[];for(let t of r)vb(t)||e.push(t);return e.length===r.length?JR(e):ZR(r)}var hr=eD;function Ka(r,...e){if(r==null)throw new Error("Empty pipeline");if(p4(r)){let n=r;r=()=>n.source}else if(Ab(r)||Sb(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&p4(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++)p4(t[n])&&(t[n]=rD(t[n]));return tD(...t)}var tD=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Sb=r=>r?.[Symbol.asyncIterator]!=null,Ab=r=>r?.[Symbol.iterator]!=null,p4=r=>r==null?!1:r.sink!=null&&r.source!=null,rD=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Kt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Sb(o))s=async function*(){yield*o,n.end()};else if(Ab(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return hr(n,s())}return r.source};var nD=4194304,Th=class extends Error{static name="UnwrappedError";name="UnwrappedError"},su=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},g4=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},y4=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function sD(r){return typeof r?.closeRead=="function"}function oD(r){return typeof r?.close=="function"}function m4(r){return sD(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:oD(r)?r.status!=="open":!1}function iD(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Ih(r,e){let t=e?.maxBufferSize??nD,n=new V,s,o=!1,i;if(!iD(r))throw new v("Argument should be a Stream or a Multiaddr");let a=d=>{if(i==null){if(n.append(d.data),n.byteLength>t){let f=n.byteLength;n.consume(f);let h=new Qo(`Read buffer overflow - ${f} > ${t}`);i=h,s?.reject(h),queueMicrotask(()=>{r.abort(h)});return}s?.resolve()}};r.addEventListener("message",a);let c=d=>{d.error!=null?s?.reject(d.error):s?.resolve()};r.addEventListener("close",c);let l=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",l);let u={readBuffer:n,async read(d){if(o===!0)throw new Th("Stream was unwrapped");if(i!=null)throw i;if(m4(r)){if(n.byteLength===0&&d?.bytes==null)return null;if(d?.bytes!=null&&n.byteLength<d.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new Ei(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}let f=d?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await be(s.promise,d?.signal),m4(r)){if(n.byteLength===0&&d?.bytes==null)return null;break}s=Promise.withResolvers()}let h=d?.bytes??n.byteLength;if(n.byteLength<h){if(m4(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Ei(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return u.read(d)}let p=n.sublist(0,h);return n.consume(h),p},async write(d,f){if(o===!0)throw new Th("Stream was unwrapped");r.send(d)||await tn(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",a),r.removeEventListener("close",c),r.removeEventListener("remoteCloseWrite",l),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function vn(r,e={}){let t=Ih(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Te(e.maxDataLength));let n=e?.lengthDecoder??Br,s=e?.lengthEncoder??Xt;return{async read(i){let a=-1,c=new V;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new su("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new y4(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new g4(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Ei(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Ei(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new V(s(i.byteLength),i),a)},async writeV(i,a){let c=new V(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Ze(r,e){let t=vn(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i,o)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var aD=1024*1024*4,cD=1024*1024*4,Ha=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new V,this.maxBufferSize=e.maxBufferSize??aD,this.maxDataLength=e.maxDataLength??cD,this.lengthDecoder=e.lengthDecoder??Br,this.encodingLength=e.encodingLength??Te}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new v(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(t<0||t>this.maxDataLength)throw new su("Invalid message length");let n=this.encodingLength(t),s=n+t;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var lD=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function w4(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=uD(r);return t||"Object"}function uD(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(lD.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}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};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 L=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 ou=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",dD=new TextEncoder;function Ch(r){return ou&&globalThis.Buffer.isBuffer(r)}function xi(r){return r instanceof Uint8Array?Ch(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var fD=24,hD=200,Va=ou?r=>r.length>=fD?globalThis.Buffer.from(r):Tb(r):r=>r.length>=hD?dD.encode(r):Tb(r),Kn=r=>Uint8Array.from(r),Cb=ou?(r,e,t)=>Ch(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),kb=ou?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),xi(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let s of r)n+s.length>t.length&&(s=s.subarray(0,t.length-n)),t.set(s,n),n+=s.length;return t},b4=ou?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function qa(r,e){if(Ch(r)&&Ch(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 Tb(r){let e=[],t=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(s>=55296&&s<=57343&&(s=65533),e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e}var Ib=4096;function _b(r){let e=r.length;if(e<=Ib)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Ib));return t}var pD=256,iu=class{constructor(e=pD){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)}pushByte(e){let t=this.chunks[this.chunks.length-1];this.cursor>this.maxCursor&&(t=b4(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t));let n=t.length-(this.maxCursor-this.cursor)-1;t[n]=e,this.cursor++}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let s=t.length-(this.maxCursor-this.cursor)-1;t.set(e,s)}else{if(t){let s=t.length-(this.maxCursor-this.cursor)-1;s<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,s),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=b4(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=Cb(n,0,this.cursor)}else t=kb(this.chunks,this.cursor);return e&&this.reset(),t}},kh=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}pushByte(e){if(this.cursor>=this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest[this.cursor++]=e}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var q="CBOR decode error:",Hn="CBOR encode error:",au=[];au[23]=1;au[24]=2;au[25]=3;au[26]=5;au[27]=9;function Es(r,e,t){if(r.length-e<t)throw new Error(`${q} not enough data for type`)}var Bt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Ur(r,e,t){Es(r,e,1);let n=r[e];if(t.strict===!0&&n<Bt[0])throw new Error(`${q} integer encoded in more bytes than necessary (strict decode)`);return n}function Fr(r,e,t){Es(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Bt[1])throw new Error(`${q} integer encoded in more bytes than necessary (strict decode)`);return n}function $r(r,e,t){Es(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Bt[2])throw new Error(`${q} integer encoded in more bytes than necessary (strict decode)`);return n}function Kr(r,e,t){Es(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],s=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(s);if(t.strict===!0&&o<Bt[3])throw new Error(`${q} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${q} integers outside of the safe integer range are not supported`)}function Pb(r,e,t,n){return new L(w.uint,Ur(r,e+1,n),2)}function Lb(r,e,t,n){return new L(w.uint,Fr(r,e+1,n),3)}function Rb(r,e,t,n){return new L(w.uint,$r(r,e+1,n),5)}function Db(r,e,t,n){return new L(w.uint,Kr(r,e+1,n),9)}function Vn(r,e){return Ct(r,0,e.value)}function Ct(r,e,t){if(t<Bt[0]){let n=Number(t);r.pushByte(e|n)}else if(t<Bt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Bt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Bt[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<Bt[4]){let s=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));s[8]=o&255,o=o>>8,s[7]=o&255,o=o>>8,s[6]=o&255,o=o>>8,s[5]=o&255,s[4]=i&255,i=i>>8,s[3]=i&255,i=i>>8,s[2]=i&255,i=i>>8,s[1]=i&255,r.push(s)}else throw new Error(`${q} encountered BigInt larger than allowable range`)}}Vn.encodedSize=function(e){return Ct.encodedSize(e.value)};Ct.encodedSize=function(e){return e<Bt[0]?1:e<Bt[1]?2:e<Bt[2]?3:e<Bt[3]?5:9};Vn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Nb(r,e,t,n){return new L(w.negint,-1-Ur(r,e+1,n),2)}function Ob(r,e,t,n){return new L(w.negint,-1-Fr(r,e+1,n),3)}function Bb(r,e,t,n){return new L(w.negint,-1-$r(r,e+1,n),5)}var E4=BigInt(-1),Mb=BigInt(1);function Ub(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s!="bigint"){let o=-1-s;if(o>=Number.MIN_SAFE_INTEGER)return new L(w.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${q} integers outside of the safe integer range are not supported`);return new L(w.negint,E4-BigInt(s),9)}function _h(r,e){let t=e.value,n=typeof t=="bigint"?t*E4-Mb:t*-1-1;Ct(r,e.type.majorEncoded,n)}_h.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*E4-Mb:t*-1-1;return n<Bt[0]?1:n<Bt[1]?2:n<Bt[2]?3:n<Bt[3]?5:9};_h.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function cu(r,e,t,n){Es(r,e,t+n);let s=r.slice(e+t,e+t+n);return new L(w.bytes,s,t+n)}function Fb(r,e,t,n){return cu(r,e,1,t)}function $b(r,e,t,n){return cu(r,e,2,Ur(r,e+1,n))}function Kb(r,e,t,n){return cu(r,e,3,Fr(r,e+1,n))}function Hb(r,e,t,n){return cu(r,e,5,$r(r,e+1,n))}function Vb(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s=="bigint")throw new Error(`${q} 64-bit integer bytes lengths not supported`);return cu(r,e,9,s)}function Ph(r){return r.encodedBytes===void 0&&(r.encodedBytes=w.equals(r.type,w.string)?Va(r.value):r.value),r.encodedBytes}function za(r,e){let t=Ph(e);Ct(r,e.type.majorEncoded,t.length),r.push(t)}za.encodedSize=function(e){let t=Ph(e);return Ct.encodedSize(t.length)+t.length};za.compareTokens=function(e,t){return gD(Ph(e),Ph(t))};function gD(r,e){return r.length<e.length?-1:r.length>e.length?1:qa(r,e)}var qb=new TextDecoder,wD=32;function bD(r,e,t){if(t-e<wD){let s="";for(let o=e;o<t;o++){let i=r[o];if(i&128)return qb.decode(r.subarray(e,t));s+=String.fromCharCode(i)}return s}return qb.decode(r.subarray(e,t))}function lu(r,e,t,n,s){let o=t+n;Es(r,e,o);let i=new L(w.string,bD(r,e+t,e+o),o);return s.retainStringBytes===!0&&(i.byteValue=r.slice(e+t,e+o)),i}function zb(r,e,t,n){return lu(r,e,1,t,n)}function Wb(r,e,t,n){return lu(r,e,2,Ur(r,e+1,n),n)}function Gb(r,e,t,n){return lu(r,e,3,Fr(r,e+1,n),n)}function jb(r,e,t,n){return lu(r,e,5,$r(r,e+1,n),n)}function Yb(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s=="bigint")throw new Error(`${q} 64-bit integer string lengths not supported`);return lu(r,e,9,s,n)}var Xb=za;function Wa(r,e,t,n){return new L(w.array,n,t)}function Qb(r,e,t,n){return Wa(r,e,1,t)}function Zb(r,e,t,n){return Wa(r,e,2,Ur(r,e+1,n))}function Jb(r,e,t,n){return Wa(r,e,3,Fr(r,e+1,n))}function e9(r,e,t,n){return Wa(r,e,5,$r(r,e+1,n))}function t9(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s=="bigint")throw new Error(`${q} 64-bit integer array lengths not supported`);return Wa(r,e,9,s)}function r9(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${q} indefinite length items not allowed`);return Wa(r,e,1,1/0)}function Lh(r,e){Ct(r,w.array.majorEncoded,e.value)}Lh.compareTokens=Vn.compareTokens;Lh.encodedSize=function(e){return Ct.encodedSize(e.value)};function Ga(r,e,t,n){return new L(w.map,n,t)}function n9(r,e,t,n){return Ga(r,e,1,t)}function s9(r,e,t,n){return Ga(r,e,2,Ur(r,e+1,n))}function o9(r,e,t,n){return Ga(r,e,3,Fr(r,e+1,n))}function i9(r,e,t,n){return Ga(r,e,5,$r(r,e+1,n))}function a9(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s=="bigint")throw new Error(`${q} 64-bit integer map lengths not supported`);return Ga(r,e,9,s)}function c9(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${q} indefinite length items not allowed`);return Ga(r,e,1,1/0)}function Rh(r,e){Ct(r,w.map.majorEncoded,e.value)}Rh.compareTokens=Vn.compareTokens;Rh.encodedSize=function(e){return Ct.encodedSize(e.value)};function l9(r,e,t,n){return new L(w.tag,t,1)}function u9(r,e,t,n){return new L(w.tag,Ur(r,e+1,n),2)}function d9(r,e,t,n){return new L(w.tag,Fr(r,e+1,n),3)}function f9(r,e,t,n){return new L(w.tag,$r(r,e+1,n),5)}function h9(r,e,t,n){return new L(w.tag,Kr(r,e+1,n),9)}function Dh(r,e){Ct(r,w.tag.majorEncoded,e.value)}Dh.compareTokens=Vn.compareTokens;Dh.encodedSize=function(e){return Ct.encodedSize(e.value)};var Nh=20,Oh=21,Bh=22,Mh=23;function m9(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${q} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new L(w.null,null,1):new L(w.undefined,void 0,1)}function g9(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${q} indefinite length items not allowed`);return new L(w.break,void 0,1)}function x4(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${q} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${q} Infinity values are not supported`)}return new L(w.float,r,e)}function y9(r,e,t,n){return x4(Uh(r,e+1),3,n)}function w9(r,e,t,n){return x4(Fh(r,e+1),5,n)}function b9(r,e,t,n){return x4(v9(r,e+1),9,n)}function uu(r,e,t){let n=e.value;if(n===!1)r.pushByte(w.float.majorEncoded|Nh);else if(n===!0)r.pushByte(w.float.majorEncoded|Oh);else if(n===null)r.pushByte(w.float.majorEncoded|Bh);else if(n===void 0)r.pushByte(w.float.majorEncoded|Mh);else{let s,o=!1;(!t||t.float64!==!0)&&(v4(n),s=Uh(kt,1),n===s||Number.isNaN(n)?(kt[0]=249,r.push(kt.slice(0,3)),o=!0):(S4(n),s=Fh(kt,1),n===s&&(kt[0]=250,r.push(kt.slice(0,5)),o=!0))),o||(x9(n),s=v9(kt,1),kt[0]=251,r.push(kt.slice(0,9)))}}uu.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){v4(n);let s=Uh(kt,1);if(n===s||Number.isNaN(n))return 3;if(S4(n),s=Fh(kt,1),n===s)return 5}return 9};var E9=new ArrayBuffer(9),rn=new DataView(E9,1),kt=new Uint8Array(E9,0);function v4(r){if(r===1/0)rn.setUint16(0,31744,!1);else if(r===-1/0)rn.setUint16(0,64512,!1);else if(Number.isNaN(r))rn.setUint16(0,32256,!1);else{rn.setFloat32(0,r);let e=rn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)rn.setUint16(0,31744,!1);else if(t===0)rn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let s=t-127;s<-24?rn.setUint16(0,0):s<-14?rn.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):rn.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function Uh(r,e){if(r.length-e<2)throw new Error(`${q} 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,s=t&1023,o;return n===0?o=s*2**-24:n!==31?o=(s+1024)*2**(n-25):o=s===0?1/0:NaN,t&32768?-o:o}function S4(r){rn.setFloat32(0,r,!1)}function Fh(r,e){if(r.length-e<4)throw new Error(`${q} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function x9(r){rn.setFloat64(0,r,!1)}function v9(r,e){if(r.length-e<8)throw new Error(`${q} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}function AD(r,e){let t=r.value;if(t===!1)return Uint8Array.of(w.float.majorEncoded|Nh);if(t===!0)return Uint8Array.of(w.float.majorEncoded|Oh);if(t===null)return Uint8Array.of(w.float.majorEncoded|Bh);if(t===void 0)return Uint8Array.of(w.float.majorEncoded|Mh);if(!e){if(v4(t),t===Uh(kt,1)||Number.isNaN(t))return kt[0]=249,kt.slice(0,3);if(S4(t),t===Fh(kt,1))return kt[0]=250,kt.slice(0,5)}return x9(t),kt[0]=251,kt.slice(0,9)}function p9(r,e){let t=r,n=e?.float64===!0,s=n?t._keyBytesFloat64:t._keyBytes;if(s!==void 0)return s;let o=AD(r,n);return n?t._keyBytesFloat64=o:t._keyBytes=o,o}uu.compareTokens=function(e,t,n){let s=p9(e,n),o=p9(t,n);return s.length!==o.length?s.length<o.length?-1:1:qa(s,o)};function De(r,e,t){throw new Error(`${q} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function $h(r){return()=>{throw new Error(`${q} ${r}`)}}var H=[];for(let r=0;r<=23;r++)H[r]=De;H[24]=Pb;H[25]=Lb;H[26]=Rb;H[27]=Db;H[28]=De;H[29]=De;H[30]=De;H[31]=De;for(let r=32;r<=55;r++)H[r]=De;H[56]=Nb;H[57]=Ob;H[58]=Bb;H[59]=Ub;H[60]=De;H[61]=De;H[62]=De;H[63]=De;for(let r=64;r<=87;r++)H[r]=Fb;H[88]=$b;H[89]=Kb;H[90]=Hb;H[91]=Vb;H[92]=De;H[93]=De;H[94]=De;H[95]=$h("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)H[r]=zb;H[120]=Wb;H[121]=Gb;H[122]=jb;H[123]=Yb;H[124]=De;H[125]=De;H[126]=De;H[127]=$h("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)H[r]=Qb;H[152]=Zb;H[153]=Jb;H[154]=e9;H[155]=t9;H[156]=De;H[157]=De;H[158]=De;H[159]=r9;for(let r=160;r<=183;r++)H[r]=n9;H[184]=s9;H[185]=o9;H[186]=i9;H[187]=a9;H[188]=De;H[189]=De;H[190]=De;H[191]=c9;for(let r=192;r<=215;r++)H[r]=l9;H[216]=u9;H[217]=d9;H[218]=f9;H[219]=h9;H[220]=De;H[221]=De;H[222]=De;H[223]=De;for(let r=224;r<=243;r++)H[r]=$h("simple values are not supported");H[244]=De;H[245]=De;H[246]=De;H[247]=m9;H[248]=$h("simple values are not supported");H[249]=y9;H[250]=w9;H[251]=b9;H[252]=De;H[253]=De;H[254]=De;H[255]=g9;var Sn=[];for(let r=0;r<24;r++)Sn[r]=new L(w.uint,r,1);for(let r=-1;r>=-24;r--)Sn[31-r]=new L(w.negint,r,1);Sn[64]=new L(w.bytes,new Uint8Array(0),1);Sn[96]=new L(w.string,"",1);Sn[128]=new L(w.array,0,1);Sn[160]=new L(w.map,0,1);Sn[244]=new L(w.false,!1,1);Sn[245]=new L(w.true,!0,1);Sn[246]=new L(w.null,null,1);function A4(r){switch(r.type){case w.false:return Kn([244]);case w.true:return Kn([245]);case w.null:return Kn([246]);case w.bytes:return r.value.length?void 0:Kn([64]);case w.string:return r.value===""?Kn([96]):void 0;case w.array:return r.value===0?Kn([128]):void 0;case w.map:return r.value===0?Kn([160]):void 0;case w.uint:return r.value<24?Kn([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return Kn([31-Number(r.value)])}}var ID={float64:!1,mapSorter:I4,quickEncodeToken:A4},C9=Object.freeze({mapSorter:_D,quickEncodeToken:A4});function CD(){let r=[];return r[w.uint.major]=Vn,r[w.negint.major]=_h,r[w.bytes.major]=za,r[w.string.major]=Xb,r[w.array.major]=Lh,r[w.map.major]=Rh,r[w.tag.major]=Dh,r[w.float.major]=uu,r}var Ai=CD(),Kh=new iu,Ya=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(`${Hn} object contains circular references`);return new r(t,e)}},co={null:new L(w.null,null),undefined:new L(w.undefined,void 0),true:new L(w.true,!0),false:new L(w.false,!1),emptyArray:new L(w.array,0),emptyMap:new L(w.map,0)},qn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new L(w.float,r):r>=0?new L(w.uint,r):new L(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new L(w.uint,r):new L(w.negint,r)},Uint8Array(r,e,t,n){return new L(w.bytes,r)},string(r,e,t,n){return new L(w.string,r)},boolean(r,e,t,n){return r?co.true:co.false},null(r,e,t,n){return co.null},undefined(r,e,t,n){return co.undefined},ArrayBuffer(r,e,t,n){return new L(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new L(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[co.emptyArray,new L(w.break)]:co.emptyArray;n=Ya.createCheck(n,r);let s=[],o=0;for(let i of r)s[o++]=Si(i,t,n);return t.addBreakTokens?[new L(w.array,r.length),s,new L(w.break)]:[new L(w.array,r.length),s]},Object(r,e,t,n){let s=e!=="Object",o=s?r.keys():Object.keys(r),i=s?r.size:o.length,a;if(i){a=new Array(i),n=Ya.createCheck(n,r);let c=!s&&t.ignoreUndefinedProperties,l=0;for(let u of o){let d=s?r.get(u):r[u];c&&d===void 0||(a[l++]=[Si(u,t,n),Si(d,t,n)])}l<i&&(a.length=l)}return a?.length?(kD(a,t),t.addBreakTokens?[new L(w.map,a.length),a,new L(w.break)]:[new L(w.map,a.length),a]):t.addBreakTokens===!0?[co.emptyMap,new L(w.break)]:co.emptyMap},Tagged(r,e,t,n){return[new L(w.tag,r.tag),Si(r.value,t,n)]}};qn.Map=qn.Object;qn.Buffer=qn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))qn[`${r}Array`]=qn.DataView;function Si(r,e={},t){let n=w4(r),s=e&&e.typeEncoders&&e.typeEncoders[n]||qn[n];if(typeof s=="function"){let i=s(r,n,e,t);if(i!=null)return i}let o=qn[n];if(!o)throw new Error(`${Hn} unsupported type: ${n}`);return o(r,n,e,t)}function kD(r,e){let t=e.mapSorter;t&&r.sort((n,s)=>t(n,s,e))}function I4(r,e,t){let n=Array.isArray(r[0])?r[0][0]:r[0],s=Array.isArray(e[0])?e[0][0]:e[0];if(n.type.major!==s.type.major)return n.type.compare(s.type);let o=n.type.major,i=Ai[o].compareTokens(n,s,t);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function _D(r,e){if(r[0]instanceof L&&e[0]instanceof L){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=S9(t.value)),n._keyBytes||(n._keyBytes=S9(n.value)),qa(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function S9(r){return Hh(r,Ai,C9)}function ja(r,e,t,n){if(Array.isArray(e))for(let s of e)ja(r,s,t,n);else t[e.type.major](r,e,n)}var A9=w.uint.majorEncoded,T9=w.negint.majorEncoded,PD=w.bytes.majorEncoded,LD=w.string.majorEncoded,I9=w.array.majorEncoded,T4=w.map.majorEncoded,RD=w.float.majorEncoded|Nh,DD=w.float.majorEncoded|Oh,ND=w.float.majorEncoded|Bh,OD=w.float.majorEncoded|Mh,BD=BigInt(-1),MD=BigInt(1);function lo(r,e,t){t<24?r.pushByte(e|Number(t)):Ct(r,e,t)}function UD(r){return r.addBreakTokens!==!0}function FD(r,e,t,n,s){let o=t==="Map",i=o?e.keys():Object.keys(e),a=o?e.size:i.length;if(!a){r.pushByte(T4);return}s=Ya.createCheck(s,e);let c=!o&&n.ignoreUndefinedProperties,l=new Array(a),u=0;for(let d of i){let f=o?e.get(d):e[d];c&&f===void 0||(l[u++]=[Si(d,n,s),f])}if(u===0){r.pushByte(T4);return}u<a&&(l.length=u),l.sort((d,f)=>I4(d,f,n)),lo(r,T4,u);for(let[d,f]of l)ja(r,d,Ai,n),C4(r,f,n,s)}function C4(r,e,t,n){let s=w4(e),o=t.typeEncoders&&t.typeEncoders[s];if(o){let i=o(e,s,t,n);if(i!=null){ja(r,i,Ai,t);return}}switch(s){case"null":r.pushByte(ND);return;case"undefined":r.pushByte(OD);return;case"boolean":r.pushByte(e?DD:RD);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?uu(r,new L(w.float,e),t):e>=0?lo(r,A9,e):lo(r,T9,e*-1-1);return;case"bigint":e>=BigInt(0)?lo(r,A9,e):lo(r,T9,e*BD-MD);return;case"string":{let i=Va(e);lo(r,LD,i.length),r.push(i);return}case"Uint8Array":lo(r,PD,e.length),r.push(e);return;case"Array":if(!e.length){r.pushByte(I9);return}n=Ya.createCheck(n,e),lo(r,I9,e.length);for(let i of e)C4(r,i,t,n);return;case"Object":case"Map":if(t.mapSorter===I4)FD(r,e,s,t,n);else{let i=qn.Object(e,s,t,n);ja(r,i,Ai,t)}return;default:{let i=qn[s];if(!i)throw new Error(`${Hn} unsupported type: ${s}`);let a=i(e,s,t,n);ja(r,a,Ai,t)}}}function Hh(r,e,t,n){let s=n instanceof Uint8Array,o=s?new kh(n):Kh,i=Si(r,t);if(!Array.isArray(i)&&t.quickEncodeToken){let a=t.quickEncodeToken(i);if(a)return s?(o.push(a),o.toBytes()):a;let c=e[i.type.major];if(c.encodedSize){let l=c.encodedSize(i,t);if(s||(o=new iu(l)),c(o,i,t),o.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${i} was wrong`);return s?o.toBytes():xi(o.chunks[0])}}return o.reset(),ja(o,i,e,t),o.toBytes(!0)}function Ti(r,e){return e=Object.assign({},ID,e),UD(e)?(Kh.reset(),C4(Kh,r,e,void 0),Kh.toBytes(!0)):Hh(r,Ai,e)}var $D={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Vh=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=Sn[e];if(t===void 0){let n=H[e];if(!n)throw new Error(`${q} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let s=e&31;t=n(this.data,this._pos,s,this.options)}return this._pos+=t.encodedLength,t}},uo=Symbol.for("DONE"),Xa=Symbol.for("BREAK");function KD(r,e,t){let n=[];for(let s=0;s<r.value;s++){let o=fo(e,t);if(o===Xa){if(r.value===1/0)break;throw new Error(`${q} got unexpected break to lengthed array`)}if(o===uo)throw new Error(`${q} found array but not enough entries (got ${s}, expected ${r.value})`);n[s]=o}return n}function HD(r,e,t){let n=t.useMaps===!0,s=t.rejectDuplicateMapKeys===!0,o=n?void 0:{},i=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=fo(e,t);if(c===Xa){if(r.value===1/0)break;throw new Error(`${q} got unexpected break to lengthed map`)}if(c===uo)throw new Error(`${q} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${q} non-string keys not supported (got ${typeof c})`);if(s&&(n&&i.has(c)||!n&&Object.hasOwn(o,c)))throw new Error(`${q} found repeat map key "${c}"`);let l=fo(e,t);if(l===uo)throw new Error(`${q} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?i.set(c,l):c==="__proto__"?Object.defineProperty(o,c,{value:l,configurable:!0,enumerable:!0,writable:!0}):o[c]=l}return n?i:o}function*VD(r,e,t){for(let n=0;n<r.value;n++){let s=fo(e,t);if(s===Xa){if(r.value===1/0)break;throw new Error(`${q} got unexpected break to lengthed map`)}if(s===uo)throw new Error(`${q} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let o=fo(e,t);if(o===uo)throw new Error(`${q} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[s,o]}}function qD(r,e){let t=function(){if(t._called)throw new Error(`${q} tag decode() may only be called once`);t._called=!0;let n=fo(r,e);if(n===uo)throw new Error(`${q} tag content missing`);if(n===Xa)throw new Error(`${q} got unexpected break in tag content`);return n};return t.entries=function(){if(t._called)throw new Error(`${q} tag decode() may only be called once`);t._called=!0;let n=r.next();if(!w.equals(n.type,w.map))throw new Error(`${q} entries() requires map content, got ${n.type.name}`);let s=[];for(let o of VD(n,r,e))s.push(o);return s},t._called=!1,t}function fo(r,e){if(r.done())return uo;let t=r.next();if(w.equals(t.type,w.break))return Xa;if(t.type.terminal)return t.value;if(w.equals(t.type,w.array))return KD(t,r,e);if(w.equals(t.type,w.map))return HD(t,r,e);if(w.equals(t.type,w.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=qD(r,e),s=e.tags[t.value](n);if(!n._called)throw new Error(`${q} tag decoder must call decode() or entries()`);return s}throw new Error(`${q} tag not supported (${t.value})`)}throw new Error("unsupported")}function k4(r,e){if(!(r instanceof Uint8Array))throw new Error(`${q} data to decode must be a Uint8Array`);e=Object.assign({},$D,e);let t=xi(r),n=e.tokenizer||new Vh(t,e),s=fo(n,e);if(s===uo)throw new Error(`${q} did not find any content to decode`);if(s===Xa)throw new Error(`${q} got unexpected break`);return[s,r.subarray(n.pos())]}function An(r,e){let[t,n]=k4(r,e);if(n.length>0)throw new Error(`${q} too many terminals, data makes no sense`);return t}var qh=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(qh.prototype,Symbol.toStringTag,{value:"Tagged"});var zh=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Qa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Wh=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},du=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Gh(r){return r[Symbol.asyncIterator]!=null}function _9(r,e){if(r.byteLength>e)throw new Qa("Message length too long")}var Yh=r=>{let e=Te(r),t=it(e);return Xt(r,t),Yh.bytes=e,t};Yh.bytes=0;function xs(r,e){e=e??{};let t=e.lengthEncoder??Yh,n=e?.maxDataLength??4194304;function*s(o){_9(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Gh(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}xs.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Yh,n=e?.maxDataLength??4194304;return _9(r,n),new V(t(r.byteLength),r)};var Ii;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ii||(Ii={}));var _4=r=>{let e=Br(r);return _4.bytes=Te(e),e};_4.bytes=0;function Ci(r,e){let t=new V,n=Ii.LENGTH,s=-1,o=e?.lengthDecoder??_4,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ii.LENGTH)try{if(s=o(t),s<0)throw new zh("Invalid message length");if(s>a)throw new Qa("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Ii.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Wh("Message length length too long");break}throw l}if(n===Ii.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Ii.LENGTH}}}return Gh(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new du("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new du("Unexpected end of input")})()}Ci.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Ci(n,{...e??{},onLength:o=>{t=o}})};function Xh(r,e){if(typeof r=="string")return WD(r);if(typeof r=="number")return YD(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function WD(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,s=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return s*315576e5;case"months":case"month":case"mo":return s*26298e5;case"weeks":case"week":case"w":return s*6048e5;case"days":case"day":case"d":return s*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return s*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return s*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return s*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:throw new Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function GD(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function jD(r){let e=Math.abs(r);return e>=315576e5?ki(r,e,315576e5,"year"):e>=26298e5?ki(r,e,26298e5,"month"):e>=6048e5?ki(r,e,6048e5,"week"):e>=864e5?ki(r,e,864e5,"day"):e>=36e5?ki(r,e,36e5,"hour"):e>=6e4?ki(r,e,6e4,"minute"):e>=1e3?ki(r,e,1e3,"second"):`${r} ms`}function YD(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?jD(r):GD(r)}function ki(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}function P4(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=Xh,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let f,h=null,p,g;function y(...m){if(!y.enabled)return;let b=y,E=Number(new Date),S=E-(f||E);b.diff=S,b.prev=f,b.curr=E,f=E,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let T=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(k,O)=>{if(k==="%%")return"%";T++;let N=t.formatters[O];if(typeof N=="function"){let K=m[T];k=N.call(b,K),m.splice(T,1),T--}return k}),t.formatArgs.call(b,m),d?.onLog!=null&&d.onLog(...m),(b.log||t.log).apply(b,m)}return y.namespace=u,y.useColors=t.useColors(),y.color=t.selectColor(u),y.extend=n,y.destroy=t.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,g=t.enabled(u)),g),set:m=>{h=m}}),typeof t.init=="function"&&t.init(y),y}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,f=(typeof u=="string"?u:"").split(/[\s,]+/),h=f.length;for(d=0;d<h;d++)f[d]&&(u=f[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let d,f;for(d=0,f=t.skips.length;d<f;d++)if(t.skips[d].test(u))return!1;for(d=0,f=t.names.length;d<f;d++)if(t.names[d].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Qh=rN(),XD=["#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 QD(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function ZD(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Xh(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}var JD=console.debug??console.log??(()=>{});function eN(r){try{r?Qh?.setItem("debug",r):Qh?.removeItem("debug")}catch{}}function tN(){let r;try{r=Qh?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function rN(){try{return localStorage}catch{}}function nN(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var L9=P4({formatArgs:ZD,save:eN,load:tN,useColors:QD,setupFormatters:nN,colors:XD,storage:Qh,log:JD});var et=L9;et.formatters.b=r=>r==null?"undefined":Se.baseEncode(r);et.formatters.t=r=>r==null?"undefined":xt.baseEncode(r);et.formatters.m=r=>r==null?"undefined":We.baseEncode(r);et.formatters.p=r=>r==null?"undefined":r.toString();et.formatters.c=r=>r==null?"undefined":r.toString();et.formatters.k=r=>r==null?"undefined":r.toString();et.formatters.a=r=>r==null?"undefined":r.toString();function R9(r,e=""){let t=D9(r.message),n=D9(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
|
|
2
|
+
"use strict";var Helia=(()=>{var R_=Object.create;var _f=Object.defineProperty;var D_=Object.getOwnPropertyDescriptor;var N_=Object.getOwnPropertyNames;var O_=Object.getPrototypeOf,B_=Object.prototype.hasOwnProperty;var un=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},we=(r,e)=>{for(var t in e)_f(r,t,{get:e[t],enumerable:!0})},F7=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of N_(e))!B_.call(r,s)&&s!==t&&_f(r,s,{get:()=>e[s],enumerable:!(n=D_(e,s))||n.enumerable});return r};var jo=(r,e,t)=>(t=r!=null?R_(O_(r)):{},F7(e||!r||!r.__esModule?_f(t,"default",{value:r,enumerable:!0}):t,r)),M_=r=>F7(_f({},"__esModule",{value:!0}),r);var B3=un(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.Netmask4Impl=void 0;Pa.ip2long=_a;Pa.long2ip=Un;function Un(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,s=r&255;return[e,t,n,s].join(".")}var XL=48,QL=97,ZL=65;function JL(r){let e=0,t=10,n="9",s=0;r.length>1&&r[s]==="0"&&(r[s+1]==="x"||r[s+1]==="X"?(s+=2,t=16):"0"<=r[s+1]&&r[s+1]<="9"&&(s++,t=8,n="7"));let o=s;for(;s<r.length;){if("0"<=r[s]&&r[s]<=n)e=e*t+(r.charCodeAt(s)-XL)>>>0;else if(t===16)if("a"<=r[s]&&r[s]<="f")e=e*t+(10+r.charCodeAt(s)-QL)>>>0;else if("A"<=r[s]&&r[s]<="F")e=e*t+(10+r.charCodeAt(s)-ZL)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");s++}if(s===o)throw new Error("empty octet");return[e,s]}function _a(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,s]=JL(r);r=r.substring(s),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var O3=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let s=e.split("/",2);e=s[0],n=s[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=_a(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let s=32;s>=0;s--)if(this.maskLong===4294967295<<32-s>>>0){this.bitmask=s;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(_a(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Un(this.netLong),this.mask=Un(this.maskLong),this.hostmask=Un(~this.maskLong),this.first=this.bitmask<=30?Un(this.netLong+1):this.base,this.last=this.bitmask<=30?Un(this.netLong+this.size-2):Un(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Un(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(_a(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(Un(this.netLong+this.size*e),this.mask)}forEach(e){let t=_a(this.first),n=_a(this.last),s=0;for(;t<=n;)e(Un(t),t,s),s++,t++}toString(){return this.base+"/"+this.bitmask}};Pa.Netmask4Impl=O3});var Kw=un(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.Netmask6Impl=void 0;La.ip6bigint=U3;La.bigint2ip6=mi;var eR=B3(),M3=(1n<<128n)-1n;function U3(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),s=(0,eR.ip2long)(n),o=r.substring(0,t+1)+"0:0";return $w(o)&~0xffffffffn|BigInt(s)}return $w(r)}function $w(r){let e=r.indexOf("::"),t;if(e!==-1){let s=r.substring(0,e),o=r.substring(e+2),i=s===""?[]:s.split(":"),a=o===""?[]:o.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...i,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let s=0;s<8;s++){let o=t[s];if(o.length===0||o.length>4)throw new Error('Invalid IPv6: bad group "'+o+'"');let i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+o+'"');n=n<<16n|BigInt(i)}return n}function mi(r){if(r<0n||r>M3)throw new Error("Invalid IPv6 address value");let e=[];for(let i=0;i<8;i++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,s=-1,o=0;for(let i=0;i<8;i++)e[i]===0?s===-1?(s=i,o=1):o++:(o>n&&o>=2&&(t=s,n=o),s=-1,o=0);if(o>n&&o>=2&&(t=s,n=o),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let i=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return e.map(i=>i.toString(16)).join(":")}var F3=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let s=e.indexOf("/");s!==-1?(n=parseInt(e.substring(s+1),10),e=e.substring(0,s)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=M3>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=U3(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=mi(this.netBigint),this.mask=mi(this.maskBigint),this.hostmask=mi(~this.maskBigint&M3),this.first=this.base,this.last=mi(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(U3(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(mi(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),s=this.netBigint+n-1n,o=0;for(;t<=s;)e(mi(t),Number(t),o),o++,t++}toString(){return this.base+"/"+this.bitmask}};La.Netmask6Impl=F3});var Hw=un(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.long2ip=no.ip2long=no.Netmask=void 0;var nh=B3();Object.defineProperty(no,"ip2long",{enumerable:!0,get:function(){return nh.ip2long}});Object.defineProperty(no,"long2ip",{enumerable:!0,get:function(){return nh.long2ip}});var tR=Kw(),$3=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new tR.Netmask6Impl(e,t):this._impl=new nh.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof nh.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};no.Netmask=$3});var dv=un((uae,uv)=>{"use strict";function MB(r){return r>=55296&&r<=56319}function UB(r){return r>=56320&&r<=57343}uv.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var s=t.length,o=0,i,a,c=0;c<s;c+=1){if(i=t.charCodeAt(c),a=t[c],MB(i)&&UB(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),o+=e(a),o===n)return t.slice(0,c+1);if(o>n)return t.slice(0,c-a.length+1)}return t}});var hv=un((dae,fv)=>{"use strict";function FB(r){return r>=55296&&r<=56319}function $B(r){return r>=56320&&r<=57343}fv.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,s=null,o=null,i=0;i<t;i++)s=e.charCodeAt(i),$B(s)?o!=null&&FB(o)?n+=1:n+=3:s<=127?n+=1:s>=128&&s<=2047?n+=2:s>=2048&&s<=65535&&(n+=3),o=s;return n}});var mv=un((fae,pv)=>{"use strict";var KB=dv(),HB=hv();pv.exports=KB.bind(null,HB)});var e6=un((hae,yv)=>{"use strict";var VB=mv(),qB=/[\/\?<>\\:\*\|"]/g,zB=/[\x00-\x1f\x80-\x9f]/g,WB=/^\.+$/,GB=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function jB(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function gv(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(qB,e).replace(zB,e).replace(WB,e).replace(GB,e);return t=jB(t,e),VB(t,255)}yv.exports=function(r,e){var t=e&&e.replacement||"",n=gv(r,t);return t===""?n:gv(n,"")}});var wv=un(Tc=>{"use strict";var XB="[object ArrayBuffer]",Rs=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===XB}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==s[o])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let s=new Uint8Array(n),o=0;for(let i of t){let a=this.toUint8Array(i);s.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}},r6="string",QB=/^[0-9a-f\s]+$/i,ZB=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,JB=/^[a-zA-Z0-9-_]+$/,up=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n.buffer}static toString(e){let t=Rs.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return decodeURIComponent(escape(n))}},cn=class{static toString(e,t=!1){let n=Rs.toArrayBuffer(e),s=new DataView(n),o="";for(let i=0;i<n.byteLength;i+=2){let a=s.getUint16(i,t);o+=String.fromCharCode(a)}return o}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),s=new DataView(n);for(let o=0;o<e.length;o++)s.setUint16(o*2,e.charCodeAt(o),t);return n}},dp=class r{static isHex(e){return typeof e===r6&&QB.test(e)}static isBase64(e){return typeof e===r6&&ZB.test(e)}static isBase64Url(e){return typeof e===r6&&JB.test(e)}static ToString(e,t="utf8"){let n=Rs.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 cn.toString(n,!0);case"utf16":case"utf16be":return cn.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 cn.fromString(e,!0);case"utf16":case"utf16be":return cn.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Rs.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 up.fromString(e);case"utf16":case"utf16be":return cn.fromString(e);case"utf16le":case"usc2":return cn.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 up.toString(e);case"utf16":case"utf16be":return cn.toString(e);case"utf16le":case"usc2":return cn.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return n.buffer}static ToBinary(e){let t=Rs.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return n}static ToHex(e){let t=Rs.toUint8Array(e),n="",s=t.length;for(let o=0;o<s;o++){let i=t[o];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let s=0;s<t.length;s=s+2){let o=t.slice(s,s+2);n[s/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,t=!1){return cn.toString(e,t)}static FromUtf16String(e,t=!1){return cn.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,"")||""}};dp.DEFAULT_UTF8_ENCODING="utf8";function eM(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let s=arguments[n];for(let o in s)t[o]=s[o]}return t}function tM(...r){let e=r.map(s=>s.byteLength).reduce((s,o)=>s+o),t=new Uint8Array(e),n=0;return r.map(s=>new Uint8Array(s)).forEach(s=>{for(let o of s)t[n++]=o}),t.buffer}function rM(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)if(t[s]!==n[s])return!1;return!0}Tc.BufferSourceConverter=Rs;Tc.Convert=dp;Tc.assign=eM;Tc.combine=tM;Tc.isEqual=rM});var qS=un((vde,x6)=>{"use strict";var rU=Object.prototype.hasOwnProperty,yr="~";function gd(){}Object.create&&(gd.prototype=Object.create(null),new gd().__proto__||(yr=!1));function nU(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function VS(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new nU(t,n||r,s),i=yr?yr+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],o]:r._events[i].push(o):(r._events[i]=o,r._eventsCount++),r}function Wm(r,e){--r._eventsCount===0?r._events=new gd:delete r._events[e]}function sr(){this._events=new gd,this._eventsCount=0}sr.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)rU.call(t,n)&&e.push(yr?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};sr.prototype.listeners=function(e){var t=yr?yr+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s<o;s++)i[s]=n[s].fn;return i};sr.prototype.listenerCount=function(e){var t=yr?yr+e:e,n=this._events[t];return n?n.fn?1:n.length:0};sr.prototype.emit=function(e,t,n,s,o,i){var a=yr?yr+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,s),!0;case 5:return c.fn.call(c.context,t,n,s,o),!0;case 6:return c.fn.call(c.context,t,n,s,o,i),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,h;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,s);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[d].fn.apply(c[d].context,u)}}return!0};sr.prototype.on=function(e,t,n){return VS(this,e,t,n,!1)};sr.prototype.once=function(e,t,n){return VS(this,e,t,n,!0)};sr.prototype.removeListener=function(e,t,n,s){var o=yr?yr+e:e;if(!this._events[o])return this;if(!t)return Wm(this,o),this;var i=this._events[o];if(i.fn)i.fn===t&&(!s||i.once)&&(!n||i.context===n)&&Wm(this,o);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||s&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[o]=c.length===1?c[0]:c:Wm(this,o)}return this};sr.prototype.removeAllListeners=function(e){var t;return e?(t=yr?yr+e:e,this._events[t]&&Wm(this,t)):(this._events=new gd,this._eventsCount=0),this};sr.prototype.off=sr.prototype.removeListener;sr.prototype.addListener=sr.prototype.on;sr.prefixed=yr;sr.EventEmitter=sr;typeof x6<"u"&&(x6.exports=sr)});var GS=un((qde,WS)=>{WS.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function s(o,i){t[o]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=n[o])!==void 0)return s(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:s(o,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var zI=un(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.parseCookie=VI;us.parse=VI;us.stringifyCookie=lH;us.stringifySetCookie=c2;us.serialize=c2;us.parseSetCookie=uH;us.stringifySetCookie=c2;us.serialize=c2;var KI=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,HI=/^[\u0021-\u003A\u003C-\u007E]*$/,sH=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,oH=/^[\u0020-\u003A\u003D-\u007E]*$/,iH=/^-?\d+$/,aH=Object.prototype.toString,cH=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function VI(r,e){let t=new cH,n=r.length;if(n<2)return t;let s=e?.decode||qI,o=0;do{let i=L5(r,o,n);if(i===-1)break;let a=P5(r,o,n);if(i>a){o=r.lastIndexOf(";",i-1)+1;continue}let c=Uo(r,o,i);t[c]===void 0&&(t[c]=s(Uo(r,i+1,a))),o=a+1}while(o<n);return t}function lH(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let s of Object.keys(r)){let o=r[s];if(o===void 0)continue;if(!KI.test(s))throw new TypeError(`cookie name is invalid: ${s}`);let i=t(o);if(!HI.test(i))throw new TypeError(`cookie val is invalid: ${o}`);n.push(`${s}=${i}`)}return n.join("; ")}function c2(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},o=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!KI.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let i=n.value?o(n.value):"";if(!HI.test(i))throw new TypeError(`argument val is invalid: ${n.value}`);let a=n.name+"="+i;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);a+="; Max-Age="+n.maxAge}if(n.domain){if(!sH.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!oH.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!dH(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.partitioned&&(a+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return a}function uH(r,e){let t=e?.decode||qI,n=r.length,s=P5(r,0,n),o=L5(r,0,s),i=o===-1?{name:"",value:t(Uo(r,0,s))}:{name:Uo(r,0,o),value:t(Uo(r,o+1,s))},a=s+1;for(;a<n;){let c=P5(r,a,n),l=L5(r,a,c),u=l===-1?Uo(r,a,c):Uo(r,a,l),d=l===-1?void 0:Uo(r,l+1,c);switch(u.toLowerCase()){case"httponly":i.httpOnly=!0;break;case"secure":i.secure=!0;break;case"partitioned":i.partitioned=!0;break;case"domain":i.domain=d;break;case"path":i.path=d;break;case"max-age":d&&iH.test(d)&&(i.maxAge=Number(d));break;case"expires":if(!d)break;let f=new Date(d);Number.isFinite(f.valueOf())&&(i.expires=f);break;case"priority":if(!d)break;let h=d.toLowerCase();(h==="low"||h==="medium"||h==="high")&&(i.priority=h);break;case"samesite":if(!d)break;let p=d.toLowerCase();(p==="lax"||p==="strict"||p==="none")&&(i.sameSite=p);break}a=c+1}return i}function P5(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function L5(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Uo(r,e,t){let n=e,s=t;do{let o=r.charCodeAt(n);if(o!==32&&o!==9)break}while(++n<s);for(;s>n;){let o=r.charCodeAt(s-1);if(o!==32&&o!==9)break;s--}return r.slice(n,s)}function qI(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function dH(r){return aH.call(r)==="[object Date]"}});var bq={};we(bq,{DEFAULT_CID_PEER_FILTER_SIZE:()=>I3,DEFAULT_SESSION_MAX_PROVIDERS:()=>T3,DEFAULT_SESSION_MIN_PROVIDERS:()=>A3,InsufficientProvidersError:()=>Kl,InvalidCodecError:()=>C3,NoEvictionError:()=>li,NoRoutersAvailableError:()=>ro,UnknownCodecError:()=>Vl,UnknownCryptoError:()=>ql,UnknownHashAlgorithmError:()=>Hl,createHelia:()=>wq,createHeliaLight:()=>k_,isPrivateKey:()=>Cw,isPublicKey:()=>S3});var $7=Symbol.for("@libp2p/connection");var Yo=Symbol.for("@libp2p/content-routing");var jt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},fa=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},ha=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},v=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},dn=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},xl=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},vl=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var Xo=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},pa=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},fn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},ma=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var On=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Qo=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},Re=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},ga=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Bn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Pf=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},ya=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Lf=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},xe=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Zo=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Mn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Nr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Qs=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Jo=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},Sl=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Rf=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},wa=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},hn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Df=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},Zs=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},Nf=class extends Zs{constructor(e,t){super(!0,e,t)}},Of=class extends Zs{constructor(e,t){super(!1,e,t)}};var ei=Symbol.for("@libp2p/peer-discovery");var Bf=Symbol.for("@libp2p/peer-id");function vr(r){return!!r?.[Bf]}var ti=Symbol.for("@libp2p/peer-routing");var ri="keep-alive";function Mf(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function yt(...r){let e=[];for(let t of r)Mf(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 Dt(...r){let e=[];for(let t of r)Mf(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Js=Symbol.for("@libp2p/transport");var Al;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Al||(Al={}));function U_(r){return typeof r?.handleEvent=="function"}function F_(r){return r===!0||r===!1}function $_(r){return F_(r)?r:r?.capture??!1}function _g(r){let e={capture:$_(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function K7(r,e){return _g(r).capture===_g(e).capture}var ge=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let s=_g(n);if(s?.signal?.aborted===!0)return;let o=l=>{s.once&&this.removeEventListener(e,t,s),U_(t)?t.handleEvent(l):t(l)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==t?!1:K7(l.options,s)))return;super.addEventListener(e,o,s);let c=()=>{this.removeEventListener(e,t,s)};s.signal?.addEventListener("abort",c),i.push({callback:t,wrapper:o,options:s,onAbort:c})}removeEventListener(e,t,n){let s=this.#e.get(e);if(s==null){super.removeEventListener(e,t??null,n);return}this.#e.set(e,s.filter(o=>o.callback===t&&K7(o.options,n)?(super.removeEventListener(e,o.wrapper,n),o.options?.signal?.removeEventListener("abort",o.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Ae=Symbol.for("@libp2p/service-capabilities"),Or=Symbol.for("@libp2p/service-dependencies");var P=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function he(r){let e=new globalThis.AbortController;function t(){let o=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(o);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let s=e.signal;return s.clear=n,s}var oz=new Uint8Array(0);function V7(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 Sr(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return ni(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return ni(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function q7(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var H7=4096;function z7(r){let e=r.length;if(e<=H7)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=H7));return t}function K_(r){return r?.buffer instanceof ArrayBuffer}function ni(r){return K_(r)?r:r.slice()}var Og={};we(Og,{base32:()=>xt,base32hex:()=>Q_,base32hexpad:()=>J_,base32hexpadupper:()=>eP,base32hexupper:()=>Z_,base32pad:()=>Y_,base32padupper:()=>X_,base32upper:()=>j_,base32z:()=>tP});function H_(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),s=0;s<n.length;s++)n[s]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=o,t){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=o),l!==a&&(n[l]=o)}}var u=r.length,d=r.charAt(0),f=Math.log(u)/Math.log(256),h=Math.log(256)/Math.log(u);function p(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 b=0,E=0,S=0,T=m.length;S!==T&&m[S]===0;)S++,b++;for(var C=(T-S)*h+1>>>0,k=new Uint8Array(C);S!==T;){for(var O=m[S],N=0,K=C-1;(O!==0||N<E)&&K!==-1;K--,N++)O+=256*k[K]>>>0,k[K]=O%u>>>0,O=O/u>>>0;if(O!==0)throw new Error("Non-zero carry");E=N,S++}for(var ee=C-E;ee!==C&&k[ee]===0;)ee++;for(var J=d.repeat(b);ee<C;++ee)J+=r.charAt(k[ee]);return J}function g(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var b=0;if(m[b]!==" "){for(var E=0,S=0;m[b]===d;)E++,b++;for(var T=(m.length-b)*f+1>>>0,C=new Uint8Array(T);m[b];){var k=n[m.charCodeAt(b)];if(k===255)return;for(var O=0,N=T-1;(k!==0||O<S)&&N!==-1;N--,O++)k+=u*C[N]>>>0,C[N]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");S=O,b++}if(m[b]!==" "){for(var K=T-S;K!==T&&C[K]===0;)K++;for(var ee=new Uint8Array(E+(T-K)),J=E;K!==T;)ee[J++]=C[K++];return ee}}}function y(m){var b=g(m);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:p,decodeUnsafe:g,decode:y}}var V_=H_,q_=V_,W7=q_;var Lg=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")}},Rg=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return G7(this,e)}},Dg=class{decoders;constructor(e){this.decoders=e}or(e){return G7(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 G7(r,e){return new Dg({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Ng=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new Lg(e,t,n),this.decoder=new Rg(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ba({name:r,prefix:e,encode:t,decode:n}){return new Ng(r,e,t,n)}function eo({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:s,decode:o}=W7(t,r,n);return ba({prefix:e,name:r,encode:s,decode:i=>Sr(o(i))})}function z_(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let o=new Uint8Array(s*t/8|0),i=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function W_(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function G_(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let s=r[n].toLowerCase(),o=r[n].toUpperCase();s!==r[n]&&(t[s]=n),o!==r[n]&&(t[o]=n)}return t}function dt({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:s=!1}){let o=G_(n,s);return ba({prefix:e,name:r,encode(i){return W_(i,n,t)},decode(i){return z_(i,o,t,r)}})}var xt=dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),j_=dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Y_=dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),X_=dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Q_=dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Z_=dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),J_=dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),eP=dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),tP=dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Bg={};we(Bg,{base36:()=>cr,base36upper:()=>rP});var cr=eo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),rP=eo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Mg={};we(Mg,{base58btc:()=>Se,base58flickr:()=>nP});var Se=eo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nP=eo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qe={};we(Qe,{Digest:()=>si,create:()=>lr,decode:()=>Ce,equals:()=>Fg,hasCode:()=>vP});var sP=X7,j7=128,oP=127,iP=~oP,aP=Math.pow(2,31);function X7(r,e,t){e=e||[],t=t||0;for(var n=t;r>=aP;)e[t++]=r&255|j7,r/=128;for(;r&iP;)e[t++]=r&255|j7,r>>>=7;return e[t]=r|0,X7.bytes=t-n+1,e}var cP=Ug,lP=128,Y7=127;function Ug(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ug.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&Y7)<<s:(i&Y7)*Math.pow(2,s),s+=7}while(i>=lP);return Ug.bytes=o-n,t}var uP=Math.pow(2,7),dP=Math.pow(2,14),fP=Math.pow(2,21),hP=Math.pow(2,28),pP=Math.pow(2,35),mP=Math.pow(2,42),gP=Math.pow(2,49),yP=Math.pow(2,56),wP=Math.pow(2,63),bP=function(r){return r<uP?1:r<dP?2:r<fP?3:r<hP?4:r<pP?5:r<mP?6:r<gP?7:r<yP?8:r<wP?9:10},EP={encode:sP,decode:cP,encodingLength:bP},xP=EP,Tl=xP;function Il(r,e=0){let t=Tl.decode(r,e),n=Tl.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&r[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,n]}function Ea(r,e,t=0){return Tl.encode(r,e,t),e}function xa(r){return Tl.encodingLength(r)}function lr(r,e){let t=e.byteLength,n=xa(r),s=n+xa(t),o=new Uint8Array(s+t);return Ea(r,o,0),Ea(t,o,n),o.set(e,s),new si(r,t,e,o)}function Ce(r){let e=Sr(r),[t,n]=Il(e),[s,o]=Il(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new si(t,s,i,e)}function Fg(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&V7(r.bytes,t.bytes)}}var si=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=ni(n),this.bytes=ni(s)}};function vP(r,e){return r.code===e}function Q7(r,e){let{bytes:t,version:n}=r;return n===0?AP(t,$g(r),e??Se.encoder):TP(t,$g(r),e??xt.encoder)}var Z7=new WeakMap;function $g(r){let e=Z7.get(r);if(e==null){let t=new Map;return Z7.set(r,t),t}return e}var $=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=ni(s),this["/"]=this.bytes}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!==Cl)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==IP)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=lr(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&&Fg(e.multihash,n.multihash)}toString(e){return Q7(this,e)}toJSON(){return{"/":Q7(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??J7(n,s,o.bytes))}else if(t[CP]===!0){let{version:n,multihash:s,code:o}=t,i=Ce(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Cl)throw new Error(`Version 0 CID must use dag-pb (code: ${Cl}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=J7(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Cl,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Sr(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new si(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=Il(e.subarray(t));return t+=f,d},s=n(),o=Cl;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=SP(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $g(o).set(n,e),o}};function SP(r,e){switch(r[0]){case"Q":{let t=e??Se;return[Se.prefix,t.decode(`${Se.prefix}${r}`)]}case Se.prefix:{let t=e??Se;return[Se.prefix,t.decode(r)]}case xt.prefix:{let t=e??xt;return[xt.prefix,t.decode(r)]}case cr.prefix:{let t=e??cr;return[cr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function AP(r,e,t){let{prefix:n}=t;if(n!==Se.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function TP(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var Cl=112,IP=18;function J7(r,e,t){let n=xa(r),s=n+xa(e),o=new Uint8Array(s+t.byteLength);return Ea(r,o,0),Ea(e,o,n),o.set(t,s),o}var CP=Symbol.for("@ipld/js-cid/CID");var kP=20;function kl({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Kg(r,e,t,n,s)}var Kg=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,s,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??kP,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?ew(n,this.code,t?.truncate):n.then(s=>ew(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ew(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return lr(e,r)}var Hg={};we(Hg,{base64:()=>We,base64pad:()=>_l,base64url:()=>fe,base64urlpad:()=>_P});var We=dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_l=dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fe=dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_P=dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Vg={};we(Vg,{identity:()=>ot});var rw=0,PP="identity",nw=Sr;function LP(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return lr(rw,nw(r))}var ot={code:rw,name:PP,encode:nw,digest:LP};function pe(r=0){return new Uint8Array(r)}function it(r=0){return new Uint8Array(r)}function RP(r){return r?.buffer instanceof ArrayBuffer}function Ff(r){if(RP(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ke(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=it(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return Ff(t)}function se(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 ow=Symbol.for("@achingbrain/uint8arraylist");function sw(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function va(r){return!!r?.[ow]}var V=class r{bufs;length;[ow]=!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(va(n)){t+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}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(va(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=sw(this.bufs,e);return t.buf[t.index]}set(e,t){let n=sw(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(va(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return Ke(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Ke(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=n,o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!va(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let d=0;d<o;d++)i[d]=-1;for(let d=0;d<s;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=pe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=pe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!se(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};function DP(r){return r.buffer instanceof ArrayBuffer}function re(r){return DP(r)?r:r.slice()}var NP=parseInt("11111",2),qg=parseInt("10000000",2),OP=parseInt("01111111",2),iw={0:Pl,1:Pl,2:BP,3:FP,4:$P,5:UP,6:MP,16:Pl,22:Pl,48:Pl};function pn(r,e={offset:0}){let t=r[e.offset]&NP;if(e.offset++,iw[t]!=null)return iw[t](r,e);throw new Error("No decoder for tag 0x"+t.toString(16).padStart(2,"0"))}function Ll(r,e){let t=0;if((r[e.offset]&qg)===qg){let n=r[e.offset]&OP,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)s+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(s,16)}else t=r[e.offset],e.offset++;return t}function Pl(r,e){Ll(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=pn(r,e);if(n===null)break;t.push(n)}return t}function BP(r,e){let t=Ll(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function MP(r,e){let t=Ll(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function UP(r,e){return e.offset++,null}function FP(r,e){let t=Ll(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function $P(r,e){let t=Ll(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function KP(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new V;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function $f(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=KP(r.byteLength);return new V(Uint8Array.from([e.byteLength|qg]),e)}function ur(r){let e=new V,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new V(Uint8Array.from([2]),$f(e),e)}function Rl(r){let e=Uint8Array.from([0]),t=new V(e,r);return new V(Uint8Array.from([3]),$f(t),t)}function aw(r){return new V(Uint8Array.from([4]),$f(r),r)}function mn(r,e=48){let t=new V;for(let n of r)t.append(re(n.subarray()));return new V(Uint8Array.from([e]),$f(t),t)}var Ge=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"};var HP=Math.pow(2,7),VP=Math.pow(2,14),qP=Math.pow(2,21),zg=Math.pow(2,28),Wg=Math.pow(2,35),Gg=Math.pow(2,42),jg=Math.pow(2,49),Me=128,Yt=127;function Te(r){if(r<HP)return 1;if(r<VP)return 2;if(r<qP)return 3;if(r<zg)return 4;if(r<Wg)return 5;if(r<Gg)return 6;if(r<jg)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Sa(r,e,t=0){switch(Te(r)){case 8:e[t++]=r&255|Me,r/=128;case 7:e[t++]=r&255|Me,r/=128;case 6:e[t++]=r&255|Me,r/=128;case 5:e[t++]=r&255|Me,r/=128;case 4:e[t++]=r&255|Me,r>>>=7;case 3:e[t++]=r&255|Me,r>>>=7;case 2:e[t++]=r&255|Me,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function zP(r,e,t=0){switch(Te(r)){case 8:e.set(t++,r&255|Me),r/=128;case 7:e.set(t++,r&255|Me),r/=128;case 6:e.set(t++,r&255|Me),r/=128;case 5:e.set(t++,r&255|Me),r/=128;case 4:e.set(t++,r&255|Me),r>>>=7;case 3:e.set(t++,r&255|Me),r>>>=7;case 2:e.set(t++,r&255|Me),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Yg(r,e){let t=r[e],n=0;if(n+=t&Yt,t<Me||(t=r[e+1],n+=(t&Yt)<<7,t<Me)||(t=r[e+2],n+=(t&Yt)<<14,t<Me)||(t=r[e+3],n+=(t&Yt)<<21,t<Me)||(t=r[e+4],n+=(t&Yt)*zg,t<Me)||(t=r[e+5],n+=(t&Yt)*Wg,t<Me)||(t=r[e+6],n+=(t&Yt)*Gg,t<Me)||(t=r[e+7],n+=(t&Yt)*jg,t<Me))return n;throw new RangeError("Could not decode varint")}function WP(r,e){let t=r.get(e),n=0;if(n+=t&Yt,t<Me||(t=r.get(e+1),n+=(t&Yt)<<7,t<Me)||(t=r.get(e+2),n+=(t&Yt)<<14,t<Me)||(t=r.get(e+3),n+=(t&Yt)<<21,t<Me)||(t=r.get(e+4),n+=(t&Yt)*zg,t<Me)||(t=r.get(e+5),n+=(t&Yt)*Wg,t<Me)||(t=r.get(e+6),n+=(t&Yt)*Gg,t<Me)||(t=r.get(e+7),n+=(t&Yt)*jg,t<Me))return n;throw new RangeError("Could not decode varint")}function Xt(r,e,t=0){return e==null&&(e=it(Te(r))),e instanceof Uint8Array?Sa(r,e,t):zP(r,e,t)}function Br(r,e=0){return r instanceof Uint8Array?Yg(r,e):WP(r,e)}var Xg=new Float32Array([-0]),to=new Uint8Array(Xg.buffer);function cw(r,e,t){Xg[0]=r,e[t]=to[0],e[t+1]=to[1],e[t+2]=to[2],e[t+3]=to[3]}function lw(r,e){return to[0]=r[e],to[1]=r[e+1],to[2]=r[e+2],to[3]=r[e+3],Xg[0]}var Qg=new Float64Array([-0]),Qt=new Uint8Array(Qg.buffer);function uw(r,e,t){Qg[0]=r,e[t]=Qt[0],e[t+1]=Qt[1],e[t+2]=Qt[2],e[t+3]=Qt[3],e[t+4]=Qt[4],e[t+5]=Qt[5],e[t+6]=Qt[6],e[t+7]=Qt[7]}function dw(r,e){return Qt[0]=r[e],Qt[1]=r[e+1],Qt[2]=r[e+2],Qt[3]=r[e+3],Qt[4]=r[e+4],Qt[5]=r[e+5],Qt[6]=r[e+6],Qt[7]=r[e+7],Qg[0]}var GP=BigInt(Number.MAX_SAFE_INTEGER),jP=BigInt(Number.MIN_SAFE_INTEGER),Mr=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 oi;if(e<GP&&e>jP)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>fw&&(s=0n,++n>fw&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return oi;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):oi}},oi=new Mr(0,0);oi.toBigInt=function(){return 0n};oi.zzEncode=oi.zzDecode=function(){return this};oi.length=function(){return 1};var fw=4294967296n;function hw(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 pw(r,e,t){if(t-e<1)return"";let s,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Zg(r,e,t){let n=t,s,o;for(let i=0;i<r.length;++i)s=r.charCodeAt(i),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}function gn(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Kf(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Jg=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=re(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,gn(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 gn(this,4);return Kf(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw gn(this,4);return Kf(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw gn(this,4);let e=lw(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw gn(this,4);let e=dw(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 gn(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return pw(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw gn(this,e);this.pos+=e}else do if(this.pos>=this.len)throw gn(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Mr(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 gn(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 gn(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 gn(this,8);let e=Kf(this.buf,this.pos+=4),t=Kf(this.buf,this.pos+=4);return new Mr(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=Yg(this.buf,this.pos);return this.pos+=Te(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 Dl(r){return new Jg(r instanceof Uint8Array?r:r.subarray())}function ae(r,e,t){let n=Dl(r);return e.decode(n,void 0,t)}var e3={};we(e3,{base10:()=>YP});var YP=eo({prefix:"9",name:"base10",alphabet:"0123456789"});var t3={};we(t3,{base16:()=>XP,base16upper:()=>QP});var XP=dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),QP=dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var r3={};we(r3,{base2:()=>ZP});var ZP=dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var n3={};we(n3,{base256emoji:()=>nL});var gw=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}"),JP=gw.reduce((r,e,t)=>(r[t]=e,r),[]),eL=gw.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function tL(r){return r.reduce((e,t)=>(e+=JP[t],e),"")}function rL(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=eL[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var nL=ba({prefix:"\u{1F680}",name:"base256emoji",encode:tL,decode:rL});var s3={};we(s3,{base8:()=>sL});var sL=dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var o3={};we(o3,{identity:()=>oL});var oL=ba({prefix:"\0",name:"identity",encode:r=>z7(Sr(r)),decode:r=>Sr(q7(r))});var Hf={};we(Hf,{code:()=>lL,decode:()=>dL,encode:()=>uL,name:()=>cL});var iL=new TextEncoder,aL=new TextDecoder,cL="json",lL=512;function uL(r){return iL.encode(JSON.stringify(r))}function dL(r){return JSON.parse(aL.decode(r))}var ii={};we(ii,{code:()=>hs,decode:()=>pL,encode:()=>hL,name:()=>fL});var fL="raw",hs=85;function hL(r){return Sr(r)}function pL(r){return Sr(r)}var a3={};we(a3,{sha256:()=>je,sha512:()=>i3});function yw(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var je=kl({name:"sha2-256",code:18,encode:yw("SHA-256")}),i3=kl({name:"sha2-512",code:19,encode:yw("SHA-512")});var ai={...o3,...r3,...s3,...e3,...t3,...Og,...Bg,...Mg,...Hg,...n3},hW={...a3,...Vg};function bw(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var ww=bw("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),c3=bw("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=it(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),mL={utf8:ww,"utf-8":ww,hex:ai.base16,latin1:c3,ascii:c3,binary:c3,...ai},Vf=mL;function A(r,e="utf8"){let t=Vf[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function l3(r){let e=r??8192,t=e>>>1,n,s=e;return function(i){if(i<1||i>t)return it(i);s+i>e&&(n=it(e),s=0);let a=n.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}var ci=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function u3(){}var f3=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},gL=l3();function yL(r){return globalThis.Buffer!=null?it(r):gL(r)}var Ol=class{len;head;tail;states;constructor(){this.len=0,this.head=new ci(u3,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ci(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new h3((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(qf,10,Mr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Mr.fromBigInt(e);return this._push(qf,t.length(),t)}uint64Number(e){return this._push(Sa,Te(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=Mr.fromBigInt(e).zzEncode();return this._push(qf,t.length(),t)}sint64Number(e){let t=Mr.fromNumber(e).zzEncode();return this._push(qf,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(d3,1,e?1:0)}fixed32(e){return this._push(Nl,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Mr.fromBigInt(e);return this._push(Nl,4,t.lo)._push(Nl,4,t.hi)}fixed64Number(e){let t=Mr.fromNumber(e);return this._push(Nl,4,t.lo)._push(Nl,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(cw,4,e)}double(e){return this._push(uw,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(d3,1,0):this.uint32(t)._push(bL,t,e)}string(e){let t=hw(e);return t!==0?this.uint32(t)._push(Zg,t,e):this._push(d3,1,0)}fork(){return this.states=new f3(this),this.head=this.tail=new ci(u3,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 ci(u3,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=yL(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function d3(r,e,t){e[t]=r&255}function wL(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var h3=class extends ci{next;constructor(e,t){super(wL,e,t),this.next=void 0}};function qf(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 Nl(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 bL(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Ol.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(EL,e,r),this},Ol.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(xL,e,r),this});function EL(r,e,t){e.set(r,t)}function xL(r,e,t){r.length<40?Zg(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(A(r),t)}function p3(){return new Ol}function ce(r,e){let t=p3();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*le(r,e,t){let n=Dl(r);yield*e.stream(n,void 0,".",t)}var zf={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Wf(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}function at(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},s=function*(i,a){};return Wf("enum",zf.VARINT,t,n,s)}function ue(r,e,t){return Wf("message",zf.LENGTH_DELIMITED,r,e,t)}var ye=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Bl=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var Gf;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Gf||(Gf={}));var m3;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(m3||(m3={}));(function(r){r.codec=()=>at(m3)})(Gf||(Gf={}));var Ar;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),i.int32(o.Type)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Ar||(Ar={}));var dr;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),i.int32(o.Type)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=o.int32();break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:o.int32()};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(dr||(dr={}));var vL=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),SL=Uint8Array.from([6,5,43,129,4,0,34]),AL=Uint8Array.from([6,5,43,129,4,0,35]),Ew={ext:!0,kty:"EC",crv:"P-256"},xw={ext:!0,kty:"EC",crv:"P-384"},vw={ext:!0,kty:"EC",crv:"P-521"},Aa=32,Ta=48,Ia=66,Ml=class{type="ECDSA";code=3;jwk;constructor(e){this.jwk=e}toMultihash(){return ot.digest(this.toProtobuf())}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return Ar.encode({Type:this.code,Data:kL(this.jwk)})}async verify(e,t,n){let s=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!1,["verify"]),o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,re(t),re(e));return n?.signal?.throwIfAborted(),o}},jf=class{type="ECDSA";code=3;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return dr.encode({Type:this.code,Data:_L(this.jwk)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"ECDSA",namedCurve:this.jwk.crv??"P-256"},!0,["sign"]),s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,re(e));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}},g3=class{type="ECDSA";code=3;async generatePrivateKey(e){let t=e?.curve??"P-256",n=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:t},!0,["sign","verify"]),s=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey);return e?.signal?.throwIfAborted(),new jf(s,new Ml(o))}async publicKeyFromProtobuf(e,t){let n=Ar.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let s=CL(n.Data);return new Ml(s)}async privateKeyFromProtobuf(e,t){let n=dr.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");let s=IL(n.Data),o=TL(s);return t?.signal?.throwIfAborted(),new jf(s,new Ml(o))}};function y3(){return new g3}function TL(r){return{crv:r.crv,ext:!0,key_ops:["verify"],kty:"EC",x:r.x,y:r.y}}function IL(r){let e=pn(r),t=e[1],n=fe.baseEncode(t),s=e[2][1][0],o=1,i,a;if(t.byteLength===Aa)return i=fe.baseEncode(s.subarray(o,o+Aa)),a=fe.baseEncode(s.subarray(o+Aa)),{...Ew,key_ops:["sign"],d:n,x:i,y:a};if(t.byteLength===Ta)return i=fe.baseEncode(s.subarray(o,o+Ta)),a=fe.baseEncode(s.subarray(o+Ta)),{...xw,key_ops:["sign"],d:n,x:i,y:a};if(t.byteLength===Ia)return i=fe.baseEncode(s.subarray(o,o+Ia)),a=fe.baseEncode(s.subarray(o+Ia)),{...vw,key_ops:["sign"],d:n,x:i,y:a};throw new Ge(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function CL(r){let t=pn(r)[1][1][0],n=1,s,o;if(t.byteLength===Aa*2+1)return s=fe.baseEncode(t.subarray(n,n+Aa)),o=fe.baseEncode(t.subarray(n+Aa)),{...Ew,key_ops:["verify"],x:s,y:o};if(t.byteLength===Ta*2+1)return s=fe.baseEncode(t.subarray(n,n+Ta)),o=fe.baseEncode(t.subarray(n+Ta)),{...xw,key_ops:["verify"],x:s,y:o};if(t.byteLength===Ia*2+1)return s=fe.baseEncode(t.subarray(n,n+Ia)),o=fe.baseEncode(t.subarray(n+Ia)),{...vw,key_ops:["verify"],x:s,y:o};throw new Ge(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function kL(r){return mn([ur(Uint8Array.from([1])),mn([Sw(r.crv)],160),mn([Rl(new V(Uint8Array.from([4]),fe.baseDecode(r.x??""),fe.baseDecode(r.y??"")))],161)]).subarray()}function _L(r){return mn([ur(Uint8Array.from([1])),aw(fe.baseDecode(r.d??"")),mn([Sw(r.crv)],160),mn([Rl(new V(Uint8Array.from([4]),fe.baseDecode(r.x??""),fe.baseDecode(r.y??"")))],161)]).subarray()}function Sw(r){if(r==="P-256")return vL;if(r==="P-384")return SL;if(r==="P-521")return AL;throw new Ge(`Invalid curve ${r}`)}var PL=32,Ul=class{type="Ed25519";code=1;jwk;constructor(e){this.jwk=e}toMultihash(){return ot.digest(this.toProtobuf())}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}toProtobuf(){return Ar.encode({Type:this.code,Data:fe.baseDecode(this.jwk.x??"")})}async verify(e,t,n){let s=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!1,["verify"]),o=await crypto.subtle.verify({name:"Ed25519"},s,re(t),re(e));return n?.signal?.throwIfAborted(),o}},Yf=class{type="Ed25519";code=1;jwk;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}toProtobuf(){return dr.encode({Type:this.code,Data:Ke([fe.baseDecode(this.jwk.d??""),fe.baseDecode(this.jwk.x??"")],64)})}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"Ed25519"},!0,["sign"]),s=await crypto.subtle.sign({name:"Ed25519"},n,re(e));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}},w3=class{type="Ed25519";code=1;async generatePrivateKey(e){let t=await crypto.subtle.generateKey("Ed25519",!0,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",t.privateKey),s=await crypto.subtle.exportKey("jwk",t.publicKey);return e?.signal?.throwIfAborted(),new Yf(n,new Ul(s))}async publicKeyFromProtobuf(e,t){let n=Ar.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");t?.signal?.throwIfAborted();let s=NL(n.Data);return new Ul(s)}async privateKeyFromProtobuf(e,t){let n=dr.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");let s=await LL(n.Data,t),o=DL(s);return new Yf(s,new Ul(o))}};function b3(){return new w3}async function LL(r,e){let t=r.subarray(0,PL),n=RL(t),s=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),o=await crypto.subtle.exportKey("jwk",s);return e?.signal?.throwIfAborted(),o}var Aw=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4]);function RL(r){return Ke([Aw,Uint8Array.from([r.byteLength]),r],Aw.byteLength+1+r.byteLength)}function DL(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:r.x}}function NL(r){return{alg:"Ed25519",crv:"Ed25519",ext:!0,key_ops:["verify"],kty:"OKP",x:fe.baseEncode(r)}}var v3=8192,Fl=class{type="RSA";code=0;_raw;digest;jwk;constructor(e,t){if(Iw(e)>v3)throw new Ge("Key size is too large");this.jwk=e,this.digest=t}toMultihash(){return this.digest}toCID(){return $.createV1(114,this.toMultihash())}toString(){return this.toCID().toString(cr)}toProtobuf(){return $L(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async verify(e,t,n){let s=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]),o=await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,re(t),re(e));return n?.signal?.throwIfAborted(),o}},Xf=class{type="RSA";code=0;publicKey;jwk;constructor(e,t){if(Iw(e)>v3)throw new Ge("Key size is too large");this.jwk=e,this.publicKey=t}toProtobuf(){return KL(this.code,this.jwk)}toJWK(){return JSON.parse(JSON.stringify(this.jwk))}async sign(e,t){let n=await crypto.subtle.importKey("jwk",this.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),s=await crypto.subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,re(e));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}},x3=class{type="RSA";code=0;async generatePrivateKey(e){let t=e?.bits??2048;if(t>v3)throw new Ge("Key size is too large");let n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),s=await crypto.subtle.exportKey("jwk",n.privateKey),o=await crypto.subtle.exportKey("jwk",n.publicKey),i=await E3(s);return e?.signal?.throwIfAborted(),new Xf(s,new Fl(o,i))}async publicKeyFromProtobuf(e,t){let n=Ar.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");let s=UL(n.Data),o=await E3(s);return t?.signal?.throwIfAborted(),new Fl(s,o)}async privateKeyFromProtobuf(e,t){let n=dr.decode(e);if(n.Data==null)throw new Ge("Data field was missing from protobuf");if(n.Type!==this.code)throw new Ge("Incorrect Type field in protobuf");let s=pn(n.Data),o=OL(s),i=FL(o),a=await E3(i);return t?.signal?.throwIfAborted(),new Xf(o,new Fl(i,a))}};function $l(){return new x3}function OL(r){return{alg:"RS256",kty:"RSA",n:fe.baseEncode(r[1]),e:fe.baseEncode(r[2]),ext:!0,key_ops:["sign"],d:fe.baseEncode(r[3]),p:fe.baseEncode(r[4]),q:fe.baseEncode(r[5]),dp:fe.baseEncode(r[6]),dq:fe.baseEncode(r[7]),qi:fe.baseEncode(r[8])}}function BL(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 Ge("JWK was missing components");return mn([ur(Uint8Array.from([0])),ur(fe.baseDecode(r.n)),ur(fe.baseDecode(r.e)),ur(fe.baseDecode(r.d)),ur(fe.baseDecode(r.p)),ur(fe.baseDecode(r.q)),ur(fe.baseDecode(r.dp)),ur(fe.baseDecode(r.dq)),ur(fe.baseDecode(r.qi))]).subarray()}var ML=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Tw(r){if(r.n==null||r.e==null)throw new Ge("JWK public key was missing components");return mn([ML,Rl(mn([ur(fe.baseDecode(r.n)),ur(fe.baseDecode(r.e))]))]).subarray()}function UL(r){let e=pn(r);if(e.length<2||e[0]?.[0]!=="1.2.840.113549.1.1.1")throw new Error("PKIX certificate was invalid");let t=pn(e[1]);return{kty:"RSA",n:fe.baseEncode(t[0]),e:fe.baseEncode(t[1])}}function FL(r){return{key_ops:["verify"],ext:!0,alg:"RS256",kty:"RSA",n:r.n,e:"AQAB"}}function Iw(r){if(r.kty!=="RSA")throw new Ge("Invalid key type");if(r.n==null)throw new Ge("Invalid key modulus");return fe.baseDecode(r.n).length*8}async function E3(r){let e=Ar.encode({Type:0,Data:Tw(r)});return je.digest(e)}function $L(r,e){return Ar.encode({Type:r,Data:Tw(e)})}function KL(r,e){return dr.encode({Type:r,Data:BL(e)})}function S3(r){return r==null?!1:typeof r.type=="string"&&typeof r.code=="number"&&typeof r.verify=="function"}function Cw(r){return r==null?!1:typeof r.type=="string"&&typeof r.code=="number"&&typeof r.sign=="function"&&S3(r.publicKey)}var A3=1,T3=5,I3=100;var Kl=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},ro=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},Hl=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},Vl=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},C3=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}},ql=class extends Error{static name="UnknownCryptoError";name="UnknownCryptoError"},li=class extends Error{static name="NoEvictionError";name="NoEvictionError"};var k3={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},kw={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},_w=new globalThis.TextEncoder;function HL(r,e){let t=k3[e],n=kw[e];for(let s=0;s<r.length;s++)n^=BigInt(r[s]),n=BigInt.asUintN(e,n*t);return n}function VL(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=k3[e],s=kw[e],o=r;for(;o.length>0;){let i=_w.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)s^=BigInt(t[a]),s=BigInt.asUintN(e,s*n)}return s}function _3(r,{size:e=32,utf8Buffer:t}={}){if(!k3[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return VL(r,e,t);r=_w.encode(r)}return HL(r,e)}var zl={hash:r=>Number(_3(r,{size:32})),hashV:(r,e)=>qL(zl.hash(r,e))};function qL(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),A(e,"base16")}var P3=64,yn=class{fp;h;seed;constructor(e,t,n,s=2){if(s>P3)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),i=pe(s);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?se(this.fp,e.fp):!1}};function ui(r,e){return Math.floor(Math.random()*(e-r))+r}var di=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof yn))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof yn))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof yn))throw new TypeError("Invalid Fingerprint");let t=ui(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof yn))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var zL=500,Wl=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??zl,this.seed=e.seed??ui(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=A(e));let t=new yn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new di(this.bucketSize)),this.buckets[s]==null&&(this.buckets[s]=new di(this.bucketSize)),this.buckets[n].add(t)||this.buckets[s].add(t))return this.count++,!0;let o=[n,s],i=o[ui(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new di(this.bucketSize));for(let a=0;a<zL;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new di(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=A(e));let t=new yn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.has(t)??!1;if(s)return s;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=A(e));let t=new yn(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,s=this.buckets[n]?.remove(t)??!1;if(s)return this.count--,s;let o=(n^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},WL={1:.5,2:.84,4:.95,8:.98};function GL(r=.001){return r>.002?2:r>1e-5?4:8}function Pw(r,e=.001){let t=GL(e),n=WL[t],s=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),P3);return{filterSize:s,bucketSize:t,fingerprintSize:o}}var Qf=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??zl,this.seed=e.seed??ui(0,Math.pow(2,10)),this.filterSeries=[new Wl({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=A(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Wl({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=A(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=A(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Ut(r,e=.001,t){return new Qf({...Pw(r,e),...t??{}})}function L3(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function me(r){let e=L3(r);if(e==null)throw new v(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var Zf=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,s){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*s)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let s=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2],t[s+3]=i[3],[s+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[s,!1];t[s]=o>>8,t[s+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,s]=e(t);if(n===16)return t;if(s||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(n+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Lw=45,jL=15,Ca=new Zf;function Jf(r){if(!(r.length>jL))return Ca.new(r).parseWith(()=>Ca.readIPv4Addr())}function eh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Lw))return Ca.new(r).parseWith(()=>Ca.readIPv6Addr())}function ka(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Lw)return;let t=Ca.new(r).parseWith(()=>Ca.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function Rw(r,e,t){let n=0;for(let s of r)if(!(n<e)){if(n>t)break;if(s!==255)return!1;n++}return!0}function Dw(r,e,t,n){let s=0;for(let o of r)if(!(s<t)){if(s>n)break;if(o!==e[s])return!1;s++}return!0}function R3(r){switch(r.length){case fi:return r.join(".");case hi:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function Nw(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let s=t+1;s<r.length;s++)if(r[s]!=0)return-1;break}return e}function Ow(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var fi=4,hi=16,pj=parseInt("0xFFFF",16),YL=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Gl(r,e){e.length===hi&&r.length===fi&&Rw(e,0,11)&&(e=e.slice(12)),e.length===fi&&r.length===hi&&Dw(r,YL,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=r[s]&e[s];return n}function Bw(r,e){if(typeof e=="string"&&(e=ka(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function D3(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=fi,s=Jf(e);if(s==null&&(n=hi,s=eh(e),s==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=N3(o,8*n);return{network:Gl(s,i),mask:i}}function N3(r,e){if(e!==8*fi&&e!==8*hi)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let s=0;s<t;s++){if(r>=8){n[s]=255,r-=8;continue}n[s]=255-(255>>r),r=0}return n}var pi=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=D3(e));else{let n=ka(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n.length*8){let o=ka(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=N3(s,8*n.length);this.network=Gl(n,this.mask)}}contains(e){return Bw({network:this.network,mask:this.mask},e)}toString(){let e=Nw(this.mask),t=e!==-1?String(e):Ow(this.mask);return R3(this.network)+"/"+t}};function Mw(r,e){return new pi(r).contains(e)}function th(r){try{let e=me(r);return e.type==="ip6"?Mw("2000::/3",e.host):!1}catch{return!1}}function Uw(r){try{let e=me(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function Fw(r){if(typeof r!="string"||!/^[0-9a-fA-FxX.:]+$/.test(r))return!1;let e=r.includes(":")?`[${r}]`:r,t;try{t=new URL(`http://${e}`)}catch{return!1}if(t.href!==`http://${t.hostname}/`)return!1;let n=t.hostname;if(n.startsWith("["))return n==="[::1]";let s=n.split(".");return s.length===4&&s[0]==="127"&&s.every(o=>/^\d{1,3}$/.test(o))}function jl(r){try{let e=me(r);switch(e.type){case"ip4":case"ip6":return Fw(e.host);default:return!1}}catch{return!1}}function Ft(r){return L3(r)!==null}function wn(r){return!!Jf(r)}function rh(r){return!!eh(r)}var Vw=jo(Hw(),1),rR=["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"],nR=rR.map(r=>new Vw.Netmask(r));function K3(r){for(let e of nR)if(e.contains(r))return!0;return!1}function sR(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function oR(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),s=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return K3(s)}function iR(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function aR(r){let e=r.split(":"),t=e[e.length-1];return K3(t)}function cR(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Ra(r){if(wn(r))return K3(r);if(sR(r))return oR(r);if(iR(r))return aR(r);if(rh(r))return cR(r)}function ft(r){try{let e=me(r);switch(e.type){case"ip4":case"ip6":return Ra(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function ps(r,e){if(r.byteLength!==e.byteLength)throw new Error("Inputs should have the same length");for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Jr(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=it(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return Ff(t)}function _(r,e="utf8"){let t=Vf[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var $t=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ms=class extends Error{static name="ValidationError";name="ValidationError"},sh=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},oh=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function V3(r){return e=>_(e,r)}function q3(r){return e=>A(e,r)}function Da(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function gi(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function qw(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=A(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=gi(n);return Ke([t,s],t.length+s.length)}function zw(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=xt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let s=gi(n);return Ke([t,s],t.length+s.length)}function z3(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=_(e,"base32"),s=Da(t);return`${n}:${s}`}var W3=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let s=parseInt(t,10);if(isNaN(s)||s<0||s>255)throw new $t("Invalid byte value in IP address");e[n]=s}),e},Ww=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=wn(t[n]),i;o&&(i=W3(t[n]),t[n]=_(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,_(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let s=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new $t("Invalid byte value in IP address");s[e++]=o>>8&255,s[e++]=o&255}return s},Gw=function(r){if(r.byteLength!==4)throw new $t("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},jw=function(r){if(r.byteLength!==16)throw new $t("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let s=r[n],o=r[n+1],i=`${s.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new $t(`Invalid IPv6 address "${t}"`)}};function Yw(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new $t(`Invalid IPv6 address "${r}"`)}}var H3=Object.values(ai).map(r=>r.decoder),lR=(function(){let r=H3[0].or(H3[1]);return H3.slice(2).forEach(e=>r=r.or(e)),r})();function Xw(r){return lR.decode(r)}function Qw(r){return e=>r.encoder.encode(e)}function uR(r){if(parseInt(r).toString()!==r)throw new ms("Value must be an integer")}function dR(r){if(r<0)throw new ms("Value must be a positive integer, or zero")}function fR(r){return e=>{if(e>r)throw new ms(`Value must be smaller than or equal to ${r}`)}}function hR(...r){return e=>{for(let t of r)t(e)}}var Yl=hR(uR,dR,fR(65535));var Nt=-1,G3=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new oh(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},ys=new G3,CR=[{code:4,name:"ip4",size:32,valueToBytes:W3,bytesToValue:Gw,validate:r=>{if(!wn(r))throw new ms(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:gi,bytesToValue:Da,validate:Yl},{code:273,name:"udp",size:16,valueToBytes:gi,bytesToValue:Da,validate:Yl},{code:33,name:"dccp",size:16,valueToBytes:gi,bytesToValue:Da,validate:Yl},{code:41,name:"ip6",size:128,valueToBytes:Ww,bytesToValue:jw,stringToValue:Yw,validate:r=>{if(!rh(r))throw new ms(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Nt},{code:43,name:"ipcidr",size:8,bytesToValue:V3("base10"),valueToBytes:q3("base10")},{code:53,name:"dns",size:Nt},{code:54,name:"dns4",size:Nt},{code:55,name:"dns6",size:Nt},{code:56,name:"dnsaddr",size:Nt},{code:132,name:"sctp",size:16,valueToBytes:gi,bytesToValue:Da,validate:Yl},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Nt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Nt,bytesToValue:V3("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?q3("base58btc")(r):$.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:z3,valueToBytes:qw},{code:445,name:"onion3",size:296,bytesToValue:z3,valueToBytes:zw},{code:446,name:"garlic64",size:Nt},{code:447,name:"garlic32",size:Nt},{code:448,name:"tls"},{code:449,name:"sni",size:Nt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Nt,bytesToValue:Qw(fe),valueToBytes:Xw},{code:480,name:"http"},{code:481,name:"http-path",size:Nt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Nt}];CR.forEach(r=>{ys.addProtocol(r)});function Zw(r){let e=[],t=0;for(;t<r.length;){let n=Br(r,t),s=ys.getProtocol(n),o=Te(n),i=kR(s,r,t+o),a=0;i>0&&s.size===Nt&&(a=Te(i));let c=o+a+i,l={code:n,name:s.name,bytes:re(r.subarray(t,t+c))};if(i>0){let u=t+o+a,d=r.subarray(u,u+i);l.value=s.bytesToValue?.(d)??_(d)}e.push(l),t+=c}return e}function Jw(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let s=ys.getProtocol(n.code),o=Te(n.code),i,a=0,c=0;n.value!=null&&(i=s.valueToBytes?.(n.value)??A(n.value),a=i.byteLength,s.size===Nt&&(c=Te(a)));let l=new Uint8Array(o+c+a),u=0;Sa(n.code,l,u),u+=o,i!=null&&(s.size===Nt&&(Sa(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ke(t,e)}function eb(r){if(r.charAt(0)!=="/")throw new $t('String multiaddr must start with "/"');let e=[],t="protocol",n="",s="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?s+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=ys.getProtocol(s);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",s="",t="protocol";continue}else if(a)throw new $t(`Component ${s} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new $t(`Component ${s} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",s="",t="protocol"}}}if(s!==""&&n!=="")throw new $t("Incomplete multiaddr");return e}function tb(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=ys.getProtocol(e.code);if(t==null)throw new $t(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function kR(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Br(e,t)}var _R=Symbol.for("nodejs.util.inspect.custom"),r4=Symbol.for("@multiformats/multiaddr");function PR(r){if(r==null&&(r="/"),en(r))return r.getComponents();if(r instanceof Uint8Array)return Zw(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),eb(r);if(Array.isArray(r))return r;throw new $t("Must be a string, Uint8Array, Component[], or another Multiaddr")}var uh=class r{[r4]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=PR(e),t.validate!==!1&&LR(this)}get bytes(){return this.#r==null&&(this.#r=Jw(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=tb(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),s=n.lastIndexOf(t);if(s<0)throw new sh(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,s),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return se(this.bytes,e.bytes)}[_R](){return`Multiaddr(${this.toString()})`}};function LR(r){r.getComponents().forEach(e=>{let t=ys.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function en(r){return!!r?.[r4]}function W(r){return new uh(r)}var Ue=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),de=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),rb=r=>({match:e=>r.match(e)===!1?e:!1}),Ie=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Zt=(...r)=>({match:e=>{let t;for(let n of r){let s=n.match(e);s!==!1&&(t==null||s.length<t.length)&&(t=s)}return t??!1}}),_e=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function Fe(...r){function e(s){if(s==null)return!1;let o=s.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(s){return e(s)!==!1}function n(s){let o=e(s);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var RR=de(421),nb=Fe(RR),fh=de(54),hh=de(55),ph=de(56),s4=de(53),nX=Fe(fh,Ie(de(421))),sX=Fe(hh,Ie(de(421))),oX=Fe(ph,Ie(de(421))),mh=Fe(Zt(s4,ph,fh,hh),Ie(de(421))),sb=_e(de(4),Ie(de(43))),ob=_e(Ie(de(42)),de(41),Ie(de(43))),o4=Zt(sb,ob),Ma=Zt(o4,s4,fh,hh,ph),ib=Fe(Zt(o4,_e(Zt(s4,ph,fh,hh),Ie(de(421))))),i4=Fe(sb),a4=Fe(ob),ab=Fe(o4),c4=_e(Ma,de(6)),tu=_e(Ma,de(273)),wi=Fe(_e(c4,Ie(de(421)))),iX=Fe(tu),l4=_e(tu,Ue(460),Ie(de(421))),gh=_e(tu,Ue(461),Ie(de(421))),DR=Zt(l4,gh),aX=Fe(l4),cb=Fe(gh),n4=Zt(Ma,c4,tu,l4,gh),lb=Zt(_e(n4,Ue(477),Ie(de(421)))),ws=Fe(lb),ub=Zt(_e(n4,Ue(478),Ie(de(421))),_e(n4,Ue(448),Ie(de(449)),Ue(477),Ie(de(421)))),bi=Fe(ub),db=_e(tu,Ue(280),Ie(de(466)),Ie(de(466)),Ie(de(421))),ru=Fe(db),fb=_e(gh,Ue(465),Ie(de(466)),Ie(de(466)),Ie(de(421))),u4=Fe(fb),dh=Zt(lb,ub,_e(c4,Ie(de(421))),_e(DR,Ie(de(421))),_e(Ma,Ie(de(421))),db,fb,de(421)),Ua=Fe(dh),NR=_e(Ie(dh),Ue(290),rb(Ue(281)),Ie(de(421))),Ot=Fe(NR),OR=Zt(_e(dh,Ue(290),Ue(281),Ie(de(421))),_e(dh,Ue(281),Ie(de(421))),_e(Ue(281),Ie(de(421)))),nu=Fe(OR),BR=_e(Ma,Zt(_e(de(6,"80")),_e(de(6),Ue(480)),Ue(480)),Ie(de(481)),Ie(de(421))),hb=Fe(BR),MR=_e(Ma,Zt(_e(de(6,"443")),_e(de(6,"443"),Ue(480)),_e(de(6),Ue(443)),_e(de(6),Ue(448),Ue(480)),_e(Ue(448),Ue(480)),Ue(448),Ue(443)),Ie(de(481)),Ie(de(421))),pb=Fe(MR),UR=Zt(_e(de(777),Ie(de(421)))),cX=Fe(UR),FR=Zt(_e(de(400),Ie(de(421)))),lX=Fe(FR);function mb(r,e){let t=wi.exactMatch(r),n=wi.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let s=bi.exactMatch(r),o=bi.exactMatch(e);if(s&&!o)return-1;if(!s&&o)return 1;let i=ws.exactMatch(r),a=ws.exactMatch(e);if(i&&!a)return-1;if(!i&&a)return 1;let c=nu.exactMatch(r),l=nu.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=ru.exactMatch(r),d=ru.exactMatch(e);if(u&&!d)return-1;if(!u&&d)return 1;let f=u4.exactMatch(r),h=u4.exactMatch(e);return f&&!h?-1:!f&&h?1:0}function gb(r,e){let t=jl(r),n=jl(e);return t&&!n?1:!t&&n?-1:0}function yb(r,e){let t=ft(r),n=ft(e);return t&&!n?1:!t&&n?-1:0}function wb(r,e){let t=Ot.exactMatch(r),n=Ot.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function Ye(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var yh=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Fa=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new yh(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 yh(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 d4=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Kt(r={}){return $R(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 $R(r,e){e=e??{};let t=e.onEnd,n=new Fa,s,o,i,a=Ye(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,m)=>{o=b=>{o=null,n.push(b);try{y(r(n))}catch(E){m(E)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ye()})}},l=y=>o!=null?o(y):(n.push(y),s),u=y=>(n=new Fa,o!=null?o({error:y}):(n.push({error:y}),s)),d=y=>{if(i)return s;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})},f=y=>i?s:(i=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new Fa,f(),{done:!0}),p=y=>(f(y),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async y=>{let m=y?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let b,E;m!=null&&(b=new Promise((S,T)=>{E=()=>{T(new d4)},m.addEventListener("abort",E)}));try{await Promise.race([a.promise,b])}finally{E!=null&&m!=null&&m?.removeEventListener("abort",E)}}},t==null)return s;let g=s;return s={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(y){return g.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(y){return g.end(y),t!=null&&(t(y),t=void 0),s},get readableLength(){return g.readableLength},onEmpty:y=>g.onEmpty(y)},s}var f4=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},bb=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function fr(r,e){let{milliseconds:t,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((d,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){f(bb(i)),r.then(d,f);return}if(i&&(c=()=>{f(bb(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new f4;a=o.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),s===!1?d():s instanceof Error?f(s):(h.message=s??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},u}var KR=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function HR(r,e,t){let n,s=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=KR(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(g){n(),i(g);return}c.push(p),t.count===c.length&&(n(),o(c))},f=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(s.cancel=n,typeof t.timeout=="number"){let o=fr(s,{milliseconds:t.timeout});return o.cancel=()=>{n(),o.clear()},o}return s}function tn(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=HR(r,e,t),s=n.then(o=>o[0]);return s.cancel=n.cancel,s}function bs(r,e){let t,n=function(){let s=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(s,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var wh=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},bh=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Ei=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Eh=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},xh=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function VR(r){return r.reason}function be(r,e,t){if(e==null||r==null)return r;let n=t?.translateError??VR;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;return Promise.race([r,new Promise((o,i)=>{s=()=>{i(n(e))},e.addEventListener("abort",s)})]).finally(()=>{s!=null&&e.removeEventListener("abort",s)})}var vh=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Ye(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function qR(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Eb=new WeakMap,Sh=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=qR(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 jt),this.cleanup())}async join(e){let t=new vh(e);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 be(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(this.recipients.length!==0&&!this.dispatchingProgress){if(typeof t=="object"&&t!==null){let n=Eb.get(t);if(n==null&&(n=new WeakSet,Eb.set(t,n)),n.has(this))return;n.add(this)}this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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.deferred.reject(e.signal?.reason??new jt),e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}),this.recipients.splice(0,this.recipients.length)}};var ht=class extends ge{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=bs(this.emitEmpty.bind(this),1),this.emitIdle=bs(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new bh;let n=new Sh(e,t);this.enqueue(n),this.safeDispatchEvent("add");let s=n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o});return this.tryToStartAnother(),s}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new jt)}),this.clear()}async onEmpty(e){this.size!==0&&await tn(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await tn(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await tn(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Kt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},s=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new jt("Queue aborted"))};this.addEventListener("completed",s),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",s),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var zR=Math.pow(2,20)*4,$n=class extends ge{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??zR,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new V,this.writeBuffer=new V,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(s){this.log.error("processSendQueue threw - %e",s)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=s=>{this.onDrainPromise?.reject(s.error??new xh)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),be(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Kt(),t=o=>{e.push(o.data)};this.addEventListener("message",t);let n=o=>{e.end(o.error)};this.addEventListener("close",n);let s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new On(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new Nf(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new On("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new On("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new On(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new On(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new Of(new ma))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new Zs))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}let o=this.writeBuffer.sublist(0,s),i=new V(o);this.writeBuffer.consume(o.byteLength);let a;try{a=this.sendData(o)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.#e||this.readBuffer.byteLength>0||this.remoteWriteStatus!=="closed"&&this.readStatus!=="closed"||(this.#e=!0,this.safeDispatchEvent("end"))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Df(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Qo(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Qo(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var oo=class extends $n{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await tn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await tn(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Ah(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var io=class extends ge{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let s=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",s);let o=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",o)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await be(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new fn;let t=this.onCreateStream({...this.streamOptions,...e});return Ah(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Eh(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let s=this.streams.findIndex(o=>o===e);s!==-1&&this.streams.splice(s,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var ao=class extends $n{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await tn(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await tn(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.maybeDispatchEnd(),this.log("closed readable end gracefully"))}};var $a=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),s=e-this.movingAverage,o=n*s;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+s*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*s}else this.movingAverage=e;this.previousTime=t}};var WR=1.2,GR=2,jR=5e3,YR=6e4,XR=5e3,xn=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??XR;this.success=new $a(t),this.failure=new $a(t),this.next=new $a(t),this.failureMultiplier=e.failureMultiplier??GR,this.timeoutMultiplier=e.timeoutMultiplier??WR,this.minTimeout=e.minTimeout??jR,this.maxTimeout=e.maxTimeout??YR,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),s=he([e.signal,n]);return s.start=Date.now(),s.timeout=t,s}cleanUp(e){e.clear();let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var h4=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Ye(),this.haveNext=Ye()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Ye(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Ye(),await be(this.readNext.promise,t?.signal,t)}};function xb(){return new h4}function vb(r){return r[Symbol.asyncIterator]!=null}async function QR(r,e,t){try{await Promise.all(r.map(async n=>{for(;;){let{value:s,done:o}=await n.next();if(o===!0)break;await e.push(s,{signal:t}),t.throwIfAborted()}})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*ZR(r){let e=new AbortController,t=xb(),n=r.map(s=>vb(s)?s[Symbol.asyncIterator]():s[Symbol.iterator]());QR(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort();for(let s of n)try{Promise.resolve(s.return?.()).catch(()=>{})}catch{}}}function*JR(r){for(let e of r)yield*e}function eD(...r){let e=[];for(let t of r)vb(t)||e.push(t);return e.length===r.length?JR(e):ZR(r)}var hr=eD;function Ka(r,...e){if(r==null)throw new Error("Empty pipeline");if(p4(r)){let n=r;r=()=>n.source}else if(Ab(r)||Sb(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&p4(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++)p4(t[n])&&(t[n]=rD(t[n]));return tD(...t)}var tD=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Sb=r=>r?.[Symbol.asyncIterator]!=null,Ab=r=>r?.[Symbol.iterator]!=null,p4=r=>r==null?!1:r.sink!=null&&r.source!=null,rD=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Kt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(Sb(o))s=async function*(){yield*o,n.end()};else if(Ab(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return hr(n,s())}return r.source};var nD=4194304,Th=class extends Error{static name="UnwrappedError";name="UnwrappedError"},su=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},g4=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},y4=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function sD(r){return typeof r?.closeRead=="function"}function oD(r){return typeof r?.close=="function"}function m4(r){return sD(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:oD(r)?r.status!=="open":!1}function iD(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Ih(r,e){let t=e?.maxBufferSize??nD,n=new V,s,o=!1,i;if(!iD(r))throw new v("Argument should be a Stream or a Multiaddr");let a=d=>{if(i==null){if(n.append(d.data),n.byteLength>t){let f=n.byteLength;n.consume(f);let h=new Qo(`Read buffer overflow - ${f} > ${t}`);i=h,s?.reject(h),queueMicrotask(()=>{r.abort(h)});return}s?.resolve()}};r.addEventListener("message",a);let c=d=>{d.error!=null?s?.reject(d.error):s?.resolve()};r.addEventListener("close",c);let l=()=>{s?.resolve()};r.addEventListener("remoteCloseWrite",l);let u={readBuffer:n,async read(d){if(o===!0)throw new Th("Stream was unwrapped");if(i!=null)throw i;if(m4(r)){if(n.byteLength===0&&d?.bytes==null)return null;if(d?.bytes!=null&&n.byteLength<d.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new Ei(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}let f=d?.bytes??1;for(s=Promise.withResolvers();;){if(n.byteLength>=f){s.resolve();break}if(await be(s.promise,d?.signal),m4(r)){if(n.byteLength===0&&d?.bytes==null)return null;break}s=Promise.withResolvers()}let h=d?.bytes??n.byteLength;if(n.byteLength<h){if(m4(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Ei(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return u.read(d)}let p=n.sublist(0,h);return n.consume(h),p},async write(d,f){if(o===!0)throw new Th("Stream was unwrapped");r.send(d)||await tn(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!0,r.removeEventListener("message",a),r.removeEventListener("close",c),r.removeEventListener("remoteCloseWrite",l),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return u}function vn(r,e={}){let t=Ih(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Te(e.maxDataLength));let n=e?.lengthDecoder??Br,s=e?.lengthEncoder??Xt;return{async read(i){let a=-1,c=new V;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new su("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new y4(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new g4(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Ei(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Ei(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new V(s(i.byteLength),i),a)},async writeV(i,a){let c=new V(...i.flatMap(l=>[s(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Ze(r,e){let t=vn(r,e),n={read:async(s,o)=>{let i=await t.read(o);return s.decode(i,o)},write:async(s,o,i)=>{await t.write(o.encode(s),i)},writeV:async(s,o,i)=>{await t.writeV(s.map(a=>o.encode(a)),i)},pb:s=>({read:async o=>n.read(s,o),write:async(o,i)=>n.write(o,s,i),writeV:async(o,i)=>n.writeV(o,s,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var aD=1024*1024*4,cD=1024*1024*4,Ha=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new V,this.maxBufferSize=e.maxBufferSize??aD,this.maxDataLength=e.maxDataLength??cD,this.lengthDecoder=e.lengthDecoder??Br,this.encodingLength=e.encodingLength??Te}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new v(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(t<0||t>this.maxDataLength)throw new su("Invalid message length");let n=this.encodingLength(t),s=n+t;if(this.buffer.byteLength>=s){let o=this.buffer.sublist(n,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}};var lD=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function w4(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=uD(r);return t||"Object"}function uD(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(lD.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}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};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 L=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 ou=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",dD=new TextEncoder;function Ch(r){return ou&&globalThis.Buffer.isBuffer(r)}function xi(r){return r instanceof Uint8Array?Ch(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var fD=24,hD=200,Va=ou?r=>r.length>=fD?globalThis.Buffer.from(r):Tb(r):r=>r.length>=hD?dD.encode(r):Tb(r),Kn=r=>Uint8Array.from(r),Cb=ou?(r,e,t)=>Ch(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),kb=ou?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),xi(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let s of r)n+s.length>t.length&&(s=s.subarray(0,t.length-n)),t.set(s,n),n+=s.length;return t},b4=ou?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function qa(r,e){if(Ch(r)&&Ch(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 Tb(r){let e=[],t=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(s=65536+((s&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(s>=55296&&s<=57343&&(s=65533),e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128)}return e}var Ib=4096;function _b(r){let e=r.length;if(e<=Ib)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Ib));return t}var pD=256,iu=class{constructor(e=pD){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)}pushByte(e){let t=this.chunks[this.chunks.length-1];this.cursor>this.maxCursor&&(t=b4(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t));let n=t.length-(this.maxCursor-this.cursor)-1;t[n]=e,this.cursor++}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let s=t.length-(this.maxCursor-this.cursor)-1;t.set(e,s)}else{if(t){let s=t.length-(this.maxCursor-this.cursor)-1;s<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,s),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=b4(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=Cb(n,0,this.cursor)}else t=kb(this.chunks,this.cursor);return e&&this.reset(),t}},kh=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}pushByte(e){if(this.cursor>=this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest[this.cursor++]=e}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var q="CBOR decode error:",Hn="CBOR encode error:",au=[];au[23]=1;au[24]=2;au[25]=3;au[26]=5;au[27]=9;function Es(r,e,t){if(r.length-e<t)throw new Error(`${q} not enough data for type`)}var Bt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Ur(r,e,t){Es(r,e,1);let n=r[e];if(t.strict===!0&&n<Bt[0])throw new Error(`${q} integer encoded in more bytes than necessary (strict decode)`);return n}function Fr(r,e,t){Es(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Bt[1])throw new Error(`${q} integer encoded in more bytes than necessary (strict decode)`);return n}function $r(r,e,t){Es(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Bt[2])throw new Error(`${q} integer encoded in more bytes than necessary (strict decode)`);return n}function Kr(r,e,t){Es(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],s=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(s);if(t.strict===!0&&o<Bt[3])throw new Error(`${q} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${q} integers outside of the safe integer range are not supported`)}function Pb(r,e,t,n){return new L(w.uint,Ur(r,e+1,n),2)}function Lb(r,e,t,n){return new L(w.uint,Fr(r,e+1,n),3)}function Rb(r,e,t,n){return new L(w.uint,$r(r,e+1,n),5)}function Db(r,e,t,n){return new L(w.uint,Kr(r,e+1,n),9)}function Vn(r,e){return Ct(r,0,e.value)}function Ct(r,e,t){if(t<Bt[0]){let n=Number(t);r.pushByte(e|n)}else if(t<Bt[1]){let n=Number(t);r.push([e|24,n])}else if(t<Bt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Bt[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<Bt[4]){let s=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));s[8]=o&255,o=o>>8,s[7]=o&255,o=o>>8,s[6]=o&255,o=o>>8,s[5]=o&255,s[4]=i&255,i=i>>8,s[3]=i&255,i=i>>8,s[2]=i&255,i=i>>8,s[1]=i&255,r.push(s)}else throw new Error(`${q} encountered BigInt larger than allowable range`)}}Vn.encodedSize=function(e){return Ct.encodedSize(e.value)};Ct.encodedSize=function(e){return e<Bt[0]?1:e<Bt[1]?2:e<Bt[2]?3:e<Bt[3]?5:9};Vn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Nb(r,e,t,n){return new L(w.negint,-1-Ur(r,e+1,n),2)}function Ob(r,e,t,n){return new L(w.negint,-1-Fr(r,e+1,n),3)}function Bb(r,e,t,n){return new L(w.negint,-1-$r(r,e+1,n),5)}var E4=BigInt(-1),Mb=BigInt(1);function Ub(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s!="bigint"){let o=-1-s;if(o>=Number.MIN_SAFE_INTEGER)return new L(w.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${q} integers outside of the safe integer range are not supported`);return new L(w.negint,E4-BigInt(s),9)}function _h(r,e){let t=e.value,n=typeof t=="bigint"?t*E4-Mb:t*-1-1;Ct(r,e.type.majorEncoded,n)}_h.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*E4-Mb:t*-1-1;return n<Bt[0]?1:n<Bt[1]?2:n<Bt[2]?3:n<Bt[3]?5:9};_h.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function cu(r,e,t,n){Es(r,e,t+n);let s=r.slice(e+t,e+t+n);return new L(w.bytes,s,t+n)}function Fb(r,e,t,n){return cu(r,e,1,t)}function $b(r,e,t,n){return cu(r,e,2,Ur(r,e+1,n))}function Kb(r,e,t,n){return cu(r,e,3,Fr(r,e+1,n))}function Hb(r,e,t,n){return cu(r,e,5,$r(r,e+1,n))}function Vb(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s=="bigint")throw new Error(`${q} 64-bit integer bytes lengths not supported`);return cu(r,e,9,s)}function Ph(r){return r.encodedBytes===void 0&&(r.encodedBytes=w.equals(r.type,w.string)?Va(r.value):r.value),r.encodedBytes}function za(r,e){let t=Ph(e);Ct(r,e.type.majorEncoded,t.length),r.push(t)}za.encodedSize=function(e){let t=Ph(e);return Ct.encodedSize(t.length)+t.length};za.compareTokens=function(e,t){return gD(Ph(e),Ph(t))};function gD(r,e){return r.length<e.length?-1:r.length>e.length?1:qa(r,e)}var qb=new TextDecoder,wD=32;function bD(r,e,t){if(t-e<wD){let s="";for(let o=e;o<t;o++){let i=r[o];if(i&128)return qb.decode(r.subarray(e,t));s+=String.fromCharCode(i)}return s}return qb.decode(r.subarray(e,t))}function lu(r,e,t,n,s){let o=t+n;Es(r,e,o);let i=new L(w.string,bD(r,e+t,e+o),o);return s.retainStringBytes===!0&&(i.byteValue=r.slice(e+t,e+o)),i}function zb(r,e,t,n){return lu(r,e,1,t,n)}function Wb(r,e,t,n){return lu(r,e,2,Ur(r,e+1,n),n)}function Gb(r,e,t,n){return lu(r,e,3,Fr(r,e+1,n),n)}function jb(r,e,t,n){return lu(r,e,5,$r(r,e+1,n),n)}function Yb(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s=="bigint")throw new Error(`${q} 64-bit integer string lengths not supported`);return lu(r,e,9,s,n)}var Xb=za;function Wa(r,e,t,n){return new L(w.array,n,t)}function Qb(r,e,t,n){return Wa(r,e,1,t)}function Zb(r,e,t,n){return Wa(r,e,2,Ur(r,e+1,n))}function Jb(r,e,t,n){return Wa(r,e,3,Fr(r,e+1,n))}function e9(r,e,t,n){return Wa(r,e,5,$r(r,e+1,n))}function t9(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s=="bigint")throw new Error(`${q} 64-bit integer array lengths not supported`);return Wa(r,e,9,s)}function r9(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${q} indefinite length items not allowed`);return Wa(r,e,1,1/0)}function Lh(r,e){Ct(r,w.array.majorEncoded,e.value)}Lh.compareTokens=Vn.compareTokens;Lh.encodedSize=function(e){return Ct.encodedSize(e.value)};function Ga(r,e,t,n){return new L(w.map,n,t)}function n9(r,e,t,n){return Ga(r,e,1,t)}function s9(r,e,t,n){return Ga(r,e,2,Ur(r,e+1,n))}function o9(r,e,t,n){return Ga(r,e,3,Fr(r,e+1,n))}function i9(r,e,t,n){return Ga(r,e,5,$r(r,e+1,n))}function a9(r,e,t,n){let s=Kr(r,e+1,n);if(typeof s=="bigint")throw new Error(`${q} 64-bit integer map lengths not supported`);return Ga(r,e,9,s)}function c9(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${q} indefinite length items not allowed`);return Ga(r,e,1,1/0)}function Rh(r,e){Ct(r,w.map.majorEncoded,e.value)}Rh.compareTokens=Vn.compareTokens;Rh.encodedSize=function(e){return Ct.encodedSize(e.value)};function l9(r,e,t,n){return new L(w.tag,t,1)}function u9(r,e,t,n){return new L(w.tag,Ur(r,e+1,n),2)}function d9(r,e,t,n){return new L(w.tag,Fr(r,e+1,n),3)}function f9(r,e,t,n){return new L(w.tag,$r(r,e+1,n),5)}function h9(r,e,t,n){return new L(w.tag,Kr(r,e+1,n),9)}function Dh(r,e){Ct(r,w.tag.majorEncoded,e.value)}Dh.compareTokens=Vn.compareTokens;Dh.encodedSize=function(e){return Ct.encodedSize(e.value)};var Nh=20,Oh=21,Bh=22,Mh=23;function m9(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${q} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new L(w.null,null,1):new L(w.undefined,void 0,1)}function g9(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${q} indefinite length items not allowed`);return new L(w.break,void 0,1)}function x4(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${q} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${q} Infinity values are not supported`)}return new L(w.float,r,e)}function y9(r,e,t,n){return x4(Uh(r,e+1),3,n)}function w9(r,e,t,n){return x4(Fh(r,e+1),5,n)}function b9(r,e,t,n){return x4(v9(r,e+1),9,n)}function uu(r,e,t){let n=e.value;if(n===!1)r.pushByte(w.float.majorEncoded|Nh);else if(n===!0)r.pushByte(w.float.majorEncoded|Oh);else if(n===null)r.pushByte(w.float.majorEncoded|Bh);else if(n===void 0)r.pushByte(w.float.majorEncoded|Mh);else{let s,o=!1;(!t||t.float64!==!0)&&(v4(n),s=Uh(kt,1),n===s||Number.isNaN(n)?(kt[0]=249,r.push(kt.slice(0,3)),o=!0):(S4(n),s=Fh(kt,1),n===s&&(kt[0]=250,r.push(kt.slice(0,5)),o=!0))),o||(x9(n),s=v9(kt,1),kt[0]=251,r.push(kt.slice(0,9)))}}uu.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){v4(n);let s=Uh(kt,1);if(n===s||Number.isNaN(n))return 3;if(S4(n),s=Fh(kt,1),n===s)return 5}return 9};var E9=new ArrayBuffer(9),rn=new DataView(E9,1),kt=new Uint8Array(E9,0);function v4(r){if(r===1/0)rn.setUint16(0,31744,!1);else if(r===-1/0)rn.setUint16(0,64512,!1);else if(Number.isNaN(r))rn.setUint16(0,32256,!1);else{rn.setFloat32(0,r);let e=rn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)rn.setUint16(0,31744,!1);else if(t===0)rn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let s=t-127;s<-24?rn.setUint16(0,0):s<-14?rn.setUint16(0,(e&2147483648)>>16|1<<24+s,!1):rn.setUint16(0,(e&2147483648)>>16|s+15<<10|n>>13,!1)}}}function Uh(r,e){if(r.length-e<2)throw new Error(`${q} 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,s=t&1023,o;return n===0?o=s*2**-24:n!==31?o=(s+1024)*2**(n-25):o=s===0?1/0:NaN,t&32768?-o:o}function S4(r){rn.setFloat32(0,r,!1)}function Fh(r,e){if(r.length-e<4)throw new Error(`${q} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function x9(r){rn.setFloat64(0,r,!1)}function v9(r,e){if(r.length-e<8)throw new Error(`${q} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}function AD(r,e){let t=r.value;if(t===!1)return Uint8Array.of(w.float.majorEncoded|Nh);if(t===!0)return Uint8Array.of(w.float.majorEncoded|Oh);if(t===null)return Uint8Array.of(w.float.majorEncoded|Bh);if(t===void 0)return Uint8Array.of(w.float.majorEncoded|Mh);if(!e){if(v4(t),t===Uh(kt,1)||Number.isNaN(t))return kt[0]=249,kt.slice(0,3);if(S4(t),t===Fh(kt,1))return kt[0]=250,kt.slice(0,5)}return x9(t),kt[0]=251,kt.slice(0,9)}function p9(r,e){let t=r,n=e?.float64===!0,s=n?t._keyBytesFloat64:t._keyBytes;if(s!==void 0)return s;let o=AD(r,n);return n?t._keyBytesFloat64=o:t._keyBytes=o,o}uu.compareTokens=function(e,t,n){let s=p9(e,n),o=p9(t,n);return s.length!==o.length?s.length<o.length?-1:1:qa(s,o)};function De(r,e,t){throw new Error(`${q} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function $h(r){return()=>{throw new Error(`${q} ${r}`)}}var H=[];for(let r=0;r<=23;r++)H[r]=De;H[24]=Pb;H[25]=Lb;H[26]=Rb;H[27]=Db;H[28]=De;H[29]=De;H[30]=De;H[31]=De;for(let r=32;r<=55;r++)H[r]=De;H[56]=Nb;H[57]=Ob;H[58]=Bb;H[59]=Ub;H[60]=De;H[61]=De;H[62]=De;H[63]=De;for(let r=64;r<=87;r++)H[r]=Fb;H[88]=$b;H[89]=Kb;H[90]=Hb;H[91]=Vb;H[92]=De;H[93]=De;H[94]=De;H[95]=$h("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)H[r]=zb;H[120]=Wb;H[121]=Gb;H[122]=jb;H[123]=Yb;H[124]=De;H[125]=De;H[126]=De;H[127]=$h("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)H[r]=Qb;H[152]=Zb;H[153]=Jb;H[154]=e9;H[155]=t9;H[156]=De;H[157]=De;H[158]=De;H[159]=r9;for(let r=160;r<=183;r++)H[r]=n9;H[184]=s9;H[185]=o9;H[186]=i9;H[187]=a9;H[188]=De;H[189]=De;H[190]=De;H[191]=c9;for(let r=192;r<=215;r++)H[r]=l9;H[216]=u9;H[217]=d9;H[218]=f9;H[219]=h9;H[220]=De;H[221]=De;H[222]=De;H[223]=De;for(let r=224;r<=243;r++)H[r]=$h("simple values are not supported");H[244]=De;H[245]=De;H[246]=De;H[247]=m9;H[248]=$h("simple values are not supported");H[249]=y9;H[250]=w9;H[251]=b9;H[252]=De;H[253]=De;H[254]=De;H[255]=g9;var Sn=[];for(let r=0;r<24;r++)Sn[r]=new L(w.uint,r,1);for(let r=-1;r>=-24;r--)Sn[31-r]=new L(w.negint,r,1);Sn[64]=new L(w.bytes,new Uint8Array(0),1);Sn[96]=new L(w.string,"",1);Sn[128]=new L(w.array,0,1);Sn[160]=new L(w.map,0,1);Sn[244]=new L(w.false,!1,1);Sn[245]=new L(w.true,!0,1);Sn[246]=new L(w.null,null,1);function A4(r){switch(r.type){case w.false:return Kn([244]);case w.true:return Kn([245]);case w.null:return Kn([246]);case w.bytes:return r.value.length?void 0:Kn([64]);case w.string:return r.value===""?Kn([96]):void 0;case w.array:return r.value===0?Kn([128]):void 0;case w.map:return r.value===0?Kn([160]):void 0;case w.uint:return r.value<24?Kn([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return Kn([31-Number(r.value)])}}var ID={float64:!1,mapSorter:I4,quickEncodeToken:A4},C9=Object.freeze({mapSorter:_D,quickEncodeToken:A4});function CD(){let r=[];return r[w.uint.major]=Vn,r[w.negint.major]=_h,r[w.bytes.major]=za,r[w.string.major]=Xb,r[w.array.major]=Lh,r[w.map.major]=Rh,r[w.tag.major]=Dh,r[w.float.major]=uu,r}var Ai=CD(),Kh=new iu,Ya=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(`${Hn} object contains circular references`);return new r(t,e)}},co={null:new L(w.null,null),undefined:new L(w.undefined,void 0),true:new L(w.true,!0),false:new L(w.false,!1),emptyArray:new L(w.array,0),emptyMap:new L(w.map,0)},qn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new L(w.float,r):r>=0?new L(w.uint,r):new L(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new L(w.uint,r):new L(w.negint,r)},Uint8Array(r,e,t,n){return new L(w.bytes,r)},string(r,e,t,n){return new L(w.string,r)},boolean(r,e,t,n){return r?co.true:co.false},null(r,e,t,n){return co.null},undefined(r,e,t,n){return co.undefined},ArrayBuffer(r,e,t,n){return new L(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new L(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[co.emptyArray,new L(w.break)]:co.emptyArray;n=Ya.createCheck(n,r);let s=[],o=0;for(let i of r)s[o++]=Si(i,t,n);return t.addBreakTokens?[new L(w.array,r.length),s,new L(w.break)]:[new L(w.array,r.length),s]},Object(r,e,t,n){let s=e!=="Object",o=s?r.keys():Object.keys(r),i=s?r.size:o.length,a;if(i){a=new Array(i),n=Ya.createCheck(n,r);let c=!s&&t.ignoreUndefinedProperties,l=0;for(let u of o){let d=s?r.get(u):r[u];c&&d===void 0||(a[l++]=[Si(u,t,n),Si(d,t,n)])}l<i&&(a.length=l)}return a?.length?(kD(a,t),t.addBreakTokens?[new L(w.map,a.length),a,new L(w.break)]:[new L(w.map,a.length),a]):t.addBreakTokens===!0?[co.emptyMap,new L(w.break)]:co.emptyMap},Tagged(r,e,t,n){return[new L(w.tag,r.tag),Si(r.value,t,n)]}};qn.Map=qn.Object;qn.Buffer=qn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))qn[`${r}Array`]=qn.DataView;function Si(r,e={},t){let n=w4(r),s=e&&e.typeEncoders&&e.typeEncoders[n]||qn[n];if(typeof s=="function"){let i=s(r,n,e,t);if(i!=null)return i}let o=qn[n];if(!o)throw new Error(`${Hn} unsupported type: ${n}`);return o(r,n,e,t)}function kD(r,e){let t=e.mapSorter;t&&r.sort((n,s)=>t(n,s,e))}function I4(r,e,t){let n=Array.isArray(r[0])?r[0][0]:r[0],s=Array.isArray(e[0])?e[0][0]:e[0];if(n.type.major!==s.type.major)return n.type.compare(s.type);let o=n.type.major,i=Ai[o].compareTokens(n,s,t);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function _D(r,e){if(r[0]instanceof L&&e[0]instanceof L){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=S9(t.value)),n._keyBytes||(n._keyBytes=S9(n.value)),qa(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function S9(r){return Hh(r,Ai,C9)}function ja(r,e,t,n){if(Array.isArray(e))for(let s of e)ja(r,s,t,n);else t[e.type.major](r,e,n)}var A9=w.uint.majorEncoded,T9=w.negint.majorEncoded,PD=w.bytes.majorEncoded,LD=w.string.majorEncoded,I9=w.array.majorEncoded,T4=w.map.majorEncoded,RD=w.float.majorEncoded|Nh,DD=w.float.majorEncoded|Oh,ND=w.float.majorEncoded|Bh,OD=w.float.majorEncoded|Mh,BD=BigInt(-1),MD=BigInt(1);function lo(r,e,t){t<24?r.pushByte(e|Number(t)):Ct(r,e,t)}function UD(r){return r.addBreakTokens!==!0}function FD(r,e,t,n,s){let o=t==="Map",i=o?e.keys():Object.keys(e),a=o?e.size:i.length;if(!a){r.pushByte(T4);return}s=Ya.createCheck(s,e);let c=!o&&n.ignoreUndefinedProperties,l=new Array(a),u=0;for(let d of i){let f=o?e.get(d):e[d];c&&f===void 0||(l[u++]=[Si(d,n,s),f])}if(u===0){r.pushByte(T4);return}u<a&&(l.length=u),l.sort((d,f)=>I4(d,f,n)),lo(r,T4,u);for(let[d,f]of l)ja(r,d,Ai,n),C4(r,f,n,s)}function C4(r,e,t,n){let s=w4(e),o=t.typeEncoders&&t.typeEncoders[s];if(o){let i=o(e,s,t,n);if(i!=null){ja(r,i,Ai,t);return}}switch(s){case"null":r.pushByte(ND);return;case"undefined":r.pushByte(OD);return;case"boolean":r.pushByte(e?DD:RD);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?uu(r,new L(w.float,e),t):e>=0?lo(r,A9,e):lo(r,T9,e*-1-1);return;case"bigint":e>=BigInt(0)?lo(r,A9,e):lo(r,T9,e*BD-MD);return;case"string":{let i=Va(e);lo(r,LD,i.length),r.push(i);return}case"Uint8Array":lo(r,PD,e.length),r.push(e);return;case"Array":if(!e.length){r.pushByte(I9);return}n=Ya.createCheck(n,e),lo(r,I9,e.length);for(let i of e)C4(r,i,t,n);return;case"Object":case"Map":if(t.mapSorter===I4)FD(r,e,s,t,n);else{let i=qn.Object(e,s,t,n);ja(r,i,Ai,t)}return;default:{let i=qn[s];if(!i)throw new Error(`${Hn} unsupported type: ${s}`);let a=i(e,s,t,n);ja(r,a,Ai,t)}}}function Hh(r,e,t,n){let s=n instanceof Uint8Array,o=s?new kh(n):Kh,i=Si(r,t);if(!Array.isArray(i)&&t.quickEncodeToken){let a=t.quickEncodeToken(i);if(a)return s?(o.push(a),o.toBytes()):a;let c=e[i.type.major];if(c.encodedSize){let l=c.encodedSize(i,t);if(s||(o=new iu(l)),c(o,i,t),o.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${i} was wrong`);return s?o.toBytes():xi(o.chunks[0])}}return o.reset(),ja(o,i,e,t),o.toBytes(!0)}function Ti(r,e){return e=Object.assign({},ID,e),UD(e)?(Kh.reset(),C4(Kh,r,e,void 0),Kh.toBytes(!0)):Hh(r,Ai,e)}var $D={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Vh=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=Sn[e];if(t===void 0){let n=H[e];if(!n)throw new Error(`${q} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let s=e&31;t=n(this.data,this._pos,s,this.options)}return this._pos+=t.encodedLength,t}},uo=Symbol.for("DONE"),Xa=Symbol.for("BREAK");function KD(r,e,t){let n=[];for(let s=0;s<r.value;s++){let o=fo(e,t);if(o===Xa){if(r.value===1/0)break;throw new Error(`${q} got unexpected break to lengthed array`)}if(o===uo)throw new Error(`${q} found array but not enough entries (got ${s}, expected ${r.value})`);n[s]=o}return n}function HD(r,e,t){let n=t.useMaps===!0,s=t.rejectDuplicateMapKeys===!0,o=n?void 0:{},i=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=fo(e,t);if(c===Xa){if(r.value===1/0)break;throw new Error(`${q} got unexpected break to lengthed map`)}if(c===uo)throw new Error(`${q} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${q} non-string keys not supported (got ${typeof c})`);if(s&&(n&&i.has(c)||!n&&Object.hasOwn(o,c)))throw new Error(`${q} found repeat map key "${c}"`);let l=fo(e,t);if(l===uo)throw new Error(`${q} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?i.set(c,l):c==="__proto__"?Object.defineProperty(o,c,{value:l,configurable:!0,enumerable:!0,writable:!0}):o[c]=l}return n?i:o}function*VD(r,e,t){for(let n=0;n<r.value;n++){let s=fo(e,t);if(s===Xa){if(r.value===1/0)break;throw new Error(`${q} got unexpected break to lengthed map`)}if(s===uo)throw new Error(`${q} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let o=fo(e,t);if(o===uo)throw new Error(`${q} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[s,o]}}function qD(r,e){let t=function(){if(t._called)throw new Error(`${q} tag decode() may only be called once`);t._called=!0;let n=fo(r,e);if(n===uo)throw new Error(`${q} tag content missing`);if(n===Xa)throw new Error(`${q} got unexpected break in tag content`);return n};return t.entries=function(){if(t._called)throw new Error(`${q} tag decode() may only be called once`);t._called=!0;let n=r.next();if(!w.equals(n.type,w.map))throw new Error(`${q} entries() requires map content, got ${n.type.name}`);let s=[];for(let o of VD(n,r,e))s.push(o);return s},t._called=!1,t}function fo(r,e){if(r.done())return uo;let t=r.next();if(w.equals(t.type,w.break))return Xa;if(t.type.terminal)return t.value;if(w.equals(t.type,w.array))return KD(t,r,e);if(w.equals(t.type,w.map))return HD(t,r,e);if(w.equals(t.type,w.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=qD(r,e),s=e.tags[t.value](n);if(!n._called)throw new Error(`${q} tag decoder must call decode() or entries()`);return s}throw new Error(`${q} tag not supported (${t.value})`)}throw new Error("unsupported")}function k4(r,e){if(!(r instanceof Uint8Array))throw new Error(`${q} data to decode must be a Uint8Array`);e=Object.assign({},$D,e);let t=xi(r),n=e.tokenizer||new Vh(t,e),s=fo(n,e);if(s===uo)throw new Error(`${q} did not find any content to decode`);if(s===Xa)throw new Error(`${q} got unexpected break`);return[s,r.subarray(n.pos())]}function An(r,e){let[t,n]=k4(r,e);if(n.length>0)throw new Error(`${q} too many terminals, data makes no sense`);return t}var qh=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(qh.prototype,Symbol.toStringTag,{value:"Tagged"});var zh=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Qa=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Wh=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},du=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Gh(r){return r[Symbol.asyncIterator]!=null}function _9(r,e){if(r.byteLength>e)throw new Qa("Message length too long")}var Yh=r=>{let e=Te(r),t=it(e);return Xt(r,t),Yh.bytes=e,t};Yh.bytes=0;function xs(r,e){e=e??{};let t=e.lengthEncoder??Yh,n=e?.maxDataLength??4194304;function*s(o){_9(o,n);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return Gh(r)?(async function*(){for await(let o of r)yield*s(o)})():(function*(){for(let o of r)yield*s(o)})()}xs.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Yh,n=e?.maxDataLength??4194304;return _9(r,n),new V(t(r.byteLength),r)};var Ii;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ii||(Ii={}));var _4=r=>{let e=Br(r);return _4.bytes=Te(e),e};_4.bytes=0;function Ci(r,e){let t=new V,n=Ii.LENGTH,s=-1,o=e?.lengthDecoder??_4,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ii.LENGTH)try{if(s=o(t),s<0)throw new zh("Invalid message length");if(s>a)throw new Qa("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(s),n=Ii.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Wh("Message length length too long");break}throw l}if(n===Ii.DATA){if(t.byteLength<s)break;let l=t.sublist(0,s);t.consume(s),e?.onData!=null&&e.onData(l),yield l,n=Ii.LENGTH}}}return Gh(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new du("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new du("Unexpected end of input")})()}Ci.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Ci(n,{...e??{},onLength:o=>{t=o}})};function Xh(r,e){if(typeof r=="string")return WD(r);if(typeof r=="number")return YD(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function WD(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,s=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return s*315576e5;case"months":case"month":case"mo":return s*26298e5;case"weeks":case"week":case"w":return s*6048e5;case"days":case"day":case"d":return s*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return s*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return s*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return s*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:throw new Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function GD(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function jD(r){let e=Math.abs(r);return e>=315576e5?ki(r,e,315576e5,"year"):e>=26298e5?ki(r,e,26298e5,"month"):e>=6048e5?ki(r,e,6048e5,"week"):e>=864e5?ki(r,e,864e5,"day"):e>=36e5?ki(r,e,36e5,"hour"):e>=6e4?ki(r,e,6e4,"minute"):e>=1e3?ki(r,e,1e3,"second"):`${r} ms`}function YD(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?jD(r):GD(r)}function ki(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}function P4(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=i,t.humanize=Xh,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let f,h=null,p,g;function y(...m){if(!y.enabled)return;let b=y,E=Number(new Date),S=E-(f||E);b.diff=S,b.prev=f,b.curr=E,f=E,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let T=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(k,O)=>{if(k==="%%")return"%";T++;let N=t.formatters[O];if(typeof N=="function"){let K=m[T];k=N.call(b,K),m.splice(T,1),T--}return k}),t.formatArgs.call(b,m),d?.onLog!=null&&d.onLog(...m),(b.log||t.log).apply(b,m)}return y.namespace=u,y.useColors=t.useColors(),y.color=t.selectColor(u),y.extend=n,y.destroy=t.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,g=t.enabled(u)),g),set:m=>{h=m}}),typeof t.init=="function"&&t.init(y),y}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,f=(typeof u=="string"?u:"").split(/[\s,]+/),h=f.length;for(d=0;d<h;d++)f[d]&&(u=f[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let d,f;for(d=0,f=t.skips.length;d<f;d++)if(t.skips[d].test(u))return!1;for(d=0,f=t.names.length;d<f;d++)if(t.names[d].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var Qh=rN(),XD=["#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 QD(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function ZD(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Xh(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}var JD=console.debug??console.log??(()=>{});function eN(r){try{r?Qh?.setItem("debug",r):Qh?.removeItem("debug")}catch{}}function tN(){let r;try{r=Qh?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function rN(){try{return localStorage}catch{}}function nN(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var L9=P4({formatArgs:ZD,save:eN,load:tN,useColors:QD,setupFormatters:nN,colors:XD,storage:Qh,log:JD});var et=L9;et.formatters.b=r=>r==null?"undefined":Se.baseEncode(r);et.formatters.t=r=>r==null?"undefined":xt.baseEncode(r);et.formatters.m=r=>r==null?"undefined":We.baseEncode(r);et.formatters.p=r=>r==null?"undefined":r.toString();et.formatters.c=r=>r==null?"undefined":r.toString();et.formatters.k=r=>r==null?"undefined":r.toString();et.formatters.a=r=>r==null?"undefined":r.toString();function R9(r,e=""){let t=D9(r.message),n=D9(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
|
|
3
3
|
`).join(`
|
|
4
4
|
${e}`)}`:`${t}
|
|
5
5
|
${e}${n.split(`
|
|
@@ -9,7 +9,7 @@ ${e}`)}`:n!=null?`${n.split(`
|
|
|
9
9
|
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function sN(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function N9(r,e=""){if(sN(r)){let t=R9(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
10
10
|
${e}${r.errors.map(n=>`${N9(n,`${e}`)}`).join(`
|
|
11
11
|
${e}`)}`):t+=`
|
|
12
|
-
${e}[Error list was empty]`,t.trim()}return R9(r,e)}et.formatters.e=r=>r==null?"undefined":N9(r);function oN(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Za(r){return{forComponent(e){return Ja(e,r)}}}function Ja(r,e){let t=oN(`${r}:trace`);return et.enabled(`${r}:trace`)&&et.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=et(`${r}:trace`,e)),Object.assign(et(r,e),{error:et(`${r}:error`,e),trace:t,newScope:n=>Ja(`${r}:${n}`,e)})}function D9(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var O9=Symbol.for("sindresorhus/unlimited-timeout#brand");function B9(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,s={[O9]:!0,id:void 0,cleared:!1,ref(){return n=!1,s.id?.ref?.(),s},unref(){return n=!0,s.id?.unref?.(),s}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return s;(!Number.isFinite(e)||e<0)&&(e=0);let o=performance.now()+e,i=a=>{s.cleared||(a<=2147483647?(s.id=globalThis.setTimeout(()=>{s.cleared||r(...t)},a),n&&s.id?.unref?.()):(s.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,o-c);i(l)},2147483647),n&&s.id?.unref?.()))};return i(e),s}function M9(r){!r||typeof r!="object"||!r[O9]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var iN=new WeakMap;function aN({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(s.reason);let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(s.reason)},u=()=>{s&&s.removeEventListener("abort",l)},d=new Promise((f,h)=>{i=()=>{u(),f(n)},a=h,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",l,{once:!0}),iN.set(d,()=>{c(o),o=null,i()}),d}}var cN=aN({setTimeout:B9,clearTimeout:M9}),U9=cN;var Jt=class extends ht{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Zh=class extends ht{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var ec=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new L4}consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new wh("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},L4=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function tc(r,e,t){let n,s,o=!1;function i(){let l={signal:s.signal},u;t?.timeout!=null&&(u=he([s.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),o=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),o=!1,!s.signal.aborted&&(n=setTimeout(i,e))})}let a=bs(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{o||(clearTimeout(n),a())},start:()=>{c||(c=!0,s=new AbortController,s.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),s?.abort(),c=!1}}}var R4=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function vt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new R4({name:e,metrics:t}):n=new Map,n}var rc=class extends ge{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Ut(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=We.encode(e.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",e),s.observers++,s.promise;let o=Ye(),i={promise:o.promise,observers:1,queryFilter:Ut(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,l=new ht({concurrency:this.maxProviders});l.addEventListener("failure",f=>{if(f.detail.job.options.provider.fallback){this.log.error("error querying fallback provider %s - %e",f.detail.job.options.provider,f.detail.error);return}if(f.detail.error.name==="NoEvictionError"){this.log.error("no-eviction error querying provider %s - %e",f.detail.job.options.provider,f.detail.error);return}this.log.error("error querying provider %s, evicting from session - %e",f.detail.job.options.provider,f.detail.error),this.evict(f.detail.job.options.provider)}),l.addEventListener("success",f=>{c=!0,o.resolve(f.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let f=0;f<this.minProviders&&this.providers.length!==0;f++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];h.fallback||(this.log("evicting %s to make room for more providers",h),this.evict(h))}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(f=>{this.log.error("could not find new providers for %c - %e",e,f),o.reject(f)})});let u=f=>{let h=this.toFilterKey(f.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,f.detail,t),l.add(async()=>this.queryProvider(e,f.detail,t),{provider:f.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,p)}))};if(this.addEventListener("provider",u),a)try{await be(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(f){throw a&&this.log("failed to find initial session peers for %c - %e",e,f),this.requests.delete(n),i.observers>1&&o.reject(f),f}Promise.all([...this.providers].filter(f=>{let h=this.toFilterKey(f),p=i.queryFilter.has(h);return p||i.queryFilter.add(this.toFilterKey(f)),!p}).map(async f=>l.add(async()=>this.queryProvider(e,f,t),{provider:f}))).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,f)});let d=()=>{o.reject(new jt(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",d);try{return await o.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",d),l.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let s=Ye(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let u=await i.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",o,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),o++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",o,t,this.providers.length),this.providers.length<t)throw new Kl(`Found ${o} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),s.reject(i)}),s.promise}};var Jh=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},fu=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},e1=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},vs=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},t1=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},r1=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},hu=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};function lN(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var nc=lN;function uN(r){return r[Symbol.asyncIterator]!=null}function dN(r,e){let t=0;if(uN(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=nc(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var Hr=dN;function fN(r){return r[Symbol.asyncIterator]!=null}function hN(r){if(fN(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=Ke([n,s],n.length+s.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ke(e,t)}var n1=hN;function s1({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*pN(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let s=[...r,t],o=$.asCID(n);o!=null?yield[s.join("/"),o]:typeof n=="object"&&(yield*D4(n,s))}else{let t=$.asCID(e);t!=null?yield[r.join("/"),t]:yield*D4(e,r)}}function*D4(r,e){if(r==null||r instanceof Uint8Array)return;let t=$.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,s]of Object.entries(r)){let o=[...e,n];yield*pN(o,s)}}function*mN(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let s=[...r,t];yield s.join("/"),typeof n=="object"&&$.asCID(n)==null&&(yield*N4(n,s))}else yield*N4(e,r)}function*N4(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let s=[...e,t];yield s.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&$.asCID(n)==null&&(yield*mN(s,n))}}function gN(r,e){let t=r;for(let[n,s]of e.entries()){if(t=t[s],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(i=>`[${JSON.stringify(i)}]`).join("")}`);let o=$.asCID(t);if(o!=null)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var O4=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:s1(),bytes:s1(),value:s1(),asBlock:s1()})}links(){return D4(this.value,[])}tree(){return N4(this.value,[])}get(e="/"){return gN(this.value,e.split("/").filter(Boolean))}};function F9({bytes:r,cid:e,value:t,codec:n}){let s=t!==void 0?t:n?.decode(r);if(s===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new O4({cid:e,bytes:r,value:s})}function U4(r){return e=>new M4(e,r)}var B4=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),s=Hr(n.toGenerator(t),c=>c!=null),o=!1,i=t?.depth??1/0,a=async c=>{let l=c.cid,u=await n1(this.components.blockstore.get(l,c)),d=F9({cid:l,bytes:u,codec:await this.components.getCodec(l.code)});if(c.depth<i)for(let[,f]of d.links())t?.includeChild?.(f,d)!==!1&&n.add(a,{...c,cid:f,depth:c.depth+1,path:[...c.path,f]}).catch(h=>{o||s.throw(h)});return{block:d,depth:c.depth,path:c.path}};n.add(a,{...t,cid:e,depth:0,path:[e]}).catch(c=>{o||s.throw(c)});try{yield*s}finally{o=!0,n.abort()}}},M4=class extends B4{getQueue(){return new ht({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}};function sc(r){return r==null?!1:$.asCID(r)!=null}function ho(r){return r?.then!=null}var $9="1.2.840.10045.3.1.7",K9="1.3.132.0.34",H9="1.3.132.0.35";async function V9(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function q9(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,re(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function z9(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,re(e),re(t.subarray()));return n?.signal?.throwIfAborted(),o}var yN=parseInt("11111",2),F4=parseInt("10000000",2),wN=parseInt("01111111",2),W9={0:pu,1:pu,2:bN,3:vN,4:SN,5:xN,6:EN,16:pu,22:pu,48:pu};function nn(r,e={offset:0}){let t=r[e.offset]&yN;if(e.offset++,W9[t]!=null)return W9[t](r,e);throw new Error("No decoder for tag "+t)}function mu(r,e){let t=0;if((r[e.offset]&F4)===F4){let n=r[e.offset]&wN,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");s+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(s,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function pu(r,e){mu(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=nn(r,e);if(n===null)break;t.push(n)}return t}function bN(r,e){let t=mu(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function EN(r,e){let t=mu(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function xN(r,e){return e.offset++,null}function vN(r,e){let t=mu(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function SN(r,e){let t=mu(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function AN(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new V;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function o1(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=AN(r.byteLength);return new V(Uint8Array.from([e.byteLength|F4]),e)}function pr(r){let e=new V,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new V(Uint8Array.from([2]),o1(e),e)}function gu(r){let e=Uint8Array.from([0]),t=new V(e,r);return new V(Uint8Array.from([3]),o1(t),t)}function G9(r){return new V(Uint8Array.from([4]),o1(r),r)}function Tn(r,e=48){let t=new V;for(let n of r)t.append(n);return new V(Uint8Array.from([e]),o1(t),t)}var TN=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),IN=Uint8Array.from([6,5,43,129,4,0,34]),CN=Uint8Array.from([6,5,43,129,4,0,35]),j9={ext:!0,kty:"EC",crv:"P-256"},Y9={ext:!0,kty:"EC",crv:"P-384"},X9={ext:!0,kty:"EC",crv:"P-521"},oc=32,ic=48,ac=66;function Q9(r){let e=nn(r);return $4(e)}function $4(r){let e=r[1],t=_(e,"base64url"),n=r[2][1][0],s=1,o,i;if(e.byteLength===oc)return o=_(n.subarray(s,s+oc),"base64url"),i=_(n.subarray(s+oc),"base64url"),new Pi({...j9,key_ops:["sign"],d:t,x:o,y:i});if(e.byteLength===ic)return o=_(n.subarray(s,s+ic),"base64url"),i=_(n.subarray(s+ic),"base64url"),new Pi({...Y9,key_ops:["sign"],d:t,x:o,y:i});if(e.byteLength===ac)return o=_(n.subarray(s,s+ac),"base64url"),i=_(n.subarray(s+ac),"base64url"),new Pi({...X9,key_ops:["sign"],d:t,x:o,y:i});throw new v(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function K4(r){let e=nn(r);return Z9(e)}function Z9(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===oc*2+1)return n=_(e.subarray(t,t+oc),"base64url"),s=_(e.subarray(t+oc),"base64url"),new _i({...j9,key_ops:["verify"],x:n,y:s});if(e.byteLength===ic*2+1)return n=_(e.subarray(t,t+ic),"base64url"),s=_(e.subarray(t+ic),"base64url"),new _i({...Y9,key_ops:["verify"],x:n,y:s});if(e.byteLength===ac*2+1)return n=_(e.subarray(t,t+ac),"base64url"),s=_(e.subarray(t+ac),"base64url"),new _i({...X9,key_ops:["verify"],x:n,y:s});throw new v(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function J9(r){return Tn([pr(Uint8Array.from([1])),G9(A(r.d??"","base64url")),Tn([tE(r.crv)],160),Tn([gu(new V(Uint8Array.from([4]),A(r.x??"","base64url"),A(r.y??"","base64url")))],161)]).subarray()}function eE(r){return Tn([pr(Uint8Array.from([1])),Tn([tE(r.crv)],160),Tn([gu(new V(Uint8Array.from([4]),A(r.x??"","base64url"),A(r.y??"","base64url")))],161)]).subarray()}function tE(r){if(r==="P-256")return TN;if(r==="P-384")return IN;if(r==="P-521")return CN;throw new v(`Invalid curve ${r}`)}async function rE(r="P-256"){let e=await V9(r);return new Pi(e.privateKey)}var _i=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=eE(this.jwk)),this._raw}toMultihash(){return ot.digest(St(this))}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}async verify(e,t,n){return z9(this.jwk,t,e,n)}},Pi=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new _i({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=J9(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}async sign(e,t){return q9(this.jwk,e,t)}};var i1=BigInt(4294967295),nE=BigInt(32);function kN(r,e=!1){return e?{h:Number(r&i1),l:Number(r>>nE&i1)}:{h:Number(r>>nE&i1)|0,l:Number(r&i1)|0}}function sE(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=kN(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var _N=r=>r/2**32|0,PN=r=>r>>>0;function oE(r,e,t,n){let s=_N(t),o=PN(t);r.setUint32(e,n?o:s,n),r.setUint32(e+4,n?s:o,n)}var H4=(r,e,t)=>r>>>t,V4=(r,e,t)=>r<<32-t|e>>>t,Li=(r,e,t)=>r>>>t|e<<32-t,Ri=(r,e,t)=>r<<32-t|e>>>t,yu=(r,e,t)=>r<<64-t|e>>>t-32,wu=(r,e,t)=>r>>>t-32|e<<64-t;function zn(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var iE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),aE=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,cE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),lE=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,uE=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),dE=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;function a1(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var q4=r=>r?`"${r}" `:"";function Ht(r,e=""){if(typeof r!="number")throw new TypeError(q4(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(q4(e)+"expected integer >= 0, got "+r);return r}function er(r,e,t=""){if(a1(r)&&(e===void 0||r.length===e))return r;e!==void 0&&Ht(e,"length");let n=a1(r),s=e!==void 0?` of length ${e}`:"",o=n?`length=${r.length}`:`type=${typeof r}`,i=q4(t)+"expected Uint8Array"+s+", got "+o;throw n?new RangeError(i):new TypeError(i)}function Ss(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Ht(r.outputLen),Ht(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var RN=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},fE=(r,e)=>{RN(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function cc(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function c1(r,e){er(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function wt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function lc(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function In(r,e){return r<<32-e|r>>>e}function l1(r,e){return r<<e|r>>>32-e>>>0}var pE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",DN=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function u1(r){if(er(r),pE)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=DN[r[t]];return e}function hE(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function d1(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(pE)try{return Uint8Array.fromHex(r)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=hE(r.charCodeAt(o)),a=hE(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function NN(r){let e=globalThis;if(typeof e.scheduler?.yield=="function"){let t=e.scheduler.yield();return r&&t.catch(r),t}return new Promise(t=>e.setTimeout(t,0))}async function mE(r,e,t,n){if(Ht(r,"iters"),Ht(e,"tick"),typeof t!="function")throw new TypeError("callback must be a function");let s=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-s;i>=0&&i<e||(await NN(n),s=Date.now())}}function ON(r){if(typeof r!="string")throw new TypeError("string expected");let e=new TextEncoder().encode(r);try{return new Uint8Array(e)}finally{wt(e)}}function z4(r,e=""){return typeof r=="string"?ON(r):er(r,void 0,e)}function W4(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];er(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function G4(r,e,t="opts"){return fE(r,"defaults"),e!==void 0&&fE(e,t),Object.assign(Object.create(null),r,e)}function bu(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=G4({},e,"info");let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function gE(r=32){Ht(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var j4=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function f1(r,e,t){return r&e^~r&t}function h1(r,e,t){return r&e^r&t^e&t}var Di=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=lc(this.buffer)}update(e){cc(this),er(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length,i=!1;for(let a=0;a<o;){let c=Math.min(s-this.pos,o-a);if(c===s){let l=lc(e);for(;s<=o-a;a+=s)this.process(l,a);i=!0;continue}n.set(a===0&&c===o?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===s&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){cc(this),c1(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>s-i&&(this.process(n,0),t.fill(0)),oE(n,s-8,this.length*8,o),this.process(n,0),this.roundClean();let a=e===t?n:lc(e),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},yE=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var wE=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var BN=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),po=new Uint32Array(64),Y4=class extends Di{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)po[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=po[d-15],h=po[d-2],p=In(f,7)^In(f,18)^f>>>3,g=In(h,17)^In(h,19)^h>>>10;po[d]=g+po[d-7]+p+po[d-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=In(a,6)^In(a,11)^In(a,25),h=u+f+f1(a,c,l)+BN[d]+po[d]|0,g=(In(n,2)^In(n,13)^In(n,22))+h1(n,s,o)|0;u=l,l=c,c=a,a=i+h|0,i=o,o=s,s=n,n=h+g|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){wt(po)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),wt(this.buffer)}},X4=class extends Y4{constructor(){super(32,yE)}};var bE=sE(["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))),MN=bE[0],UN=bE[1],mo=new Uint32Array(80),go=new Uint32Array(80),Q4=class extends Di{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:g,Hl:y}=this;return[e,t,n,s,o,i,a,c,l,u,d,f,h,p,g,y]}set(e,t,n,s,o,i,a,c,l,u,d,f,h,p,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let E=0;E<16;E++,t+=4)mo[E]=e.getUint32(t),go[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let S=mo[E-15]|0,T=go[E-15]|0,C=Li(S,T,1)^Li(S,T,8)^H4(S,T,7),k=Ri(S,T,1)^Ri(S,T,8)^V4(S,T,7),O=mo[E-2]|0,N=go[E-2]|0,K=Li(O,N,19)^yu(O,N,61)^H4(O,N,6),ee=Ri(O,N,19)^wu(O,N,61)^V4(O,N,6),J=cE(k,ee,go[E-7],go[E-16]),ie=lE(J,C,K,mo[E-7],mo[E-16]);mo[E]=ie|0,go[E]=J|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:g,Gl:y,Hh:m,Hl:b}=this;for(let E=0;E<80;E++){let S=Li(d,f,14)^Li(d,f,18)^yu(d,f,41),T=Ri(d,f,14)^Ri(d,f,18)^wu(d,f,41),C=d&h^~d&g,k=f&p^~f&y,O=uE(b,T,k,UN[E],go[E]),N=dE(O,m,S,C,MN[E],mo[E]),K=O|0,ee=Li(n,s,28)^yu(n,s,34)^yu(n,s,39),J=Ri(n,s,28)^wu(n,s,34)^wu(n,s,39),ie=n&o^n&a^o&a,M=s&i^s&c^i&c;m=g|0,b=y|0,g=h|0,y=p|0,h=d|0,p=f|0,{h:d,l:f}=zn(l|0,u|0,N|0,K|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let G=iE(K,J,M);n=aE(G,N,ee,ie),s=G|0}({h:n,l:s}=zn(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=zn(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=zn(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=zn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=zn(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=zn(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:y}=zn(this.Gh|0,this.Gl|0,g|0,y|0),{h:m,l:b}=zn(this.Hh|0,this.Hl|0,m|0,b|0),this.set(n,s,o,i,a,c,l,u,d,f,h,p,g,y,m,b)}roundClean(){wt(mo,go)}destroy(){this.destroyed=!0,wt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Z4=class extends Q4{constructor(){super(64,wE)}};var tr=bu(()=>new X4,j4(1));var As=bu(()=>new Z4,j4(3));function m1(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var Pe=(r,e,t)=>er(r,e,t),J4=Ht;function xE(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function yo(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function Ni(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var Eu=u1,sn=(...r)=>W4(...r),uc=r=>d1(r),bo=a1,Ts=r=>gE(r),p1=BigInt(0),EE=BigInt(1),FN=r=>r?`"${r}" `:"";function Ir(r,e=""){if(typeof r!="boolean")throw new TypeError(FN(e)+"expected boolean, got type="+typeof r);return r}function g1(r){if(typeof r=="bigint"){if(!wo(r))throw new RangeError("positive bigint expected, got "+r)}else J4(r);return r}function Is(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function xu(r){let e=g1(r).toString(16);return e.length&1?"0"+e:e}function vE(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?p1:BigInt("0x"+r)}function Wn(r){return vE(u1(r))}function Gn(r){return vE(u1(Eo(er(r)).reverse()))}function y1(r,e){if(Ht(e),e===0)throw new Error("zero output length is invalid");r=g1(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return d1(n.padStart(t,"0"))}function vu(r,e){return y1(r,e).reverse()}function Eo(r){return Uint8Array.from(Pe(r))}function wo(r){return typeof r=="bigint"&&p1<=r}function ey(r,e,t){return wo(r)&&wo(e)&&wo(t)&&e<=r&&r<t}function jn(r,e,t,n){if(!ey(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function dc(r){if(r<p1)throw new Error("expected non-negative bigint, got "+r);return r===p1?0:r.toString(2).length}var Su=r=>(Is(r,"n"),(EE<<BigInt(r))-EE);function SE(r,e,t){if(Ht(r,"hashLen"),Ht(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},f=(...y)=>t(l,sn(c,...y)),h=(y=s)=>{l=f(o,y),c=f(),y.length!==0&&(l=f(i,y),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,m=[];for(;y<e;){c=f();let b=c.slice();m.push(b),y+=c.length}return sn(...m)};return(y,m)=>{d(),h(y);let b;for(;(b=m(p()))===void 0;)h();return d(),b}}function rr(r,e={},t={},n="object"){yo(r,n),yo(e,"fields"),yo(t,"optFields");function s(i,a,c){let l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,u=r[i];if(!Object.hasOwn(r,i)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&u===void 0)return;let d=typeof u;if(d!==a||u===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let o=(i,a)=>Object.entries(i).forEach(([c,l])=>s(c,l,a));o(e,!1),o(t,!0)}var _t=BigInt(0),$e=BigInt(1),xo=BigInt(2),IE=BigInt(3),ty=BigInt(4),CE=BigInt(5),$N=BigInt(7),kE=BigInt(8),KN=BigInt(9),HN=BigInt(15),_E=BigInt(16),VN=BigInt("0x10000000000000000");function He(r,e){if(e<=_t)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=_t?t:e+t}function PE(r,e,t){if(t<=$e)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<_t)throw new Error("invalid exponent, negatives unsupported");if(e===_t)return $e;if(e===$e)return r;let n=r%t;if(n<_t&&(n+=t),e<VN){let a=$e;for(;e>_t;)e&$e&&(a=a*n%t),n=n*n%t,e>>=$e;return a}let s=[];for(;e>_t;)s.push(Number(e&HN)),e>>=ty;let o=new Array(16);o[0]=$e,o[1]=n;for(let a=2;a<16;a++)o[a]=o[a-1]*n%t;let i=o[s[s.length-1]];for(let a=s.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=s[a];c!==0&&(i=i*o[c]%t)}return i}function tt(r,e,t){if(t<=$e)throw new Error("pow2: expected modulus > 1, got "+t);if(e<_t)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >_t;)n*=n,n%=t;return n}function AE(r,e){if(r===_t)throw new Error("invert: expected non-zero number");if(e<=$e)throw new Error("invert: expected modulus > 1, got "+e);let t=He(r,e),n=e,s=_t,o=$e;for(;t!==_t;){let a=n/t,c=n-t*a,l=s-o*a;n=t,t=c,s=o,o=l}if(n!==$e)throw new Error("invert: does not exist");return He(s,e)}function LE(r,e){if(e<=$e)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=He(r,e);if(t===_t)throw new Error("invertCt: expected non-zero number");let n=PE(t,e-xo,e);if(He(t*n,e)!==$e)throw new Error("invertCt: does not exist");return n}function ry(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function ny(r,e){if((r&$e)===_t)throw new Error(e+": expected odd modulus, got "+r)}function RE(r,e){let t=r,n=(t.ORDER+$e)/ty,s=t.pow(e,n);return ry(t,s,e),s}function qN(r,e){let t=r,n=(t.ORDER-CE)/kE,s=t.mul(e,xo),o=t.pow(s,n),i=t.mul(e,o),a=t.mul(t.mul(i,xo),o),c=t.mul(i,t.sub(a,t.ONE));return ry(t,c,e),c}function zN(r){let e=hc(r),t=DE(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+$N)/_E;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,n),f=l.mul(u,s),h=l.mul(u,o),p=l.eql(l.sqr(d),c),g=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,g);let y=l.eql(l.sqr(d),c),m=l.cmov(u,d,y);return ry(l,m,c),m})}function DE(r){if(r<IE)throw new Error("sqrt is not defined for small field");ny(r,"tonelliShanks");let e=r-$e,t=0;for(;e%xo===_t;)e/=xo,t++;let n=xo,s=hc(r);for(;Au(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return RE;let o=s.pow(n,e),i=(e+$e)/xo;return function(c,l){let u=c;if(u.is0(l))return l;if(Au(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,o),h=u.pow(l,e),p=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=u.sqr(h);for(;!u.eql(y,u.ONE);)if(g++,y=u.sqr(y),g===d)throw new Error("Cannot find square root");let m=$e<<BigInt(d-g-1),b=u.pow(f,m);d=g,f=u.sqr(b),h=u.mul(h,f),p=u.mul(p,b)}return p}}function WN(r){return ny(r,"Fp.sqrt"),r%ty===IE?RE:r%kE===CE?qN:r%_E===KN?zN(r):DE(r)}var NE=(r,e)=>(He(r,e)&$e)===$e,GN=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function fc(r){if(yo(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);Is(r.BYTES,"BYTES"),Is(r.BITS,"BITS");for(let e of GN)Ni(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=$e)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function b1(r,e,t=!1){fc(r),m1(e,"nums"),Ir(t,"passZero");let n=r,s=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((a,c,l)=>n.is0(c)?a:(s[l]=a,n.mul(a,c)),n.ONE),i=n.inv(o);return e.reduceRight((a,c,l)=>n.is0(c)?a:(s[l]=n.mul(a,s[l]),n.mul(a,c)),i),s}function Au(r,e){fc(r);let t=r;ny(t.ORDER,"FpLegendre");let n=(t.ORDER-$e)/xo,s=t.pow(e,n),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function jN(r,e){if(e!==void 0&&J4(e),r<=_t)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=dc(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var TE=new WeakMap,w1=class{ORDER;BITS;BYTES;isLE;ZERO=_t;ONE=$e;_lengths;_mod;constructor(e,t={}){if(e<=$e)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=jN(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return He(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return _t<=e&&e<this.ORDER}is0(e){return e===_t}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&$e)===$e}neg(e){return He(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return He(e*e,this.ORDER)}add(e,t){return He(e+t,this.ORDER)}sub(e,t){return He(e-t,this.ORDER)}mul(e,t){return He(e*t,this.ORDER)}pow(e,t){return PE(e,t,this.ORDER)}div(e,t){return He(e*AE(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return AE(e,this.ORDER)}sqrt(e){let t=TE.get(this);return t||TE.set(this,t=WN(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?vu(e,this.BYTES):y1(e,this.BYTES)}fromBytes(e,t=!1){Pe(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?Gn(e):Wn(e);if(a&&(c=He(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return b1(this,e,!0)}cmov(e,t,n){return Ir(n,"condition"),n?t:e}};function hc(r,e={}){return Object.freeze(w1.prototype),new w1(r,e)}function OE(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=$e)throw new Error("field order must be greater than 1");let e=dc(r-$e);return Math.ceil(e/8)}function E1(r){let e=OE(r);return e+Math.ceil(e/2)}function x1(r,e,t=!1){Pe(r);let n=r.length,s=OE(e),o=Math.max(E1(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?Gn(r):Wn(r),a=He(i,e-$e)+$e;return t?vu(a,s):y1(a,s)}var iy=BigInt(0),Tu=BigInt(1),YN=BigInt(4),sy=16,BE=128,XN=5,ME=2**31;function vo(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);Ni(e.fromAffine,"Point.fromAffine"),Ni(e.fromBytes,"Point.fromBytes"),Ni(e.fromHex,"Point.fromHex"),yo(e.BASE,"Point.BASE"),yo(e.ZERO,"Point.ZERO"),fc(e.Fp),fc(e.Fn)}function v1(r,e){vo(r),FE(e,r);let t=b1(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function QN(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function ZN(r,e){let t=r*(4*e+128);if(t>ME)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+ME/2**20+" MiB")}function ay(r,e){if(r!==void 0){Ni(r,"randomBytes");try{let t=r(e);if(!bo(t)||t.length!==e)return}catch{return}return r}}function FE(r,e){m1(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function JN(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,s)=>{if(!(t===void 0?e.isValid(n):wo(n)&&n<t))throw new Error("invalid scalar at index "+s)})}var $E=new WeakMap;function oy(r){return $E.get(r)||1}function eO(r,e){let t=r.double(),n=[r];for(let s=1;s<e;s++)n.push(n[s-1].add(t));return n}function tO(r,e){let t=2**e,n=t/2,s=BigInt(t-1),o=[];for(;r>iy;){let i=0;r&Tu&&(i=Number(r&s),i>=n&&(i-=t),r-=BigInt(i)),o.push(i),r>>=Tu}return o}function rO(r,e,t){let n=2**e,s=n/2,o=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let l=Number(r&o);r>>=i,l>s&&(l-=n,r+=Tu),a.push(l)}if(r!==iy)throw new Error("invalid wnaf");return a}function nO(r,e,t){let n=0;for(let o of t)n=Math.max(n,o.length);let s=r;for(let o=n-1;o>=0;o--){o!==n-1&&(s=s.double());for(let i=0;i<t.length;i++){let a=t[i][o];if(a){let c=e[i][Math.abs(a)-1>>1];s=s.add(a<0?c.negate():c)}}}return s}var pc=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){vo(e),this.randomBytes=ay(t,sy),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let s=Math.ceil(n/t)+1,o=2**(t-1),i=[],a=e;for(let c=0;c<s;c++){let l=a;for(let u=0;u<o;u++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:s,comp:i}}wnafCachedCT(e,t){let{W:n,windows:s,comp:o}=e,i=2**(n-1),a=rO(t,n,s),c=this.ZERO,l=this.BASE;for(let u=0;u<s;u++){let d=a[u],f=u*i,h=Math.abs(d)-1,p=o[f];for(let y=1;y<i;y++)p=y===h?o[f+y]:p;let g=p.negate();d===0?l=l.add(o[f]):c=c.add(d<0?g:p)}return{p:c,f:l}}getWnafPrecomputes(e,t,n,s){let o=this.wnafPrecomputes.get(t),i=o?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof s=="function"&&(i={...i,comp:s(i.comp)}),o||(o=[],this.wnafPrecomputes.set(t,o)),o.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!ey(t,Tu,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,s){let o=oy(e);return o===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(o,e,n,s),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let s=this.Point.Fn.BITS+BE,o=this.randomBytes(sy);if(!bo(o)||o.length!==sy)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+Wn(o)*this.Point.Fn.ORDER;return this.runCT(e,i,s,n)}fixedWindowCT(e,t,n){let s=XN,o=1<<s,i=Su(s),a=new Array(o);a[0]=this.ZERO;for(let u=1;u<o;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/s),l=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let h=0;h<s;h++)l=l.double();let d=Number(t>>BigInt(u*s)&i),f=a[0];for(let h=1;h<o;h++)f=h===d?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Tu?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,s){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,s):this.mulCT(e,t,s)}mulUnsafe(e,t,n){if(this.assertPoint(e),!wo(t))throw new Error("invalid scalar");let s=oy(e);if(s===1||t>=this.Point.Fn.ORDER)return S1(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(s,e,this.bits,n);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),QN(t,this.bits);let n=Math.ceil((this.bits+BE)/t)+1;ZN(n*2**(t-1),this.Point.Fp.BYTES),$E.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return oy(e)!==1}};function S1(r,e,t,n=!1){if(vo(r),FE(e,r),Ir(n,"allowOversized"),JN(t,r.Fn,n?r.Fn.ORDER**YN:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let s=e.map(i=>eO(i,4)),o=t.map(i=>tO(i,4));return nO(r.ZERO,s,o)}function UE(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return fc(e),e}else return hc(r,{isLE:t})}function A1(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);rr(t);for(let c of["p","n","h"]){let l=e[c];if(!(wo(l)&&l!==iy))throw new Error(`CURVE.${c} must be positive bigint`)}let s=UE(e.p,t.Fp,n),o=UE(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function mc(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var T1=BigInt(0),I1=BigInt(1),C1=BigInt(2),sO=BigInt(4),KE=BigInt(8);function oO(r,e,t,n){let s=r.sqr(t),o=r.sqr(n),i=r.add(r.mul(e.a,s),o),a=r.add(r.ONE,r.mul(e.d,r.mul(s,o)));return r.eql(i,a)}function HE(r,e={}){rr(e,{},{},"extraOpts");let t=e,n=A1("edwards",r,t,t.FpFnLE),{Fp:s,Fn:o}=n,i=n.CURVE,{h:a}=i;if(Au(s,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Au(s,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");rr(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Ts:t.randomBytes,l=C1<<BigInt(s.BYTES*8)-I1;function u(b){if(!s.isOdd)throw new Error("Field does not have .isOdd()");return s.isOdd(b)}let d=t.uvRatio===void 0?(b,E)=>{try{return{isValid:!0,value:s.sqrt(s.div(b,E))}}catch{return{isValid:!1,value:T1}}}:t.uvRatio;if(!oO(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let f=s.eql(i.a,s.neg(s.ONE))?b=>s.neg(b):s.eql(i.a,s.ONE)?b=>b:b=>s.mul(i.a,b);function h(b,E,S=!1){let T=S?I1:T1;return jn("coordinate "+b,E,T,l),E}function p(b){if(!(b instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(i.Gx,i.Gy,s.ONE,s.mul(i.Gx,i.Gy));static ZERO=new g(s.ZERO,s.ONE,s.ONE,s.ZERO);static Fp=s;static Fn=o;X;Y;Z;T;constructor(E,S,T,C){this.X=h("x",E),this.Y=h("y",S),this.Z=h("z",T,!0),this.T=h("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(E){if(E instanceof g)throw new Error("extended point not allowed");let{x:S,y:T}=E||{};return h("x",S),h("y",T),new g(S,T,s.ONE,s.mul(S,T))}static fromBytes(E,S=!1){let T=s.BYTES,{a:C,d:k}=i;E=Eo(Pe(E,T,"point")),Ir(S,"zip215");let O=Eo(E),N=E[T-1];O[T-1]=N&-129;let K=Gn(O),ee=S?l:s.ORDER;jn("point.y",K,T1,ee);let J=s.sqr(K),ie=s.sub(J,s.ONE),M=s.sub(s.mulN(k,J),C),{isValid:G,value:U}=d(ie,M);if(!G)throw new Error("bad point: invalid y coordinate");let B=u(U),te=(N&128)!==0;if(!S&&s.is0(U)&&te)throw new Error("bad point: x=0 and x_0=1");return te!==B&&(U=s.neg(U)),g.fromAffine({x:U,y:K})}static fromHex(E,S=!1){return g.fromBytes(uc(E),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=6,S=!0){return m.setWindowSize(this,E),S||this.multiply(C1),this}assertValidity(){let E=this,{a:S,d:T}=i;if(E.is0())throw new Error("bad point: ZERO");let{X:C,Y:k,Z:O,T:N}=E,K=s.sqr(C),ee=s.sqr(k),J=s.sqr(O),ie=s.sqr(J),M=s.mul(K,S),G=s.mul(s.add(M,ee),J),U=s.add(ie,s.mul(T,s.mul(K,ee)));if(!s.eql(G,U))throw new Error("bad point: equation left != right (1)");let B=s.mul(C,k),te=s.mul(O,N);if(!s.eql(B,te))throw new Error("bad point: equation left != right (2)")}equals(E){p(E);let{X:S,Y:T,Z:C}=this,{X:k,Y:O,Z:N}=E,K=s.mul(S,N),ee=s.mul(k,C),J=s.mul(T,N),ie=s.mul(O,C);return s.eql(K,ee)&&s.eql(J,ie)}is0(){return this.equals(g.ZERO)}negate(){return new g(s.neg(this.X),this.Y,this.Z,s.neg(this.T))}double(){let{X:E,Y:S,Z:T}=this,C=s.sqr(E),k=s.sqr(S),O=s.mul(s.sqr(T),C1),N=f(C),K=s.addN(E,S),ee=s.sub(s.subN(s.sqr(K),C),k),J=s.addN(N,k),ie=s.subN(J,O),M=s.subN(N,k),G=s.mul(ee,ie),U=s.mul(J,M),B=s.mul(ee,M),te=s.mul(ie,J);return new g(G,U,te,B)}add(E){p(E);let{d:S}=i,{X:T,Y:C,Z:k,T:O}=this,{X:N,Y:K,Z:ee,T:J}=E,ie=s.mul(T,N),M=s.mul(C,K),G=s.mul(s.mulN(O,S),J),U=s.mul(k,ee),B=s.sub(s.subN(s.mulN(s.addN(T,C),s.addN(N,K)),ie),M),te=s.subN(U,G),F=s.addN(U,G),R=s.sub(M,f(ie)),x=s.mul(B,te),I=s.mul(F,R),D=s.mul(B,R),z=s.mul(te,F);return new g(x,I,z,D)}subtract(E){return p(E),this.add(E.negate())}multiply(E){if(!o.isValidNot0(E))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:T}=m.mulSecret(this,E,a,y);return y([S,T])[0]}multiplyUnsafe(E){if(!o.isValid(E))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return E===T1?g.ZERO:this.is0()||E===I1?this:m.mulUnsafe(this,E,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.mulUnsafe(this,i.n).is0()}toAffine(E){let S=this,T=E;if(T!=null&&typeof T!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof T);let{X:C,Y:k,Z:O}=S,N=S.is0();T==null&&(T=N?s.create(KE):s.inv(O));let K=s.mul(C,T),ee=s.mul(k,T),J=s.mul(O,T);if(N)return{x:s.ZERO,y:s.ONE};if(!s.eql(J,s.ONE))throw new Error("invZ was invalid");return{x:K,y:ee}}clearCofactor(){return a===I1?this:a===C1?this.double():a===sO?this.double().double():a===KE?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:E,y:S}=this.toAffine(),T=s.toBytes(S);return T[T.length-1]|=u(E)?128:0,T}toHex(){return Eu(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=b=>v1(g,b),m=new pc(g,c);return m.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function VE(r,e,t={}){if(vo(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,s=t;rr(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(Is(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=s.randomBytes===void 0?Ts:s.randomBytes,f=s.toMontgomery,h=s.toMontgomerySecret,p=s.adjustScalarBytes===void 0?M=>M:s.adjustScalarBytes,g=s.domain===void 0?(M,G,U)=>{if(Ir(U,"phflag"),G.length||U)throw new Error("Contexts/pre-hash are not supported");return M}:s.domain;function y(M){return c.create(Gn(M))}function m(M){let G=N.secretKey;Pe(M,N.secretKey,"secretKey");let U=Pe(n(M),2*G,"hashedSecretKey"),B=p(U.slice(0,G)),te=U.slice(G,2*G),F=y(B);return{head:B,prefix:te,scalar:F}}function b(M){let{head:G,prefix:U,scalar:B}=m(M),te=i.multiply(B),F=te.toBytes();return{head:G,prefix:U,scalar:B,point:te,pointBytes:F}}function E(M){return b(M).pointBytes}function S(M=Uint8Array.of(),...G){let U=sn(...G);return y(n(g(U,Pe(M,void 0,"context"),!!o)))}function T(M,G,U={}){rr(U,{},{},"options"),M=Eo(Pe(M,void 0,"message")),o&&(M=o(M));let{prefix:B,scalar:te,pointBytes:F}=b(G),R=S(U.context,B,M),x=i.multiply(R).toBytes(),I=S(U.context,x,F,M),D=c.create(R+I*te);if(!c.isValid(D))throw new Error("sign failed: invalid s");let z=sn(x,c.toBytes(D));return Pe(z,N.signature,"result")}let C={zip215:s.zip215};function k(M,G,U,B=C){rr(B);let{context:te}=B,F=B.zip215===void 0?!!C.zip215:B.zip215,R=N.signature;M=Pe(M,R,"signature"),G=Pe(G,void 0,"message"),U=Pe(U,N.publicKey,"publicKey"),F!==void 0&&Ir(F,"zip215"),o&&(G=o(G));let x=R/2,I=M.subarray(0,x),D=Gn(M.subarray(x,R)),z,Q,Z;try{z=r.fromBytes(U,F),Q=r.fromBytes(I,F),Z=i.multiplyUnsafe(D)}catch{return!1}if(!F&&z.isSmallOrder())return!1;let ne=S(te,I,U,G);return Q.add(z.multiplyUnsafe(ne)).subtract(Z).clearCofactor().is0()}let O=a.BYTES,N={secretKey:O,publicKey:O,signature:2*O,seed:O};function K(M){return M=M===void 0?d(N.seed):M,Pe(M,N.seed,"seed")}function ee(M){return bo(M)&&M.length===N.secretKey}function J(M,G){try{return!!r.fromBytes(M,G===void 0?C.zip215:G)}catch{return!1}}let ie={getExtendedPublicKey:b,randomSecretKey:K,isValidSecretKey:ee,isValidPublicKey:J,toMontgomery(M){if(f===void 0)throw new Error("Montgomery conversion is not supported for this curve");return f(r.fromBytes(M))},toMontgomerySecret(M){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(M)}};return Object.freeze(N),Object.freeze(ie),Object.freeze({keygen:mc(K,E),getPublicKey:E,sign:T,verify:k,utils:ie,Point:r,lengths:N})}var Oi=BigInt(0),on=BigInt(1),k1=BigInt(2);function qE(r,e){return r+e-(e>>on<<on)}function iO(r){let e=BigInt(6)*r;return(t,n,s)=>{let o=n+s,a=((e+s-n)*t+n)%r;return{x_2:a,x_3:o-a}}}function aO(r){return rr(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...r})}function zE(r){let e=aO(r),{P:t,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");let l=i===void 0?Ts:i,u=c?255:448,d=iO(t),f=c?32:56,h=BigInt(c?9:5),p=BigInt(c?121665:39081),g=c?k1**BigInt(254):k1**BigInt(447),y=c?BigInt(8)*(k1**BigInt(251)-on):BigInt(4)*(k1**BigInt(445)-on),m=g+y+on,b=U=>He(U,t),E=S(h);function S(U){return vu(b(U),f)}function T(U){let B=Eo(Pe(U,f,"uCoordinate"));return c&&(B[31]&=127),b(Gn(B))}function C(U){return Gn(s(Eo(Pe(U,f,"scalar"))))}let k=new Set(c?[Oi,on,t-on,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Oi,on,t-on]);function O(U,B){let te=T(B);if(k.has(te))throw new Error("invalid private or public key received");let F=J(te,C(U));if(F===Oi)throw new Error("invalid private or public key received");return S(F)}function N(U){if(a===void 0)return O(U,E);let B=C(U);jn("scalar",B,g,m);let te=b(a(B));if(te===Oi)throw new Error("invalid private or public key received");return S(te)}let K=N,ee=O;function J(U,B){jn("u",U,Oi,t),jn("scalar",B,g,m);let te=B,F=U,R=on,x=Oi,I=U,D=on,z=te^te>>on;for(let ne=BigInt(u-1);ne>=Oi;ne--){let oe=qE(t,z>>ne);({x_2:R,x_3:I}=d(oe,R,I)),{x_2:x,x_3:D}=d(oe,x,D);let Ee=R+x,ve=b(Ee*Ee),Je=R-x,ze=b(Je*Je),gt=ve-ze,xr=I+D,Xe=I-D,st=b(Xe*Ee),da=b(xr*Je),El=st+da,Xs=st-da;I=b(El*El),D=b(F*b(Xs*Xs)),R=b(ve*ze),x=b(gt*(ve+b(p*gt)))}let Q=qE(t,te);({x_2:R,x_3:I}=d(Q,R,I)),{x_2:x,x_3:D}=d(Q,x,D);let Z=o(x);return b(R*Z)}let ie={secretKey:f,publicKey:f,seed:f},M=U=>(U=U===void 0?l(f):U,Pe(U,ie.seed,"seed"),U),G={randomSecretKey:M};return Object.freeze(ie),Object.freeze(G),Object.freeze({keygen:mc(M,K),getSharedSecret:ee,getPublicKey:K,scalarMult:O,scalarMultBase:N,utils:G,GuBytes:E.slice(),lengths:ie})}var WE=BigInt(0),cy=BigInt(1),GE=BigInt(2),cO=BigInt(3),lO=BigInt(5),uO=BigInt(8),_1=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),dO={p:_1,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:uO,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function XE(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=_1,a=r*r%o*r%o,c=tt(a,GE,o)*a%o,l=tt(c,cy,o)*r%o,u=tt(l,lO,o)*l%o,d=tt(u,e,o)*u%o,f=tt(d,t,o)*d%o,h=tt(f,n,o)*f%o,p=tt(h,s,o)*h%o,g=tt(p,s,o)*h%o,y=tt(g,e,o)*u%o;return{pow_p_5_8:tt(y,GE,o)*r%o,b2:a}}function ly(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var jE=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function fO(r,e){let t=_1,n=He(e*e*e,t),s=He(n*n*e,t),o=XE(r*s).pow_p_5_8,i=He(r*n*o,t),a=He(e*i*i,t),c=i,l=He(i*jE,t),u=a===r,d=a===He(-r,t),f=a===He(-r*jE,t);return u&&(i=c),(d||f)&&(i=l),NE(i,t)&&(i=He(-i,t)),{isValid:u||d,value:i}}var Iu=HE(dO,{uvRatio:fO}),YE=Iu.Fp;function hO(r){let{y:e}=r;return YE.toBytes(YE.div(cy+e,cy-e))}function pO(r){let e=Iu.Fp.BYTES;return er(r,e),ly(As(r.subarray(0,e))).subarray(0,e)}function mO(r){return VE(Iu,As,Object.assign({adjustScalarBytes:ly,toMontgomery:hO,toMontgomerySecret:pO,zip215:!0},r))}var Cu=mO({});var Yn=(()=>{let r=_1,e=t=>{let{pow_p_5_8:n,b2:s}=XE(t);return He(tt(n,cO,r)*s,r)};return zE({P:r,type:"x25519",powPminus2:e,adjustScalarBytes:ly,scalarMultBase:t=>{let n=He(t,Iu.Fn.ORDER);if(n===WE)return WE;let s=Iu.BASE.multiply(n);return He((s.Z+s.Y)*e(He(s.Z-s.Y,r)),r)}})})();var ku=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},_u=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},P1=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var At={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new P1("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Bi=32,Vr=64,uy=32;var gc,QE=(async()=>{try{return await At.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function ZE(){let r=Cu.utils.randomSecretKey(),e=Cu.getPublicKey(r);return{privateKey:EO(r,e),publicKey:e}}async function gO(r,e){let t;r.length===Vr?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:_(r.subarray(32),"base64url"),d:_(t,"base64url"),ext:!0,key_ops:["sign"]},s=await At.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),o=await At.get().subtle.sign({name:"Ed25519"},s,re(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(o,0,o.byteLength)}function yO(r,e){let t=r.subarray(0,uy);return Cu.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function JE(r,e){return gc==null&&(gc=await QE),gc?gO(r,e):yO(r,e)}async function wO(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await At.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await At.get().subtle.verify({name:"Ed25519"},n,re(e),re(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function bO(r,e,t){return Cu.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function ex(r,e,t){return gc==null&&(gc=await QE),gc?wO(r,e,t):bO(r,e,t)}function EO(r,e){let t=new Uint8Array(Vr);for(let n=0;n<uy;n++)t[n]=r[n],t[uy+n]=e[n];return t}function yc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Pu=class{type="Ed25519";raw;constructor(e){this.raw=bc(e,Bi)}toMultihash(){return ot.digest(St(this))}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=ex(this.raw,t,e);return yc(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}},wc=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=bc(e,Vr),this.publicKey=new Pu(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=JE(this.raw,e);return yc(n)?n.then(s=>(t?.signal?.throwIfAborted(),s)):(t?.signal?.throwIfAborted(),n)}};function dy(r){if(r.length>Vr){r=bc(r,Vr+Bi);let n=r.subarray(0,Vr),s=r.subarray(Vr,r.length);return new wc(n,s)}r=bc(r,Vr);let e=r.subarray(0,Vr),t=r.subarray(Bi);return new wc(e,t)}function fy(r){return r=bc(r,Bi),new Pu(r)}async function rx(){let{privateKey:r,publicKey:e}=ZE();return new wc(r,e)}function bc(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new v(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var qe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(qe||(qe={}));var hy;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(hy||(hy={}));(function(r){r.codec=()=>at(hy)})(qe||(qe={}));var Xn;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),qe.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=qe.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:qe.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Xn||(Xn={}));var Lu;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),qe.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=qe.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:qe.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Lu||(Lu={}));var Du={};we(Du,{MAX_RSA_KEY_SIZE:()=>py,generateRSAKeyPair:()=>Sy,jwkToJWKKeyPair:()=>ix,jwkToPkcs1:()=>AO,jwkToPkix:()=>wy,jwkToRSAPrivateKey:()=>vy,pkcs1MessageToJwk:()=>gy,pkcs1MessageToRSAPrivateKey:()=>L1,pkcs1ToJwk:()=>SO,pkcs1ToRSAPrivateKey:()=>by,pkixMessageToJwk:()=>yy,pkixMessageToRSAPublicKey:()=>xy,pkixToJwk:()=>TO,pkixToRSAPublicKey:()=>Ey});var Ec=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Du.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return $.createV1(114,this._multihash)}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}verify(e,t,n){return ox(this.jwk,t,e,n)}},Ru=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Du.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}sign(e,t){return sx(this.jwk,e,t)}};var py=8192,my=18,xO=1062,vO=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function SO(r){let e=nn(r);return gy(e)}function gy(r){return{n:_(r[1],"base64url"),e:_(r[2],"base64url"),d:_(r[3],"base64url"),p:_(r[4],"base64url"),q:_(r[5],"base64url"),dp:_(r[6],"base64url"),dq:_(r[7],"base64url"),qi:_(r[8],"base64url"),kty:"RSA"}}function AO(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 v("JWK was missing components");return Tn([pr(Uint8Array.from([0])),pr(A(r.n,"base64url")),pr(A(r.e,"base64url")),pr(A(r.d,"base64url")),pr(A(r.p,"base64url")),pr(A(r.q,"base64url")),pr(A(r.dp,"base64url")),pr(A(r.dq,"base64url")),pr(A(r.qi,"base64url"))]).subarray()}function TO(r){let e=nn(r,{offset:0});return yy(e)}function yy(r){let e=nn(r[1],{offset:0});return{kty:"RSA",n:_(e[0],"base64url"),e:_(e[1],"base64url")}}function wy(r){if(r.n==null||r.e==null)throw new v("JWK was missing components");return Tn([vO,gu(Tn([pr(A(r.n,"base64url")),pr(A(r.e,"base64url"))]))]).subarray()}function by(r){let e=nn(r);return L1(e)}function L1(r){let e=gy(r);return vy(e)}function Ey(r,e){if(r.byteLength>=xO)throw new dn("Key size is too large");let t=nn(r,{offset:0});return xy(t,r,e)}function xy(r,e,t){let n=yy(r);if(t==null){let s=tr(Xn.encode({Type:qe.RSA,Data:e}));t=lr(my,s)}return new Ec(n,t)}function vy(r){if(cx(r)>py)throw new v("Key size is too large");let e=ix(r),t=tr(Xn.encode({Type:qe.RSA,Data:wy(e.publicKey)})),n=lr(my,t);return new Ru(e.privateKey,new Ec(e.publicKey,n))}async function Sy(r){if(r>py)throw new v("Key size is too large");let e=await ax(r),t=tr(Xn.encode({Type:qe.RSA,Data:wy(e.publicKey)})),n=lr(my,t);return new Ru(e.privateKey,new Ec(e.publicKey,n))}function ix(r){if(r==null)throw new v("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function ax(r,e){let t=await At.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await IO(t,e);return{privateKey:n[0],publicKey:n[1]}}async function sx(r,e,t){let n=await At.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let s=await At.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,re(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function ox(r,e,t,n){let s=await At.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await At.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,re(e),re(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),o}async function IO(r,e){if(r.privateKey==null||r.publicKey==null)throw new v("Private and public key are required");let t=await Promise.all([At.get().subtle.exportKey("jwk",r.privateKey),At.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function cx(r){if(r.kty!=="RSA")throw new v("invalid key type");if(r.n==null)throw new v("invalid key modulus");return A(r.n,"base64url").length*8}var R1=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ss(e),er(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),wt(s)}update(e){return cc(this),this.iHash.update(e),this}digestInto(e){cc(this),c1(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Mi=(()=>{let r=((e,t,n)=>new R1(e,t).update(n).digest());return r.create=(e,t)=>new R1(e,t),r})();var CO=BigInt(0),Ay=class extends Error{constructor(e=""){super(e)}},Cs={Err:Ay,_tlv:{encode:(r,e)=>{let{Err:t}=Cs;if(Is(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(xE(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=xu(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?xu(s.length/2|128):"";return xu(r)+o+s+e},decode(r,e){let{Err:t}=Cs;e=Pe(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Cs;if(g1(r),r<CO)throw new e("integer: negative integers are not allowed");let t=xu(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Cs;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Wn(r)}},toSig(r,e){let{Err:t,_int:n,_tlv:s}=Cs;if(e!==void 0&&(Is(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=Pe(r,void 0,"signature"),{v:i,l:a}=s.decode(48,o);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l}=s.decode(2,i),{v:u,l:d}=s.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||u.length>e))throw new t("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Cs;rr(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},D1=(Object.freeze(Cs._tlv),Object.freeze(Cs._int),Object.freeze(Cs));var lx=(r,e)=>(r+(r>=0?e:-e)/ux)/e;function kO(r,e,t){jn("scalar",r,ks,t);let[[n,s],[o,i]]=e,a=lx(i*r,t),c=lx(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,d=l<ks,f=u<ks;d&&(l=-l),f&&(u=-u);let h=Su(Math.ceil(dc(t)/2))+Ui;if(l<ks||l>=h||u<ks||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function Cy(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ty(r,e){rr(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ir(t.lowS,"lowS"),Ir(t.prehash,"prehash"),t.format!==void 0&&Cy(t.format),t}var ks=BigInt(0),Ui=BigInt(1),ux=BigInt(2),Iy=BigInt(3),_O=BigInt(4);function dx(r,e={}){let t=A1("weierstrass",r,e),n=t.Fp,s=t.Fn,o=t.CURVE,{h:i,n:a}=o;rr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l,clearCofactor:u,isTorsionFree:d,fromBytes:f,toBytes:h}=e,p=e.randomBytes===void 0?Ts:e.randomBytes;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=c?{beta:c.beta,basises:c.basises.map(R=>[...R])}:void 0,y=hx(n,s);function m(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function b(R,x,I){if(x.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:D,y:z}=x.toAffine(),Q=n.toBytes(D);if(Ir(I,"isCompressed"),I){m();let Z=!n.isOdd(z);return sn(fx(Z),Q)}else return sn(Uint8Array.of(4),Q,n.toBytes(z))}function E(R){Pe(R,void 0,"Point");let{publicKey:x,publicKeyUncompressed:I}=y,D=R.length,z=R[0],Q=R.subarray(1);if(l&&D===1&&z===0)return{x:n.ZERO,y:n.ZERO};if(D===x&&(z===2||z===3)){let Z=n.fromBytes(Q);if(!n.isValid(Z))throw new Error("bad point: is not on curve, wrong x");let ne=O(Z),oe;try{oe=n.sqrt(ne)}catch(Je){let ze=Je instanceof Error?": "+Je.message:"";throw new Error("bad point: is not on curve, sqrt error"+ze)}m();let Ee=n.isOdd(oe);return(z&1)===1!==Ee&&(oe=n.neg(oe)),{x:Z,y:oe}}else if(D===I&&z===4){let Z=n.BYTES,ne=n.fromBytes(Q.subarray(0,Z)),oe=n.fromBytes(Q.subarray(Z,Z*2));if(!N(ne,oe))throw new Error("bad point: is not on curve");return{x:ne,y:oe}}else throw new Error(`bad point: got length ${D}, expected compressed=${x} or uncompressed=${I}`)}let S=h===void 0?b:h,T=f===void 0?E:f,C=n.mul(o.b,Iy),k=n.is0(o.a)?R=>n.ZERO:R=>n.mul(o.a,R);function O(R){let x=n.sqr(R),I=n.mul(x,R);return n.add(n.add(I,n.mul(R,o.a)),o.b)}function N(R,x){let I=n.sqr(x),D=O(R);return n.eql(I,D)}if(!N(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let K=n.mul(n.pow(o.a,Iy),_O),ee=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(K,ee)))throw new Error("bad curve params: a or b");function J(R,x,I=!1){if(!n.isValid(x)||I&&n.is0(x))throw new Error(`bad point coordinate ${R}`);return typeof x=="object"&&x!==null?n.create(x):x}function ie(R){if(!(R instanceof B))throw new Error("Weierstrass Point expected")}function M(R){if(!g||!g.basises)throw new Error("no endo");return kO(R,g.basises,s.ORDER)}function G(R,x,I,D){if(!s.isValid(D))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:z,k1:Q,k2neg:Z,k2:ne}=M(D),oe=new B(n.mul(I.X,g.beta),I.Y,I.Z);R.push(z?I.negate():I,Z?oe.negate():oe),x.push(Q,ne)}else R.push(I),x.push(D)}let U=new WeakSet;class B{static BASE=new B(o.Gx,o.Gy,n.ONE);static ZERO=new B(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(x,I,D){this.X=J("x",x),this.Y=J("y",I,!0),this.Z=J("z",D),Object.freeze(this)}static CURVE(){return o}static fromAffine(x){let{x:I,y:D}=x||{};if(!x||!n.isValid(I)||!n.isValid(D))throw new Error("invalid affine point");if(x instanceof B)throw new Error("projective point not allowed");return n.is0(I)&&n.is0(D)?B.ZERO:new B(I,D,n.ONE)}static fromBytes(x){let I=B.fromAffine(T(Pe(x,void 0,"point")));return I.assertValidity(),I}static fromHex(x){return B.fromBytes(uc(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=6,I=!0){return F.setWindowSize(this,x),I||this.multiply(Iy),this}assertValidity(){let x=this;if(x.is0()){if(l&&n.is0(x.X)&&n.eql(x.Y,n.ONE)&&n.is0(x.Z))return;throw new Error("bad point: ZERO")}if(U.has(x))return;let{x:I,y:D}=x.toAffine();if(!n.isValid(I)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!N(I,D))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");U.add(x)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){ie(x);let{X:I,Y:D,Z:z}=this,{X:Q,Y:Z,Z:ne}=x,oe=n.eql(n.mul(I,ne),n.mul(Q,z)),Ee=n.eql(n.mul(D,ne),n.mul(Z,z));return oe&&Ee}negate(){return new B(this.X,n.neg(this.Y),this.Z)}double(){let{X:x,Y:I,Z:D}=this,z=n.ZERO,Q=n.ZERO,Z=n.ZERO,ne=n.mul(x,x),oe=n.mul(I,I),Ee=n.mul(D,D),ve=n.mul(x,I);return ve=n.add(ve,ve),Z=n.mul(x,D),Z=n.add(Z,Z),z=k(Z),Q=n.mul(C,Ee),Q=n.add(z,Q),z=n.sub(oe,Q),Q=n.add(oe,Q),Q=n.mul(z,Q),z=n.mul(ve,z),Z=n.mul(C,Z),Ee=k(Ee),ve=n.sub(ne,Ee),ve=k(ve),ve=n.add(ve,Z),Z=n.add(ne,ne),ne=n.add(Z,ne),ne=n.add(ne,Ee),ne=n.mul(ne,ve),Q=n.add(Q,ne),Ee=n.mul(I,D),Ee=n.add(Ee,Ee),ne=n.mul(Ee,ve),z=n.sub(z,ne),Z=n.mul(Ee,oe),Z=n.add(Z,Z),Z=n.add(Z,Z),new B(z,Q,Z)}add(x){ie(x);let{X:I,Y:D,Z:z}=this,{X:Q,Y:Z,Z:ne}=x,oe=n.ZERO,Ee=n.ZERO,ve=n.ZERO,Je=n.mul(I,Q),ze=n.mul(D,Z),gt=n.mul(z,ne),xr=n.add(I,D),Xe=n.add(Q,Z);xr=n.mul(xr,Xe),Xe=n.add(Je,ze),xr=n.sub(xr,Xe),Xe=n.add(I,z);let st=n.add(Q,ne);return Xe=n.mul(Xe,st),st=n.add(Je,gt),Xe=n.sub(Xe,st),st=n.add(D,z),oe=n.add(Z,ne),st=n.mul(st,oe),oe=n.add(ze,gt),st=n.sub(st,oe),ve=k(Xe),oe=n.mul(C,gt),ve=n.add(oe,ve),oe=n.sub(ze,ve),ve=n.add(ze,ve),Ee=n.mul(oe,ve),ze=n.add(Je,Je),ze=n.add(ze,Je),gt=k(gt),Xe=n.mul(C,Xe),ze=n.add(ze,gt),gt=n.sub(Je,gt),gt=k(gt),Xe=n.add(Xe,gt),Je=n.mul(ze,Xe),Ee=n.add(Ee,Je),Je=n.mul(st,Xe),oe=n.mul(xr,oe),oe=n.sub(oe,Je),Je=n.mul(xr,ze),ve=n.mul(st,ve),ve=n.add(ve,Je),new B(oe,Ee,ve)}subtract(x){return ie(x),this.add(x.negate())}is0(){return this.equals(B.ZERO)}multiply(x){if(!s.isValidNot0(x))throw new RangeError("invalid scalar: out of range");let{p:I,f:D}=F.mulSecret(this,x,i,te);return te([I,D])[0]}multiplyUnsafe(x){let I=this,D=x;if(!s.isValid(D))throw new RangeError("invalid scalar: out of range");if(D===ks||I.is0())return B.ZERO;if(D===Ui)return I;if(F.hasWindowSize(this))return F.mulUnsafe(I,D,te);let z=[],Q=[];return G(z,Q,I,D),S1(B,z,Q)}mulAddUnsafe(x,I,D){ie(I);let z=[],Q=[];return G(z,Q,this,x),G(z,Q,I,D),S1(B,z,Q)}toAffine(x){let I=this,D=x;if(D!=null&&!n.isValid(D))throw new RangeError('"invertedZ" expected valid field element');let{X:z,Y:Q,Z}=I;if(n.eql(Z,n.ONE))return{x:z,y:Q};let ne=I.is0();D==null&&(D=ne?n.ONE:n.inv(Z));let oe=n.mul(z,D),Ee=n.mul(Q,D),ve=n.mul(Z,D);if(ne)return{x:n.ZERO,y:n.ZERO};if(!n.eql(ve,n.ONE))throw new Error("invZ was invalid");return{x:oe,y:Ee}}isTorsionFree(){return i===Ui?!0:d?d(B,this):F.mulUnsafe(this,a).is0()}clearCofactor(){return i===Ui?this:u?u(B,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ui?this.is0():this.clearCofactor().is0()}toBytes(x=!0){return Ir(x,"isCompressed"),this.assertValidity(),S(B,this,x)}toHex(x=!0){return Eu(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let te=R=>v1(B,R),F=new pc(B,p);return F.bits>=6&&B.BASE.precompute(6),Object.freeze(B.prototype),Object.freeze(B),B}function fx(r){return Uint8Array.of(r?2:3)}function hx(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function PO(r,e={}){vo(r);let{Fn:t}=r,n=e.randomBytes===void 0?Ts:e.randomBytes,s=Object.assign(hx(r.Fp,t),{seed:Math.max(E1(t.ORDER),16)});function o(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:g,publicKeyUncompressed:y}=s;try{let m=h.length;return p===!0&&m!==g||p===!1&&m!==y?!1:!r.fromBytes(h).is0()}catch{return!1}}function a(h){return h=h===void 0?n(s.seed):h,x1(Pe(h,s.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:g,publicKeyUncompressed:y}=s,m=t._lengths;if(!bo(h))return;let b=Pe(h,void 0,"key").length,E=b===g||b===y,S=b===p||!!m?.includes(b);if(!(E&&S))return E}function u(h,p,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(h),m=r.fromBytes(p);if(m.is0())throw new Error("invalid public key: point at infinity");return m.multiply(y).toBytes(g)}let d={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},f=mc(a,c);return Object.freeze(d),Object.freeze(s),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:s})}function px(r,e,t={}){vo(r);let n=e;Ss(n),rr(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=Object.assign({},t),o=s.randomBytes===void 0?Ts:s.randomBytes,i=s.hmac===void 0?(R,x)=>Mi(n,R,x):s.hmac,{Fp:a,Fn:c}=r,{ORDER:l,BITS:u}=c,d=E1(l),f=ay(o,d),{keygen:h,getPublicKey:p,getSharedSecret:g,utils:y,lengths:m}=PO(r,s),b={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},E=l*ux+Ui<a.ORDER;function S(R){let x=l>>Ui;return R>x}function T(R,x){if(!c.isValidNot0(x))throw new Error(`invalid signature ${R}: out of range 1..Point.Fn.ORDER`);return x}function C(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function k(R,x,I){return C(),(R===I?0:2)|Number(a.isOdd(x))}function O(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function N(R,x){Cy(x);let I=m.signature,D=x==="compact"?I:x==="recovered"?I+1:void 0;return Pe(R,D)}class K{r;s;recovery;constructor(x,I,D){if(this.r=T("r",x),this.s=T("s",I),D!=null){if(O(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(x,I=b.format){N(x,I);let D;if(I==="der"){if(x.length>2*c.BYTES+16)throw new D1.Err("invalid signature: DER signature too long");let{r:ne,s:oe}=D1.toSig(Pe(x),c.BYTES+1);return new K(ne,oe)}I==="recovered"&&(D=x[0],I="compact",x=x.subarray(1));let z=m.signature/2,Q=x.subarray(0,z),Z=x.subarray(z,z*2);return new K(c.fromBytes(Q),c.fromBytes(Z),D)}static fromHex(x,I){return this.fromBytes(uc(x),I)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new K(this.r,this.s,x)}recoverPublicKey(x){let{r:I,s:D}=this,z=this.assertRecovery(),Q=z===2||z===3?I+l:I;if(!a.isValid(Q))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let Z=a.toBytes(Q),ne=r.fromBytes(sn(fx((z&1)===0),Z)),oe=c.inv(Q),Ee=J(Pe(x,void 0,"msgHash")),ve=c.create(-Ee*oe),Je=c.create(D*oe),ze=r.BASE.mulAddUnsafe(ve,ne,Je);if(ze.is0())throw new Error("invalid recovery: point at infinify");return ze.assertValidity(),ze}hasHighS(){return S(this.s)}toBytes(x=b.format){if(Cy(x),x==="der")return uc(D1.hexFromSig(this));let{r:I,s:D}=this,z=c.toBytes(I),Q=c.toBytes(D);return x==="recovered"?(O(),sn(Uint8Array.of(this.assertRecovery()),z,Q)):sn(z,Q)}toHex(x){return Eu(this.toBytes(x))}}Object.freeze(K.prototype),Object.freeze(K);let ee=s.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let I=Wn(x),D=x.length*8-u;return D>0?I>>BigInt(D):I}:s.bits2int,J=s.bits2int_modN===void 0?function(x){return c.create(ee(x))}:s.bits2int_modN,ie=Su(u);function M(R){return jn("num < 2^"+u,R,ks,ie),c.toBytes(R)}function G(R,x){return Pe(R,void 0,"message"),x?Pe(n(R),void 0,"prehashed message"):R}function U(R,x,I){let{lowS:D,prehash:z,extraEntropy:Q}=Ty(I,b);R=G(R,z);let Z=J(R),ne=c.fromBytes(x);if(!c.isValidNot0(ne))throw new Error("invalid private key");let oe=[M(ne),M(Z)];if(Q!=null&&Q!==!1){let ze=Q===!0?o(m.secretKey):Q;oe.push(Pe(ze,void 0,"extraEntropy"))}let Ee=sn(...oe),ve=Z;function Je(ze){let gt=ee(ze);if(!c.isValidNot0(gt))return;let xr=r.BASE.multiply(gt).toAffine(),Xe=c.create(xr.x);if(Xe===ks)return;let st;if(f!==void 0){let Xs=Wn(x1(f(d),l)),__=c.inv(c.mul(Xs,gt)),P_=c.mul(Xs,ve),L_=c.mul(Xs,ne);st=c.create(__*c.create(P_+L_*Xe))}else{let Xs=LE(gt,l);st=c.create(Xs*c.create(ve+Xe*ne))}if(st===ks)return;let da=k(xr.x,xr.y,Xe),El=st;return D&&S(st)&&(El=c.neg(st),da^=1),new K(Xe,El,E?void 0:da)}return{seed:Ee,k2sig:Je}}function B(R,x,I={}){let{seed:D,k2sig:z}=U(R,x,I);return SE(n.outputLen,c.BYTES,i)(D,z).toBytes(I.format)}function te(R,x,I,D={}){let{lowS:z,prehash:Q,format:Z}=Ty(D,b);if(I=Pe(I,void 0,"publicKey"),x=G(x,Q),!bo(R)){let ne=R instanceof K?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+ne)}N(R,Z);try{let ne=K.fromBytes(R,Z),oe=r.fromBytes(I);if(oe.is0()||z&&ne.hasHighS())return!1;let{r:Ee,s:ve}=ne,Je=J(x),ze=c.inv(ve),gt=c.create(Je*ze),xr=c.create(Ee*ze),Xe=r.BASE.mulAddUnsafe(gt,oe,xr);if(Xe.is0())return!1;let st=Xe.toAffine();return!(c.create(st.x)!==Ee||Z==="recovered"&&ne.recovery!==k(st.x,st.y,Ee))}catch{return!1}}function F(R,x,I={}){let{prehash:D}=Ty(I,b);return x=G(x,D),K.fromBytes(R,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:h,getPublicKey:p,getSharedSecret:g,utils:y,lengths:m,Point:r,sign:B,verify:te,recoverPublicKey:F,Signature:K,hash:n})}var _y={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},LO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var mx=BigInt(2);function RO(r){let e=_y.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=tt(u,t,e)*u%e,f=tt(d,t,e)*u%e,h=tt(f,mx,e)*l%e,p=tt(h,s,e)*h%e,g=tt(p,o,e)*p%e,y=tt(g,a,e)*g%e,m=tt(y,c,e)*y%e,b=tt(m,a,e)*g%e,E=tt(b,t,e)*u%e,S=tt(E,i,e)*p%e,T=tt(S,n,e)*l%e,C=tt(T,mx,e);if(!ky.eql(ky.sqr(C),r))throw new Error("Cannot find square root");return C}var ky=hc(_y.p,{sqrt:RO}),DO=dx(_y,{Fp:ky,endo:LO}),Cn=px(DO,tr);var gx=32;function yx(r,e,t){let n=je.digest(e instanceof Uint8Array?e:e.subarray());if(yc(n))return n.then(({digest:s})=>(t?.signal?.throwIfAborted(),Cn.sign(s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new ku(String(s))});try{return Cn.sign(n.digest,r,{prehash:!1,format:"der"})}catch(s){throw new ku(String(s))}}function wx(r,e,t,n){let s=je.digest(t instanceof Uint8Array?t:t.subarray());if(yc(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),Cn.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new _u(String(o))});try{return n?.signal?.throwIfAborted(),Cn.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new _u(String(o))}}var Nu=class{type="secp256k1";raw;_key;constructor(e){this._key=xx(e),this.raw=bx(this._key)}toMultihash(){return ot.digest(St(this))}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}verify(e,t,n){return wx(this._key,t,e,n)}},Ou=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Ex(e),this.publicKey=new Nu(t??vx(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}sign(e,t){return yx(this.raw,e,t)}};function Py(r){return new Ou(r)}function Ly(r){return new Nu(r)}async function Sx(){let r=NO();return new Ou(r)}function bx(r){return Cn.Point.fromBytes(r).toBytes()}function Ex(r){try{return Cn.getPublicKey(r,!0),r}catch(e){throw new xl(String(e))}}function xx(r){try{return Cn.Point.fromBytes(r),r}catch(e){throw new dn(String(e))}}function vx(r){try{return Cn.getPublicKey(r,!0)}catch(e){throw new xl(String(e))}}function NO(){return Cn.utils.randomSecretKey()}async function N1(r,e){if(r==="Ed25519")return rx();if(r==="secp256k1")return Sx();if(r==="RSA")return Sy(OO(e));if(r==="ECDSA")return rE(BO(e));throw new hn}function ct(r,e){let{Type:t,Data:n}=Xn.decode(r),s=n??new Uint8Array;switch(t){case qe.RSA:return Ey(s,e);case qe.Ed25519:return fy(s);case qe.secp256k1:return Ly(s);case qe.ECDSA:return K4(s);default:throw new hn}}function Ax(r){let{Type:e,Data:t}=Xn.decode(r.digest),n=t??new Uint8Array;switch(e){case qe.Ed25519:return fy(n);case qe.secp256k1:return Ly(n);case qe.ECDSA:return K4(n);default:throw new hn}}function St(r){return Xn.encode({Type:qe[r.type],Data:r.raw})}function Tx(r){let e=Lu.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case qe.RSA:return by(t);case qe.Ed25519:return dy(t);case qe.secp256k1:return Py(t);case qe.ECDSA:return Q9(t);default:throw new hn}}function Ix(r){if(r.byteLength===Vr)return dy(r);if(r.byteLength===gx)return Py(r);let e=nn(r),t=e[2]?.[0];if(t===$9||t===K9||t===H9)return $4(e);if(e.length>8)return L1(e);throw new v("Could not extract private key from raw bytes")}function Fi(r){return Lu.encode({Type:qe[r.type],Data:r.raw})}function OO(r){return r==null?2048:parseInt(r,10)}function BO(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new v("Unsupported curve, should be P-256, P-384 or P-521")}var Cx=Symbol.for("nodejs.util.inspect.custom"),MO=114,Bu=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Bf]=!0;toString(){return this.string==null&&(this.string=Se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return $.createV1(MO,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return se(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return se(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Cx](){return`PeerId(${this.toString()})`}},Mu=class extends Bu{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Uu=class extends Bu{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Fu=class extends Bu{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},UO=2336,$u=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ot.digest(A(this.url))}[Cx](){return`PeerId(${this.url})`}[Bf]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return $.createV1(UO,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=_(e)),e.toString()===this.toString())}};var FO=114,kx=2336;function rt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ce(Se.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return bt($.parse(r));if(e==null)throw new v('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ce(e.decode(r))}return Tt(t)}function qr(r){if(r.type==="Ed25519")return new Uu({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Fu({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Mu({multihash:r.toCID().multihash,publicKey:r});throw new hn}function _x(r){return qr(r.publicKey)}function Tt(r){if(KO(r))return new Mu({multihash:r});if($O(r))try{let e=Ax(r);if(e.type==="Ed25519")return new Uu({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Fu({multihash:r,publicKey:e})}catch{let t=_(r.digest);return new $u(new URL(t))}throw new ya("Supplied PeerID Multihash is invalid")}function bt(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==FO&&r.code!==kx)throw new Pf("Supplied PeerID CID is invalid");if(r.code===kx){let e=_(r.multihash.digest);return new $u(new URL(e))}return Tt(r.multihash)}function $O(r){return r.code===ot.code}function KO(r){return r.code===je.code}function HO(r){return r[Symbol.asyncIterator]!=null}function VO(r){if(HO(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Cr=VO;function qO(r){return r[Symbol.asyncIterator]!=null}function zO(r,e){let t=0;if(qO(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=nc(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Vt=zO;function WO(r){return r[Symbol.asyncIterator]!=null}function GO(r,e){return WO(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 So=GO;var Ry="/ipfs/bitswap/1.2.0";var lt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(lt||(lt={}));var Dy;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Dy||(Dy={}));(function(r){r.codec=()=>at(Dy)})(lt||(lt={}));var $i;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.priority!=null&&o.priority!==0&&(i.uint32(16),i.int32(o.priority)),o.cancel!=null&&(i.uint32(24),i.bool(o.cancel)),o.wantType!=null&&(i.uint32(32),lt.codec().encode(o.wantType,i)),o.sendDontHave!=null&&(i.uint32(40),i.bool(o.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:pe(0),priority:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.priority=o.int32();break}case 3:{c.cancel=o.bool();break}case 4:{c.wantType=lt.codec().decode(o);break}case 5:{c.sendDontHave=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=a==null?o.len:o.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"WantlistEntry"});o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${i}cid`,value:o.bytes()};break}case 2:{yield{field:`${i}priority`,value:o.int32()};break}case 3:{yield{field:`${i}cancel`,value:o.bool()};break}case 4:{yield{field:`${i}wantType`,value:lt.codec().decode(o)};break}case 5:{yield{field:`${i}sendDontHave`,value:o.bool()};break}default:{o.skipType(u&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"WantlistEntry"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})($i||($i={}));var Ku;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.entries!=null&&o.entries.length>0)for(let c of o.entries)i.uint32(10),$i.codec().encode(c,i);o.full!=null&&(i.uint32(16),i.bool(o.full)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={entries:[]},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new ye('Decode error - repeated field "entries" had too many elements');c.entries.push($i.codec().decode(o,o.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={entries:0},u=a==null?o.len:o.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"Wantlist"});o.pos<u;){let d=o.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new ye('Streaming decode error - repeated field "entries" had too many elements');for(let f of $i.codec().stream(o,`${i}entries[].`,o.uint32(),{limits:c.limits?.entries$}))yield{...f,index:l.entries};l.entries++;break}case 2:{yield{field:`${i}full`,value:o.bool()};break}default:{o.skipType(d&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"Wantlist"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Ku||(Ku={}));var Ki;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.prefix!=null&&o.prefix.byteLength>0&&(i.uint32(10),i.bytes(o.prefix)),o.data!=null&&o.data.byteLength>0&&(i.uint32(18),i.bytes(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={prefix:pe(0),data:pe(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.prefix=o.bytes();break}case 2:{c.data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=a==null?o.len:o.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"Block"});o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${i}prefix`,value:o.bytes()};break}case 2:{yield{field:`${i}data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"Block"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Ki||(Ki={}));var zr;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(zr||(zr={}));var O1;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(O1||(O1={}));(function(r){r.codec=()=>at(O1)})(zr||(zr={}));var Hi;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.type!=null&&O1[o.type]!==0&&(i.uint32(16),zr.codec().encode(o.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:pe(0),type:zr.HaveBlock},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.type=zr.codec().decode(o);break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=a==null?o.len:o.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"BlockPresence"});o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${i}cid`,value:o.bytes()};break}case 2:{yield{field:`${i}type`,value:zr.codec().decode(o)};break}default:{o.skipType(u&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"BlockPresence"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Hi||(Hi={}));var Vi;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.wantlist!=null&&(i.uint32(10),Ku.codec().encode(o.wantlist,i)),o.blocks!=null&&o.blocks.length>0)for(let c of o.blocks)i.uint32(26),Ki.codec().encode(c,i);if(o.blockPresences!=null&&o.blockPresences.length>0)for(let c of o.blockPresences)i.uint32(34),Hi.codec().encode(c,i);o.pendingBytes!=null&&o.pendingBytes!==0&&(i.uint32(40),i.int32(o.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.wantlist=Ku.codec().decode(o,o.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new ye('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Ki.codec().decode(o,o.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new ye('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Hi.codec().decode(o,o.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=o.int32();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={blocks:0,blockPresences:0},u=a==null?o.len:o.pos+a;for(i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"start",message:"BitswapMessage"});o.pos<u;){let d=o.uint32();switch(d>>>3){case 1:{yield*Ku.codec().stream(o,`${i}wantlist.`,o.uint32(),{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new ye('Streaming decode error - repeated field "blocks" had too many elements');for(let f of Ki.codec().stream(o,`${i}blocks[].`,o.uint32(),{limits:c.limits?.blocks$}))yield{...f,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new ye('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of Hi.codec().stream(o,`${i}blockPresences[].`,o.uint32(),{limits:c.limits?.blockPresences$}))yield{...f,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${i}pendingBytes`,value:o.int32()};break}default:{o.skipType(d&7);break}}}i!=="."&&(yield{field:i.endsWith(".")?i.substring(0,i.length-1):i,type:"end",message:"BitswapMessage"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Vi||(Vi={}));function Px(r,e){for(let[t,n]of e.wantlist.entries()){let s=r.wantlist.get(t);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var B1=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var jO=4193648,YO=jO+16;function*Lx(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Vi.encode(l).byteLength,{added:d,hasMore:f,newSize:h}=Ny(s,l.blocks,a,e,u,XO);a+=d,u=h;let p=f;({added:d,hasMore:f,newSize:h}=Ny(n,l.blockPresences,i,e,u,QO)),i+=d,u=h;let g=f;if({added:d,hasMore:f,newSize:h}=Ny(t,l.wantlist.entries,o,e,u,ZO),o+=d,u=h,c=!p&&!g&&!f,c||(l.wantlist.full=!1),yield Vi.encode(l),c)break}}function Ny(r,e,t,n,s,o){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=o(l);if(u>YO)throw new B1("Cannot send block as after encoding it is over the max message size");let d=s+u;if(d>n){a=!0;break}e.push(l),i++,s=d}return{hasMore:a,added:i,newSize:s}}function XO(r){return Oy(3,Ki.encode(r))}function QO(r){return Oy(4,Hi.encode(r))}function ZO(r){return Oy(1,$i.encode(r))}function Oy(r,e){let t=Te(r),n=Te(e.byteLength);return t+n+e.byteLength}function cB(r){if(vr(r))return r;if(sc(r))return bt(r);if(en(r)||Array.isArray(r))return r;throw new v(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var M1=class extends ge{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Ry],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Jt({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new Mn(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);s.addEventListener("abort",n),await e.close({signal:s});let o=Kt();e.addEventListener("message",i=>{o.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{o.end()}),e.addEventListener("close",i=>{i.error!=null&&o.end(i.error)});for await(let i of Ci(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Vi.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),s.removeEventListener("abort",n),s=AbortSignal.timeout(this.messageReceiveTimeout),s.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new P("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new P("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,router:n.router})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Cr(Vt(So(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>e.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=Px(s.options.message,t),await s.join(n);return}await this.sendQueue.add(async o=>{let i=o.message;if(i==null)throw new v("No message to send");this.log("sendMessage to %p",e),o.onProgress?.(new P("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Ry,o);await a.closeRead(o);try{for(let c of Lx(i,this.maxOutgoingMessageSize))a.send(xs.single(c))||await a.onDrain(o);await a.close(o)}catch(c){this.log.error("error sending message to %p - %e",e,c),o?.onProgress?.(new P("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Nr("Network isn't running");return e=cB(e),t?.onProgress?.(new P("bitswap:dial",e)),this.libp2p.dial(e,t)}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function qi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function U1(r){let e=Ce(Se.decode(`z${r}`));return Tt(e)}var nr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return qi(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return qi(this.map.values(),e=>e.key)}values(){return qi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Wr=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return qi(this.set.entries(),e=>{let t=U1(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=U1(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return qi(this.set.values(),e=>U1(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};function By(){return new Wr}var F1=class{filter;constructor(e,t){this.filter=Ut(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function My(r,e=.001){return new F1(r,e)}var Uy=class extends nr{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function _s(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Uy({name:e,metrics:t}):n=new nr,n}var kr=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};var Ps=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=We.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=We.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=We.encode(e.multihash.bytes);this.blocks.set(n,t)}};function lB(r){let e=new Uint8Array(r.reduce((n,s)=>n+Te(s),0)),t=0;for(let n of r)e=Xt(n,e,t),t+=Te(n);return e}var Rx=lB;function Fy(r){return Rx([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var $1=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;sendQueue;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024,this.sendQueue=new ht({concurrency:t.sendBlocksConcurrency??1,maxSize:t.sendBlocksMaxQueueLength??10})}stop(){this.sendQueue.abort()}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of e.entries){let s=$.decode(n.cid),o=_(s.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,s),this.wants.delete(o);else{n.wantType===lt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,s):this.log("peer %p wanted block for %c",this.peerId,s);let i=this.wants.get(o);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===lt.WantHave&&(n.wantType==null||n.wantType===lt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??lt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??lt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,s])=>s.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,s)=>n[1].created<s[1].created?-1:s[1].created<n[1].created?1:0).sort((n,s)=>n[1].haveBlock===!1?-1:s[1].haveBlock===!1?1:0).sort((n,s)=>n[1].priority<s[1].priority?-1:s[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=_(e.multihash.bytes,"base64");return this.wants.has(t)}queueSendOperation(e,t){e!=null&&(this.receivedBytes(e.blocks?.reduce((n,s)=>n+s.data.byteLength,0)??0),this.addWants(e.wantlist));try{this.sendQueue.add(async n=>{this.log("send blocks to peer"),await this.sendBlocksToPeer(n)},t).catch(n=>{n.name==="QueueFullError"?this.log.error("Dropping bitswap message as peer send queue is full"):this.log.error("Error when trying to add queue a send operation")})}catch(n){if(n.name==="QueueFullError")this.log.error("Dropping bitswap message as peer send queue is full");else throw n}}async sendBlocksToPeer(e){let t=new Ps,n=new Set;this.removeExpiredWants();let s=[...this.wants.entries()].filter(([o,i])=>i.status==="want");if(s.length!==0){s.forEach(([o,i])=>{i.status="sending"});for(let[o,i]of s)try{if(!await this.blockstore.has(i.cid,e))throw new kr;let c=await n1(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===lt.WantHave?c.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:c,prefix:Fy(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:zr.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:c,prefix:Fy(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:zr.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0)))}}};var K1=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;sendBlocksConcurrency;sendBlocksMaxQueueLength;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.sendBlocksConcurrency=t.sendBlocksConcurrency,this.sendBlocksMaxQueueLength=t.sendBlocksMaxQueueLength,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=_s({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{try{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message)}catch(s){this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)}}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}start(){}stop(){this.ledgerMap.forEach(e=>{e.stop()})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount,sendQueue:t.sendQueue}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new $1({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize,sendBlocksConcurrency:this.sendBlocksConcurrency,sendBlocksMaxQueueLength:this.sendBlocksMaxQueueLength}),this.ledgerMap.set(e,n)),n.queueSendOperation(t)}async receivedBlock(e,t){let n=[];for(let s of this.ledgerMap.values())s.hasWant(e)&&n.push(s);await Promise.all(n.map(async s=>s.queueSendOperation(void 0,t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var $y=class extends rc{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){if(n.signal?.aborted===!0)throw new li(`Signal to want session block for CID ${e} from peer ${t} was aborted prior to want`);let s=bt(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,s);let o=await this.wantList.wantSessionBlock(e,s,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has){if(o.block!=null)return o.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,router:n.router,toString:()=>`Bitswap(${n.id})`,fallback:n.fallback}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(sc(e))return{peerId:e,router:t,toString:()=>`Bitswap(${e})`,fallback:!1};if(await this.libp2p.isDialable(e)!==!1)try{let s=await this.libp2p.dial(e,n);return{peerId:s.remotePeer.toCID(),router:t,toString:()=>`Bitswap(${s.remotePeer})`,fallback:!1}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new P("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],router:t.router,fallback:t.fallback},router:t.router}))}};function Dx(r,e){return new $y(r,e)}var H1=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var Gr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function jr(r,e,t,n){let s=new Gr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Hy(t,"abort",d),Hy(r,e,l),Hy(r,o,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(h){c(),a(h);return}c(),i(f)},u=f=>{if(c(),f instanceof Error){a(f);return}a(f.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(s)};Ky(t,"abort",d),Ky(r,e,l),Ky(r,o,u)})}function Ky(r,e,t){r!=null&&(Nx(r)?r.addEventListener(e,t):r.addListener(e,t))}function Hy(r,e,t){r!=null&&(Nx(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Nx(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function uB(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Br(r);e.push(t),r=r.slice(Te(t))}return e}var Ox=uB;var V1=class extends ge{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=_s({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=vt({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=_(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??lt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,s)),t.onProgress!=null&&s.onProgress.push({onProgress:t.onProgress,signal:t.signal}),s.wantType===lt.WantHave&&t.wantType===lt.WantBlock&&(s.wantType=lt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===lt.WantBlock?(await jr(this,"block",t?.signal,{filter:a=>se(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await jr(this,"presence",t?.signal,{filter:i=>se(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ye(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,s=new Ps;for(let[o,i]of this.wants.entries())t.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(e,s,{onProgress:o=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(o)})})}});for(let o of n)t.add(o)}catch(o){this.log.error("error sending full wantlist to new peer - %e",o)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=_(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let s=new Ps;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:lt.WantHave,priority:1}),await this.network.sendMessage(t,s,n),(await jr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&se(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:lt.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new Ps;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:lt.WantBlock,priority:1}),await this.network.sendMessage(t,s,n),(await jr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&se(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=_(e.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let s of t.blocks){if(s.prefix==null||s.data==null)continue;let o=Ox(s.prefix),i=o[0],a=o[1],c=o[2],l=o[3],u=c===je.code?je:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let d=u.digest(s.data,{truncate:l});d.then!=null&&(d=await d);let f=$.create(i===0?0:1,a,d);this.log("received block from %p for %c",e.remotePeer,f),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:f,block:s.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:f,has:!0,block:s.data}});let h=_(f.multihash.bytes,"base64"),p=this.wants.get(h);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:s,type:o}of t.blockPresences){let i=$.decode(s);this.log("received %s from %p for %c",o,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:o===zr.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Ps(!0);for(let[s,o]of this.wants.entries())o.cancel||(t.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:lt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:s=>{this.wants.forEach(({onProgress:o})=>{o.forEach(({onProgress:i})=>{i(s)})})}}),this.peers.set(e,t)}catch(s){this.log.error("error sending full wantlist to new peer %p - %e",e,s)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var q1=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new H1(e),this.network=new M1(e,t),this.peerWantLists=new K1({...e,network:this.network},t),this.wantList=new V1({...e,network:this.network},t)}createSession(e={}){return Dx({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,s=he([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,o)});try{let o=await this.wantList.wantBlock(e,{...t,signal:s});return t.onProgress?.(new P("bitswap:block",{cid:e,sender:o.connection.remotePeer})),o.block}finally{n.abort(),s.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),this.peerWantLists.stop(),await this.network.stop()}};var z1=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new q1(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(s){if(t?.onProgress!=null)if(t.onProgress(s),s.type==="connection:open"){if(!vr(s.detail))return;t.onProgress(new P("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:s.detail.toCID(),cid:e}))}else s.type==="connection:opened"?t.onProgress(new P("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:s.detail.remotePeer.toCID(),address:s.detail.remoteAddr,cid:e})):s.type==="bitswap:send-wantlist"?t.onProgress(new P("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:s.detail.toCID(),cid:e})):s.type==="bitswap:block"&&t.onProgress(new P("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:s.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,s)=>{await t.addPeer(n,s)},announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>t.retrieve(n,s)}}};function Bx(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let s=new z1(n,e);await yt(s),n.addBlockBroker(s)}}};return r.addMixin(t),r}async function*Hu(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 W1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*xc(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),s="";for await(let o of r){if(typeof o=="string"&&(o=new TextEncoder().encode(o)),va(o)&&(o=o.subarray()),s+=n.decode(o,{stream:!0}),s.length>(e?.maxMessageLength??s.length))throw new W1("Incoming message too long");let i=s.split(t);s=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}s+=n.decode(),s!==""&&(yield JSON.parse(s))}var zi=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},an=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};var G1={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},j1=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("helia:delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new ht({concurrency:t.concurrentRequests??G1.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??G1.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.cacheName=t.cacheName??G1.cacheName,this.cacheTTL=t.cacheTTL??G1.cacheTTL}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,n,t.signal]);let o=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(o.resolve(),i.promise));try{await be(o.promise,s);let c=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l=await this.#r(c.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:s});if(!l.ok){if(l.status===404)return;throw l.status===422?new zi("Request does not conform to schema or semantic constraints"):new an(`Unexpected status code: ${l.status}`)}let u=l.headers.get("Content-Type");if(u==null)throw new an("No Content-Type header received");if(l.body==null){if(u!=="application/x-ndjson")throw new an("Routing response had no body");return}if(u.startsWith("application/json")){let f=(await be(l.json(),s)).Providers??[];for(let h of f){let p=this.#e(h);p!=null&&(a++,yield p)}}else if(u.includes("application/x-ndjson")){s.addEventListener("abort",()=>{l?.body?.cancel()});for await(let d of xc(Hu(l.body))){let f=this.#e(d);f!=null&&(a++,yield f)}}else throw new an(`Unsupported Content-Type: ${u}`)}finally{s.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",a,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,n,t.signal]);let o=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(o.resolve(),i.promise));try{await be(o.promise,s);let a=new URL(`${this.url}routing/v1/peers/${e}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c=await this.#r(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(c.status===404)return;if(c.status===422)throw new zi("Request does not conform to schema or semantic constraints");if(c.body==null)throw new an("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let d=(await be(c.json(),s)).Peers??[];for(let f of d){let h=this.#e(f);h!=null&&(yield h)}}else{s.addEventListener("abort",()=>{c.body?.cancel()});for await(let u of xc(Hu(c.body))){let d=this.#e(u);d!=null&&(yield d)}}}catch(a){this.log.error("getPeers errored - %e",a)}finally{s.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if($.asCID(e)===e||e instanceof $)n=e.toV1().toString();else throw new v("Key must be CID");this.log("getClosestPeers starts: %s",n);let s=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,s,t.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await be(i.promise,o);let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l=await this.#r(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)return;if(l.status===422)throw new zi("Request does not conform to schema or semantic constraints");if(l.body==null)throw new an("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let f=(await be(l.json(),o)).Peers??[];for(let h of f){let p=this.#e(h);p!=null&&(yield p)}}else{o.addEventListener("abort",()=>{l.body?.cancel()});for await(let d of xc(Hu(l.body))){let f=this.#e(d);f!=null&&(yield f)}}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{o.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(e,t={}){this.log("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,n,t.signal]);let o=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(o.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await be(o.promise,s);let c=await this.#r(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:s});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new Re("No matching records found");if(c.status===422)throw new zi("Request does not conform to schema or semantic constraints");if(!c.ok)throw new an(`Unexpected status code: ${c.status}`);let l=c.headers.get("Content-Type");if(l==null||!l.includes("application/vnd.ipfs.ipns-record"))throw new Re("No matching records found");if(c.body==null)throw new an("GET ipns response had no body");let u=await be(c.arrayBuffer(),s);return new Uint8Array(u,0,u.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{s.clear(),i.resolve(),this.log("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let s=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,s,n.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await be(i.promise,o);let l=await this.#r(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:re(t),signal:o});if(this.log("putIPNS PUT %s %d",c,l.status),l.status!==200)throw new an("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{o.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(W)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:$.createV1(114,dB(e.ID)),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let s=t?.join(",")??this.filterAddrs?.join(",")??"";s!==""&&e.searchParams.set("filter-addrs",s)}if(n!=null||this.filterProtocols!=null){let s=n?.join(",")??this.filterProtocols?.join(",")??"";s!==""&&e.searchParams.set("filter-protocols",s)}}async#r(e,t){let n=t.method??"GET",s=`${n}-${e}`;if(n==="GET"){let c=await be(this.cache?.match(e),t.signal);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",s),this.logResponse(c),c;this.log("evicting cached response for %s",s),await be(this.cache?.delete(e),t.signal)}else this.cache!=null&&this.log("cache miss for %s",s)}let o=this.inFlightRequests.get(s);if(o!=null){let c=await be(o,t.signal);return this.log("deduplicating outgoing request for %s",s),c.clone()}this.log("outgoing request:"),this.logRequest(e,t);let i=fetch(e,t).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let d=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await be(this.cache.put(e,d),t.signal)}return c}).finally(()=>{this.inFlightRequests.delete(s)});return this.inFlightRequests.set(s,i),await be(i,t.signal)}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[s,o]of n.entries())this.log("%s: %s",s,o)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function dB(r){let e=Se.baseDecode(r);return Ce(e)}function fB(r){return r[Symbol.asyncIterator]!=null}function hB(r){if(fB(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Y1=hB;var X1=A("/ipns/");function Mx(r){return se(r.subarray(0,X1.byteLength),X1)}var Q1=class{client;constructor(e){this.client=e}get[Yo](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async*findProviders(e,t={}){try{yield*Vt(this.client.getProviders(e,t),n=>({id:bt(n.ID),multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof Re)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!Mx(e))return;let s=Ce(e.slice(X1.length)),o=$.createV1(114,s);await this.client.putIPNS(o,t,n)}async get(e,t){if(!Mx(e))throw new Re("Not found");let n=Ce(e.slice(X1.length)),s=$.createV1(114,n);try{return await this.client.getIPNS(s,t)}catch(o){throw o.name==="BadResponseError"?new Re("Not found"):o}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},Z1=class{client;constructor(e){this.client=e}get[ti](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async findPeer(e,t={}){let n=await Y1(this.client.getPeers(e.toCID(),t));if(n!=null)return{id:bt(n.ID),multiaddrs:n.Addrs??[]};throw new Re("Not found")}async*getClosestPeers(e,t={}){let n;try{n=$.decode(e)}catch{try{n=$.createV1(114,Qe.decode(e))}catch{n=$.createV1(hs,ot.digest(e))}}for await(let s of this.client.getClosestPeers(n,t))yield{id:bt(s.ID),multiaddrs:s.Addrs??[]}}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};function J1(r){return e=>new j1(e,r)}function Ux(r){return e=>new Q1(J1(r)(e))}function Fx(r){return e=>new Z1(J1(r)(e))}var ep=A("/ipns/");function $x(r){return se(r.subarray(0,ep.byteLength),ep)}var tp=class{name="delegated-http-router";client;constructor(e,t){this.client=J1(t)(e)}async provide(e,t){}async cancelReprovide(e,t){}async*findProviders(e,t){yield*Vt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,router:this.name,fallback:!1}))}async put(e,t,n){if(!$x(e))return;let s=Ce(e.slice(ep.length)),o=$.createV1(114,s);await this.client.putIPNS(o,t,n)}async get(e,t){if(!$x(e))throw new Re("Not found");let n=Ce(e.slice(ep.length)),s=$.createV1(114,n);try{return await this.client.getIPNS(s,t)}catch(o){throw o.name==="BadResponseError"?new Re("Not found"):o}}async findPeer(e,t){let n=await Y1(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[],router:this.name};throw new Re("Not found")}async*getClosestPeers(e,t){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function Vu(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"],...r??{}}}function Kx(r){return e=>new tp(e,Vu(r))}var Hx="[a-fA-F\\d:]",Ao=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Hx})|(?<=${Hx})(?=\\s|$))`:"",kn="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",It="[a-fA-F\\d]{1,4}",rp=`
|
|
12
|
+
${e}[Error list was empty]`,t.trim()}return R9(r,e)}et.formatters.e=r=>r==null?"undefined":N9(r);function oN(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Za(r){return{forComponent(e){return Ja(e,r)}}}function Ja(r,e){let t=oN(`${r}:trace`);return et.enabled(`${r}:trace`)&&et.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=et(`${r}:trace`,e)),Object.assign(et(r,e),{error:et(`${r}:error`,e),trace:t,newScope:n=>Ja(`${r}:${n}`,e)})}function D9(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var O9=Symbol.for("sindresorhus/unlimited-timeout#brand");function B9(r,e,...t){if(typeof r!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,s={[O9]:!0,id:void 0,cleared:!1,ref(){return n=!1,s.id?.ref?.(),s},unref(){return n=!0,s.id?.unref?.(),s}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return s;(!Number.isFinite(e)||e<0)&&(e=0);let o=performance.now()+e,i=a=>{s.cleared||(a<=2147483647?(s.id=globalThis.setTimeout(()=>{s.cleared||r(...t)},a),n&&s.id?.unref?.()):(s.id=globalThis.setTimeout(()=>{let c=performance.now(),l=Math.max(0,o-c);i(l)},2147483647),n&&s.id?.unref?.()))};return i(e),s}function M9(r){!r||typeof r!="object"||!r[O9]||(r.cleared=!0,r.id!==void 0&&(globalThis.clearTimeout(r.id),r.id=void 0))}var iN=new WeakMap;function aN({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(s.reason);let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(s.reason)},u=()=>{s&&s.removeEventListener("abort",l)},d=new Promise((f,h)=>{i=()=>{u(),f(n)},a=h,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",l,{once:!0}),iN.set(d,()=>{c(o),o=null,i()}),d}}var cN=aN({setTimeout:B9,clearTimeout:M9}),U9=cN;var Jt=class extends ht{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var Zh=class extends ht{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var ec=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new L4}consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new wh("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},L4=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function tc(r,e,t){let n,s,o=!1;function i(){let l={signal:s.signal},u;t?.timeout!=null&&(u=he([s.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),o=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),o=!1,!s.signal.aborted&&(n=setTimeout(i,e))})}let a=bs(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{o||(clearTimeout(n),a())},start:()=>{c||(c=!0,s=new AbortController,s.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),s?.abort(),c=!1}}}var R4=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function vt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new R4({name:e,metrics:t}):n=new Map,n}var rc=class extends ge{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(e,t){super(),this.logName=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.cidPeerFilterSize=t.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Ut(this.maxProviders),this.initialProviders=[...t.providers??[]]}async retrieve(e,t={}){let n=We.encode(e.multihash.bytes),s=this.requests.get(n);if(s!=null)return this.log("join existing request for %c",e),s.observers++,s.promise;let o=Ye(),i={promise:o.promise,observers:1,queryFilter:Ut(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t));let c=!1,l=new ht({concurrency:this.maxProviders});l.addEventListener("failure",f=>{if(f.detail.job.options.provider.fallback){this.log.error("error querying fallback provider %s - %e",f.detail.job.options.provider,f.detail.error);return}if(f.detail.error.name==="NoEvictionError"){this.log.error("no-eviction error querying provider %s - %e",f.detail.job.options.provider,f.detail.error);return}this.log.error("error querying provider %s, evicting from session - %e",f.detail.job.options.provider,f.detail.error),this.evict(f.detail.job.options.provider)}),l.addEventListener("success",f=>{c=!0,o.resolve(f.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(t.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let f=0;f<this.minProviders&&this.providers.length!==0;f++){let h=this.providers[Math.floor(Math.random()*this.providers.length)];h.fallback||(this.log("evicting %s to make room for more providers",h),this.evict(h))}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(f=>{this.log.error("could not find new providers for %c - %e",e,f),o.reject(f)})});let u=f=>{let h=this.toFilterKey(f.detail);i.queryFilter.has(h)||(i.queryFilter.add(h),this.emitFoundProviderProgressEvent(e,f.detail,t),l.add(async()=>this.queryProvider(e,f.detail,t),{provider:f.detail}).catch(p=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,p)}))};if(this.addEventListener("provider",u),a)try{await be(this.initialPeerSearchComplete,t.signal),a&&this.log("found initial session peers for %c",e)}catch(f){throw a&&this.log("failed to find initial session peers for %c - %e",e,f),this.requests.delete(n),i.observers>1&&o.reject(f),f}Promise.all([...this.providers].filter(f=>{let h=this.toFilterKey(f),p=i.queryFilter.has(h);return p||i.queryFilter.add(this.toFilterKey(f)),!p}).map(async f=>l.add(async()=>this.queryProvider(e,f,t),{provider:f}))).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",e,f)});let d=()=>{o.reject(new jt(t.signal?.reason??"Session aborted")),l.abort()};t.signal?.addEventListener("abort",d);try{return await o.promise}finally{this.removeEventListener("provider",u),t.signal?.removeEventListener("abort",d),l.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toFilterKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toFilterKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async addPeer(e,t){let n=await this.convertToProvider(e,"manually-added",t);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(e,t,n){let s=Ye(),o=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",t,this.maxProviders,e,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let u=await i.convertToProvider(l,"manual",n);u!=null&&(yield u)}},c=async function*(){yield*a(),yield*i.findNewProviders(e,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",o,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),o++,this.providers.length===t&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),s.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",o,t,this.providers.length),this.providers.length<t)throw new Kl(`Found ${o} of ${t} ${this.name} providers for ${e}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",e,i),s.reject(i)}),s.promise}};var Jh=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},fu=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},e1=class extends Error{static name="InvalidDatastoreVersionError";name="InvalidDatastoreVersionError"},vs=class extends Error{static name="InvalidConfigurationError";name="InvalidConfigurationError"},t1=class extends AggregateError{static name="GetFailedError";name="GetFailedError"},r1=class extends AggregateError{static name="LoadBlockFailedError";name="LoadBlockFailedError"},hu=class extends Error{static name="BlockNotFoundWhileOfflineError";name="BlockNotFoundWhileOfflineError"};function lN(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var nc=lN;function uN(r){return r[Symbol.asyncIterator]!=null}function dN(r,e){let t=0;if(uN(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=nc(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var Hr=dN;function fN(r){return r[Symbol.asyncIterator]!=null}function hN(r){if(fN(r))return(async()=>{let n=new Uint8Array(0);for await(let s of r)n=Ke([n,s],n.length+s.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ke(e,t)}var n1=hN;function s1({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*pN(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let s=[...r,t],o=$.asCID(n);o!=null?yield[s.join("/"),o]:typeof n=="object"&&(yield*D4(n,s))}else{let t=$.asCID(e);t!=null?yield[r.join("/"),t]:yield*D4(e,r)}}function*D4(r,e){if(r==null||r instanceof Uint8Array)return;let t=$.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,s]of Object.entries(r)){let o=[...e,n];yield*pN(o,s)}}function*mN(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let s=[...r,t];yield s.join("/"),typeof n=="object"&&$.asCID(n)==null&&(yield*N4(n,s))}else yield*N4(e,r)}function*N4(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let s=[...e,t];yield s.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&$.asCID(n)==null&&(yield*mN(s,n))}}function gN(r,e){let t=r;for(let[n,s]of e.entries()){if(t=t[s],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(i=>`[${JSON.stringify(i)}]`).join("")}`);let o=$.asCID(t);if(o!=null)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var O4=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:s1(),bytes:s1(),value:s1(),asBlock:s1()})}links(){return D4(this.value,[])}tree(){return N4(this.value,[])}get(e="/"){return gN(this.value,e.split("/").filter(Boolean))}};function F9({bytes:r,cid:e,value:t,codec:n}){let s=t!==void 0?t:n?.decode(r);if(s===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new O4({cid:e,bytes:r,value:s})}function U4(r){return e=>new M4(e,r)}var B4=class{components;constructor(e,t={}){this.components=e}async*walk(e,t){let n=this.getQueue(),s=Hr(n.toGenerator(t),c=>c!=null),o=!1,i=t?.depth??1/0,a=async c=>{let l=c.cid,u=await n1(this.components.blockstore.get(l,c)),d=F9({cid:l,bytes:u,codec:await this.components.getCodec(l.code)});if(c.depth<i)for(let[,f]of d.links())t?.includeChild?.(f,d)!==!1&&n.add(a,{...c,cid:f,depth:c.depth+1,path:[...c.path,f]}).catch(h=>{o||s.throw(h)});return{block:d,depth:c.depth,path:c.path}};n.add(a,{...t,cid:e,depth:0,path:[e]}).catch(c=>{o||s.throw(c)});try{yield*s}finally{o=!0,n.abort()}}},M4=class extends B4{getQueue(){return new ht({concurrency:1,sort:(e,t)=>e.options.depth===t.options.depth?0:e.options.depth<t.options.depth?1:-1})}};function sc(r){return r==null?!1:$.asCID(r)!=null}function ho(r){return r?.then!=null}var $9="1.2.840.10045.3.1.7",K9="1.3.132.0.34",H9="1.3.132.0.35";async function V9(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function q9(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,re(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function z9(r,e,t,n){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,re(e),re(t.subarray()));return n?.signal?.throwIfAborted(),o}var yN=parseInt("11111",2),F4=parseInt("10000000",2),wN=parseInt("01111111",2),W9={0:pu,1:pu,2:bN,3:vN,4:SN,5:xN,6:EN,16:pu,22:pu,48:pu};function nn(r,e={offset:0}){let t=r[e.offset]&yN;if(e.offset++,W9[t]!=null)return W9[t](r,e);throw new Error("No decoder for tag "+t)}function mu(r,e){let t=0;if((r[e.offset]&F4)===F4){let n=r[e.offset]&wN,s="0x";e.offset++;for(let o=0;o<n;o++,e.offset++){if(e.offset>=r.byteLength)throw new Error("invalid DER element length");s+=r[e.offset].toString(16).padStart(2,"0")}t=parseInt(s,16)}else t=r[e.offset],e.offset++;if(!Number.isInteger(t)||t<0||t>r.byteLength-e.offset)throw new Error("invalid DER element length");return t}function pu(r,e){mu(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=nn(r,e);if(n===null)break;t.push(n)}return t}function bN(r,e){let t=mu(r,e),n=e.offset,s=e.offset+t,o=[];for(let i=n;i<s;i++)i===n&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function EN(r,e){let t=mu(r,e),n=e.offset+t,s=r[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function xN(r,e){return e.offset++,null}function vN(r,e){let t=mu(r,e),n=r[e.offset];e.offset++;let s=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function SN(r,e){let t=mu(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function AN(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new V;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function o1(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=AN(r.byteLength);return new V(Uint8Array.from([e.byteLength|F4]),e)}function pr(r){let e=new V,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new V(Uint8Array.from([2]),o1(e),e)}function gu(r){let e=Uint8Array.from([0]),t=new V(e,r);return new V(Uint8Array.from([3]),o1(t),t)}function G9(r){return new V(Uint8Array.from([4]),o1(r),r)}function Tn(r,e=48){let t=new V;for(let n of r)t.append(n);return new V(Uint8Array.from([e]),o1(t),t)}var TN=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),IN=Uint8Array.from([6,5,43,129,4,0,34]),CN=Uint8Array.from([6,5,43,129,4,0,35]),j9={ext:!0,kty:"EC",crv:"P-256"},Y9={ext:!0,kty:"EC",crv:"P-384"},X9={ext:!0,kty:"EC",crv:"P-521"},oc=32,ic=48,ac=66;function Q9(r){let e=nn(r);return $4(e)}function $4(r){let e=r[1],t=_(e,"base64url"),n=r[2][1][0],s=1,o,i;if(e.byteLength===oc)return o=_(n.subarray(s,s+oc),"base64url"),i=_(n.subarray(s+oc),"base64url"),new Pi({...j9,key_ops:["sign"],d:t,x:o,y:i});if(e.byteLength===ic)return o=_(n.subarray(s,s+ic),"base64url"),i=_(n.subarray(s+ic),"base64url"),new Pi({...Y9,key_ops:["sign"],d:t,x:o,y:i});if(e.byteLength===ac)return o=_(n.subarray(s,s+ac),"base64url"),i=_(n.subarray(s+ac),"base64url"),new Pi({...X9,key_ops:["sign"],d:t,x:o,y:i});throw new v(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function K4(r){let e=nn(r);return Z9(e)}function Z9(r){let e=r[1][1][0],t=1,n,s;if(e.byteLength===oc*2+1)return n=_(e.subarray(t,t+oc),"base64url"),s=_(e.subarray(t+oc),"base64url"),new _i({...j9,key_ops:["verify"],x:n,y:s});if(e.byteLength===ic*2+1)return n=_(e.subarray(t,t+ic),"base64url"),s=_(e.subarray(t+ic),"base64url"),new _i({...Y9,key_ops:["verify"],x:n,y:s});if(e.byteLength===ac*2+1)return n=_(e.subarray(t,t+ac),"base64url"),s=_(e.subarray(t+ac),"base64url"),new _i({...X9,key_ops:["verify"],x:n,y:s});throw new v(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function J9(r){return Tn([pr(Uint8Array.from([1])),G9(A(r.d??"","base64url")),Tn([tE(r.crv)],160),Tn([gu(new V(Uint8Array.from([4]),A(r.x??"","base64url"),A(r.y??"","base64url")))],161)]).subarray()}function eE(r){return Tn([pr(Uint8Array.from([1])),Tn([tE(r.crv)],160),Tn([gu(new V(Uint8Array.from([4]),A(r.x??"","base64url"),A(r.y??"","base64url")))],161)]).subarray()}function tE(r){if(r==="P-256")return TN;if(r==="P-384")return IN;if(r==="P-521")return CN;throw new v(`Invalid curve ${r}`)}async function rE(r="P-256"){let e=await V9(r);return new Pi(e.privateKey)}var _i=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=eE(this.jwk)),this._raw}toMultihash(){return ot.digest(St(this))}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}async verify(e,t,n){return z9(this.jwk,t,e,n)}},Pi=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new _i({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=J9(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}async sign(e,t){return q9(this.jwk,e,t)}};var i1=BigInt(4294967295),nE=BigInt(32);function kN(r,e=!1){return e?{h:Number(r&i1),l:Number(r>>nE&i1)}:{h:Number(r>>nE&i1)|0,l:Number(r&i1)|0}}function sE(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=kN(r[o],e);[n[o],s[o]]=[i,a]}return[n,s]}var _N=r=>r/2**32|0,PN=r=>r>>>0;function oE(r,e,t,n){let s=_N(t),o=PN(t);r.setUint32(e,n?o:s,n),r.setUint32(e+4,n?s:o,n)}var H4=(r,e,t)=>r>>>t,V4=(r,e,t)=>r<<32-t|e>>>t,Li=(r,e,t)=>r>>>t|e<<32-t,Ri=(r,e,t)=>r<<32-t|e>>>t,yu=(r,e,t)=>r<<64-t|e>>>t-32,wu=(r,e,t)=>r>>>t-32|e<<64-t;function zn(r,e,t,n){let s=(e>>>0)+(n>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}var iE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),aE=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,cE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),lE=(r,e,t,n,s)=>e+t+n+s+(r/2**32|0)|0,uE=(r,e,t,n,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),dE=(r,e,t,n,s,o)=>e+t+n+s+o+(r/2**32|0)|0;function a1(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var q4=r=>r?`"${r}" `:"";function Ht(r,e=""){if(typeof r!="number")throw new TypeError(q4(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(q4(e)+"expected integer >= 0, got "+r);return r}function er(r,e,t=""){if(a1(r)&&(e===void 0||r.length===e))return r;e!==void 0&&Ht(e,"length");let n=a1(r),s=e!==void 0?` of length ${e}`:"",o=n?`length=${r.length}`:`type=${typeof r}`,i=q4(t)+"expected Uint8Array"+s+", got "+o;throw n?new RangeError(i):new TypeError(i)}function Ss(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Ht(r.outputLen),Ht(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var RN=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},fE=(r,e)=>{RN(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function cc(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function c1(r,e){er(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function wt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function lc(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function In(r,e){return r<<32-e|r>>>e}function l1(r,e){return r<<e|r>>>32-e>>>0}var pE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",DN=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function u1(r){if(er(r),pE)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=DN[r[t]];return e}function hE(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function d1(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(pE)try{return Uint8Array.fromHex(r)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=hE(r.charCodeAt(o)),a=hE(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}n[s]=i*16+a}return n}function NN(r){let e=globalThis;if(typeof e.scheduler?.yield=="function"){let t=e.scheduler.yield();return r&&t.catch(r),t}return new Promise(t=>e.setTimeout(t,0))}async function mE(r,e,t,n){if(Ht(r,"iters"),Ht(e,"tick"),typeof t!="function")throw new TypeError("callback must be a function");let s=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-s;i>=0&&i<e||(await NN(n),s=Date.now())}}function ON(r){if(typeof r!="string")throw new TypeError("string expected");let e=new TextEncoder().encode(r);try{return new Uint8Array(e)}finally{wt(e)}}function z4(r,e=""){return typeof r=="string"?ON(r):er(r,void 0,e)}function W4(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];er(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function G4(r,e,t="opts"){return fE(r,"defaults"),e!==void 0&&fE(e,t),Object.assign(Object.create(null),r,e)}function bu(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=G4({},e,"info");let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function gE(r=32){Ht(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var j4=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function f1(r,e,t){return r&e^~r&t}function h1(r,e,t){return r&e^r&t^e&t}var Di=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=lc(this.buffer)}update(e){cc(this),er(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length,i=!1;for(let a=0;a<o;){let c=Math.min(s-this.pos,o-a);if(c===s){let l=lc(e);for(;s<=o-a;a+=s)this.process(l,a);i=!0;continue}n.set(a===0&&c===o?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===s&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){cc(this),c1(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>s-i&&(this.process(n,0),t.fill(0)),oE(n,s-8,this.length*8,o),this.process(n,0),this.roundClean();let a=e===t?n:lc(e),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},yE=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var wE=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var BN=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),po=new Uint32Array(64),Y4=class extends Di{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[e,t,n,s,o,i,a,c]}set(e,t,n,s,o,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)po[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=po[d-15],h=po[d-2],p=In(f,7)^In(f,18)^f>>>3,g=In(h,17)^In(h,19)^h>>>10;po[d]=g+po[d-7]+p+po[d-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=In(a,6)^In(a,11)^In(a,25),h=u+f+f1(a,c,l)+BN[d]+po[d]|0,g=(In(n,2)^In(n,13)^In(n,22))+h1(n,s,o)|0;u=l,l=c,c=a,a=i+h|0,i=o,o=s,s=n,n=h+g|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,o,i,a,c,l,u)}roundClean(){wt(po)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),wt(this.buffer)}},X4=class extends Y4{constructor(){super(32,yE)}};var bE=sE(["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))),MN=bE[0],UN=bE[1],mo=new Uint32Array(80),go=new Uint32Array(80),Q4=class extends Di{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:g,Hl:y}=this;return[e,t,n,s,o,i,a,c,l,u,d,f,h,p,g,y]}set(e,t,n,s,o,i,a,c,l,u,d,f,h,p,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let E=0;E<16;E++,t+=4)mo[E]=e.getUint32(t),go[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let S=mo[E-15]|0,T=go[E-15]|0,C=Li(S,T,1)^Li(S,T,8)^H4(S,T,7),k=Ri(S,T,1)^Ri(S,T,8)^V4(S,T,7),O=mo[E-2]|0,N=go[E-2]|0,K=Li(O,N,19)^yu(O,N,61)^H4(O,N,6),ee=Ri(O,N,19)^wu(O,N,61)^V4(O,N,6),J=cE(k,ee,go[E-7],go[E-16]),ie=lE(J,C,K,mo[E-7],mo[E-16]);mo[E]=ie|0,go[E]=J|0}let{Ah:n,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:g,Gl:y,Hh:m,Hl:b}=this;for(let E=0;E<80;E++){let S=Li(d,f,14)^Li(d,f,18)^yu(d,f,41),T=Ri(d,f,14)^Ri(d,f,18)^wu(d,f,41),C=d&h^~d&g,k=f&p^~f&y,O=uE(b,T,k,UN[E],go[E]),N=dE(O,m,S,C,MN[E],mo[E]),K=O|0,ee=Li(n,s,28)^yu(n,s,34)^yu(n,s,39),J=Ri(n,s,28)^wu(n,s,34)^wu(n,s,39),ie=n&o^n&a^o&a,M=s&i^s&c^i&c;m=g|0,b=y|0,g=h|0,y=p|0,h=d|0,p=f|0,{h:d,l:f}=zn(l|0,u|0,N|0,K|0),l=a|0,u=c|0,a=o|0,c=i|0,o=n|0,i=s|0;let G=iE(K,J,M);n=aE(G,N,ee,ie),s=G|0}({h:n,l:s}=zn(this.Ah|0,this.Al|0,n|0,s|0)),{h:o,l:i}=zn(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=zn(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=zn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=zn(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=zn(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:y}=zn(this.Gh|0,this.Gl|0,g|0,y|0),{h:m,l:b}=zn(this.Hh|0,this.Hl|0,m|0,b|0),this.set(n,s,o,i,a,c,l,u,d,f,h,p,g,y,m,b)}roundClean(){wt(mo,go)}destroy(){this.destroyed=!0,wt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Z4=class extends Q4{constructor(){super(64,wE)}};var tr=bu(()=>new X4,j4(1));var As=bu(()=>new Z4,j4(3));function m1(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var Pe=(r,e,t)=>er(r,e,t),J4=Ht;function xE(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function yo(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function Ni(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var Eu=u1,sn=(...r)=>W4(...r),uc=r=>d1(r),bo=a1,Ts=r=>gE(r),p1=BigInt(0),EE=BigInt(1),FN=r=>r?`"${r}" `:"";function Ir(r,e=""){if(typeof r!="boolean")throw new TypeError(FN(e)+"expected boolean, got type="+typeof r);return r}function g1(r){if(typeof r=="bigint"){if(!wo(r))throw new RangeError("positive bigint expected, got "+r)}else J4(r);return r}function Is(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function xu(r){let e=g1(r).toString(16);return e.length&1?"0"+e:e}function vE(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?p1:BigInt("0x"+r)}function Wn(r){return vE(u1(r))}function Gn(r){return vE(u1(Eo(er(r)).reverse()))}function y1(r,e){if(Ht(e),e===0)throw new Error("zero output length is invalid");r=g1(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return d1(n.padStart(t,"0"))}function vu(r,e){return y1(r,e).reverse()}function Eo(r){return Uint8Array.from(Pe(r))}function wo(r){return typeof r=="bigint"&&p1<=r}function ey(r,e,t){return wo(r)&&wo(e)&&wo(t)&&e<=r&&r<t}function jn(r,e,t,n){if(!ey(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function dc(r){if(r<p1)throw new Error("expected non-negative bigint, got "+r);return r===p1?0:r.toString(2).length}var Su=r=>(Is(r,"n"),(EE<<BigInt(r))-EE);function SE(r,e,t){if(Ht(r,"hashLen"),Ht(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},f=(...y)=>t(l,sn(c,...y)),h=(y=s)=>{l=f(o,y),c=f(),y.length!==0&&(l=f(i,y),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,m=[];for(;y<e;){c=f();let b=c.slice();m.push(b),y+=c.length}return sn(...m)};return(y,m)=>{d(),h(y);let b;for(;(b=m(p()))===void 0;)h();return d(),b}}function rr(r,e={},t={},n="object"){yo(r,n),yo(e,"fields"),yo(t,"optFields");function s(i,a,c){let l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,u=r[i];if(!Object.hasOwn(r,i)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&u===void 0)return;let d=typeof u;if(d!==a||u===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let o=(i,a)=>Object.entries(i).forEach(([c,l])=>s(c,l,a));o(e,!1),o(t,!0)}var _t=BigInt(0),$e=BigInt(1),xo=BigInt(2),IE=BigInt(3),ty=BigInt(4),CE=BigInt(5),$N=BigInt(7),kE=BigInt(8),KN=BigInt(9),HN=BigInt(15),_E=BigInt(16),VN=BigInt("0x10000000000000000");function He(r,e){if(e<=_t)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=_t?t:e+t}function PE(r,e,t){if(t<=$e)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<_t)throw new Error("invalid exponent, negatives unsupported");if(e===_t)return $e;if(e===$e)return r;let n=r%t;if(n<_t&&(n+=t),e<VN){let a=$e;for(;e>_t;)e&$e&&(a=a*n%t),n=n*n%t,e>>=$e;return a}let s=[];for(;e>_t;)s.push(Number(e&HN)),e>>=ty;let o=new Array(16);o[0]=$e,o[1]=n;for(let a=2;a<16;a++)o[a]=o[a-1]*n%t;let i=o[s[s.length-1]];for(let a=s.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=s[a];c!==0&&(i=i*o[c]%t)}return i}function tt(r,e,t){if(t<=$e)throw new Error("pow2: expected modulus > 1, got "+t);if(e<_t)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >_t;)n*=n,n%=t;return n}function AE(r,e){if(r===_t)throw new Error("invert: expected non-zero number");if(e<=$e)throw new Error("invert: expected modulus > 1, got "+e);let t=He(r,e),n=e,s=_t,o=$e;for(;t!==_t;){let a=n/t,c=n-t*a,l=s-o*a;n=t,t=c,s=o,o=l}if(n!==$e)throw new Error("invert: does not exist");return He(s,e)}function LE(r,e){if(e<=$e)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=He(r,e);if(t===_t)throw new Error("invertCt: expected non-zero number");let n=PE(t,e-xo,e);if(He(t*n,e)!==$e)throw new Error("invertCt: does not exist");return n}function ry(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function ny(r,e){if((r&$e)===_t)throw new Error(e+": expected odd modulus, got "+r)}function RE(r,e){let t=r,n=(t.ORDER+$e)/ty,s=t.pow(e,n);return ry(t,s,e),s}function qN(r,e){let t=r,n=(t.ORDER-CE)/kE,s=t.mul(e,xo),o=t.pow(s,n),i=t.mul(e,o),a=t.mul(t.mul(i,xo),o),c=t.mul(i,t.sub(a,t.ONE));return ry(t,c,e),c}function zN(r){let e=hc(r),t=DE(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+$N)/_E;return((a,c)=>{let l=a,u=l.pow(c,i),d=l.mul(u,n),f=l.mul(u,s),h=l.mul(u,o),p=l.eql(l.sqr(d),c),g=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,g);let y=l.eql(l.sqr(d),c),m=l.cmov(u,d,y);return ry(l,m,c),m})}function DE(r){if(r<IE)throw new Error("sqrt is not defined for small field");ny(r,"tonelliShanks");let e=r-$e,t=0;for(;e%xo===_t;)e/=xo,t++;let n=xo,s=hc(r);for(;Au(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return RE;let o=s.pow(n,e),i=(e+$e)/xo;return function(c,l){let u=c;if(u.is0(l))return l;if(Au(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,o),h=u.pow(l,e),p=u.pow(l,i);for(;!u.eql(h,u.ONE);){if(u.is0(h))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=u.sqr(h);for(;!u.eql(y,u.ONE);)if(g++,y=u.sqr(y),g===d)throw new Error("Cannot find square root");let m=$e<<BigInt(d-g-1),b=u.pow(f,m);d=g,f=u.sqr(b),h=u.mul(h,f),p=u.mul(p,b)}return p}}function WN(r){return ny(r,"Fp.sqrt"),r%ty===IE?RE:r%kE===CE?qN:r%_E===KN?zN(r):DE(r)}var NE=(r,e)=>(He(r,e)&$e)===$e,GN=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function fc(r){if(yo(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);Is(r.BYTES,"BYTES"),Is(r.BITS,"BITS");for(let e of GN)Ni(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=$e)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function b1(r,e,t=!1){fc(r),m1(e,"nums"),Ir(t,"passZero");let n=r,s=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((a,c,l)=>n.is0(c)?a:(s[l]=a,n.mul(a,c)),n.ONE),i=n.inv(o);return e.reduceRight((a,c,l)=>n.is0(c)?a:(s[l]=n.mul(a,s[l]),n.mul(a,c)),i),s}function Au(r,e){fc(r);let t=r;ny(t.ORDER,"FpLegendre");let n=(t.ORDER-$e)/xo,s=t.pow(e,n),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function jN(r,e){if(e!==void 0&&J4(e),r<=_t)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=dc(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var TE=new WeakMap,w1=class{ORDER;BITS;BYTES;isLE;ZERO=_t;ONE=$e;_lengths;_mod;constructor(e,t={}){if(e<=$e)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=jN(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return He(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return _t<=e&&e<this.ORDER}is0(e){return e===_t}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&$e)===$e}neg(e){return He(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return He(e*e,this.ORDER)}add(e,t){return He(e+t,this.ORDER)}sub(e,t){return He(e-t,this.ORDER)}mul(e,t){return He(e*t,this.ORDER)}pow(e,t){return PE(e,t,this.ORDER)}div(e,t){return He(e*AE(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return AE(e,this.ORDER)}sqrt(e){let t=TE.get(this);return t||TE.set(this,t=WN(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?vu(e,this.BYTES):y1(e,this.BYTES)}fromBytes(e,t=!1){Pe(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?Gn(e):Wn(e);if(a&&(c=He(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return b1(this,e,!0)}cmov(e,t,n){return Ir(n,"condition"),n?t:e}};function hc(r,e={}){return Object.freeze(w1.prototype),new w1(r,e)}function OE(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=$e)throw new Error("field order must be greater than 1");let e=dc(r-$e);return Math.ceil(e/8)}function E1(r){let e=OE(r);return e+Math.ceil(e/2)}function x1(r,e,t=!1){Pe(r);let n=r.length,s=OE(e),o=Math.max(E1(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?Gn(r):Wn(r),a=He(i,e-$e)+$e;return t?vu(a,s):y1(a,s)}var iy=BigInt(0),Tu=BigInt(1),YN=BigInt(4),sy=16,BE=128,XN=5,ME=2**31;function vo(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);Ni(e.fromAffine,"Point.fromAffine"),Ni(e.fromBytes,"Point.fromBytes"),Ni(e.fromHex,"Point.fromHex"),yo(e.BASE,"Point.BASE"),yo(e.ZERO,"Point.ZERO"),fc(e.Fp),fc(e.Fn)}function v1(r,e){vo(r),FE(e,r);let t=b1(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function QN(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function ZN(r,e){let t=r*(4*e+128);if(t>ME)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+ME/2**20+" MiB")}function ay(r,e){if(r!==void 0){Ni(r,"randomBytes");try{let t=r(e);if(!bo(t)||t.length!==e)return}catch{return}return r}}function FE(r,e){m1(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function JN(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,s)=>{if(!(t===void 0?e.isValid(n):wo(n)&&n<t))throw new Error("invalid scalar at index "+s)})}var $E=new WeakMap;function oy(r){return $E.get(r)||1}function eO(r,e){let t=r.double(),n=[r];for(let s=1;s<e;s++)n.push(n[s-1].add(t));return n}function tO(r,e){let t=2**e,n=t/2,s=BigInt(t-1),o=[];for(;r>iy;){let i=0;r&Tu&&(i=Number(r&s),i>=n&&(i-=t),r-=BigInt(i)),o.push(i),r>>=Tu}return o}function rO(r,e,t){let n=2**e,s=n/2,o=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let l=Number(r&o);r>>=i,l>s&&(l-=n,r+=Tu),a.push(l)}if(r!==iy)throw new Error("invalid wnaf");return a}function nO(r,e,t){let n=0;for(let o of t)n=Math.max(n,o.length);let s=r;for(let o=n-1;o>=0;o--){o!==n-1&&(s=s.double());for(let i=0;i<t.length;i++){let a=t[i][o];if(a){let c=e[i][Math.abs(a)-1>>1];s=s.add(a<0?c.negate():c)}}}return s}var pc=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){vo(e),this.randomBytes=ay(t,sy),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let s=Math.ceil(n/t)+1,o=2**(t-1),i=[],a=e;for(let c=0;c<s;c++){let l=a;for(let u=0;u<o;u++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:t,bits:n,windows:s,comp:i}}wnafCachedCT(e,t){let{W:n,windows:s,comp:o}=e,i=2**(n-1),a=rO(t,n,s),c=this.ZERO,l=this.BASE;for(let u=0;u<s;u++){let d=a[u],f=u*i,h=Math.abs(d)-1,p=o[f];for(let y=1;y<i;y++)p=y===h?o[f+y]:p;let g=p.negate();d===0?l=l.add(o[f]):c=c.add(d<0?g:p)}return{p:c,f:l}}getWnafPrecomputes(e,t,n,s){let o=this.wnafPrecomputes.get(t),i=o?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof s=="function"&&(i={...i,comp:s(i.comp)}),o||(o=[],this.wnafPrecomputes.set(t,o)),o.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!ey(t,Tu,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,s){let o=oy(e);return o===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(o,e,n,s),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let s=this.Point.Fn.BITS+BE,o=this.randomBytes(sy);if(!bo(o)||o.length!==sy)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+Wn(o)*this.Point.Fn.ORDER;return this.runCT(e,i,s,n)}fixedWindowCT(e,t,n){let s=XN,o=1<<s,i=Su(s),a=new Array(o);a[0]=this.ZERO;for(let u=1;u<o;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/s),l=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let h=0;h<s;h++)l=l.double();let d=Number(t>>BigInt(u*s)&i),f=a[0];for(let h=1;h<o;h++)f=h===d?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Tu?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,s){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,s):this.mulCT(e,t,s)}mulUnsafe(e,t,n){if(this.assertPoint(e),!wo(t))throw new Error("invalid scalar");let s=oy(e);if(s===1||t>=this.Point.Fn.ORDER)return S1(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(s,e,this.bits,n);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),QN(t,this.bits);let n=Math.ceil((this.bits+BE)/t)+1;ZN(n*2**(t-1),this.Point.Fp.BYTES),$E.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return oy(e)!==1}};function S1(r,e,t,n=!1){if(vo(r),FE(e,r),Ir(n,"allowOversized"),JN(t,r.Fn,n?r.Fn.ORDER**YN:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let s=e.map(i=>eO(i,4)),o=t.map(i=>tO(i,4));return nO(r.ZERO,s,o)}function UE(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return fc(e),e}else return hc(r,{isLE:t})}function A1(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);rr(t);for(let c of["p","n","h"]){let l=e[c];if(!(wo(l)&&l!==iy))throw new Error(`CURVE.${c} must be positive bigint`)}let s=UE(e.p,t.Fp,n),o=UE(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!s.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function mc(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var T1=BigInt(0),I1=BigInt(1),C1=BigInt(2),sO=BigInt(4),KE=BigInt(8);function oO(r,e,t,n){let s=r.sqr(t),o=r.sqr(n),i=r.add(r.mul(e.a,s),o),a=r.add(r.ONE,r.mul(e.d,r.mul(s,o)));return r.eql(i,a)}function HE(r,e={}){rr(e,{},{},"extraOpts");let t=e,n=A1("edwards",r,t,t.FpFnLE),{Fp:s,Fn:o}=n,i=n.CURVE,{h:a}=i;if(Au(s,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Au(s,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");rr(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Ts:t.randomBytes,l=C1<<BigInt(s.BYTES*8)-I1;function u(b){if(!s.isOdd)throw new Error("Field does not have .isOdd()");return s.isOdd(b)}let d=t.uvRatio===void 0?(b,E)=>{try{return{isValid:!0,value:s.sqrt(s.div(b,E))}}catch{return{isValid:!1,value:T1}}}:t.uvRatio;if(!oO(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let f=s.eql(i.a,s.neg(s.ONE))?b=>s.neg(b):s.eql(i.a,s.ONE)?b=>b:b=>s.mul(i.a,b);function h(b,E,S=!1){let T=S?I1:T1;return jn("coordinate "+b,E,T,l),E}function p(b){if(!(b instanceof g))throw new Error("EdwardsPoint expected")}class g{static BASE=new g(i.Gx,i.Gy,s.ONE,s.mul(i.Gx,i.Gy));static ZERO=new g(s.ZERO,s.ONE,s.ONE,s.ZERO);static Fp=s;static Fn=o;X;Y;Z;T;constructor(E,S,T,C){this.X=h("x",E),this.Y=h("y",S),this.Z=h("z",T,!0),this.T=h("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(E){if(E instanceof g)throw new Error("extended point not allowed");let{x:S,y:T}=E||{};return h("x",S),h("y",T),new g(S,T,s.ONE,s.mul(S,T))}static fromBytes(E,S=!1){let T=s.BYTES,{a:C,d:k}=i;E=Eo(Pe(E,T,"point")),Ir(S,"zip215");let O=Eo(E),N=E[T-1];O[T-1]=N&-129;let K=Gn(O),ee=S?l:s.ORDER;jn("point.y",K,T1,ee);let J=s.sqr(K),ie=s.sub(J,s.ONE),M=s.sub(s.mulN(k,J),C),{isValid:G,value:U}=d(ie,M);if(!G)throw new Error("bad point: invalid y coordinate");let B=u(U),te=(N&128)!==0;if(!S&&s.is0(U)&&te)throw new Error("bad point: x=0 and x_0=1");return te!==B&&(U=s.neg(U)),g.fromAffine({x:U,y:K})}static fromHex(E,S=!1){return g.fromBytes(uc(E),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=6,S=!0){return m.setWindowSize(this,E),S||this.multiply(C1),this}assertValidity(){let E=this,{a:S,d:T}=i;if(E.is0())throw new Error("bad point: ZERO");let{X:C,Y:k,Z:O,T:N}=E,K=s.sqr(C),ee=s.sqr(k),J=s.sqr(O),ie=s.sqr(J),M=s.mul(K,S),G=s.mul(s.add(M,ee),J),U=s.add(ie,s.mul(T,s.mul(K,ee)));if(!s.eql(G,U))throw new Error("bad point: equation left != right (1)");let B=s.mul(C,k),te=s.mul(O,N);if(!s.eql(B,te))throw new Error("bad point: equation left != right (2)")}equals(E){p(E);let{X:S,Y:T,Z:C}=this,{X:k,Y:O,Z:N}=E,K=s.mul(S,N),ee=s.mul(k,C),J=s.mul(T,N),ie=s.mul(O,C);return s.eql(K,ee)&&s.eql(J,ie)}is0(){return this.equals(g.ZERO)}negate(){return new g(s.neg(this.X),this.Y,this.Z,s.neg(this.T))}double(){let{X:E,Y:S,Z:T}=this,C=s.sqr(E),k=s.sqr(S),O=s.mul(s.sqr(T),C1),N=f(C),K=s.addN(E,S),ee=s.sub(s.subN(s.sqr(K),C),k),J=s.addN(N,k),ie=s.subN(J,O),M=s.subN(N,k),G=s.mul(ee,ie),U=s.mul(J,M),B=s.mul(ee,M),te=s.mul(ie,J);return new g(G,U,te,B)}add(E){p(E);let{d:S}=i,{X:T,Y:C,Z:k,T:O}=this,{X:N,Y:K,Z:ee,T:J}=E,ie=s.mul(T,N),M=s.mul(C,K),G=s.mul(s.mulN(O,S),J),U=s.mul(k,ee),B=s.sub(s.subN(s.mulN(s.addN(T,C),s.addN(N,K)),ie),M),te=s.subN(U,G),F=s.addN(U,G),R=s.sub(M,f(ie)),x=s.mul(B,te),I=s.mul(F,R),D=s.mul(B,R),z=s.mul(te,F);return new g(x,I,z,D)}subtract(E){return p(E),this.add(E.negate())}multiply(E){if(!o.isValidNot0(E))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:T}=m.mulSecret(this,E,a,y);return y([S,T])[0]}multiplyUnsafe(E){if(!o.isValid(E))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return E===T1?g.ZERO:this.is0()||E===I1?this:m.mulUnsafe(this,E,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.mulUnsafe(this,i.n).is0()}toAffine(E){let S=this,T=E;if(T!=null&&typeof T!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof T);let{X:C,Y:k,Z:O}=S,N=S.is0();T==null&&(T=N?s.create(KE):s.inv(O));let K=s.mul(C,T),ee=s.mul(k,T),J=s.mul(O,T);if(N)return{x:s.ZERO,y:s.ONE};if(!s.eql(J,s.ONE))throw new Error("invZ was invalid");return{x:K,y:ee}}clearCofactor(){return a===I1?this:a===C1?this.double():a===sO?this.double().double():a===KE?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:E,y:S}=this.toAffine(),T=s.toBytes(S);return T[T.length-1]|=u(E)?128:0,T}toHex(){return Eu(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=b=>v1(g,b),m=new pc(g,c);return m.bits>=6&&g.BASE.precompute(6),Object.freeze(g.prototype),Object.freeze(g),g}function VE(r,e,t={}){if(vo(r),typeof e!="function")throw new Error('"hash" function param is required');let n=e,s=t;rr(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(Is(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=s.randomBytes===void 0?Ts:s.randomBytes,f=s.toMontgomery,h=s.toMontgomerySecret,p=s.adjustScalarBytes===void 0?M=>M:s.adjustScalarBytes,g=s.domain===void 0?(M,G,U)=>{if(Ir(U,"phflag"),G.length||U)throw new Error("Contexts/pre-hash are not supported");return M}:s.domain;function y(M){return c.create(Gn(M))}function m(M){let G=N.secretKey;Pe(M,N.secretKey,"secretKey");let U=Pe(n(M),2*G,"hashedSecretKey"),B=p(U.slice(0,G)),te=U.slice(G,2*G),F=y(B);return{head:B,prefix:te,scalar:F}}function b(M){let{head:G,prefix:U,scalar:B}=m(M),te=i.multiply(B),F=te.toBytes();return{head:G,prefix:U,scalar:B,point:te,pointBytes:F}}function E(M){return b(M).pointBytes}function S(M=Uint8Array.of(),...G){let U=sn(...G);return y(n(g(U,Pe(M,void 0,"context"),!!o)))}function T(M,G,U={}){rr(U,{},{},"options"),M=Eo(Pe(M,void 0,"message")),o&&(M=o(M));let{prefix:B,scalar:te,pointBytes:F}=b(G),R=S(U.context,B,M),x=i.multiply(R).toBytes(),I=S(U.context,x,F,M),D=c.create(R+I*te);if(!c.isValid(D))throw new Error("sign failed: invalid s");let z=sn(x,c.toBytes(D));return Pe(z,N.signature,"result")}let C={zip215:s.zip215};function k(M,G,U,B=C){rr(B);let{context:te}=B,F=B.zip215===void 0?!!C.zip215:B.zip215,R=N.signature;M=Pe(M,R,"signature"),G=Pe(G,void 0,"message"),U=Pe(U,N.publicKey,"publicKey"),F!==void 0&&Ir(F,"zip215"),o&&(G=o(G));let x=R/2,I=M.subarray(0,x),D=Gn(M.subarray(x,R)),z,Q,Z;try{z=r.fromBytes(U,F),Q=r.fromBytes(I,F),Z=i.multiplyUnsafe(D)}catch{return!1}if(!F&&z.isSmallOrder())return!1;let ne=S(te,I,U,G);return Q.add(z.multiplyUnsafe(ne)).subtract(Z).clearCofactor().is0()}let O=a.BYTES,N={secretKey:O,publicKey:O,signature:2*O,seed:O};function K(M){return M=M===void 0?d(N.seed):M,Pe(M,N.seed,"seed")}function ee(M){return bo(M)&&M.length===N.secretKey}function J(M,G){try{return!!r.fromBytes(M,G===void 0?C.zip215:G)}catch{return!1}}let ie={getExtendedPublicKey:b,randomSecretKey:K,isValidSecretKey:ee,isValidPublicKey:J,toMontgomery(M){if(f===void 0)throw new Error("Montgomery conversion is not supported for this curve");return f(r.fromBytes(M))},toMontgomerySecret(M){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(M)}};return Object.freeze(N),Object.freeze(ie),Object.freeze({keygen:mc(K,E),getPublicKey:E,sign:T,verify:k,utils:ie,Point:r,lengths:N})}var Oi=BigInt(0),on=BigInt(1),k1=BigInt(2);function qE(r,e){return r+e-(e>>on<<on)}function iO(r){let e=BigInt(6)*r;return(t,n,s)=>{let o=n+s,a=((e+s-n)*t+n)%r;return{x_2:a,x_3:o-a}}}function aO(r){return rr(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...r})}function zE(r){let e=aO(r),{P:t,type:n,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");let l=i===void 0?Ts:i,u=c?255:448,d=iO(t),f=c?32:56,h=BigInt(c?9:5),p=BigInt(c?121665:39081),g=c?k1**BigInt(254):k1**BigInt(447),y=c?BigInt(8)*(k1**BigInt(251)-on):BigInt(4)*(k1**BigInt(445)-on),m=g+y+on,b=U=>He(U,t),E=S(h);function S(U){return vu(b(U),f)}function T(U){let B=Eo(Pe(U,f,"uCoordinate"));return c&&(B[31]&=127),b(Gn(B))}function C(U){return Gn(s(Eo(Pe(U,f,"scalar"))))}let k=new Set(c?[Oi,on,t-on,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Oi,on,t-on]);function O(U,B){let te=T(B);if(k.has(te))throw new Error("invalid private or public key received");let F=J(te,C(U));if(F===Oi)throw new Error("invalid private or public key received");return S(F)}function N(U){if(a===void 0)return O(U,E);let B=C(U);jn("scalar",B,g,m);let te=b(a(B));if(te===Oi)throw new Error("invalid private or public key received");return S(te)}let K=N,ee=O;function J(U,B){jn("u",U,Oi,t),jn("scalar",B,g,m);let te=B,F=U,R=on,x=Oi,I=U,D=on,z=te^te>>on;for(let ne=BigInt(u-1);ne>=Oi;ne--){let oe=qE(t,z>>ne);({x_2:R,x_3:I}=d(oe,R,I)),{x_2:x,x_3:D}=d(oe,x,D);let Ee=R+x,ve=b(Ee*Ee),Je=R-x,ze=b(Je*Je),gt=ve-ze,xr=I+D,Xe=I-D,st=b(Xe*Ee),da=b(xr*Je),El=st+da,Xs=st-da;I=b(El*El),D=b(F*b(Xs*Xs)),R=b(ve*ze),x=b(gt*(ve+b(p*gt)))}let Q=qE(t,te);({x_2:R,x_3:I}=d(Q,R,I)),{x_2:x,x_3:D}=d(Q,x,D);let Z=o(x);return b(R*Z)}let ie={secretKey:f,publicKey:f,seed:f},M=U=>(U=U===void 0?l(f):U,Pe(U,ie.seed,"seed"),U),G={randomSecretKey:M};return Object.freeze(ie),Object.freeze(G),Object.freeze({keygen:mc(M,K),getSharedSecret:ee,getPublicKey:K,scalarMult:O,scalarMultBase:N,utils:G,GuBytes:E.slice(),lengths:ie})}var WE=BigInt(0),cy=BigInt(1),GE=BigInt(2),cO=BigInt(3),lO=BigInt(5),uO=BigInt(8),_1=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),dO={p:_1,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:uO,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function XE(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),o=_1,a=r*r%o*r%o,c=tt(a,GE,o)*a%o,l=tt(c,cy,o)*r%o,u=tt(l,lO,o)*l%o,d=tt(u,e,o)*u%o,f=tt(d,t,o)*d%o,h=tt(f,n,o)*f%o,p=tt(h,s,o)*h%o,g=tt(p,s,o)*h%o,y=tt(g,e,o)*u%o;return{pow_p_5_8:tt(y,GE,o)*r%o,b2:a}}function ly(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var jE=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function fO(r,e){let t=_1,n=He(e*e*e,t),s=He(n*n*e,t),o=XE(r*s).pow_p_5_8,i=He(r*n*o,t),a=He(e*i*i,t),c=i,l=He(i*jE,t),u=a===r,d=a===He(-r,t),f=a===He(-r*jE,t);return u&&(i=c),(d||f)&&(i=l),NE(i,t)&&(i=He(-i,t)),{isValid:u||d,value:i}}var Iu=HE(dO,{uvRatio:fO}),YE=Iu.Fp;function hO(r){let{y:e}=r;return YE.toBytes(YE.div(cy+e,cy-e))}function pO(r){let e=Iu.Fp.BYTES;return er(r,e),ly(As(r.subarray(0,e))).subarray(0,e)}function mO(r){return VE(Iu,As,Object.assign({adjustScalarBytes:ly,toMontgomery:hO,toMontgomerySecret:pO,zip215:!0},r))}var Cu=mO({});var Yn=(()=>{let r=_1,e=t=>{let{pow_p_5_8:n,b2:s}=XE(t);return He(tt(n,cO,r)*s,r)};return zE({P:r,type:"x25519",powPminus2:e,adjustScalarBytes:ly,scalarMultBase:t=>{let n=He(t,Iu.Fn.ORDER);if(n===WE)return WE;let s=Iu.BASE.multiply(n);return He((s.Z+s.Y)*e(He(s.Z-s.Y,r)),r)}})})();var ku=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},_u=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},P1=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var At={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new P1("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Bi=32,Vr=64,uy=32;var gc,QE=(async()=>{try{return await At.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function ZE(){let r=Cu.utils.randomSecretKey(),e=Cu.getPublicKey(r);return{privateKey:EO(r,e),publicKey:e}}async function gO(r,e){let t;r.length===Vr?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:_(r.subarray(32),"base64url"),d:_(t,"base64url"),ext:!0,key_ops:["sign"]},s=await At.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),o=await At.get().subtle.sign({name:"Ed25519"},s,re(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(o,0,o.byteLength)}function yO(r,e){let t=r.subarray(0,uy);return Cu.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function JE(r,e){return gc==null&&(gc=await QE),gc?gO(r,e):yO(r,e)}async function wO(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await At.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await At.get().subtle.verify({name:"Ed25519"},n,re(e),re(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function bO(r,e,t){return Cu.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function ex(r,e,t){return gc==null&&(gc=await QE),gc?wO(r,e,t):bO(r,e,t)}function EO(r,e){let t=new Uint8Array(Vr);for(let n=0;n<uy;n++)t[n]=r[n],t[uy+n]=e[n];return t}function yc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Pu=class{type="Ed25519";raw;constructor(e){this.raw=bc(e,Bi)}toMultihash(){return ot.digest(St(this))}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let s=ex(this.raw,t,e);return yc(s)?s.then(o=>(n?.signal?.throwIfAborted(),o)):s}},wc=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=bc(e,Vr),this.publicKey=new Pu(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=JE(this.raw,e);return yc(n)?n.then(s=>(t?.signal?.throwIfAborted(),s)):(t?.signal?.throwIfAborted(),n)}};function dy(r){if(r.length>Vr){r=bc(r,Vr+Bi);let n=r.subarray(0,Vr),s=r.subarray(Vr,r.length);return new wc(n,s)}r=bc(r,Vr);let e=r.subarray(0,Vr),t=r.subarray(Bi);return new wc(e,t)}function fy(r){return r=bc(r,Bi),new Pu(r)}async function rx(){let{privateKey:r,publicKey:e}=ZE();return new wc(r,e)}function bc(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new v(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var qe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(qe||(qe={}));var hy;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(hy||(hy={}));(function(r){r.codec=()=>at(hy)})(qe||(qe={}));var Xn;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),qe.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=qe.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:qe.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Xn||(Xn={}));var Lu;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),qe.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.Type=qe.codec().decode(o);break}case 2:{c.Data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:qe.codec().decode(o)};break}case 2:{yield{field:`${a}.Data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Lu||(Lu={}));var Du={};we(Du,{MAX_RSA_KEY_SIZE:()=>py,generateRSAKeyPair:()=>Sy,jwkToJWKKeyPair:()=>ix,jwkToPkcs1:()=>AO,jwkToPkix:()=>wy,jwkToRSAPrivateKey:()=>vy,pkcs1MessageToJwk:()=>gy,pkcs1MessageToRSAPrivateKey:()=>L1,pkcs1ToJwk:()=>SO,pkcs1ToRSAPrivateKey:()=>by,pkixMessageToJwk:()=>yy,pkixMessageToRSAPublicKey:()=>xy,pkixToJwk:()=>TO,pkixToRSAPublicKey:()=>Ey});var Ec=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Du.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return $.createV1(114,this._multihash)}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}verify(e,t,n){return ox(this.jwk,t,e,n)}},Ru=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Du.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}sign(e,t){return sx(this.jwk,e,t)}};var py=8192,my=18,xO=1062,vO=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function SO(r){let e=nn(r);return gy(e)}function gy(r){return{n:_(r[1],"base64url"),e:_(r[2],"base64url"),d:_(r[3],"base64url"),p:_(r[4],"base64url"),q:_(r[5],"base64url"),dp:_(r[6],"base64url"),dq:_(r[7],"base64url"),qi:_(r[8],"base64url"),kty:"RSA"}}function AO(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 v("JWK was missing components");return Tn([pr(Uint8Array.from([0])),pr(A(r.n,"base64url")),pr(A(r.e,"base64url")),pr(A(r.d,"base64url")),pr(A(r.p,"base64url")),pr(A(r.q,"base64url")),pr(A(r.dp,"base64url")),pr(A(r.dq,"base64url")),pr(A(r.qi,"base64url"))]).subarray()}function TO(r){let e=nn(r,{offset:0});return yy(e)}function yy(r){let e=nn(r[1],{offset:0});return{kty:"RSA",n:_(e[0],"base64url"),e:_(e[1],"base64url")}}function wy(r){if(r.n==null||r.e==null)throw new v("JWK was missing components");return Tn([vO,gu(Tn([pr(A(r.n,"base64url")),pr(A(r.e,"base64url"))]))]).subarray()}function by(r){let e=nn(r);return L1(e)}function L1(r){let e=gy(r);return vy(e)}function Ey(r,e){if(r.byteLength>=xO)throw new dn("Key size is too large");let t=nn(r,{offset:0});return xy(t,r,e)}function xy(r,e,t){let n=yy(r);if(t==null){let s=tr(Xn.encode({Type:qe.RSA,Data:e}));t=lr(my,s)}return new Ec(n,t)}function vy(r){if(cx(r)>py)throw new v("Key size is too large");let e=ix(r),t=tr(Xn.encode({Type:qe.RSA,Data:wy(e.publicKey)})),n=lr(my,t);return new Ru(e.privateKey,new Ec(e.publicKey,n))}async function Sy(r){if(r>py)throw new v("Key size is too large");let e=await ax(r),t=tr(Xn.encode({Type:qe.RSA,Data:wy(e.publicKey)})),n=lr(my,t);return new Ru(e.privateKey,new Ec(e.publicKey,n))}function ix(r){if(r==null)throw new v("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function ax(r,e){let t=await At.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await IO(t,e);return{privateKey:n[0],publicKey:n[1]}}async function sx(r,e,t){let n=await At.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let s=await At.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,re(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function ox(r,e,t,n){let s=await At.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await At.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,re(e),re(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),o}async function IO(r,e){if(r.privateKey==null||r.publicKey==null)throw new v("Private and public key are required");let t=await Promise.all([At.get().subtle.exportKey("jwk",r.privateKey),At.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function cx(r){if(r.kty!=="RSA")throw new v("invalid key type");if(r.n==null)throw new v("invalid key modulus");return A(r.n,"base64url").length*8}var R1=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ss(e),er(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),wt(s)}update(e){return cc(this),this.iHash.update(e),this}digestInto(e){cc(this),c1(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Mi=(()=>{let r=((e,t,n)=>new R1(e,t).update(n).digest());return r.create=(e,t)=>new R1(e,t),r})();var CO=BigInt(0),Ay=class extends Error{constructor(e=""){super(e)}},Cs={Err:Ay,_tlv:{encode:(r,e)=>{let{Err:t}=Cs;if(Is(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(xE(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=xu(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?xu(s.length/2|128):"";return xu(r)+o+s+e},decode(r,e){let{Err:t}=Cs;e=Pe(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Cs;if(g1(r),r<CO)throw new e("integer: negative integers are not allowed");let t=xu(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Cs;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Wn(r)}},toSig(r,e){let{Err:t,_int:n,_tlv:s}=Cs;if(e!==void 0&&(Is(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=Pe(r,void 0,"signature"),{v:i,l:a}=s.decode(48,o);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l}=s.decode(2,i),{v:u,l:d}=s.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||u.length>e))throw new t("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=Cs;rr(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},D1=(Object.freeze(Cs._tlv),Object.freeze(Cs._int),Object.freeze(Cs));var lx=(r,e)=>(r+(r>=0?e:-e)/ux)/e;function kO(r,e,t){jn("scalar",r,ks,t);let[[n,s],[o,i]]=e,a=lx(i*r,t),c=lx(-s*r,t),l=r-a*n-c*o,u=-a*s-c*i,d=l<ks,f=u<ks;d&&(l=-l),f&&(u=-u);let h=Su(Math.ceil(dc(t)/2))+Ui;if(l<ks||l>=h||u<ks||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function Cy(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ty(r,e){rr(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ir(t.lowS,"lowS"),Ir(t.prehash,"prehash"),t.format!==void 0&&Cy(t.format),t}var ks=BigInt(0),Ui=BigInt(1),ux=BigInt(2),Iy=BigInt(3),_O=BigInt(4);function dx(r,e={}){let t=A1("weierstrass",r,e),n=t.Fp,s=t.Fn,o=t.CURVE,{h:i,n:a}=o;rr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l,clearCofactor:u,isTorsionFree:d,fromBytes:f,toBytes:h}=e,p=e.randomBytes===void 0?Ts:e.randomBytes;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=c?{beta:c.beta,basises:c.basises.map(R=>[...R])}:void 0,y=hx(n,s);function m(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function b(R,x,I){if(x.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:D,y:z}=x.toAffine(),Q=n.toBytes(D);if(Ir(I,"isCompressed"),I){m();let Z=!n.isOdd(z);return sn(fx(Z),Q)}else return sn(Uint8Array.of(4),Q,n.toBytes(z))}function E(R){Pe(R,void 0,"Point");let{publicKey:x,publicKeyUncompressed:I}=y,D=R.length,z=R[0],Q=R.subarray(1);if(l&&D===1&&z===0)return{x:n.ZERO,y:n.ZERO};if(D===x&&(z===2||z===3)){let Z=n.fromBytes(Q);if(!n.isValid(Z))throw new Error("bad point: is not on curve, wrong x");let ne=O(Z),oe;try{oe=n.sqrt(ne)}catch(Je){let ze=Je instanceof Error?": "+Je.message:"";throw new Error("bad point: is not on curve, sqrt error"+ze)}m();let Ee=n.isOdd(oe);return(z&1)===1!==Ee&&(oe=n.neg(oe)),{x:Z,y:oe}}else if(D===I&&z===4){let Z=n.BYTES,ne=n.fromBytes(Q.subarray(0,Z)),oe=n.fromBytes(Q.subarray(Z,Z*2));if(!N(ne,oe))throw new Error("bad point: is not on curve");return{x:ne,y:oe}}else throw new Error(`bad point: got length ${D}, expected compressed=${x} or uncompressed=${I}`)}let S=h===void 0?b:h,T=f===void 0?E:f,C=n.mul(o.b,Iy),k=n.is0(o.a)?R=>n.ZERO:R=>n.mul(o.a,R);function O(R){let x=n.sqr(R),I=n.mul(x,R);return n.add(n.add(I,n.mul(R,o.a)),o.b)}function N(R,x){let I=n.sqr(x),D=O(R);return n.eql(I,D)}if(!N(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let K=n.mul(n.pow(o.a,Iy),_O),ee=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(K,ee)))throw new Error("bad curve params: a or b");function J(R,x,I=!1){if(!n.isValid(x)||I&&n.is0(x))throw new Error(`bad point coordinate ${R}`);return typeof x=="object"&&x!==null?n.create(x):x}function ie(R){if(!(R instanceof B))throw new Error("Weierstrass Point expected")}function M(R){if(!g||!g.basises)throw new Error("no endo");return kO(R,g.basises,s.ORDER)}function G(R,x,I,D){if(!s.isValid(D))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:z,k1:Q,k2neg:Z,k2:ne}=M(D),oe=new B(n.mul(I.X,g.beta),I.Y,I.Z);R.push(z?I.negate():I,Z?oe.negate():oe),x.push(Q,ne)}else R.push(I),x.push(D)}let U=new WeakSet;class B{static BASE=new B(o.Gx,o.Gy,n.ONE);static ZERO=new B(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(x,I,D){this.X=J("x",x),this.Y=J("y",I,!0),this.Z=J("z",D),Object.freeze(this)}static CURVE(){return o}static fromAffine(x){let{x:I,y:D}=x||{};if(!x||!n.isValid(I)||!n.isValid(D))throw new Error("invalid affine point");if(x instanceof B)throw new Error("projective point not allowed");return n.is0(I)&&n.is0(D)?B.ZERO:new B(I,D,n.ONE)}static fromBytes(x){let I=B.fromAffine(T(Pe(x,void 0,"point")));return I.assertValidity(),I}static fromHex(x){return B.fromBytes(uc(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=6,I=!0){return F.setWindowSize(this,x),I||this.multiply(Iy),this}assertValidity(){let x=this;if(x.is0()){if(l&&n.is0(x.X)&&n.eql(x.Y,n.ONE)&&n.is0(x.Z))return;throw new Error("bad point: ZERO")}if(U.has(x))return;let{x:I,y:D}=x.toAffine();if(!n.isValid(I)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!N(I,D))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");U.add(x)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){ie(x);let{X:I,Y:D,Z:z}=this,{X:Q,Y:Z,Z:ne}=x,oe=n.eql(n.mul(I,ne),n.mul(Q,z)),Ee=n.eql(n.mul(D,ne),n.mul(Z,z));return oe&&Ee}negate(){return new B(this.X,n.neg(this.Y),this.Z)}double(){let{X:x,Y:I,Z:D}=this,z=n.ZERO,Q=n.ZERO,Z=n.ZERO,ne=n.mul(x,x),oe=n.mul(I,I),Ee=n.mul(D,D),ve=n.mul(x,I);return ve=n.add(ve,ve),Z=n.mul(x,D),Z=n.add(Z,Z),z=k(Z),Q=n.mul(C,Ee),Q=n.add(z,Q),z=n.sub(oe,Q),Q=n.add(oe,Q),Q=n.mul(z,Q),z=n.mul(ve,z),Z=n.mul(C,Z),Ee=k(Ee),ve=n.sub(ne,Ee),ve=k(ve),ve=n.add(ve,Z),Z=n.add(ne,ne),ne=n.add(Z,ne),ne=n.add(ne,Ee),ne=n.mul(ne,ve),Q=n.add(Q,ne),Ee=n.mul(I,D),Ee=n.add(Ee,Ee),ne=n.mul(Ee,ve),z=n.sub(z,ne),Z=n.mul(Ee,oe),Z=n.add(Z,Z),Z=n.add(Z,Z),new B(z,Q,Z)}add(x){ie(x);let{X:I,Y:D,Z:z}=this,{X:Q,Y:Z,Z:ne}=x,oe=n.ZERO,Ee=n.ZERO,ve=n.ZERO,Je=n.mul(I,Q),ze=n.mul(D,Z),gt=n.mul(z,ne),xr=n.add(I,D),Xe=n.add(Q,Z);xr=n.mul(xr,Xe),Xe=n.add(Je,ze),xr=n.sub(xr,Xe),Xe=n.add(I,z);let st=n.add(Q,ne);return Xe=n.mul(Xe,st),st=n.add(Je,gt),Xe=n.sub(Xe,st),st=n.add(D,z),oe=n.add(Z,ne),st=n.mul(st,oe),oe=n.add(ze,gt),st=n.sub(st,oe),ve=k(Xe),oe=n.mul(C,gt),ve=n.add(oe,ve),oe=n.sub(ze,ve),ve=n.add(ze,ve),Ee=n.mul(oe,ve),ze=n.add(Je,Je),ze=n.add(ze,Je),gt=k(gt),Xe=n.mul(C,Xe),ze=n.add(ze,gt),gt=n.sub(Je,gt),gt=k(gt),Xe=n.add(Xe,gt),Je=n.mul(ze,Xe),Ee=n.add(Ee,Je),Je=n.mul(st,Xe),oe=n.mul(xr,oe),oe=n.sub(oe,Je),Je=n.mul(xr,ze),ve=n.mul(st,ve),ve=n.add(ve,Je),new B(oe,Ee,ve)}subtract(x){return ie(x),this.add(x.negate())}is0(){return this.equals(B.ZERO)}multiply(x){if(!s.isValidNot0(x))throw new RangeError("invalid scalar: out of range");let{p:I,f:D}=F.mulSecret(this,x,i,te);return te([I,D])[0]}multiplyUnsafe(x){let I=this,D=x;if(!s.isValid(D))throw new RangeError("invalid scalar: out of range");if(D===ks||I.is0())return B.ZERO;if(D===Ui)return I;if(F.hasWindowSize(this))return F.mulUnsafe(I,D,te);let z=[],Q=[];return G(z,Q,I,D),S1(B,z,Q)}mulAddUnsafe(x,I,D){ie(I);let z=[],Q=[];return G(z,Q,this,x),G(z,Q,I,D),S1(B,z,Q)}toAffine(x){let I=this,D=x;if(D!=null&&!n.isValid(D))throw new RangeError('"invertedZ" expected valid field element');let{X:z,Y:Q,Z}=I;if(n.eql(Z,n.ONE))return{x:z,y:Q};let ne=I.is0();D==null&&(D=ne?n.ONE:n.inv(Z));let oe=n.mul(z,D),Ee=n.mul(Q,D),ve=n.mul(Z,D);if(ne)return{x:n.ZERO,y:n.ZERO};if(!n.eql(ve,n.ONE))throw new Error("invZ was invalid");return{x:oe,y:Ee}}isTorsionFree(){return i===Ui?!0:d?d(B,this):F.mulUnsafe(this,a).is0()}clearCofactor(){return i===Ui?this:u?u(B,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ui?this.is0():this.clearCofactor().is0()}toBytes(x=!0){return Ir(x,"isCompressed"),this.assertValidity(),S(B,this,x)}toHex(x=!0){return Eu(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let te=R=>v1(B,R),F=new pc(B,p);return F.bits>=6&&B.BASE.precompute(6),Object.freeze(B.prototype),Object.freeze(B),B}function fx(r){return Uint8Array.of(r?2:3)}function hx(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function PO(r,e={}){vo(r);let{Fn:t}=r,n=e.randomBytes===void 0?Ts:e.randomBytes,s=Object.assign(hx(r.Fp,t),{seed:Math.max(E1(t.ORDER),16)});function o(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function i(h,p){let{publicKey:g,publicKeyUncompressed:y}=s;try{let m=h.length;return p===!0&&m!==g||p===!1&&m!==y?!1:!r.fromBytes(h).is0()}catch{return!1}}function a(h){return h=h===void 0?n(s.seed):h,x1(Pe(h,s.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:g,publicKeyUncompressed:y}=s,m=t._lengths;if(!bo(h))return;let b=Pe(h,void 0,"key").length,E=b===g||b===y,S=b===p||!!m?.includes(b);if(!(E&&S))return E}function u(h,p,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(h),m=r.fromBytes(p);if(m.is0())throw new Error("invalid public key: point at infinity");return m.multiply(y).toBytes(g)}let d={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},f=mc(a,c);return Object.freeze(d),Object.freeze(s),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:s})}function px(r,e,t={}){vo(r);let n=e;Ss(n),rr(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=Object.assign({},t),o=s.randomBytes===void 0?Ts:s.randomBytes,i=s.hmac===void 0?(R,x)=>Mi(n,R,x):s.hmac,{Fp:a,Fn:c}=r,{ORDER:l,BITS:u}=c,d=E1(l),f=ay(o,d),{keygen:h,getPublicKey:p,getSharedSecret:g,utils:y,lengths:m}=PO(r,s),b={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},E=l*ux+Ui<a.ORDER;function S(R){let x=l>>Ui;return R>x}function T(R,x){if(!c.isValidNot0(x))throw new Error(`invalid signature ${R}: out of range 1..Point.Fn.ORDER`);return x}function C(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function k(R,x,I){return C(),(R===I?0:2)|Number(a.isOdd(x))}function O(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function N(R,x){Cy(x);let I=m.signature,D=x==="compact"?I:x==="recovered"?I+1:void 0;return Pe(R,D)}class K{r;s;recovery;constructor(x,I,D){if(this.r=T("r",x),this.s=T("s",I),D!=null){if(O(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(x,I=b.format){N(x,I);let D;if(I==="der"){if(x.length>2*c.BYTES+16)throw new D1.Err("invalid signature: DER signature too long");let{r:ne,s:oe}=D1.toSig(Pe(x),c.BYTES+1);return new K(ne,oe)}I==="recovered"&&(D=x[0],I="compact",x=x.subarray(1));let z=m.signature/2,Q=x.subarray(0,z),Z=x.subarray(z,z*2);return new K(c.fromBytes(Q),c.fromBytes(Z),D)}static fromHex(x,I){return this.fromBytes(uc(x),I)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new K(this.r,this.s,x)}recoverPublicKey(x){let{r:I,s:D}=this,z=this.assertRecovery(),Q=z===2||z===3?I+l:I;if(!a.isValid(Q))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let Z=a.toBytes(Q),ne=r.fromBytes(sn(fx((z&1)===0),Z)),oe=c.inv(Q),Ee=J(Pe(x,void 0,"msgHash")),ve=c.create(-Ee*oe),Je=c.create(D*oe),ze=r.BASE.mulAddUnsafe(ve,ne,Je);if(ze.is0())throw new Error("invalid recovery: point at infinify");return ze.assertValidity(),ze}hasHighS(){return S(this.s)}toBytes(x=b.format){if(Cy(x),x==="der")return uc(D1.hexFromSig(this));let{r:I,s:D}=this,z=c.toBytes(I),Q=c.toBytes(D);return x==="recovered"?(O(),sn(Uint8Array.of(this.assertRecovery()),z,Q)):sn(z,Q)}toHex(x){return Eu(this.toBytes(x))}}Object.freeze(K.prototype),Object.freeze(K);let ee=s.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let I=Wn(x),D=x.length*8-u;return D>0?I>>BigInt(D):I}:s.bits2int,J=s.bits2int_modN===void 0?function(x){return c.create(ee(x))}:s.bits2int_modN,ie=Su(u);function M(R){return jn("num < 2^"+u,R,ks,ie),c.toBytes(R)}function G(R,x){return Pe(R,void 0,"message"),x?Pe(n(R),void 0,"prehashed message"):R}function U(R,x,I){let{lowS:D,prehash:z,extraEntropy:Q}=Ty(I,b);R=G(R,z);let Z=J(R),ne=c.fromBytes(x);if(!c.isValidNot0(ne))throw new Error("invalid private key");let oe=[M(ne),M(Z)];if(Q!=null&&Q!==!1){let ze=Q===!0?o(m.secretKey):Q;oe.push(Pe(ze,void 0,"extraEntropy"))}let Ee=sn(...oe),ve=Z;function Je(ze){let gt=ee(ze);if(!c.isValidNot0(gt))return;let xr=r.BASE.multiply(gt).toAffine(),Xe=c.create(xr.x);if(Xe===ks)return;let st;if(f!==void 0){let Xs=Wn(x1(f(d),l)),__=c.inv(c.mul(Xs,gt)),P_=c.mul(Xs,ve),L_=c.mul(Xs,ne);st=c.create(__*c.create(P_+L_*Xe))}else{let Xs=LE(gt,l);st=c.create(Xs*c.create(ve+Xe*ne))}if(st===ks)return;let da=k(xr.x,xr.y,Xe),El=st;return D&&S(st)&&(El=c.neg(st),da^=1),new K(Xe,El,E?void 0:da)}return{seed:Ee,k2sig:Je}}function B(R,x,I={}){let{seed:D,k2sig:z}=U(R,x,I);return SE(n.outputLen,c.BYTES,i)(D,z).toBytes(I.format)}function te(R,x,I,D={}){let{lowS:z,prehash:Q,format:Z}=Ty(D,b);if(I=Pe(I,void 0,"publicKey"),x=G(x,Q),!bo(R)){let ne=R instanceof K?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+ne)}N(R,Z);try{let ne=K.fromBytes(R,Z),oe=r.fromBytes(I);if(oe.is0()||z&&ne.hasHighS())return!1;let{r:Ee,s:ve}=ne,Je=J(x),ze=c.inv(ve),gt=c.create(Je*ze),xr=c.create(Ee*ze),Xe=r.BASE.mulAddUnsafe(gt,oe,xr);if(Xe.is0())return!1;let st=Xe.toAffine();return!(c.create(st.x)!==Ee||Z==="recovered"&&ne.recovery!==k(st.x,st.y,Ee))}catch{return!1}}function F(R,x,I={}){let{prehash:D}=Ty(I,b);return x=G(x,D),K.fromBytes(R,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:h,getPublicKey:p,getSharedSecret:g,utils:y,lengths:m,Point:r,sign:B,verify:te,recoverPublicKey:F,Signature:K,hash:n})}var _y={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},LO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var mx=BigInt(2);function RO(r){let e=_y.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=tt(u,t,e)*u%e,f=tt(d,t,e)*u%e,h=tt(f,mx,e)*l%e,p=tt(h,s,e)*h%e,g=tt(p,o,e)*p%e,y=tt(g,a,e)*g%e,m=tt(y,c,e)*y%e,b=tt(m,a,e)*g%e,E=tt(b,t,e)*u%e,S=tt(E,i,e)*p%e,T=tt(S,n,e)*l%e,C=tt(T,mx,e);if(!ky.eql(ky.sqr(C),r))throw new Error("Cannot find square root");return C}var ky=hc(_y.p,{sqrt:RO}),DO=dx(_y,{Fp:ky,endo:LO}),Cn=px(DO,tr);var gx=32;function yx(r,e,t){let n=je.digest(e instanceof Uint8Array?e:e.subarray());if(yc(n))return n.then(({digest:s})=>(t?.signal?.throwIfAborted(),Cn.sign(s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new ku(String(s))});try{return Cn.sign(n.digest,r,{prehash:!1,format:"der"})}catch(s){throw new ku(String(s))}}function wx(r,e,t,n){let s=je.digest(t instanceof Uint8Array?t:t.subarray());if(yc(s))return s.then(({digest:o})=>(n?.signal?.throwIfAborted(),Cn.verify(e,o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new _u(String(o))});try{return n?.signal?.throwIfAborted(),Cn.verify(e,s.digest,r,{prehash:!1,format:"der"})}catch(o){throw new _u(String(o))}}var Nu=class{type="secp256k1";raw;_key;constructor(e){this._key=xx(e),this.raw=bx(this._key)}toMultihash(){return ot.digest(St(this))}toCID(){return $.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}verify(e,t,n){return wx(this._key,t,e,n)}},Ou=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Ex(e),this.publicKey=new Nu(t??vx(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:se(this.raw,e.raw)}sign(e,t){return yx(this.raw,e,t)}};function Py(r){return new Ou(r)}function Ly(r){return new Nu(r)}async function Sx(){let r=NO();return new Ou(r)}function bx(r){return Cn.Point.fromBytes(r).toBytes()}function Ex(r){try{return Cn.getPublicKey(r,!0),r}catch(e){throw new xl(String(e))}}function xx(r){try{return Cn.Point.fromBytes(r),r}catch(e){throw new dn(String(e))}}function vx(r){try{return Cn.getPublicKey(r,!0)}catch(e){throw new xl(String(e))}}function NO(){return Cn.utils.randomSecretKey()}async function N1(r,e){if(r==="Ed25519")return rx();if(r==="secp256k1")return Sx();if(r==="RSA")return Sy(OO(e));if(r==="ECDSA")return rE(BO(e));throw new hn}function ct(r,e){let{Type:t,Data:n}=Xn.decode(r),s=n??new Uint8Array;switch(t){case qe.RSA:return Ey(s,e);case qe.Ed25519:return fy(s);case qe.secp256k1:return Ly(s);case qe.ECDSA:return K4(s);default:throw new hn}}function Ax(r){let{Type:e,Data:t}=Xn.decode(r.digest),n=t??new Uint8Array;switch(e){case qe.Ed25519:return fy(n);case qe.secp256k1:return Ly(n);case qe.ECDSA:return K4(n);default:throw new hn}}function St(r){return Xn.encode({Type:qe[r.type],Data:r.raw})}function Tx(r){let e=Lu.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case qe.RSA:return by(t);case qe.Ed25519:return dy(t);case qe.secp256k1:return Py(t);case qe.ECDSA:return Q9(t);default:throw new hn}}function Ix(r){if(r.byteLength===Vr)return dy(r);if(r.byteLength===gx)return Py(r);let e=nn(r),t=e[2]?.[0];if(t===$9||t===K9||t===H9)return $4(e);if(e.length>8)return L1(e);throw new v("Could not extract private key from raw bytes")}function Fi(r){return Lu.encode({Type:qe[r.type],Data:r.raw})}function OO(r){return r==null?2048:parseInt(r,10)}function BO(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new v("Unsupported curve, should be P-256, P-384 or P-521")}var Cx=Symbol.for("nodejs.util.inspect.custom"),MO=114,Bu=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Bf]=!0;toString(){return this.string==null&&(this.string=Se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return $.createV1(MO,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return se(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return se(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Cx](){return`PeerId(${this.toString()})`}},Mu=class extends Bu{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Uu=class extends Bu{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Fu=class extends Bu{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},UO=2336,$u=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ot.digest(A(this.url))}[Cx](){return`PeerId(${this.url})`}[Bf]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return $.createV1(UO,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=_(e)),e.toString()===this.toString())}};var FO=114,kx=2336;function rt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ce(Se.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return bt($.parse(r));if(e==null)throw new v('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ce(e.decode(r))}return Tt(t)}function qr(r){if(r.type==="Ed25519")return new Uu({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Fu({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Mu({multihash:r.toCID().multihash,publicKey:r});throw new hn}function _x(r){return qr(r.publicKey)}function Tt(r){if(KO(r))return new Mu({multihash:r});if($O(r))try{let e=Ax(r);if(e.type==="Ed25519")return new Uu({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Fu({multihash:r,publicKey:e})}catch{let t=_(r.digest);return new $u(new URL(t))}throw new ya("Supplied PeerID Multihash is invalid")}function bt(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==FO&&r.code!==kx)throw new Pf("Supplied PeerID CID is invalid");if(r.code===kx){let e=_(r.multihash.digest);return new $u(new URL(e))}return Tt(r.multihash)}function $O(r){return r.code===ot.code}function KO(r){return r.code===je.code}function HO(r){return r[Symbol.asyncIterator]!=null}function VO(r){if(HO(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Cr=VO;function qO(r){return r[Symbol.asyncIterator]!=null}function zO(r,e){let t=0;if(qO(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=nc(r),{value:s,done:o}=n.next();if(o===!0)return(function*(){})();let i=e(s,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var Vt=zO;function WO(r){return r[Symbol.asyncIterator]!=null}function GO(r,e){return WO(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 So=GO;var Ry="/ipfs/bitswap/1.2.0";var lt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(lt||(lt={}));var Dy;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Dy||(Dy={}));(function(r){r.codec=()=>at(Dy)})(lt||(lt={}));var $i;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.priority!=null&&o.priority!==0&&(i.uint32(16),i.int32(o.priority)),o.cancel!=null&&(i.uint32(24),i.bool(o.cancel)),o.wantType!=null&&(i.uint32(32),lt.codec().encode(o.wantType,i)),o.sendDontHave!=null&&(i.uint32(40),i.bool(o.sendDontHave)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:pe(0),priority:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.priority=o.int32();break}case 3:{c.cancel=o.bool();break}case 4:{c.wantType=lt.codec().decode(o);break}case 5:{c.sendDontHave=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"start",message:"WantlistEntry"});o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}cid`,value:o.bytes()};break}case 2:{yield{field:`${a}priority`,value:o.int32()};break}case 3:{yield{field:`${a}cancel`,value:o.bool()};break}case 4:{yield{field:`${a}wantType`,value:lt.codec().decode(o)};break}case 5:{yield{field:`${a}sendDontHave`,value:o.bool()};break}default:{o.skipType(u&7);break}}}a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"end",message:"WantlistEntry"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})($i||($i={}));var Ku;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.entries!=null&&o.entries.length>0)for(let c of o.entries)i.uint32(10),$i.codec().encode(c,i);o.full!=null&&(i.uint32(16),i.bool(o.full)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={entries:[]},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{if(a.limits?.entries!=null&&c.entries.length===a.limits.entries)throw new ye('Decode error - repeated field "entries" had too many elements');c.entries.push($i.codec().decode(o,o.uint32(),{limits:a.limits?.entries$}));break}case 2:{c.full=o.bool();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={entries:0},u=i==null?o.len:o.pos+i;for(a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"start",message:"Wantlist"});o.pos<u;){let d=o.uint32();switch(d>>>3){case 1:{if(c.limits?.entries!=null&&l.entries===c.limits.entries)throw new ye('Streaming decode error - repeated field "entries" had too many elements');for(let f of $i.codec().stream(o,o.uint32(),`${a}entries[].`,{limits:c.limits?.entries$}))yield{...f,index:l.entries};l.entries++;break}case 2:{yield{field:`${a}full`,value:o.bool()};break}default:{o.skipType(d&7);break}}}a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"end",message:"Wantlist"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Ku||(Ku={}));var Ki;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.prefix!=null&&o.prefix.byteLength>0&&(i.uint32(10),i.bytes(o.prefix)),o.data!=null&&o.data.byteLength>0&&(i.uint32(18),i.bytes(o.data)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={prefix:pe(0),data:pe(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.prefix=o.bytes();break}case 2:{c.data=o.bytes();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"start",message:"Block"});o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}prefix`,value:o.bytes()};break}case 2:{yield{field:`${a}data`,value:o.bytes()};break}default:{o.skipType(u&7);break}}}a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"end",message:"Block"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Ki||(Ki={}));var zr;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(zr||(zr={}));var O1;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})(O1||(O1={}));(function(r){r.codec=()=>at(O1)})(zr||(zr={}));var Hi;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.cid!=null&&o.cid.byteLength>0&&(i.uint32(10),i.bytes(o.cid)),o.type!=null&&O1[o.type]!==0&&(i.uint32(16),zr.codec().encode(o.type,i)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={cid:pe(0),type:zr.HaveBlock},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.cid=o.bytes();break}case 2:{c.type=zr.codec().decode(o);break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l=i==null?o.len:o.pos+i;for(a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"start",message:"BlockPresence"});o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{yield{field:`${a}cid`,value:o.bytes()};break}case 2:{yield{field:`${a}type`,value:zr.codec().decode(o)};break}default:{o.skipType(u&7);break}}}a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"end",message:"BlockPresence"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Hi||(Hi={}));var Vi;(function(r){let e;r.codec=()=>(e==null&&(e=ue((o,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),o.wantlist!=null&&(i.uint32(10),Ku.codec().encode(o.wantlist,i)),o.blocks!=null&&o.blocks.length>0)for(let c of o.blocks)i.uint32(26),Ki.codec().encode(c,i);if(o.blockPresences!=null&&o.blockPresences.length>0)for(let c of o.blockPresences)i.uint32(34),Hi.codec().encode(c,i);o.pendingBytes!=null&&o.pendingBytes!==0&&(i.uint32(40),i.int32(o.pendingBytes)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={blocks:[],blockPresences:[],pendingBytes:0},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.wantlist=Ku.codec().decode(o,o.uint32(),{limits:a.limits?.wantlist});break}case 3:{if(a.limits?.blocks!=null&&c.blocks.length===a.limits.blocks)throw new ye('Decode error - repeated field "blocks" had too many elements');c.blocks.push(Ki.codec().decode(o,o.uint32(),{limits:a.limits?.blocks$}));break}case 4:{if(a.limits?.blockPresences!=null&&c.blockPresences.length===a.limits.blockPresences)throw new ye('Decode error - repeated field "blockPresences" had too many elements');c.blockPresences.push(Hi.codec().decode(o,o.uint32(),{limits:a.limits?.blockPresences$}));break}case 5:{c.pendingBytes=o.int32();break}default:{o.skipType(u&7);break}}}return c},function*(o,i,a,c={}){let l={blocks:0,blockPresences:0},u=i==null?o.len:o.pos+i;for(a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"start",message:"BitswapMessage"});o.pos<u;){let d=o.uint32();switch(d>>>3){case 1:{yield*Ku.codec().stream(o,o.uint32(),`${a}wantlist.`,{limits:c.limits?.wantlist});break}case 3:{if(c.limits?.blocks!=null&&l.blocks===c.limits.blocks)throw new ye('Streaming decode error - repeated field "blocks" had too many elements');for(let f of Ki.codec().stream(o,o.uint32(),`${a}blocks[].`,{limits:c.limits?.blocks$}))yield{...f,index:l.blocks};l.blocks++;break}case 4:{if(c.limits?.blockPresences!=null&&l.blockPresences===c.limits.blockPresences)throw new ye('Streaming decode error - repeated field "blockPresences" had too many elements');for(let f of Hi.codec().stream(o,o.uint32(),`${a}blockPresences[].`,{limits:c.limits?.blockPresences$}))yield{...f,index:l.blockPresences};l.blockPresences++;break}case 5:{yield{field:`${a}pendingBytes`,value:o.int32()};break}default:{o.skipType(d&7);break}}}a!=="."&&(yield{field:a.endsWith(".")?a.substring(0,a.length-1):a,type:"end",message:"BitswapMessage"})})),e);function t(o){return ce(o,r.codec())}r.encode=t;function n(o,i){return ae(o,r.codec(),i)}r.decode=n;function s(o,i){return le(o,r.codec(),i)}r.stream=s})(Vi||(Vi={}));function Px(r,e){for(let[t,n]of e.wantlist.entries()){let s=r.wantlist.get(t);s!=null&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=n.cancel??s.cancel,n.wantType=n.wantType??s.wantType,n.sendDontHave=n.sendDontHave??s.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var B1=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var jO=4193648,YO=jO+16;function*Lx(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],s=[...r.blocks.values()],o=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=Vi.encode(l).byteLength,{added:d,hasMore:f,newSize:h}=Ny(s,l.blocks,a,e,u,XO);a+=d,u=h;let p=f;({added:d,hasMore:f,newSize:h}=Ny(n,l.blockPresences,i,e,u,QO)),i+=d,u=h;let g=f;if({added:d,hasMore:f,newSize:h}=Ny(t,l.wantlist.entries,o,e,u,ZO),o+=d,u=h,c=!p&&!g&&!f,c||(l.wantlist.full=!1),yield Vi.encode(l),c)break}}function Ny(r,e,t,n,s,o){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=o(l);if(u>YO)throw new B1("Cannot send block as after encoding it is over the max message size");let d=s+u;if(d>n){a=!0;break}e.push(l),i++,s=d}return{hasMore:a,added:i,newSize:s}}function XO(r){return Oy(3,Ki.encode(r))}function QO(r){return Oy(4,Hi.encode(r))}function ZO(r){return Oy(1,$i.encode(r))}function Oy(r,e){let t=Te(r),n=Te(e.byteLength);return t+n+e.byteLength}function cB(r){if(vr(r))return r;if(sc(r))return bt(r);if(en(r)||Array.isArray(r))return r;throw new v(`Peer ${r} was not a CID, a Multiaddr or a Multiaddr[]`)}var M1=class extends ge{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;messageSendTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[Ry],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??1e4,this.messageSendTimeout=t.messageSendTimeout??1e4,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Jt({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e,t){this.running&&Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",e.protocol,t.remotePeer);let n=()=>{e.status==="open"?e.abort(new Mn(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",e.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);s.addEventListener("abort",n),await e.close({signal:s});let o=Kt();e.addEventListener("message",i=>{o.push(i.data)}),e.addEventListener("remoteCloseWrite",()=>{o.end()}),e.addEventListener("close",i=>{i.error!=null&&o.end(i.error)});for await(let i of Ci(o,{maxDataLength:this.maxIncomingMessageSize}))try{let a=Vi.decode(i);this.log("incoming new bitswap %s message from %p on stream",e.protocol,t.remotePeer,e.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:t.remotePeer,message:a,connection:t}}),s.removeEventListener("abort",n),s=AbortSignal.timeout(this.messageReceiveTimeout),s.addEventListener("abort",n)}catch(a){this.log.error("error reading incoming bitswap message from %p on stream - %e",t.remotePeer,e.id,a),e.abort(a);break}}).catch(n=>{this.log.error("error handling incoming stream from %p - %e",t.remotePeer,n),e.abort(n)})}async*findProviders(e,t){t?.onProgress?.(new P("bitswap:find-providers",e));for await(let n of this.routing.findProviders(e,t)){if(!await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})){this.log("skipping peer %p as they are not dialable - %a",n.id,n.multiaddrs);continue}t?.onProgress?.(new P("bitswap:found-provider",{type:"bitswap",cid:e,provider:n,router:n.router})),yield n}}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n,t).catch(s=>{this.log.error("could not connect to supplied provider - %e",s)}))),await Cr(Vt(So(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let s=this.sendQueue.queue.find(o=>e.equals(o.options.peerId)&&o.status==="queued");if(s!=null){s.options.message=Px(s.options.message,t),await s.join(n);return}await this.sendQueue.add(async o=>{let i=o.message;if(i==null)throw new v("No message to send");this.log("sendMessage to %p",e),o.onProgress?.(new P("bitswap:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,Ry,o);await a.closeRead(o);try{for(let c of Lx(i,this.maxOutgoingMessageSize))a.send(xs.single(c))||await a.onDrain(o);await a.close(o)}catch(c){this.log.error("error sending message to %p - %e",e,c),o?.onProgress?.(new P("bitswap:send-wantlist:error",{peer:e,error:c})),a.abort(c)}this._updateSentStats(i.blocks)},{onProgress:n?.onProgress,peerId:e,signal:n?.signal??AbortSignal.timeout(this.messageSendTimeout),message:t})}async connectTo(e,t){if(!this.running)throw new Nr("Network isn't running");return e=cB(e),t?.onProgress?.(new P("bitswap:dial",e)),this.libp2p.dial(e,t)}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function qi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),s=n.value;return n.done===!0||s==null?{done:!0,value:void 0}:{done:!1,value:e(s)}}};return t}function U1(r){let e=Ce(Se.decode(`z${r}`));return Tt(e)}var nr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return qi(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return qi(this.map.values(),e=>e.key)}values(){return qi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Wr=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return qi(this.set.entries(),e=>{let t=U1(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=U1(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return qi(this.set.values(),e=>U1(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};function By(){return new Wr}var F1=class{filter;constructor(e,t){this.filter=Ut(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function My(r,e=.001){return new F1(r,e)}var Uy=class extends nr{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function _s(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Uy({name:e,metrics:t}):n=new nr,n}var kr=class r extends Error{static name="NotFoundError";name=r.name;static code="ERR_NOT_FOUND";code=r.code;constructor(e="Not Found"){super(e)}};var Ps=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=We.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=We.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=We.encode(e.multihash.bytes);this.blocks.set(n,t)}};function lB(r){let e=new Uint8Array(r.reduce((n,s)=>n+Te(s),0)),t=0;for(let n of r)e=Xt(n,e,t),t+=Te(n);return e}var Rx=lB;function Fy(r){return Rx([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var $1=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;sendQueue;maxSizeReplaceHasWithBlock;log;doNotResendBlockWindow;maxWantListSize;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024,this.doNotResendBlockWindow=t.doNotResendBlockWindow??5e3,this.maxWantListSize=t.maxWantListSize??1024,this.sendQueue=new ht({concurrency:t.sendBlocksConcurrency??1,maxSize:t.sendBlocksMaxQueueLength??10})}stop(){this.sendQueue.abort()}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}removeExpiredWants(){this.wants.forEach((e,t)=>{e.expires!=null&&e.expires<Date.now()&&this.wants.delete(t)})}addWants(e){if(e==null)return;e.full===!0&&this.wants.forEach((n,s)=>{n.status==="want"&&this.wants.delete(s)});for(let n of e.entries){let s=$.decode(n.cid),o=_(s.multihash.bytes,"base64");if(n.cancel===!0)this.log("peer %p cancelled want of block for %c",this.peerId,s),this.wants.delete(o);else{n.wantType===lt.WantHave?this.log("peer %p wanted block presence for %c",this.peerId,s):this.log("peer %p wanted block for %c",this.peerId,s);let i=this.wants.get(o);if(i!=null){let a=i.status==="sent"||i.status==="sending",c=i.wantType===lt.WantHave&&(n.wantType==null||n.wantType===lt.WantBlock);a&&c&&(i.status="want"),i.priority=n.priority,i.wantType=n.wantType??lt.WantBlock,i.sendDontHave=n.sendDontHave??!1;continue}this.wants.set(o,{cid:s,priority:n.priority,wantType:n.wantType??lt.WantBlock,sendDontHave:n.sendDontHave??!1,status:"want",created:Date.now()})}}let t=[...this.wants.entries()].filter(([n,s])=>s.status==="want");t.length>this.maxWantListSize&&this.truncateWants(t)}truncateWants(e){e=e.sort((n,s)=>n[1].created<s[1].created?-1:s[1].created<n[1].created?1:0).sort((n,s)=>n[1].haveBlock===!1?-1:s[1].haveBlock===!1?1:0).sort((n,s)=>n[1].priority<s[1].priority?-1:s[1].priority<n[1].priority?1:0);let t=e.length-this.maxWantListSize;for(let n=0;n<t;n++)this.wants.delete(e[n][0])}getWants(){return[...this.wants.values()]}hasWant(e){let t=_(e.multihash.bytes,"base64");return this.wants.has(t)}queueSendOperation(e,t){e!=null&&(this.receivedBytes(e.blocks?.reduce((n,s)=>n+s.data.byteLength,0)??0),this.addWants(e.wantlist));try{this.sendQueue.add(async n=>{this.log("send blocks to peer"),await this.sendBlocksToPeer(n)},t).catch(n=>{n.name==="QueueFullError"?this.log.error("Dropping bitswap message as peer send queue is full"):this.log.error("Error when trying to add queue a send operation")})}catch(n){if(n.name==="QueueFullError")this.log.error("Dropping bitswap message as peer send queue is full");else throw n}}async sendBlocksToPeer(e){let t=new Ps,n=new Set;this.removeExpiredWants();let s=[...this.wants.entries()].filter(([o,i])=>i.status==="want");if(s.length!==0){s.forEach(([o,i])=>{i.status="sending"});for(let[o,i]of s)try{if(!await this.blockstore.has(i.cid,e))throw new kr;let c=await n1(this.blockstore.get(i.cid,e));if(i.status!=="sending")continue;i.wantType===lt.WantHave?c.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:c,prefix:Fy(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:zr.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:c,prefix:Fy(i.cid)})),i.status="sent",i.expires=Date.now()+this.doNotResendBlockWindow}catch(a){if(a.name!=="NotFoundError")throw a;if(i.status="want",i.haveBlock=!1,this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDoNotHave===!0)continue;i.sentDoNotHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:zr.DoNotHaveBlock})}(t.blocks.size>0||t.blockPresences.size>0)&&(this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,i)=>o+i.data.byteLength,0)))}}};var K1=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;doNotResendBlockWindow;maxWantListSize;sendBlocksConcurrency;sendBlocksMaxQueueLength;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.doNotResendBlockWindow=t.doNotResendBlockWindow,this.maxWantListSize=t.maxWantListSize,this.sendBlocksConcurrency=t.sendBlocksConcurrency,this.sendBlocksMaxQueueLength=t.sendBlocksMaxQueueLength,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=_s({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{try{this.receiveMessage(n.detail.connection.remotePeer,n.detail.message)}catch(s){this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)}}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}start(){}stop(){this.ledgerMap.forEach(e=>{e.stop()})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount,sendQueue:t.sendQueue}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return t.removeExpiredWants(),t.getWants()}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}receiveMessage(e,t){let n=this.ledgerMap.get(e);n==null&&(n=new $1({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock,doNotResendBlockWindow:this.doNotResendBlockWindow,maxWantListSize:this.maxWantListSize,sendBlocksConcurrency:this.sendBlocksConcurrency,sendBlocksMaxQueueLength:this.sendBlocksMaxQueueLength}),this.ledgerMap.set(e,n)),n.queueSendOperation(t)}async receivedBlock(e,t){let n=[];for(let s of this.ledgerMap.values())s.hasWant(e)&&n.push(s);await Promise.all(n.map(async s=>s.queueSendOperation(void 0,t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var $y=class extends rc{name="bitswap-session";wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){if(n.signal?.aborted===!0)throw new li(`Signal to want session block for CID ${e} from peer ${t} was aborted prior to want`);let s=bt(t.peerId);this.log("sending WANT-BLOCK for %c to %p",e,s);let o=await this.wantList.wantSessionBlock(e,s,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has){if(o.block!=null)return o.block;throw new Error("Provider has block but did not send it to us")}throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield{peerId:n.id,router:n.router,toString:()=>`Bitswap(${n.id})`,fallback:n.fallback}}toFilterKey(e){return e.peerId.multihash.bytes}equals(e,t){return e.peerId.equals(t.peerId)}async convertToProvider(e,t,n){if(sc(e))return{peerId:e,router:t,toString:()=>`Bitswap(${e})`,fallback:!1};if(await this.libp2p.isDialable(e)!==!1)try{let s=await this.libp2p.dial(e,n);return{peerId:s.remotePeer.toCID(),router:t,toString:()=>`Bitswap(${s.remotePeer})`,fallback:!1}}catch{}}emitFoundProviderProgressEvent(e,t,n){n?.onProgress?.(new P("bitswap:found-provider",{type:"bitswap",cid:e,provider:{id:t.peerId,multiaddrs:[],router:t.router,fallback:t.fallback},router:t.router}))}};function Dx(r,e){return new $y(r,e)}var H1=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var Gr=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function jr(r,e,t,n){let s=new Gr(n?.errorMessage);n?.errorCode!=null&&(s.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(s):new Promise((i,a)=>{function c(){Hy(t,"abort",d),Hy(r,e,l),Hy(r,o,u)}let l=f=>{try{if(n?.filter?.(f)===!1)return}catch(h){c(),a(h);return}c(),i(f)},u=f=>{if(c(),f instanceof Error){a(f);return}a(f.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},d=()=>{c(),a(s)};Ky(t,"abort",d),Ky(r,e,l),Ky(r,o,u)})}function Ky(r,e,t){r!=null&&(Nx(r)?r.addEventListener(e,t):r.addListener(e,t))}function Hy(r,e,t){r!=null&&(Nx(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Nx(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function uB(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Br(r);e.push(t),r=r.slice(Te(t))}return e}var Ox=uB;var V1=class extends ge{peers;wants;network;log;sendWantlistDebounce;sendMessagesTimeout;getHasher;sendingMessages;constructor(e,t={}){super(),this.peers=_s({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=vt({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendWantlistDebounce=t.sendWantlistDebounce??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.getHasher=e.getHasher,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.connection,n.detail.message).catch(s=>{this.log.error("error receiving bitswap message from %p - %e",n.detail.connection.remotePeer,s)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(s=>{this.log.error("error processing newly connected bitswap peer %p - %e",n.detail,s)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=_(e.multihash.bytes,"base64"),s=this.wants.get(n);s==null&&(s={cid:e,priority:t.priority??1,wantType:t.wantType??lt.WantBlock,cancel:!1,sendDontHave:!0,onProgress:[]},this.wants.set(n,s)),t.onProgress!=null&&s.onProgress.push({onProgress:t.onProgress,signal:t.signal}),s.wantType===lt.WantHave&&t.wantType===lt.WantBlock&&(s.wantType=lt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===lt.WantBlock?(await jr(this,"block",t?.signal,{filter:a=>se(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await jr(this,"presence",t?.signal,{filter:i=>se(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),s.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers - %e",e)})},this.sendWantlistDebounce)}async sendMessages(){this.sendingMessages=Ye(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,s=new Ps;for(let[o,i]of this.wants.entries())t.has(o)||i.cancel||(n.add(o),s.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(s.wantlist.size!==0)try{await this.network.sendMessage(e,s,{onProgress:o=>{this.wants.forEach(({onProgress:i})=>{i.forEach(({onProgress:a})=>{a(o)})})}});for(let o of n)t.add(o)}catch(o){this.log.error("error sending full wantlist to new peer - %e",o)}})).catch(e=>{this.log.error("error sending messages - %e",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=_(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let s=new Ps;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:lt.WantHave,priority:1}),await this.network.sendMessage(t,s,n),(await jr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&se(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:lt.WantBlock})}async wantSessionBlock(e,t,n={}){let s=new Ps;return s.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:lt.WantBlock,priority:1}),await this.network.sendMessage(t,s,n),(await jr(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&se(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=_(e.multihash.bytes,"base64"),s=this.wants.get(n);s!=null&&(s.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e.remotePeer,t.blocks.length);let n=!1;for(let s of t.blocks){if(s.prefix==null||s.data==null)continue;let o=Ox(s.prefix),i=o[0],a=o[1],c=o[2],l=o[3],u=c===je.code?je:await this.getHasher(c);if(u==null){this.log.error("unknown hash algorithm",c);continue}let d=u.digest(s.data,{truncate:l});d.then!=null&&(d=await d);let f=$.create(i===0?0:1,a,d);this.log("received block from %p for %c",e.remotePeer,f),this.safeDispatchEvent("block",{detail:{sender:e.remotePeer,cid:f,block:s.data,connection:e}}),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:f,has:!0,block:s.data}});let h=_(f.multihash.bytes,"base64"),p=this.wants.get(h);p!=null&&(p.cancel=!0,n=!0)}for(let{cid:s,type:o}of t.blockPresences){let i=$.decode(s);this.log("received %s from %p for %c",o,e.remotePeer,i),this.safeDispatchEvent("presence",{detail:{sender:e.remotePeer,cid:i,has:o===zr.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Ps(!0);for(let[s,o]of this.wants.entries())o.cancel||(t.add(s),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:lt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n,{onProgress:s=>{this.wants.forEach(({onProgress:o})=>{o.forEach(({onProgress:i})=>{i(s)})})}}),this.peers.set(e,t)}catch(s){this.log.error("error sending full wantlist to new peer %p - %e",e,s)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var q1=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new H1(e),this.network=new M1(e,t),this.peerWantLists=new K1({...e,network:this.network},t),this.wantList=new V1({...e,network:this.network},t)}createSession(e={}){return Dx({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,s=he([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:s}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c - %e",e,o)});try{let o=await this.wantList.wantBlock(e,{...t,signal:s});return t.onProgress?.(new P("bitswap:block",{cid:e,sender:o.connection.remotePeer})),o.block}finally{n.abort(),s.clear()}}async notify(e,t={}){await Promise.all([this.peerWantLists.receivedBlock(e,t),this.wantList.receivedBlock(e,t)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),this.peerWantLists.stop(),await this.network.stop()}};var z1=class{name="bitswap";bitswap;started;constructor(e,t={}){this.bitswap=new q1(e,t),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t){await this.bitswap.notify(e,t)}async retrieve(e,t={}){return this.bitswap.want(e,{...t,onProgress:function(s){if(t?.onProgress!=null)if(t.onProgress(s),s.type==="connection:open"){if(!vr(s.detail))return;t.onProgress(new P("helia:block-broker:connect",{broker:"bitswap",type:"connect",provider:s.detail.toCID(),cid:e}))}else s.type==="connection:opened"?t.onProgress(new P("helia:block-broker:connected",{broker:"bitswap",type:"connected",provider:s.detail.remotePeer.toCID(),address:s.detail.remoteAddr,cid:e})):s.type==="bitswap:send-wantlist"?t.onProgress(new P("helia:block-broker:request-block",{broker:"bitswap",type:"request-block",provider:s.detail.toCID(),cid:e})):s.type==="bitswap:block"&&t.onProgress(new P("helia:block-broker:receive-block",{broker:"bitswap",type:"receive-block",provider:s.detail.sender.toCID(),cid:e}))}})}createSession(e){let t=this.bitswap.createSession(e);return{name:"bitswap-session",addPeer:async(n,s)=>{await t.addPeer(n,s)},announce:async(n,s)=>{await this.bitswap.notify(n,s)},retrieve:async(n,s)=>t.retrieve(n,s)}}};function Bx(r,e={}){let t={name:"bitswap",start:async n=>{if(n.status==="starting"&&!n.hasBlockBroker("bitswap")){let s=new z1(n,e);await yt(s),n.addBlockBroker(s)}}};return r.addMixin(t),r}async function*Hu(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 W1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*xc(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),s="";for await(let o of r){if(typeof o=="string"&&(o=new TextEncoder().encode(o)),va(o)&&(o=o.subarray()),s+=n.decode(o,{stream:!0}),s.length>(e?.maxMessageLength??s.length))throw new W1("Incoming message too long");let i=s.split(t);s=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}s+=n.decode(),s!==""&&(yield JSON.parse(s))}var zi=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},an=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};var G1={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},j1=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("helia:delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new ht({concurrency:t.concurrentRequests??G1.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??G1.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.cacheName=t.cacheName??G1.cacheName,this.cacheTTL=t.cacheTTL??G1.cacheTTL}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,n,t.signal]);let o=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(o.resolve(),i.promise));try{await be(o.promise,s);let c=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l=await this.#r(c.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:s});if(!l.ok){if(l.status===404)return;throw l.status===422?new zi("Request does not conform to schema or semantic constraints"):new an(`Unexpected status code: ${l.status}`)}let u=l.headers.get("Content-Type");if(u==null)throw new an("No Content-Type header received");if(l.body==null){if(u!=="application/x-ndjson")throw new an("Routing response had no body");return}if(u.startsWith("application/json")){let f=(await be(l.json(),s)).Providers??[];for(let h of f){let p=this.#e(h);p!=null&&(a++,yield p)}}else if(u.includes("application/x-ndjson")){s.addEventListener("abort",()=>{l?.body?.cancel()});for await(let d of xc(Hu(l.body))){let f=this.#e(d);f!=null&&(a++,yield f)}}else throw new an(`Unsupported Content-Type: ${u}`)}finally{s.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",a,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,n,t.signal]);let o=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(o.resolve(),i.promise));try{await be(o.promise,s);let a=new URL(`${this.url}routing/v1/peers/${e}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c=await this.#r(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(c.status===404)return;if(c.status===422)throw new zi("Request does not conform to schema or semantic constraints");if(c.body==null)throw new an("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let d=(await be(c.json(),s)).Peers??[];for(let f of d){let h=this.#e(f);h!=null&&(yield h)}}else{s.addEventListener("abort",()=>{c.body?.cancel()});for await(let u of xc(Hu(c.body))){let d=this.#e(u);d!=null&&(yield d)}}}catch(a){this.log.error("getPeers errored - %e",a)}finally{s.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if($.asCID(e)===e||e instanceof $)n=e.toV1().toString();else throw new v("Key must be CID");this.log("getClosestPeers starts: %s",n);let s=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,s,t.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await be(i.promise,o);let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l=await this.#r(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)return;if(l.status===422)throw new zi("Request does not conform to schema or semantic constraints");if(l.body==null)throw new an("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let f=(await be(l.json(),o)).Peers??[];for(let h of f){let p=this.#e(h);p!=null&&(yield p)}}else{o.addEventListener("abort",()=>{l.body?.cancel()});for await(let d of xc(Hu(l.body))){let f=this.#e(d);f!=null&&(yield f)}}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{o.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(e,t={}){this.log("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,n,t.signal]);let o=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(o.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await be(o.promise,s);let c=await this.#r(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:s});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new Re("No matching records found");if(c.status===422)throw new zi("Request does not conform to schema or semantic constraints");if(!c.ok)throw new an(`Unexpected status code: ${c.status}`);let l=c.headers.get("Content-Type");if(l==null||!l.includes("application/vnd.ipfs.ipns-record"))throw new Re("No matching records found");if(c.body==null)throw new an("GET ipns response had no body");let u=await be(c.arrayBuffer(),s);return new Uint8Array(u,0,u.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{s.clear(),i.resolve(),this.log("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let s=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,s,n.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await be(i.promise,o);let l=await this.#r(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:re(t),signal:o});if(this.log("putIPNS PUT %s %d",c,l.status),l.status!==200)throw new an("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{o.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(W)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:$.createV1(114,dB(e.ID)),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let s=t?.join(",")??this.filterAddrs?.join(",")??"";s!==""&&e.searchParams.set("filter-addrs",s)}if(n!=null||this.filterProtocols!=null){let s=n?.join(",")??this.filterProtocols?.join(",")??"";s!==""&&e.searchParams.set("filter-protocols",s)}}async#r(e,t){let n=t.method??"GET",s=`${n}-${e}`;if(n==="GET"){let c=await be(this.cache?.match(e),t.signal);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",s),this.logResponse(c),c;this.log("evicting cached response for %s",s),await be(this.cache?.delete(e),t.signal)}else this.cache!=null&&this.log("cache miss for %s",s)}let o=this.inFlightRequests.get(s);if(o!=null){let c=await be(o,t.signal);return this.log("deduplicating outgoing request for %s",s),c.clone()}this.log("outgoing request:"),this.logRequest(e,t);let i=fetch(e,t).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let d=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await be(this.cache.put(e,d),t.signal)}return c}).finally(()=>{this.inFlightRequests.delete(s)});return this.inFlightRequests.set(s,i),await be(i,t.signal)}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[s,o]of n.entries())this.log("%s: %s",s,o)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function dB(r){let e=Se.baseDecode(r);return Ce(e)}function fB(r){return r[Symbol.asyncIterator]!=null}function hB(r){if(fB(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Y1=hB;var X1=A("/ipns/");function Mx(r){return se(r.subarray(0,X1.byteLength),X1)}var Q1=class{client;constructor(e){this.client=e}get[Yo](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async*findProviders(e,t={}){try{yield*Vt(this.client.getProviders(e,t),n=>({id:bt(n.ID),multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof Re)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!Mx(e))return;let s=Ce(e.slice(X1.length)),o=$.createV1(114,s);await this.client.putIPNS(o,t,n)}async get(e,t){if(!Mx(e))throw new Re("Not found");let n=Ce(e.slice(X1.length)),s=$.createV1(114,n);try{return await this.client.getIPNS(s,t)}catch(o){throw o.name==="BadResponseError"?new Re("Not found"):o}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},Z1=class{client;constructor(e){this.client=e}get[ti](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async findPeer(e,t={}){let n=await Y1(this.client.getPeers(e.toCID(),t));if(n!=null)return{id:bt(n.ID),multiaddrs:n.Addrs??[]};throw new Re("Not found")}async*getClosestPeers(e,t={}){let n;try{n=$.decode(e)}catch{try{n=$.createV1(114,Qe.decode(e))}catch{n=$.createV1(hs,ot.digest(e))}}for await(let s of this.client.getClosestPeers(n,t))yield{id:bt(s.ID),multiaddrs:s.Addrs??[]}}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};function J1(r){return e=>new j1(e,r)}function Ux(r){return e=>new Q1(J1(r)(e))}function Fx(r){return e=>new Z1(J1(r)(e))}var ep=A("/ipns/");function $x(r){return se(r.subarray(0,ep.byteLength),ep)}var tp=class{name="delegated-http-router";client;constructor(e,t){this.client=J1(t)(e)}async provide(e,t){}async cancelReprovide(e,t){}async*findProviders(e,t){yield*Vt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,router:this.name,fallback:!1}))}async put(e,t,n){if(!$x(e))return;let s=Ce(e.slice(ep.length)),o=$.createV1(114,s);await this.client.putIPNS(o,t,n)}async get(e,t){if(!$x(e))throw new Re("Not found");let n=Ce(e.slice(ep.length)),s=$.createV1(114,n);try{return await this.client.getIPNS(s,t)}catch(o){throw o.name==="BadResponseError"?new Re("Not found"):o}}async findPeer(e,t){let n=await Y1(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[],router:this.name};throw new Re("Not found")}async*getClosestPeers(e,t){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function Vu(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"],...r??{}}}function Kx(r){return e=>new tp(e,Vu(r))}var Hx="[a-fA-F\\d:]",Ao=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Hx})|(?<=${Hx})(?=\\s|$))`:"",kn="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",It="[a-fA-F\\d]{1,4}",rp=`
|
|
13
13
|
(?:
|
|
14
14
|
(?:${It}:){7}(?:${It}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
15
15
|
(?:${It}:){6}(?:${kn}|:${It}|:)| // 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
|
|
@@ -110,7 +110,7 @@ ${e}`)}`:n!=null?`${n.split(`
|
|
|
110
110
|
${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function QV(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function t_(r,e=""){if(QV(r)){let t=Jk(r,e);return r.errors.length>0?(e=`${e} `,t+=`
|
|
111
111
|
${e}${r.errors.map(n=>`${t_(n,`${e}`)}`).join(`
|
|
112
112
|
${e}`)}`):t+=`
|
|
113
|
-
${e}[Error list was empty]`,t.trim()}return Jk(r,e)}function ZV(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function r_(r){return{forComponent(e){return n_(e,r)}}}function n_(r,e){let t=ZV(`${r}:trace`);return et.enabled(`${r}:trace`)&&et.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=et(`${r}:trace`,e)),Object.assign(et(r,e),{error:et(`${r}:error`,e),trace:t,newScope:n=>n_(`${r}:${n}`,e)})}function e_(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Ys=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,bytes:s}of e)await this.put(n,s,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes: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")}};function JV(r){return typeof r?.then=="function"}var Cf=class extends Ys{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let s;if(t instanceof Uint8Array)s=[t];else{let o=Fs(t);if(JV(o))return o.then(i=>this._put(e,i,n));s=o}return this._put(e,s,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(xt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(xt.encode(e.multihash.bytes));if(n==null)throw new kr;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(xt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(xt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:$.createV1(hs,Ce(xt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var _Ae=Ja("blockstore:core:tiered");var s_="SHARDING";var XAe=new Ve(s_);var uTe=Ja("datastore:core:tiered");var bg=class{lock;child;pins;routing;started;constructor(e,t,n,s={}){this.child=e,this.pins=t,this.routing=n,this.lock=cd({singleProcess:s.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child),this.started=!0}async stop(){await Dt(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let s=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{s()}}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{yield*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 fu("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let s=this;yield*this.child.deleteMany((async function*(){for await(let o of e){if(await s.pins.isPinned(o))throw new fu("Block was pinned - please unpin and try again");await s.routing.cancelReprovide(o,t),yield o}})(),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 L7=new Ve("/version"),i_=1;async function a_(r){if(!await r.has(L7)){await r.put(L7,A(`${i_}`));return}let e=await r.get(L7),t=_(e);if(parseInt(t,10)!==i_)throw new e1("Invalid datastore version, a datastore migration may be required")}var M7={};we(M7,{code:()=>B7,createLink:()=>w_,createNode:()=>y_,decode:()=>hq,encode:()=>fq,name:()=>dq,prepare:()=>N7,validate:()=>O7});var tq=new TextDecoder;function R7(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 s=r[e++];if(t+=n<28?(s&127)<<n:(s&127)*2**n,s<128)break}return[t,e]}function Eg(r,e){let t;[t,e]=R7(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 c_(r,e){let t;return[t,e]=R7(r,e),[t&7,t>>3,e]}function rq(r){let e={},t=r.length,n=0;for(;n<t;){let s,o;if([s,o,n]=c_(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) 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]=Eg(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Eg(r,n),e.Name=tq.decode(i)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(s!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Tsize`);[e.Tsize,n]=R7(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function l_(r){let e=r.length,t=0,n,s=!1,o;for(;t<e;){let a,c;if([a,c,t]=c_(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Eg(r,t),n&&(s=!0)}else if(c===2){if(s)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Eg(r,t),n.push(rq(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 i={};return o&&(i.Data=o),i.Links=n||[],i}var f_=new TextEncoder,u_=2**32,nq=2**31;function sq(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=kf(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=f_.encode(r.Name);t-=n.length,e.set(n,t),t=kf(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=kf(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function d_(r,e,t){return r-=e.Data.length,t.set(e.Data,r),r=kf(t,r,e.Data.length)-1,t[r]=10,r}function h_(r,e){let t=iq(r),n=new Uint8Array(t),s=t,o=e?.fieldOrder==="data-first"?e.fieldOrder:"links-first";if(r.Data&&o==="links-first"&&(s=d_(s,r,n)),r.Links)for(let i=r.Links.length-1;i>=0;i--){let a=sq(r.Links[i],n.subarray(0,s));s-=a,s=kf(n,s,a)-1,n[s]=18}return r.Data&&o==="data-first"&&(s=d_(s,r,n)),n}function oq(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+yl(t)}if(typeof r.Name=="string"){let t=f_.encode(r.Name).length;e+=1+t+yl(t)}return typeof r.Tsize=="number"&&(e+=1+yl(r.Tsize)),e}function iq(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+yl(t)}if(r.Links)for(let t of r.Links){let n=oq(t);e+=1+n+yl(n)}return e}function kf(r,e,t){e-=yl(t);let n=e;for(;t>=nq;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function yl(r){return r%2===0&&r++,Math.floor((aq(r)+6)/7)}function aq(r){let e=0;return r>=u_&&(r=Math.floor(r/u_),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+cq[r]}var cq=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var lq=["Data","Links"],uq=["Hash","Name","Tsize"],D7=new TextEncoder;function m_(r,e){if(r===e)return 0;let t=r.Name?D7.encode(r.Name):[],n=e.Name?D7.encode(e.Name):[],s=t.length,o=n.length;for(let i=0,a=Math.min(s,o);i<a;++i)if(t[i]!==n[i]){s=t[i],o=n[i];break}return s<o?-1:o<s?1:0}function p_(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function g_(r){if(typeof r.asCID=="object"){let t=$.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=$.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=$.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=$.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function N7(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=D7.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(g_),e.Links.sort(m_);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function O7(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!p_(r,lq))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!p_(t,uq))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&m_(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function y_(r,e=[]){return N7({Data:r,Links:e})}function w_(r,e,t){return g_({Hash:t,Name:r,Tsize:e})}function b_(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var dq="dag-pb",B7=112;function fq(r,e){O7(r);let t={};return r.Links&&(t.Links=r.Links.map(n=>{let s={};return n.Hash&&(s.Hash=n.Hash.bytes),n.Name!==void 0&&(s.Name=n.Name),n.Tsize!==void 0&&(s.Tsize=n.Tsize),s})),r.Data&&(t.Data=r.Data),h_(t,e)}function hq(r){let e=b_(r),t=l_(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(s=>{let o={};try{o.Hash=$.decode(s.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return s.Name!==void 0&&(o.Name=s.Name),s.Tsize!==void 0&&(o.Tsize=s.Tsize),o})),n}function E_(r=[],e){let t={[B7]:M7,[hs]:ii};return r.forEach(n=>{t[n.code]=n}),async n=>{let s=t[n];if(s==null&&e!=null){let o=e(n);ho(o)?s=await o:s=o,t[s.code]=s}if(s!=null)return s;throw new Vl(`Could not load codec for ${n}`)}}function x_(r=[],e){let t={};return r=[y3(),b3(),$l(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let s=t[n];if(s==null&&e!=null){let o=e(n);ho(o)?s=await o:s=o,t[s.type]=s,t[s.code]=s}if(s!=null)return s;throw new ql(`Could not load crypto for ${s}`)}}function v_(r=[],e){let t={[je.code]:je,[ot.code]:ot};return r.forEach(n=>{t[n.code]=n}),async n=>{let s=t[n];if(s==null&&e!=null){let o=e(n);ho(o)?s=await o:s=o,t[s.code]=s}if(s!=null)return s;throw new Hl(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var xg=0,wl=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},vg=class extends Ys{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new kr;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};var pq=128,bl=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new vg(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??pq}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new P("blocks:put:duplicate",e)),e):(n.onProgress?.(new P("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(e,n))),n.onProgress?.(new P("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Hr(e,async({cid:o})=>{let i=await this.child.has(o,t);return i&&t.onProgress?.(new P("blocks:put-many:duplicate",o)),!i}),s=_c(n,async({cid:o})=>{t.onProgress?.(new P("blocks:put-many:providers:notify",o)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(o,t)))});t.onProgress?.(new P("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(s,t)}async*get(e,t={}){let n=await this.child.has(e,t),s=t.offline===!0;if(!n){if(s)throw new hu("The block was present in the blockstore and the node is running offline so cannot fetch it");let o=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new P("blocks:get:providers:get",e));let i=await S_(e,this.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new P("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new P("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield i;return}t.onProgress?.(new P("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new P("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(_c(e,async n=>{let s=await this.child.has(n,t),o=t.offline===!0;if(!s){if(o)throw new hu("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new P("blocks:get-many:providers:get",n));let a=await S_(n,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new P("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new P("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new P("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new P("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 P("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function S_(r,e,t,n){let s=gq(r,t),o=new AbortController,i=he([o.signal,n.signal]);o.signal;let a=[];for(let c of e)mq(c)&&a.push(c);if(a.length===0)throw new vs(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:i,validateFn:async d=>{await s(d),n.signal?.throwIfAborted(),l=!0}});return l||(await s(u),n.signal?.throwIfAborted()),u}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new r1(c.errors,`Failed to load block for ${r}`)}finally{o.abort(),i.clear()}}function mq(r){return typeof r.retrieve=="function"}var gq=(r,e)=>{if(e==null)throw new v(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,s=e.digest(t,{truncate:r.multihash.digest.byteLength});if(ho(s)?n=await s:n=s,!se(n.digest,r.multihash.digest))throw new ya("Hash of downloaded block did not match multihash from passed CID")}};var Sg=class extends bl{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}async put(e,t,n={}){let s=he([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:s})}finally{s.clear()}}async*putMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=he([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=he([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=he([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Ag=class extends bl{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child,...this.blockBrokers),this.started=!0}async stop(){await Dt(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new vs("No block brokers configured");let n=this.blockBrokers.map(s=>s.createSession?.(t)).filter(s=>s!=null);if(n.length===0)throw new vs(`No configured block brokers support sessions - tried ${this.blockBrokers.map(s=>s.name).join(", ")}`);return new Sg({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var T_="/pin/",A_="/pinned-block/",U7=cr;function Tg(r){return r.version===0&&(r=r.toV1()),new Ve(`${T_}${r.toString(U7)}`)}var Ig=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Tg(e);if(await this.datastore.has(n))throw new Jh("Already pinned");let s=Math.round(t.depth??1/0);if(s<0)throw new v("Depth must be greater than or equal to 0");let o=(t.walker??U4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of o.walk(e,{...t,depth:s})){let c=a.block.cid;await this.#e(c,l=>l.pinnedBy.find(u=>se(u,e.bytes))!=null?!1:(l.pinCount++,l.pinnedBy.push(e.bytes),!0),t),yield c}let i={depth:s,metadata:t.metadata??{}};await this.datastore.put(n,Ti(i),t)}async#e(e,t,n){let s=new Ve(`${A_}${U7.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=An(await this.datastore.get(s,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(o)){if(o.pinCount===0&&await this.datastore.has(s)){await this.datastore.delete(s);return}await this.datastore.put(s,Ti(o),n),n.onProgress?.(new P("helia:pin:add",e))}}async*rm(e,t={}){let n=Tg(e),s=await this.datastore.get(n,t),o=An(s);await this.datastore.delete(n,t);let i=(t.walker??U4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of i.walk(e,{...t,depth:o.depth})){let c=a.block.cid;await this.#e(c,l=>(l.pinCount--,l.pinnedBy=l.pinnedBy.filter(u=>se(u,e.bytes)),!0),{...t,depth:o.depth}),yield c}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:T_+(e.cid!=null?`${e.cid.toString(cr)}`:"")},e)){let s=$.parse(t.toString().substring(5),cr),o=An(n);yield{cid:s,...o}}}async isPinned(e,t={}){let n=new Ve(`${A_}${U7.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Tg(e),s=await this.datastore.get(n,t);return An(s)}async setMetadata(e,t,n){let s=Tg(e),o=await this.datastore.get(s,n),i=An(o);i.metadata=t??{},await this.datastore.put(s,Ti(i),n)}};var yq=5,Cg=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??yq,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await yt(...this.routers)}async stop(){await Dt(...this.routers)}hasRouter(e){return this.routers.findIndex(t=>t.name===e)!==-1}addRouter(e){this.routers.push(e)}async*findProviders(e,t={}){if(this.routers.length===0)throw new ro("No content routers available");let n=0,s=[],o=this;async function*i(u){let d=0,f=u.map(async function*(p){let g=0;t?.onProgress?.(new P("helia:routing:find-providers:start",{router:p.name,cid:e}));try{for await(let y of p.findProviders(e,t))g++,t?.onProgress?.(new P("helia:routing:find-providers:provider",{router:p.name,cid:e,provider:y})),yield y}catch(y){s.push(y)}finally{o.log("router %s found %d providers for %c",p.name,g,e),t?.onProgress?.(new P("helia:routing:find-providers:end",{router:p.name,cid:e,found:g})),d++,d===u.length&&h.size===0&&h.emitIdle()}}),h=new ht({concurrency:o.providerLookupConcurrency});for await(let p of hr(h.toGenerator(),...f))if(p!=null){if(p.multiaddrs.length===0){if(h.queue.find(g=>g.options.peer.equals(p.id))!=null)continue;h.add(async()=>{try{let g=await o.findPeer(p.id,t);return g.multiaddrs.length===0?null:{...g,protocols:p.protocols,router:p.router,fallback:p.fallback}}catch(g){return o.log.error("could not load multiaddrs for peer %p - %e",p.id,g),null}},{peer:p.id,signal:t.signal}).catch(g=>{o.log.error("could not load multiaddrs for peer %p - %e",p.id,g)});continue}n++,yield p}}let a=ua(this.routers,"findProviders"),c=a.filter(u=>u.capabilities==null||!u.capabilities().includes("fallback")),l=a.filter(u=>u.capabilities?.().includes("fallback")===!0);this.log("findProviders for %c start using routers %s",e,c.map(u=>u.name).join(", ")),yield*i(c),l.length>0&&(this.log("findProviders for %c using fallback routers %s",e,l.map(u=>u.name).join(", ")),yield*i(l)),this.log("findProviders finished, found %d providers for %c",n,e)}async provide(e,t={}){if(this.routers.length===0)throw new ro("No content routers available");await Promise.all(ua(this.routers,"provide").map(async n=>{t?.onProgress?.(new P("helia:routing:provide:start",{router:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new P("helia:routing:provide:end",{router:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(ua(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new P("helia:routing:cancel-reprovide:start",{router:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new P("helia:routing:cancel-reprovide:end",{router:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(ua(this.routers,"put").map(async s=>{n?.onProgress?.(new P("helia:routing:put:start",{router:s.name,key:e,value:t})),await s.put(e,t,n),n?.onProgress?.(new P("helia:routing:put:end",{router:s.name,key:e,value:t}))}))}async get(e,t){let n=[],s,o=new AbortController,i=he([o.signal,t?.signal]);try{s=await Promise.any(ua(this.routers,"get").map(async a=>{t?.onProgress?.(new P("helia:routing:get:start",{router:a.name,key:e}));try{return await a.get(e,{...t,signal:i})}catch(c){throw this.log("router %s failed with %e",a.name,c),n.push(c),c}finally{t?.onProgress?.(new P("helia:routing:get:end",{router:a.name,key:e}))}}))}catch{}finally{o.abort(),i.clear()}if(s==null)throw new t1(n,`Failed to get value key ${_(e,"base58btc")}`);return s}async findPeer(e,t){if(this.routers.length===0)throw new ro("No peer routers available");let n=new AbortController,s=he([n.signal,t?.signal]);let o=this,i=hr(...ua(this.routers,"findPeer").map(a=>(async function*(){t?.onProgress?.(new P("helia:routing:find-peer:start",{router:a.name,peerId:e}));try{yield await a.findPeer(e,{...t,signal:s})}catch(c){o.log.error(c)}finally{t?.onProgress?.(new P("helia:routing:find-peer:end",{router:a.name,peerId:e}))}})()));try{for await(let a of i)if(a!=null)return a}finally{n.abort(),s.clear()}throw new Re("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new ro("No peer routers available");for await(let n of hr(...ua(this.routers,"getClosestPeers").map(async function*(s){t?.onProgress?.(new P("helia:routing:get-closest-peers:start",{router:s.name,key:e}));try{yield*s.getClosestPeers(e,t)}finally{t?.onProgress?.(new P("helia:routing:get-closest-peers:end",{router:s.name,key:e}))}})))n!=null&&(yield n)}};function ua(r,e){return r.filter(t=>t[e]!=null)}var kg=class{info;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;status;log;blockBrokers;mixins;components;constructor(e){this.info={name:e.name,version:e.version},this.logger=e.logger??r_(),this.log=this.logger.forComponent("helia"),this.getHasher=v_(e.hashers,e.loadHasher),this.getCodec=E_(e.codecs,e.loadCodec),this.getCrypto=x_(e.cryptos,e.loadCrypto),this.dns=e.dns??Xm(),this.metrics=e.metrics,this.events=new ge,this.status="stopped",this.mixins=[],this.components={blockstore:e.blockstore??new Cf,datastore:e.datastore??new Qi,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}},this.keychain=this.components.keychain=Zk()(this.components),this.routing=this.components.routing=new Cg(this.components,{routers:(e.routers??[]).flatMap(n=>(typeof n=="function"&&(n=n(this.components)),[n])),providerLookupConcurrency:e.providerLookupConcurrency}),this.blockBrokers=this.components.blockBrokers=(e.blockBrokers??[]).map(n=>(typeof n=="function"&&(n=n(this.components)),n));let t=new Ag(this.components,e);this.pins=new Ig(this.components.datastore,t,this.getCodec),this.blockstore=new bg(t,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=this.components.datastore}hasRouter(e){return this.routing.hasRouter(e)}addRouter(e){typeof e=="function"&&(e=e(this.components)),this.routing.addRouter(e)}hasBlockBroker(e){return this.blockBrokers.findIndex(t=>t.name===e)!==-1}addBlockBroker(e){typeof e=="function"&&(e=e(this.components)),this.blockBrokers.push(e)}addMixin(e){if(this.mixins.find(t=>t.name===e.name)!=null)throw new vs(`A mixin with the name "${e.name} is already present`);this.mixins.push(e)}async start(){this.status="starting",await a_(this.datastore),await yt(this.blockstore,this.datastore,this.routing,...this.blockBrokers);for(let e of this.mixins)await e.start?.(this);return this.status="started",this.events.dispatchEvent(new CustomEvent("start",{detail:this})),this}async stop(){this.status="stopping";for(let e of this.mixins)await e.stop?.(this);return await Dt(this.blockstore,this.datastore,this.routing,...this.blockBrokers),this.status="stopped",this.events.dispatchEvent(new CustomEvent("stop",{detail:this})),this}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,s=this.blockstore.unwrap();this.log("gc start"),await Cr(s.deleteMany((async function*(){for await(let{cid:o}of s.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new P("helia:gc:deleted",o))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new P("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};var I_="7.1.11",C_="helia";function wq(r={}){return Bx($k(sv(k_({...r,codecs:[A7,_7,Hf,...r.codecs??[]],hashers:[i3,...r.hashers??[]]}),r.http),r.libp2p),r.bitswap)}function k_(r={}){return new kg({name:C_,version:I_,...r})}return M_(bq);})();
|
|
113
|
+
${e}[Error list was empty]`,t.trim()}return Jk(r,e)}function ZV(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function r_(r){return{forComponent(e){return n_(e,r)}}}function n_(r,e){let t=ZV(`${r}:trace`);return et.enabled(`${r}:trace`)&&et.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=et(`${r}:trace`,e)),Object.assign(et(r,e),{error:et(`${r}:error`,e),trace:t,newScope:n=>n_(`${r}:${n}`,e)})}function e_(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Ys=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,bytes:s}of e)await this.put(n,s,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes: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")}};function JV(r){return typeof r?.then=="function"}var Cf=class extends Ys{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let s;if(t instanceof Uint8Array)s=[t];else{let o=Fs(t);if(JV(o))return o.then(i=>this._put(e,i,n));s=o}return this._put(e,s,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(xt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(xt.encode(e.multihash.bytes));if(n==null)throw new kr;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(xt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(xt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:$.createV1(hs,Ce(xt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var _Ae=Ja("blockstore:core:tiered");var s_="SHARDING";var XAe=new Ve(s_);var uTe=Ja("datastore:core:tiered");var bg=class{lock;child;pins;routing;started;constructor(e,t,n,s={}){this.child=e,this.pins=t,this.routing=n,this.lock=cd({singleProcess:s.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child),this.started=!0}async stop(){await Dt(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let s=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{s()}}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{yield*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 fu("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let s=this;yield*this.child.deleteMany((async function*(){for await(let o of e){if(await s.pins.isPinned(o))throw new fu("Block was pinned - please unpin and try again");await s.routing.cancelReprovide(o,t),yield o}})(),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 L7=new Ve("/version"),i_=1;async function a_(r){if(!await r.has(L7)){await r.put(L7,A(`${i_}`));return}let e=await r.get(L7),t=_(e);if(parseInt(t,10)!==i_)throw new e1("Invalid datastore version, a datastore migration may be required")}var M7={};we(M7,{code:()=>B7,createLink:()=>w_,createNode:()=>y_,decode:()=>hq,encode:()=>fq,name:()=>dq,prepare:()=>N7,validate:()=>O7});var tq=new TextDecoder;function R7(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 s=r[e++];if(t+=n<28?(s&127)<<n:(s&127)*2**n,s<128)break}return[t,e]}function Eg(r,e){let t;[t,e]=R7(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 c_(r,e){let t;return[t,e]=R7(r,e),[t&7,t>>3,e]}function rq(r){let e={},t=r.length,n=0;for(;n<t;){let s,o;if([s,o,n]=c_(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) 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]=Eg(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Eg(r,n),e.Name=tq.decode(i)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(s!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Tsize`);[e.Tsize,n]=R7(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function l_(r){let e=r.length,t=0,n,s=!1,o;for(;t<e;){let a,c;if([a,c,t]=c_(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=Eg(r,t),n&&(s=!0)}else if(c===2){if(s)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Eg(r,t),n.push(rq(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 i={};return o&&(i.Data=o),i.Links=n||[],i}var f_=new TextEncoder,u_=2**32,nq=2**31;function sq(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=kf(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=f_.encode(r.Name);t-=n.length,e.set(n,t),t=kf(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=kf(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function d_(r,e,t){return r-=e.Data.length,t.set(e.Data,r),r=kf(t,r,e.Data.length)-1,t[r]=10,r}function h_(r,e){let t=iq(r),n=new Uint8Array(t),s=t,o=e?.fieldOrder==="data-first"?e.fieldOrder:"links-first";if(r.Data&&o==="links-first"&&(s=d_(s,r,n)),r.Links)for(let i=r.Links.length-1;i>=0;i--){let a=sq(r.Links[i],n.subarray(0,s));s-=a,s=kf(n,s,a)-1,n[s]=18}return r.Data&&o==="data-first"&&(s=d_(s,r,n)),n}function oq(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+yl(t)}if(typeof r.Name=="string"){let t=f_.encode(r.Name).length;e+=1+t+yl(t)}return typeof r.Tsize=="number"&&(e+=1+yl(r.Tsize)),e}function iq(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+yl(t)}if(r.Links)for(let t of r.Links){let n=oq(t);e+=1+n+yl(n)}return e}function kf(r,e,t){e-=yl(t);let n=e;for(;t>=nq;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function yl(r){return r%2===0&&r++,Math.floor((aq(r)+6)/7)}function aq(r){let e=0;return r>=u_&&(r=Math.floor(r/u_),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+cq[r]}var cq=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var lq=["Data","Links"],uq=["Hash","Name","Tsize"],D7=new TextEncoder;function m_(r,e){if(r===e)return 0;let t=r.Name?D7.encode(r.Name):[],n=e.Name?D7.encode(e.Name):[],s=t.length,o=n.length;for(let i=0,a=Math.min(s,o);i<a;++i)if(t[i]!==n[i]){s=t[i],o=n[i];break}return s<o?-1:o<s?1:0}function p_(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function g_(r){if(typeof r.asCID=="object"){let t=$.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=$.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=$.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=$.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function N7(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=D7.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(g_),e.Links.sort(m_);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function O7(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!p_(r,lq))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!p_(t,uq))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&m_(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function y_(r,e=[]){return N7({Data:r,Links:e})}function w_(r,e,t){return g_({Hash:t,Name:r,Tsize:e})}function b_(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var dq="dag-pb",B7=112;function fq(r,e){O7(r);let t={};return r.Links&&(t.Links=r.Links.map(n=>{let s={};return n.Hash&&(s.Hash=n.Hash.bytes),n.Name!==void 0&&(s.Name=n.Name),n.Tsize!==void 0&&(s.Tsize=n.Tsize),s})),r.Data&&(t.Data=r.Data),h_(t,e)}function hq(r){let e=b_(r),t=l_(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(s=>{let o={};try{o.Hash=$.decode(s.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return s.Name!==void 0&&(o.Name=s.Name),s.Tsize!==void 0&&(o.Tsize=s.Tsize),o})),n}function E_(r=[],e){let t={[B7]:M7,[hs]:ii};return r.forEach(n=>{t[n.code]=n}),async n=>{let s=t[n];if(s==null&&e!=null){let o=e(n);ho(o)?s=await o:s=o,t[s.code]=s}if(s!=null)return s;throw new Vl(`Could not load codec for ${n}`)}}function x_(r=[],e){let t={};return r=[y3(),b3(),$l(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let s=t[n];if(s==null&&e!=null){let o=e(n);ho(o)?s=await o:s=o,t[s.type]=s,t[s.code]=s}if(s!=null)return s;throw new ql(`Could not load crypto for ${s}`)}}function v_(r=[],e){let t={[je.code]:je,[ot.code]:ot};return r.forEach(n=>{t[n.code]=n}),async n=>{let s=t[n];if(s==null&&e!=null){let o=e(n);ho(o)?s=await o:s=o,t[s.code]=s}if(s!=null)return s;throw new Hl(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var xg=0,wl=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},vg=class extends Ys{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new kr;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};var pq=128,bl=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new vg(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??pq}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new P("blocks:put:duplicate",e)),e):(n.onProgress?.(new P("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async s=>s.announce?.(e,n))),n.onProgress?.(new P("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Hr(e,async({cid:o})=>{let i=await this.child.has(o,t);return i&&t.onProgress?.(new P("blocks:put-many:duplicate",o)),!i}),s=_c(n,async({cid:o})=>{t.onProgress?.(new P("blocks:put-many:providers:notify",o)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(o,t)))});t.onProgress?.(new P("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(s,t)}async*get(e,t={}){let n=await this.child.has(e,t),s=t.offline===!0;if(!n){if(s)throw new hu("The block was present in the blockstore and the node is running offline so cannot fetch it");let o=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new P("blocks:get:providers:get",e));let i=await S_(e,this.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new P("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new P("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield i;return}t.onProgress?.(new P("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new P("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(_c(e,async n=>{let s=await this.child.has(n,t),o=t.offline===!0;if(!s){if(o)throw new hu("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new P("blocks:get-many:providers:get",n));let a=await S_(n,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new P("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new P("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new P("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new P("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 P("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function S_(r,e,t,n){let s=gq(r,t),o=new AbortController,i=he([o.signal,n.signal]);o.signal;let a=[];for(let c of e)mq(c)&&a.push(c);if(a.length===0)throw new vs(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:i,validateFn:async d=>{await s(d),n.signal?.throwIfAborted(),l=!0}});return l||(await s(u),n.signal?.throwIfAborted()),u}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new r1(c.errors,`Failed to load block for ${r}`)}finally{o.abort(),i.clear()}}function mq(r){return typeof r.retrieve=="function"}var gq=(r,e)=>{if(e==null)throw new v(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,s=e.digest(t,{truncate:r.multihash.digest.byteLength});if(ho(s)?n=await s:n=s,!se(n.digest,r.multihash.digest))throw new ya("Hash of downloaded block did not match multihash from passed CID")}};var Sg=class extends bl{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}async put(e,t,n={}){let s=he([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:s})}finally{s.clear()}}async*putMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=he([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=he([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=he([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Ag=class extends bl{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child,...this.blockBrokers),this.started=!0}async stop(){await Dt(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new vs("No block brokers configured");let n=this.blockBrokers.map(s=>s.createSession?.(t)).filter(s=>s!=null);if(n.length===0)throw new vs(`No configured block brokers support sessions - tried ${this.blockBrokers.map(s=>s.name).join(", ")}`);return new Sg({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var T_="/pin/",A_="/pinned-block/",U7=cr;function Tg(r){return r.version===0&&(r=r.toV1()),new Ve(`${T_}${r.toString(U7)}`)}var Ig=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Tg(e);if(await this.datastore.has(n))throw new Jh("Already pinned");let s=Math.round(t.depth??1/0);if(s<0)throw new v("Depth must be greater than or equal to 0");let o=(t.walker??U4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of o.walk(e,{...t,depth:s})){let c=a.block.cid;await this.#e(c,l=>l.pinnedBy.find(u=>se(u,e.bytes))!=null?!1:(l.pinCount++,l.pinnedBy.push(e.bytes),!0),t),yield c}let i={depth:s,metadata:t.metadata??{}};await this.datastore.put(n,Ti(i),t)}async#e(e,t,n){let s=new Ve(`${A_}${U7.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=An(await this.datastore.get(s,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(o)){if(o.pinCount===0&&await this.datastore.has(s)){await this.datastore.delete(s);return}await this.datastore.put(s,Ti(o),n),n.onProgress?.(new P("helia:pin:add",e))}}async*rm(e,t={}){let n=Tg(e),s=await this.datastore.get(n,t),o=An(s);await this.datastore.delete(n,t);let i=(t.walker??U4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of i.walk(e,{...t,depth:o.depth})){let c=a.block.cid;await this.#e(c,l=>(l.pinCount--,l.pinnedBy=l.pinnedBy.filter(u=>se(u,e.bytes)),!0),{...t,depth:o.depth}),yield c}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:T_+(e.cid!=null?`${e.cid.toString(cr)}`:"")},e)){let s=$.parse(t.toString().substring(5),cr),o=An(n);yield{cid:s,...o}}}async isPinned(e,t={}){let n=new Ve(`${A_}${U7.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Tg(e),s=await this.datastore.get(n,t);return An(s)}async setMetadata(e,t,n){let s=Tg(e),o=await this.datastore.get(s,n),i=An(o);i.metadata=t??{},await this.datastore.put(s,Ti(i),n)}};var yq=5,Cg=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??yq,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await yt(...this.routers)}async stop(){await Dt(...this.routers)}hasRouter(e){return this.routers.findIndex(t=>t.name===e)!==-1}addRouter(e){this.routers.push(e)}async*findProviders(e,t={}){if(this.routers.length===0)throw new ro("No content routers available");let n=0,s=[],o=this;async function*i(u){let d=0,f=u.map(async function*(p){let g=0;t?.onProgress?.(new P("helia:routing:find-providers:start",{router:p.name,cid:e}));try{for await(let y of p.findProviders(e,t))g++,t?.onProgress?.(new P("helia:routing:find-providers:provider",{router:p.name,cid:e,provider:y})),yield y}catch(y){s.push(y)}finally{o.log("router %s found %d providers for %c",p.name,g,e),t?.onProgress?.(new P("helia:routing:find-providers:end",{router:p.name,cid:e,found:g})),d++,d===u.length&&h.size===0&&h.emitIdle()}}),h=new ht({concurrency:o.providerLookupConcurrency});for await(let p of hr(h.toGenerator(),...f))if(p!=null){if(p.multiaddrs.length===0){if(h.queue.find(g=>g.options.peer.equals(p.id))!=null)continue;h.add(async()=>{try{let g=await o.findPeer(p.id,t);return g.multiaddrs.length===0?null:{...g,protocols:p.protocols,router:p.router,fallback:p.fallback}}catch(g){return o.log.error("could not load multiaddrs for peer %p - %e",p.id,g),null}},{peer:p.id,signal:t.signal}).catch(g=>{o.log.error("could not load multiaddrs for peer %p - %e",p.id,g)});continue}n++,yield p}}let a=ua(this.routers,"findProviders"),c=a.filter(u=>u.capabilities==null||!u.capabilities().includes("fallback")),l=a.filter(u=>u.capabilities?.().includes("fallback")===!0);this.log("findProviders for %c start using routers %s",e,c.map(u=>u.name).join(", ")),yield*i(c),l.length>0&&(this.log("findProviders for %c using fallback routers %s",e,l.map(u=>u.name).join(", ")),yield*i(l)),this.log("findProviders finished, found %d providers for %c",n,e)}async provide(e,t={}){if(this.routers.length===0)throw new ro("No content routers available");await Promise.all(ua(this.routers,"provide").map(async n=>{t?.onProgress?.(new P("helia:routing:provide:start",{router:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new P("helia:routing:provide:end",{router:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(ua(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new P("helia:routing:cancel-reprovide:start",{router:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new P("helia:routing:cancel-reprovide:end",{router:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(ua(this.routers,"put").map(async s=>{n?.onProgress?.(new P("helia:routing:put:start",{router:s.name,key:e,value:t})),await s.put(e,t,n),n?.onProgress?.(new P("helia:routing:put:end",{router:s.name,key:e,value:t}))}))}async get(e,t){let n=[],s,o=new AbortController,i=he([o.signal,t?.signal]);try{s=await Promise.any(ua(this.routers,"get").map(async a=>{t?.onProgress?.(new P("helia:routing:get:start",{router:a.name,key:e}));try{return await a.get(e,{...t,signal:i})}catch(c){throw this.log("router %s failed with %e",a.name,c),n.push(c),c}finally{t?.onProgress?.(new P("helia:routing:get:end",{router:a.name,key:e}))}}))}catch{}finally{o.abort(),i.clear()}if(s==null)throw new t1(n,`Failed to get value key ${_(e,"base58btc")}`);return s}async findPeer(e,t){if(this.routers.length===0)throw new ro("No peer routers available");let n=new AbortController,s=he([n.signal,t?.signal]);let o=this,i=hr(...ua(this.routers,"findPeer").map(a=>(async function*(){t?.onProgress?.(new P("helia:routing:find-peer:start",{router:a.name,peerId:e}));try{yield await a.findPeer(e,{...t,signal:s})}catch(c){o.log.error(c)}finally{t?.onProgress?.(new P("helia:routing:find-peer:end",{router:a.name,peerId:e}))}})()));try{for await(let a of i)if(a!=null)return a}finally{n.abort(),s.clear()}throw new Re("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new ro("No peer routers available");for await(let n of hr(...ua(this.routers,"getClosestPeers").map(async function*(s){t?.onProgress?.(new P("helia:routing:get-closest-peers:start",{router:s.name,key:e}));try{yield*s.getClosestPeers(e,t)}finally{t?.onProgress?.(new P("helia:routing:get-closest-peers:end",{router:s.name,key:e}))}})))n!=null&&(yield n)}};function ua(r,e){return r.filter(t=>t[e]!=null)}var kg=class{info;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;status;log;blockBrokers;mixins;components;constructor(e){this.info={name:e.name,version:e.version},this.logger=e.logger??r_(),this.log=this.logger.forComponent("helia"),this.getHasher=v_(e.hashers,e.loadHasher),this.getCodec=E_(e.codecs,e.loadCodec),this.getCrypto=x_(e.cryptos,e.loadCrypto),this.dns=e.dns??Xm(),this.metrics=e.metrics,this.events=new ge,this.status="stopped",this.mixins=[],this.components={blockstore:e.blockstore??new Cf,datastore:e.datastore??new Qi,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}},this.keychain=this.components.keychain=Zk()(this.components),this.routing=this.components.routing=new Cg(this.components,{routers:(e.routers??[]).flatMap(n=>(typeof n=="function"&&(n=n(this.components)),[n])),providerLookupConcurrency:e.providerLookupConcurrency}),this.blockBrokers=this.components.blockBrokers=(e.blockBrokers??[]).map(n=>(typeof n=="function"&&(n=n(this.components)),n));let t=new Ag(this.components,e);this.pins=new Ig(this.components.datastore,t,this.getCodec),this.blockstore=new bg(t,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=this.components.datastore}hasRouter(e){return this.routing.hasRouter(e)}addRouter(e){typeof e=="function"&&(e=e(this.components)),this.routing.addRouter(e)}hasBlockBroker(e){return this.blockBrokers.findIndex(t=>t.name===e)!==-1}addBlockBroker(e){typeof e=="function"&&(e=e(this.components)),this.blockBrokers.push(e)}addMixin(e){if(this.mixins.find(t=>t.name===e.name)!=null)throw new vs(`A mixin with the name "${e.name} is already present`);this.mixins.push(e)}async start(){this.status="starting",await a_(this.datastore),await yt(this.blockstore,this.datastore,this.routing,...this.blockBrokers);for(let e of this.mixins)await e.start?.(this);return this.status="started",this.events.dispatchEvent(new CustomEvent("start",{detail:this})),this}async stop(){this.status="stopping";for(let e of this.mixins)await e.stop?.(this);return await Dt(this.blockstore,this.datastore,this.routing,...this.blockBrokers),this.status="stopped",this.events.dispatchEvent(new CustomEvent("stop",{detail:this})),this}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,s=this.blockstore.unwrap();this.log("gc start"),await Cr(s.deleteMany((async function*(){for await(let{cid:o}of s.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new P("helia:gc:deleted",o))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new P("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};var I_="7.1.12",C_="helia";function wq(r={}){return Bx($k(sv(k_({...r,codecs:[A7,_7,Hf,...r.codecs??[]],hashers:[i3,...r.hashers??[]]}),r.http),r.libp2p),r.bitswap)}function k_(r={}){return new kg({name:C_,version:I_,...r})}return M_(bq);})();
|
|
114
114
|
/*! Bundled license information:
|
|
115
115
|
|
|
116
116
|
pvtsutils/build/index.js:
|